![]() |
VOOZH | about |
Java provides a rich set of modifiers. They are used to control access mechanisms and also provide information about class functionalities to the JVM. They are divided into two categories, namely:
Java access modifiers are used to control the visibility and accessibility of classes, methods, and variables in a program. They help achieve encapsulation and secure access control by defining where a member can be accessed from. They are following:
1. public:
public int count;
2. private:
private int salary;
3. default (Package-Private):
int age; // default access
4. protected:
Accessible:
protected String name;
In java, we have 7 non-access modifiers. They are used with classes, methods, variables, constructors, etc to provide information about their behavior to JVM. They are as follows:
The static modifier in Java indicates that a member belongs to the class itself rather than any specific object. All instances of the class share the same static variable or method, allowing common access without creating an object.
Syntax:
static int count;
static void display() { }
The final modifier in Java prevents modification of the element it is applied to. It can be used with variables (constant values), methods (cannot be overridden), and classes (cannot be subclassed).
Syntax:
final int MAX = 100;
final void show() { }
final class Vehicle { }
The abstract modifier in Java is used with classes and methods to define incomplete implementations. An abstract method has no body and must be implemented by a subclass, while an abstract class cannot be instantiated directly.
Syntax:
abstract class Shape {
abstract void draw();
}
The synchronized modifier in Java is used in multithreading to control access to critical sections. It ensures that only one thread can execute a method or block at a time, preventing race conditions.
Syntax:
synchronized void update() { }
The transient modifier in Java prevents a variable from being serialized when an object is converted to a byte stream. It is useful for excluding sensitive or non-essential data from serialization.
Syntax:
transient int password;
The volatile keyword in Java ensures that updates to a variable by one thread are immediately visible to other threads. It prevents threads from caching the variable locally, guaranteeing consistent and up-to-date values across all threads.
Syntax:
volatile boolean flag;
The native keyword in Java is used to declare a method whose implementation is provided in platform-specific code, typically using C or C++. It allows Java programs to interact with non-Java libraries via JNI (Java Native Interface).
Syntax:
native void loadLibrary();