Static Initializer

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Static Initializer

Post 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?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Static Initializer

Post by admin »

Are you sure 2 is printed twice?

Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Re: Static Initializer

Post by Sweetpin2 »

admin wrote:Are you sure 2 is printed twice?
Yes, 2 is printed twice.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Static Initializer

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests