This is good question Dolly!
Hope this will help you to understand now!!!
Lets trace the code line by line Hope this will help you?
public static void main(
String... args){ //1
Animal2 a=new Animal2(); //2
System.out.println(a.name); //3
Animal2 b=new Animal2("Zeus"); //4
System.out.println(b.name); //5
}
As soon as this class is loaded in the JVM
static block will be loaded
(This is static so it will be loaded one time for the JVM not for every object created for this class)
so
System.out.println(" C's static" ); is execute and print
C's static line //2 is execute and it call constructor Animal2()which call makeRandomName() which first call System.out.println("static"); then print
static Then it will load the
Variable I for the object(This is non-static so it is loaded for object not for the class)
int i = InitialValue();
Which execute method InitialValue();
Which will execute System.out.println("Initial"); and print
Initial We are still in the constructor Animal2()Then it will execute
System.out.println("this"); and print
this Now we are out of constructor and in line 3
which will execute
System.out.println(a.name);
Since this statement is already executed in makeRandomName() method
String name = new String[] { "Fluffy", "Fido", "Rover", "Spike", "Gidi" }[x];
It will print
Gidi Because Gidi is the last value in the array.
Now we are in the line //4
So it will call constructer
Animal2(String name)
Which will assign name = �Zeus�
Then it will load the
Variable I from the class
int i = InitialValue();
Which execute method InitialValue();
Which will execute System.out.println("Initial"); and print
Initial Next it will be in line //5 which will execute
System.out.println(b.name); and print
Zeus [ August 02, 2007: Message edited by: Aaron Raja ]
[ August 02, 2007: Message edited by: Aaron Raja ]
[ August 02, 2007: Message edited by: Aaron Raja ]
[ August 02, 2007: Message edited by: Aaron Raja ]