Static Keyword in java .

Static Keyword  in  java .

Table of contents

No heading

No headings in the article.

  • Introduction

The "static" keyword in Java is used to define class-level members that belong to the class itself, rather than individual instances of the class. It signifies that a variable or method is shared among all instances of the class.

The significance of the "static" keyword lies in its ability to provide consistent values or behaviour across all objects of the class. By using static variables, you can store data that remains the same for every instance, ensuring uniformity. Similarly, static methods allow you to define the functionality that can be accessed without creating an instance of the class.

  • Static Variable

Static variables in Java are class-level variables that are shared among all instances of the class. Unlike instance variables (Reference variables ), which have separate copies for each object, static variables belong to the class itself.

public class Car {
    private static int numberOfCars = 0;
    private String brand;

    public Car(String brand) {
        this.brand = brand;
        numberOfCars++;
    }

    public static int getNumberOfCars() {
        return numberOfCars;
    }

}

In this example, the numberOfCars variable is declared as static. It keeps track of the total number of Car objects created. Each time a new Car object is instantiated in the constructor, the numberOfCars variable is incremented by one. Since numberOfCars is a static variable, it is shared among all instances of the Car class.

Using static variables is beneficial when you need to store values that remain consistent across all instances. In our example, the number of cars is a property that should be the same for all Car objects. By using a static variable, we ensure that the count is shared and updated correctly for every Car instance created.

  • Static Method

Static methods in Java are class-level methods like static variables that belong to the class rather than to specific instances of the class. They can be called directly on the class itself without the need to create an instance of the class. In Java, static methods are defined using the static keyword. And methods which are not defined with static keywords are called an instance methods.

public class Car {
    private static int numberOfCars = 0;
    private String brand;

    public Car(String brand) {
        this.brand = brand;
        numberOfCars++;
    }

    public static int getNumberOfCars() {
        return numberOfCars;
    }

     public static void main(){

       int totalaCar1 = Car.getNumberOfCars();
       System.out.println("Total cars" + ":" + totalaCar1)  
        // Output is : Total cars : 0 

       Car bmw = new Car("BMW");
       Car nano = new Car("nano");

       int totalaCar2 = Car.getNumberOfCars();
       System.out.println("Total cars" + ":" + totalaCar2)  
       // Output is : Total cars : 2 
     }

}

In the above example, we have a static method getNumberOfCars, So basically that means we can call it without creating any instance or we can say without creating any object for Car class. So for the first method call, we are not creating any object for a class method yet, So it gives us 0 is the default value. Why? Because numberOfCars will only increase when the constructor will be called, And when the constructor will be called? Yes, you are right when we create an object for a class. After we create an object for the class car by instance variable bmw and nano , constructor has been called for each one and it increases the numberOfCars variable by plus one each time. That is why if we call getNumberOfCars method after creating an object gives us 2 as a result.

public class Car {
    private static int numberOfCars = 0;
    private String brand;

    public Car(String brand) {
        this.brand = brand;
        numberOfCars++;
    }

    public String getNameOfCars() {
        return brand;
    }

     public static void main(){
         String nameOfCar = getNameOfCars(); 
         // Now this will throw an error               
     }

}

In the previous example, we call getNumberOfCars method inside main method, and it works fine, but when we try to code the above example and call getNameOfCars within main function we will get an error saying "YOU CAN NOT CALL NON-STATIC METHOD FROM STATIC MATHOD", That means you can only call any, method inside the static method if it is static too, You can not call a static method from the non-static method.

The reason for that is, the static method invoked without any object creation or without any instance variable, Which means the main method invokes initially as code gets run without any object creation, and the method which we are trying to call inside main is non-static, which means it needs an instance or we can say we need to create an object of class to call it.

Again, the static method will execute without any instance of the class and the non-static method inside the class need an instance for being called. So it gives us an error?

