static means a member belongs to the class rather than to individual objects.
Normally, instance members belong to each object. Static members are shared by all objects of the class.
A static variable belongs to the class and has one shared copy.
class Student {
static String college = "ABC College";
String name;
}
Student s1 = new Student();
Student s2 = new Student();
System.out.println(Student.college);
There is only one college variable shared by s1 and s2.
Student Class
│
└── static college
↑
┌───┴───┐
s1 s2
Use:
Student.college
rather than accessing it through an object.
A static method belongs to the class and can be called without creating an object.
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
Call it using:
int result = MathUtils.add(10, 20);
A static method cannot directly access instance members.