The static Keyword in Java
The static keyword in Java is a non-access modifier that makes members (variables, methods, and
blocks) belong to the class itself, rather than to any specific instance (object) of that class. This means
you can access them directly using the class name.
1. Static Variables (Class Variables)
• Purpose: Static variables are used for properties that are common to all instances of a class.
They are shared among all objects of the class, and there's only one copy in memory, regardless
of how many objects are created. This helps in memory management.
• Initialization: Static variables are initialized once when the class is loaded into memory, even
before any objects are created.
• Access: Accessed directly using the class name.
Code Example:
Java
class Student {
// static variable: belongs to the class, shared by all Student objects
public static int studentCount = 0;
String name;
public Student(String name) {
[Link] = name;
studentCount++; // Increment the count every time a new student is created
}
public void displayStudentInfo() {
[Link]("Student Name: " + [Link] + ", Total Students: " +
[Link]);
}
}
public class StaticVariableDemo {
public static void main(String[] args) {
Student s1 = new Student("Alice");
[Link](); // Output: Student Name: Alice, Total Students: 1
Student s2 = new Student("Bob");
[Link](); // Output: Student Name: Bob, Total Students: 2
// Accessing static variable directly via class name
[Link]("Current total students (from class): " +
[Link]); // Output: Current total students (from class): 2
}
}
2. Static Methods (Class Methods)
• Purpose: Static methods belong to the class and can be called directly using the class name
without creating an object. They are often used for utility functions that don't depend on the
state of an object.
• Restrictions:
• Cannot directly use non-static (instance) data members.
• Cannot call non-static (instance) methods.
• Cannot use this or super keywords, as they refer to object instances.
• Common Use Case: The main method in Java is static because the JVM calls it directly
without needing to create an object of the class.
Code Example:
Java
class MathOperations {
public static int add(int a, int b) {
return a + b;
}
public static int multiply(int a, int b) {
return a * b;
}
// A non-static method (instance method)
public void printMessage() {
[Link]("This is an instance method.");
}
// Example of restriction:
// public static void invalidMethod() {
// printMessage(); // Error: Cannot make a static reference to the non-
static method printMessage()
// }
}
public class StaticMethodDemo {
public static void main(String[] args) {
// Calling static methods directly using the class name
int sum = [Link](5, 3);
[Link]("Sum: " + sum); // Output: Sum: 8
int product = [Link](4, 2);
[Link]("Product: " + product); // Output: Product: 8
// To call an instance method, you need an object
MathOperations obj = new MathOperations();
[Link](); // Output: This is an instance method.
}
}
3. Static Blocks
• Purpose: Static blocks are used for one-time initialization of static variables or for performing
setup tasks that need to run only once when the class is loaded into memory.
• Execution: They are executed automatically and exactly once when the class is loaded.
• Syntax: static { // code here }
Code Example:
Java
class DatabaseConnector {
public static String DB_URL;
public static String DB_USERNAME;
public static String DB_PASSWORD;
// Static block to initialize static variables or perform setup
static {
[Link]("Static block executed: Initializing database connection
details...");
DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
DB_USERNAME = "root";
DB_PASSWORD = "password";
// Simulate a complex setup operation, e.g., loading driver
[Link]("Database driver loaded successfully.");
}
public static void connect() {
[Link]("Connecting to database at: " + DB_URL);
[Link]("Using username: " + DB_USERNAME);
// In a real application, you'd use these details to establish a connection
}
}
public class StaticBlockDemo {
public static void main(String[] args) {
[Link]("Main method started.");
// The static block will execute when DatabaseConnector class is first
accessed
[Link]();
[Link]("Main method finished.");
}
}
The final Keyword in Java
The final keyword in Java is used to restrict the user. It can be applied to variables, methods, and
classes to prevent modification, overriding, or inheritance, respectively.
1. Final Variables
• Purpose: When a variable is declared final, its value becomes a constant and cannot be
changed after it has been initialized.
• Initialization: A final variable must be initialized either at the time of declaration or within a
constructor (for instance variables) or a static block (for static variables). If not initialized at
declaration, the compiler will enforce initialization elsewhere.
Code Example:
Java
class Car {
// Final instance variable initialized at declaration
public final int MAX_SPEED = 200;
String model;
// Final instance variable initialized in the constructor
public final String chassisNumber;
// Static final variable (constant)
public static final String BRAND = "LuxuryMotors";
static {
// Final static variables can also be initialized in a static block
// BRAND = "AnotherBrand"; // This would cause an error as BRAND is already
initialized
}
public Car(String model, String chassisNumber) {
[Link] = model;
[Link] = chassisNumber; // Initialize final variable in
constructor
// this.MAX_SPEED = 220; // Error: cannot assign a value to final variable
MAX_SPEED
}
public void displayCarInfo() {
[Link]("Brand: " + [Link]);
[Link]("Model: " + [Link]);
[Link]("Chassis Number: " + [Link]);
[Link]("Max Speed: " + this.MAX_SPEED + " km/h");
}
}
public class FinalVariableDemo {
public static void main(String[] args) {
Car myCar = new Car("X7", "CHAS12345");
[Link]();
// [Link](myCar.MAX_SPEED);
// myCar.MAX_SPEED = 250; // Error: cannot assign a value to final variable
MAX_SPEED
}
}
2. Final Methods
• Purpose: When a method is declared final, it cannot be overridden by any subclass. This
ensures that the behavior defined in the final method remains consistent and cannot be
altered by derived classes.
• Use Cases: Often used for methods that contain critical logic, security-sensitive operations, or
fundamental behavior that should not be changed.
Code Example:
Java
class Vehicle {
// This method is final and cannot be overridden by subclasses
public final void startEngine() {
[Link]("Engine started with standard procedure.");
}
public void stopEngine() {
[Link]("Engine stopped.");
}
}
class SportsCar extends Vehicle {
// Attempting to override a final method results in a compile-time error
// @Override
// public void startEngine() { // Error: startEngine() in SportsCar cannot
override startEngine() in Vehicle
// [Link]("Sports car engine started with high performance
mode.");
// }
@Override
public void stopEngine() { // This is allowed as stopEngine is not final
[Link]("Sports car engine stopped quickly.");
}
}
public class FinalMethodDemo {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
[Link](); // Calls the final method from Vehicle
[Link](); // Calls the overridden method from SportsCar
}
}
3. Final Classes
• Purpose: When a class is declared final, it cannot be extended by any other class. This
prevents inheritance and ensures that the class's implementation remains fixed and cannot be
altered through subclassing.
• Use Cases:
• Security: To prevent malicious subclasses from altering critical behavior.
• Immutability: Classes like String in Java are final to ensure their immutability.
• Design Control: When you want to ensure that a class's behavior is exactly as defined
and cannot be extended or modified.
Code Example:
Java
// This class is final and cannot be extended
final class SecretVault {
private String secretCode;
public SecretVault(String secretCode) {
[Link] = secretCode;
}
public String retrieveSecret() {
return "Secret retrieved: " + secretCode;
}
}
// Attempting to extend a final class results in a compile-time error
// class HackerVault extends SecretVault { // Error: cannot inherit from final
SecretVault
// public HackerVault(String secretCode) {
// super(secretCode);
// }
// // ... malicious code ...
// }
public class FinalClassDemo {
public static void main(String[] args) {
SecretVault vault = new SecretVault("TopSecret123");
[Link]([Link]());
}
}
4. Final Keyword with Constructors
• Can a constructor be final? No, a constructor cannot be declared final.
• Reasoning:
• Constructors are used to initialize the state of an object.
• The final keyword for methods prevents overriding. Constructors are not inherited or
overridden in the same way as regular methods. A subclass has its own constructor
which might call the parent's constructor using super().
• Declaring a constructor as final would lead to a "modifier not allowed here"
compilation error because it doesn't align with the purpose of final.
Code Example (Illustrating the error):
Java
class MyClass {
// public final MyClass() { // Error: modifier final not allowed here
// [Link]("Constructor");
// }
public MyClass() {
[Link]("Regular constructor");
}
}
public class FinalConstructorDemo {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}