File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initialization blocks..." Watch "Initialization blocks..." New topic

Initialization blocks...

sonia jaswal
Ranch Hand

Joined: Jun 01, 2007
Posts: 42

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 ");


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.


SCJP 1.5 91%
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
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.)



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:
subject: Initialization blocks...
jQuery in Action, 3rd edition