Points to remember :

  • Static methods do not need any instance or object for being called

  • You can only be called a static method inside the static method

  • For the Non-static method to call inside the static method, you need to create an object of class first

Here we get one more answer, Question is, Why do we call getNumberOfCars() method in the first example with an instance of Car class Car.getNumberOfCars() rather than calling it with this, Because getNumberOfCars is a static method, does not depends on any object, and this represents the object's scope. We can also use this but using class names for static methods is a good practice.

  • Static Blocks

Static blocks in Java are used for class initialization and are executed only once when the class is loaded into memory. They play a crucial role in initializing static variables or performing other one-time setup tasks before any instance of the class is created or any static method is called.

  1. Execution timing: Static blocks are executed only once when the class is loaded for the first time by the Java Virtual Machine (JVM).

  2. No explicit invocation: Static blocks are automatically executed by the JVM and do not require any explicit method call.

  3. Order of execution: If a class contains multiple static blocks, they are executed in the order they appear in the source code.

Static blocks can be used for various purposes, such as initializing static variables or performing other one-time setup tasks.

public class MyClass {
    static int myStaticVariable;

    static {
        // This is a static block
        // It is executed once when the class is loaded

        // Perform initialization or setup tasks here
        myStaticVariable = 10;
        System.out.println("Static block executed");

    }

    public static void main(String[] args) {
        // The main method or any other code

        System.out.println("Value of myStaticVariable: " + myStaticVariable);
        // Output: Value of myStaticVariable: 10
    }
}

In the above example, we have a class called MyClass that contains a static block. When the class is loaded, the static block is executed. In this case, it initializes the static variable myStaticVariable with the value 10 and prints "Static block executed" to the console. The main method then accesses the value of myStaticVariable and prints it.

Static blocks are particularly useful when you need to ensure that certain initialization tasks are performed before any instance of the class is created or any static method is called

  • Nested Static

Static nested classes in Java are nested classes that are declared as static within another class. They are closely associated with the outer class but have the unique feature of being instantiated independently, without requiring an instance of the outer class.

One advantage of using static nested classes is that they can access static members of the outer class directly, without the need for an instance. This allows for better encapsulation and organization of related code within a single class structure.

public class OuterClass {
    private static int outerStaticVariable = 10;

    public static class StaticNestedClass {
        private int nestedVariable = 20;

        public void nestedMethod() {
            int result = outerStaticVariable + nestedVariable;
            System.out.println("Result: " + result);
        }
    }
}

To instantiate the static nested class independently, you can use the following code.

public class Main {
    public static void main(String[] args) {
       OuterClass.StaticNestedClass nestedObject = new                                    OuterClass.StaticNestedClass();
        nestedObject.nestedMethod();
    }
}

this example, we create an instance of the StaticNestedClass without creating an instance of the OuterClass. We can then call the nestedMethod() on the nestedObject, which will access the static variable from the outer class and print the result.

Nested Static is a vast topic in itself, Will discuss it in next blog.

  • Important Considerations

When using the static keyword in programming, there are several important considerations to keep in mind. While static members can provide convenience and efficiency in certain scenarios, their excessive use can lead to tight coupling, hinder testability and maintainability, and introduce concurrency issues.

public class Math {
    public static final double PI = 3.14159;

    public static int add(int a, int b) {
        return a + b;
    }
}

public class Circle {
    public double calculateArea(double radius) {
        return MathUtils.PI * radius * radius;
    }
}

In this example, the Math class has a static constant PI and a static method add(). The Circle class uses the static constant PI to calculate the area of a circle. While this usage is appropriate, imagine if multiple classes relied on the Math class and its static members. If the value of PI were to change, all the dependent classes would need to be updated accordingly, making the code more rigid and error-prone.

  • Conclusion

The "static" keyword in Java is essential for defining class-level members and behavior. It allows the creation of static variables that belong to the class itself, rather than individual instances, ensuring their shared nature among all objects of the class. Static variables are ideal for storing values that need to remain consistent across instances.