• Post Reply Bookmark Topic Watch Topic
  • New Topic

illegal start of type error  RSS feed

 
Patrick Nodder
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the println statement not compile? And then why does it compile when I put it within braces?



 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't have a statement outside of a method body. The one exception as you found out is un-named block used for static initializers that are executed once when the class gets loaded. Unless you understand how static initializers work, stay away from them.

Edit: So, it's not a "static" initializer because it is missing the word "static". It is however an instance initializer.
See: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:



The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
 
Patrick Nodder
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a similar example in the OCA exam book I was reading and I didn't understand what it was doing- thanks for explaining.

Cheers
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch

Did you copy the example which does compile exactly? Note how the {} are indented incorrectly, squeezed against the statement so you might miss them. They like that sort of poor formatting in certification books, so as to see whether you are awake.
 
Patrick Nodder
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I've noticed. Not exactly copied but there is a similar example where the braces are not lined up on page 19 of the 1Z0-808 book by Boyarsky/Selikoff.

Cheers!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!