The static and final keywords in Java are fundamental modifiers that control how variables, methods, and classes behave in terms of memory, inheritance, and mutability.
Mastering these helps in writing efficient, clear, and secure Java programs.
The static and final keywords in Java are fundamental modifiers that control how variables, methods, and classes behave in terms of memory, inheritance, and mutability.
Mastering these helps in writing efficient, clear, and secure Java programs.
Static Keyword:
Final Keyword:
final variable’s value cannot be changed once assigned.Combining static and final is commonly used to define constants.
Understand how static variables and methods work in Java.
// Static variable and method example
class Counter {
static int count = 0;
Counter() {
count++; // Increment count for every new object
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
Counter.displayCount(); // Output: Count: 2
}
}
// Final variable and method example
class Constants {
final int MAX_VALUE = 100;
final void display() {
System.out.println("This is a final method.");
}
}
class SubClass extends Constants {
// This would cause an error if uncommented:
// void display() {
// System.out.println("Cannot override final method");
// }
}
public class Main {
public static void main(String[] args) {
Constants obj = new Constants();
System.out.println(obj.MAX_VALUE); // Output: 100
obj.display();
}
}
// Static final variable example (constant)
class MathConstants {
static final double PI = 3.14159;
}
public class Main {
public static void main(String[] args) {
System.out.println(MathConstants.PI); // Output: 3.14159
}
}
Static methods are often used in utility/helper classes like Math and Collections.
Using static final variables to define constants helps maintain consistent values across the application.
Final variables help create immutable objects and prevent unwanted changes.
The static keyword makes a variable or method belong to the class rather than instances of the class.
No, a final method cannot be overridden by subclasses.
static final variables are constants that are shared among all instances and cannot be changed after initialization.