• Post Reply Bookmark Topic Watch Topic
  • New Topic

Order of precedence  RSS feed

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I missed this question in the scjp 6 study guide and am hoping for clarification. Chapter 4 question 6:


I thought the instance code block would execute before the member variable "index" was defined and so not compile, which is wrong. This does compile and that tells me that the member vars get defined prior to the instance code block being executed.

Is there a complete listing somewhere of the sequence of events that occur (as far as scjp 6 is concerned) when you start a java program and when you instantiate a class? For example: Class vars are defined, main method, local method vars defined...

Thanks,
Gil
 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rules are all in the JLS, the full sequence of initialization is spread out between sections on initializers and constructors. But the rule you specifically want is this section: 8.3.2.3 Restrictions on the use of Fields during Initialization. Basically, the reason it doesn't fail is because the variable index is on the left side of the equal sign. If it were on the right side, you would get an exception or would have to move the initializer after the declaration.
 
Gil Steidle
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the link. It explained my scenario perfectly. I'm frustrated with the authors for not mentioning this non trivial jls spec but including it on a question. At least I don't remember reading about it before. Anyway, I'll just keep plugging along through the practice tests.

Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!