Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

different output for java static initialization

public class DemoApplication {

    public static void main(String[] args) {
        System.out.println("count: "+A.count);
        System.out.println("count: "+A.count);
        var a1=new A();
        var a2=new A();
        System.out.println("count: "+A.count);

    }
}

1)

public class A {

    public static A inst = new A();
    public static int count;

    public A() {
        A.inst.count++;
    }
}

output:

count: 1
count: 1
count: 3

2)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class A {

    public static A inst = new A();
    public static int count=0;
    public A() {
        A.inst.count++;
    }
}

output:

count: 0
count: 0
count: 2

The differences is in

  1. public static int count;
  2. public static int count=0;

Can anyone explain this?

>Solution :

Static initialization occurs in order.

In your first code snippet, the first action is to create a new instance of A for the static field. It needs the static field so that gets initialized to the default value, 0. The constructor then increases it to 1.

In your second code snippet, after the initialization of the static field, the value (1) is reset back to 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading