This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Curly braces 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 "Curly braces" Watch "Curly braces" New topic
Author

Curly braces

Rao Rekha
Greenhorn

Joined: Jul 29, 2002
Posts: 11
Could somebody kindly explain to me why a system.out.println("...") statement works without giving any error when specified within a pair of curly braces inside a class like the following.
0
class test{
{
System.out.println("...");
}
}
But it gives an error without the inner curly braces. Why?

Thank you
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
Originally posted by Rao Rekha:
Could somebody kindly explain to me why a system.out.println("...") statement works without giving any error when specified within a pair of curly braces inside a class like the following.
0
class test{
{
System.out.println("...");
}
}
But it gives an error without the inner curly braces. Why?

Thank you

The pair of curly braces forms an instance initializer. The body is processed just before processing the body of the constructor. If you put the word "static" in front of the curly braces, then it becomes a "static initializer" and would then be processed when the class is loaded.
If you would like to see more examples of instance initializers, then please see the single topic exam titled "constructors" on my web site.
[ September 09, 2002: Message edited by: Dan Chisholm ]

Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Rao Rekha
Greenhorn

Joined: Jul 29, 2002
Posts: 11
Thank you Dan. I didnt know about this instance intializer before. It is only after seeing the questions at your web site that I got the doubt.
Anyway, your website has been very useful this way.
Thanks again.
 
GeeCON Prague 2014
 
subject: Curly braces