Static V/s Non-static Reserved Keyword In Java
In Java, the static
keyword is used to define members (variables and methods) that belong to a class itself rather than to instances (objects) of the class. On the other hand, non-static (sometimes called "instance") members belong to individual instances of the class. Here are the key differences between static
and non-static members in Java:
1. Ownership:
1.
static
belongs to the class itself, shared by all instances of the class. There is only one copy of a static member in memory, regardless of how many instances of the class exist.- 2. Non-static: Belongs to individual instances of the class. Each instance has its own copy of non-static members.
2. Access:
1.
static
: Can be accessed using the class name (e.g.,ClassName.staticMember
) or directly without an instance reference.- 2. Non-static: Requires an instance of the class to be created before accessing non-static members (e.g.,
object.nonStaticMember
).
3. Memory Allocation:
1.
static
: Allocated memory once when the class is loaded by the classloader.- 2. Non-static: Allocated memory separately for each instance when objects are created.
4. Lifecycle:
1.
static
: Exists for the entire lifetime of the program or until the class is unloaded.- 2. Non-static: Exists as long as the instance to which it belongs exists and is eligible for garbage collection when the instance is no longer referenced.
5. Common Use Cases:
1. static
: Used for constants, utility methods, shared resources, and for defining class-level behavior that is not dependent on instance-specific data.- 2. Non-static: Used for instance-specific data and behavior that depends on the state of individual objects.
Here's an example illustrating the differences:
In this example, staticVar
and staticMethod
are shared among all instances of Blog02(i.e My Class)
, while nonStaticVar
and nonStaticMethod
are specific to each instance. Understanding when to use static
and non-static members is crucial for designing and implementing effective Java classes.
package Tutorial_00;
public class Blog02 {
public static int staticVar = 0; // Static variable
public int nonStaticVar = 0; // Non-static variable
public static void staticMethod() {
// Static method
System.out.println("This is a static method.");
}
public void nonStaticMethod() {
// Non-static method
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Blog02.staticVar = 42; // Accessing static variable
Blog02.staticMethod(); // Calling static method
Blog02 obj1 = new Blog02();
obj1.nonStaticVar = 10; // Accessing non-static variable
obj1.nonStaticMethod(); // Calling non-static method
Blog02 obj2 = new Blog02();
obj2.nonStaticVar = 20;
obj2.nonStaticMethod();
}
}