On Day 22, we learn about the static keyword in Java. Static members (fields, methods, and blocks) belong to the class itself rather than to individual objects. This means they can be accessed without creating an object of the class.
1. Static Fields (Class Variables)
Static fields are shared among all objects of a class.
class Student {
String name;
static String school = "ABC High School"; // shared by all students
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(s1.name + " studies at " + Student.school);
System.out.println(s2.name + " studies at " + Student.school);
Student.school = "XYZ Academy"; // change for all
System.out.println(s1.name + " now studies at " + Student.school);
}
}
Explanation: The school
variable belongs to the class, so changing it affects all objects.
2. Static Methods
Static methods can be called without creating an object. They can only access static members directly.
class MathUtil {
// static method
static int square(int x) {
return x * x;
}
}
public class Main {
public static void main(String[] args) {
// calling static method without object
System.out.println("Square of 5: " + MathUtil.square(5));
}
}
Explanation: square()
is static, so we can call it directly using the class name.
3. Static Blocks
A static block is used to initialize static variables. It runs once when the class is loaded.
class Config {
static String appName;
// static block
static {
appName = "My Java App";
System.out.println("Static block executed");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("App: " + Config.appName);
}
}
Explanation: The static block initializes appName
before the main method runs.
4. Key Rules of Static Members
- Static fields are shared across all objects.
- Static methods can be called without objects.
- Static methods can only access static fields directly (not instance fields).
- Static blocks are executed once when the class is loaded.
Summary
The static keyword is useful when data or behavior should belong to the class as a whole, rather than individual objects. Common use cases include utility methods (like Math
class), configuration values, and constants.