Static and Non-Static in Java
Static and Non-Static in Java In Java, static and non-static determine whether a variable or method belongs to a class or an object. Understanding this concept is important because it helps us understand memory, object
Static and Non-Static in Java
In Java, static and non-static determine whether a variable or method belongs to a class or an object. Understanding this concept is important because it helps us understand memory, object creation, and how Java programs work.
1. Static
The static keyword is used to declare variables and methods that belong to the class rather than individual objects.
A static variable is shared among all objects of a class. Only one copy of the static variable exists, regardless of how many objects are created.
class Student {
String name;
static String college = "ABC College";
}
Here, name is a non-static variable, while college is a static variable. Every student object shares the same college name.
We can access a static variable using the class name:
System.out.println(Student.college);
Static Method
A static method belongs to the class and can be called without creating an object.
class Calculator {
static int add(int a, int b) {
return a + b;
}
}
Calling the method:
int result = Calculator.add(10, 20);
System.out.println(result);
Output:
30
Static methods can directly access static variables and other static methods. However, they cannot directly access non-static members because those members belong to individual objects.
2. Non-Static
Non-static variables and methods belong to objects. Whenever we create an object, it gets its own copy of non-static variables.
class Student {
String name;
int age;
void display() {
System.out.println(name);
System.out.println(age);
}
}
Creating objects:
Student s1 = new Student();
Student s2 = new Student();
s1.name = "Arun";
s1.age = 21;
s2.name = "Kumar";
s2.age = 22;
s1.display();
s2.display();
Each object has its own name and age. Changing the values of one object does not affect another object.
Non-static methods can access both static and non-static members of the class.
5. Why Is the Main Method Static?
The main method in Java is declared as static:
public static void main(String[] args)
The JVM needs to execute the main method to start the program. Since it should not need to create an object before starting execution, the main method is static.
This allows the JVM to call the method directly using the class.
Conclusion
Static members belong to the class and are shared among all objects, whereas non-static members belong to individual objects and maintain their own values. Static is useful for common data and utility methods, while non-static is useful for representing the properties and behaviours of individual objects.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.