The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes initializer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "initializer" Watch "initializer" New topic


meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
Hi all....I have a dought in the value of m.Kindly help to clarify this.
public class initialize
public initialize(int m)
public static void main(String[]args)
initialize obj=new initialize(x); //line 4

static int i=5; //line 1
static int x; //line 2

int j=7; //line 3

int k;

The output of this program is 50 70 0 20 0.
The follow of this program is
1. line 1
2 line 2
3. line 3
4. static block
5. then it goes to main method
6. before the constructor is invoked initialization block gets executed.

If this program flow is correct then
line 4 should be
initialize obj = new initialize(20);//as x=20
and so in the output shouldnt be the m value 20.
Why the m value is 0 in the output.
[ February 18, 2005: Message edited by: ramya jp ]
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
instance variable initialization occurs after the constructors are called but before they get past the first line of code ( super() or this() ).

Constructor initialize() was called with the argument x when x had the default value of 0. When the rest of the constructor executed, x was already 20 but the constructor used the formal parameter m which had already been assigned the old value of x.

Mike Gershman
SCJP 1.4, SCWCD in process
marc weber

Joined: Aug 31, 2004
Posts: 11343

When the class is loaded (with the call to its static main method), the static variables initialize and the static block executes. So i=5, x=0, and then i is reassigned to i=50.

Now the constructor is called, passing x as a parameter. At this point, x=0, and this is the value passed to the constructor, where it's assigned to m.

Before the constructor executes, the instance variables initialize and non-static block executes. So j=7, k=0, then j=70 and x=20.

Now the constructor body executes.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
Thanks Mike and Marc..
I agree. Here's the link:
subject: initializer
It's not a secret anymore!