• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question from ExamLab practice test 1

 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Larry Olson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you sir for replying
nice explanation
 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Larry Olson for your rule !!! Many new things are discovered today !!!

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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic