wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initialization blocks... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initialization blocks..." Watch "Initialization blocks..." New topic
Author

Initialization blocks...

sonia jaswal
Ranch Hand

Joined: Jun 01, 2007
Posts: 42
Given:

class Bird {
{ System.out.print("bl "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

Output:

r1 r4 pre b1 b2 r3 r2 hawk

//Shouldn't the ouput of the code be r2 first and then r3....
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368
Since Instance initializer blocks are executed prior to constructors, 'r3' is printd before 'r2'


Thanks and Regards
sonia jaswal
Ranch Hand

Joined: Jun 01, 2007
Posts: 42
thanks for the reply....
Hamraj Kulshreshtha
Ranch Hand

Joined: Oct 06, 2007
Posts: 31
Since the instance init blocks run right after the call to super() in
a constructor,so r3 will be printed first and then r2.

And if more than one init blocks(Static or Instance) occurs in a class they run in the same order as they are defined i.e. from top to down.

Regards,
Hamraj


SCJP 1.5 91%
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8803
    
    5
Hi Sonia,

It's great to post mock exam questions on this forum for discussion purposes, so please carry on! However, in respect to all authors of mock exam questions, please indicate in your posts where each question came from. (In this case this is one of my questions, so no need in this case - but in the future.)

Thanks,

Bert


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Initialization blocks...
 
Similar Threads
Please explain the output
Please explian the output ....
11 K&B questions. Question 3
K&B Ch3 Self Test Que 14: need more clarification
Problem in understanding output of Program