Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

initializer

 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mike and Marc..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic