java

Java Static Keyword


What is static keyword?


In Java, the static keyword is used to declare members (fields, methods and nested classes) that belong to the class rather than to instances of the class. This means that there is only one copy of the static member, regardless of how many instances of the class are created.

 

  • Here are some common uses of the static keyword in Java:

1.  Static Variables ( class variable ): 

  • A static variable is shared among all instances of a class.
  • It is declared using the static keyword before the data type.

Syntax

public class MyClass {
    static int staticVariable = 10;
}

Example 1

class Counter{  
    int intCount = 0; // //will get memory each time when the instance is created  
	static int count=0; //will get memory only once and retain its value  
  
Counter(){  
    intCount ++; // incrementing value
    count++; //incrementing the value of static variable  
    System.out.println(intCount);
    System.out.println(count);
}  
  
public static void main(String args[]){  
	    //creating objects  
    	Counter obj1=new Counter();  
		Counter obj2=new Counter();  
		Counter obj3=new Counter();  
	}  
}

Output:

Normal Variable: 1
Static Variable: 1
Normal Variable: 1
Static Variable: 2
Normal Variable: 1
Static Variable: 3

 

Example 2

calling static variables with class name.

public class StaticVariableExample {
    // Static variable shared among all instances of the class
    static int staticVariable = 100;

    public static void main(String[] args) {
        // Accessing static variable through the class name
        System.out.println("Static Variable: " + StaticVariableExample.staticVariable);
	}
}

 

Output:

Static Variable: 100

 

2.  Static Methods ( class methods ):

  • A static method belongs to the class rather than any particular instance.
  • It is called on the class itself, not on an instance of the class.

Syntax

public class MyClass {
    static void staticMethod() {
        // code
    }
}

 

Example

public class StaticMethodExample {
    // Static method to add two numbers
    static int add(int a, int b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        // Calling static methods directly through the class name
        int sumResult = StaticMethodExample.add(5, 3);
       
        // Displaying the results
        System.out.println("Sum Result: " + sumResult);
     }
}

 

Output:

Sum Result: 8

 

Restrictions for the static method

  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.

 

3.  static block:

  • The static block is executed only once when the .class file is loaded by the Java Virtual Machine (JVM). 
  • It runs before the execution of any static methods or the creation of any static variables within the class.

Syntax

class MyClass {
    // Static block
    static {
        // Code to initialize static variables or perform other operations

	}

}

 

Example:

public class Main {
    // static block
    static {
        System.out.println("This is a static block!");
    }

	// main method the execution point
    public static void main(String[] args) {
        System.out.println("Main method executed!");
    }
}

 

Output:

This is a static block!
Main method executed!

 

Note: 

In Java, when a class is loaded into the Java Virtual Machine (JVM), the static block is executed before any other code in the class that's why in output “This is a static block!”  came first.

 

Why static block?

1.  Initializing Static Variables: 

a) Static blocks are often used to initialize static variables with specific values.

b) This is useful when you want to set up certain constants or configurations that are shared among all instances of the class.

class MyClass {
    // Static variable
    static int myStaticVariable;

    // Static block to initialize the static variable
    static {
        myStaticVariable = 42;
    }
}

 

2. Loading Drivers or Libraries:

a) If your class requires the use of external libraries or needs to load a driver, static blocks can be used to handle such tasks.

b) This ensures that the necessary components are set up before any methods are invoked.

public class DatabaseConnector {
    static {
        // Load the database driver or initialize necessary resources
        // ...
    }
}

3. Complex Initialization: 

If the initialization of a static variable involves complex logic or needs to handle exceptions, using a static block allows you to encapsulate that logic in a structured manner.

class ComplexInitialization {
    static {
        try {
            // Complex initialization logic
            // ...
        } catch (Exception e) {
            // Handle exceptions during initialization
            // ...
        }
    }
}

 

4. Static Nested Classes:

A static nested class is a static member of the outer class and can be accessed without instantiating the outer class.

 

Syntax

public class OuterClass {
    static class StaticNestedClass {
        // Nested class code
    }
}

 

Example

public class OuterClass {
    // Outer class members

    // Static nested class
    static class StaticNestedClass {
        void display() {
            System.out.println("This is a static nested class.");
        }
    }

    public static void main(String[] args) {
        // Creating an instance of the static nested class
        OuterClass.StaticNestedClass nestedInstance = new OuterClass.StaticNestedClass();

        // Calling the method of the static nested class
        nestedInstance.display();
    }
}

 

Output:

This is a static nested class.

 

Explanation:

  • The class OuterClass contains a static nested class named StaticNestedClass.
  • The StaticNestedClass has a method display that prints a message.
  • In the main method, we create an instance of the static nested class using the syntax OuterClass.StaticNestedClass.
  • We then call the display method on the created instance.

 

about static keyword

Note: It's important to note that you can access static members using the class name rather than an instance of the class. For example, MyClass.staticVariable or MyClass.staticMethod(). Additionally, static members are loaded into memory when the class is loaded, and they exist for the entire lifetime of the program.