This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "initializer" Watch "initializer" New topic
Author

initializer

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)
{
System.out.println(i+","+j+","+k+","+x+","+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;
{
j=70;x=20;
}

static
{
i=50;
}
}
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
Sheriff

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
sscce.org
meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
Thanks Mike and Marc..
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: initializer
 
Similar Threads
From mock...
Reg. class initialization sequence
Static variable initialization...
Static Int and Methods
methods or what?