Page 1 of 1

Static Initializer

Posted: Fri Mar 01, 2013 11:38 am
by Sweetpin2
Hi,

I have following code

public class A {

public A() { }
public A(int i) { System.out.println(i ); }
}

public class B {

static A s1 = new A(1);
A a1 = new A(2);

public B(int i)
{
System.out.println(i);
}

public static void main(String[] args){
B b1 = new B(10);

A a2 = new A(3);
}

static A s2 = new A(4);
static B b2 = new B(15);
}

The o/p from this program is

1
4
2
15
2
10
3

My doubt is why 2 is printed twice instead of once, as instance a1 should have initialized only once?

Re: Static Initializer

Posted: Fri Mar 01, 2013 2:47 pm
by admin
Are you sure 2 is printed twice?

Re: Static Initializer

Posted: Sat Mar 02, 2013 11:44 pm
by Sweetpin2
admin wrote:Are you sure 2 is printed twice?
Yes, 2 is printed twice.

Re: Static Initializer

Posted: Sun Mar 03, 2013 6:45 am
by admin
You are instantiating two instances of class B ( new B(10) and new B(15) and class B has an instance member A, which you are initializing as A a1 = new A(2);

In such cases, it is a good idea to use an IDE and run the program step by step.