• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

braces without name

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I am studying for the scjp I noticed that you can have code like this



When you instantiate the class Test the value for x is 1 is this another form of constructor or is it something else.

Thanks
 
Ranch Hand
Posts: 140
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
its what you call "instance init blocks"

instance init blocks run after the super() contsructor is called.

public class Sample {
int x = 0;
{ x+=1 }

Sample() {
// call to super()
// <------------ instance init block runs at this point
// other constuctor codes.....
}

}
 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

its a non-static-initializer... Any code in that runs before the constructor is invoked. So when you have overloaded constructors and there is a common initalization code, doing that initalization in the initalizer simplifies the job. There are static initalizers too...

like


and these static initializers are run when the class is loaded.. so can be used to initalize static variables...


Regards,
Vishwa
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rancher ,

If anywhere you see block outside method , it is either instance initializer block or static initializer block .

Instance initializer block is called each time , you create new object of that class .


Static instance initializer block is called only once when class is loaded by JVM in memory .


 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Some more info:

Java instance initializers - shows a trick I didn't know yet!

Object Initialization in Java - a longer story that explains everything in detail, old (1998!) but still valid
reply
    Bookmark Topic Watch Topic
  • New Topic