Understanding Static in Java

 The keyword static tells Java that a particular property, method, or code block belongs to the class itself, rather than any individual instance of that class. Lets look at the difference between static and non-static properties.


class MyClass {
  
  public int notStaticInt;
  public static int staticInt;

} //MyClass

public class MainClass {

  public static void main(String[] args) {

    MyClass myClass1 = new MyClass();
    MyClass myClass2 = new MyClass();

    myClass1.notStaticInt = 1;
    myClass2.notStaticInt = 2;

    myClass1.staticInt = 3;
    myClass2.staticInt = 4;
  
    System.out.println("myClass1: " + myClass1.notStaticInt);
    System.out.println("myClass2: " + myClass2.notStaticInt);
    System.out.println("myClass1: " + myClass1.staticInt);
    System.out.println("myClass2: " + myClass2.staticInt);
 
  } //main
} //MainClass

The output of this code is...


myClass1: 1
myClass2: 2
myClass1: 4
myClass2: 4

We learn from this, that myClass1 and myClass2 can have different values for the notStaticInt properties but they share the same value for the staticInt property. The staticInt is static and so it does not belong to either myClass1 or myClass2 but it belongs to the class itself and so all instances of MyClass will have that same value. If you try to change the value using one of the instances, the value is changed for all instances because they all share it.

If you make a method of a class static, then you can call the method without even having to create an instance of the class.



class MyClass {
  
  static void speak() {
    System.out.println("Hello my friends!");
  }

} //MyClass

public class MainClass {

  public static void main(String[] args) { 

    MyClass.speak();
 
  } //main
} //MainClass

Static blocks are used for initialization of static properties. It is executed, like a default constructor, when the class is loaded into memory, once only.


class MyClass {

  static int myInt;
  
  static {
    myInt = 3;
  }

} //MyClass

public class MainClass {

  public static void main(String[] args) { 

    MyClass myClass1 = new MyClass();

    System.out.println(myClass1.myInt);
 
  } //main
} //MainClass

It is especially useful for complex initialization logic like error handling.
Here is an example...


class MyClass {
  
  static {
    try {
        someStaticResource = loadResource();
    } catch (IOException e) {
        System.err.println("Error loading resource");
    }
  }

} //MyClass

And here is something interesting... A class can have both a default constructor and a static block, and they serve different purposes: the static block is for class-level initialization, while the constructor is for instance-level initialization. They do not conflict with each other and can work together.

Comments

Popular Posts