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 question from ExamLab practice test 1 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question from ExamLab practice test 1" Watch "question from ExamLab practice test 1" New topic

question from ExamLab practice test 1

Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 446

I got this question from ExamLab practice test 2
I am not able to understand the flow of the program
please provide some help on initializer blocks and initialization process when the class in loaded in the memory

The output is

F:\Java\Javaranch problems>java ExamLabBoard
Current Cam=1

SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142

Remember the principle "static code (and block) is executed in sequence from top to bottom". The only relevant lines of code (to the method call in main) are:

When you call the capture() method, the static door variable has a value of 1. Hence capture() returns 1 and this gets assigned to the static cam variable. After that whatever happens to door DOESN'T affect cam. It only affects door when the static block below is executed:

The above code simply changes the value of door, but remember, cam has already been assigned. So cam will have a valu of 1. Hence what you see in the output of the program.

The instance initializer block

is irrelevant in the static context, since no objects have been created. It doesn't impact the value of cam in any way.
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 446

Thank you sir for replying
nice explanation
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
Thanks Larry Olson for your rule !!! Many new things are discovered today !!!

Thanks Prasad for you query, it contributed to my knowledge domain !!!

SCJP 6.0 96%

(Connecting the Dots ....)
I agree. Here's the link:
subject: question from ExamLab practice test 1
It's not a secret anymore!