wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question about code in { } 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 "question about code in { } " Watch "question about code in { } " New topic
Author

question about code in { }

mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
i have a doubt with the code enclosed in { } without the static initializer. when is this block of code run ?
we know that static initializer is run at class load time.
when is this { } block run ? because the string "run-non-static" is not printed, meaning this piece is not run when the class is not instantiated ie Test t = new Test(); without this statement the {} block will not run.
i am a bit confused here. please explain this.

class Test {
int x=1;
static{System.out.println("run-static");int x=0;}
{System.out.println("run-non-static");x=2;}

private static void main(String args[])
{Test t = new Test();int a = t.x;
System.out.println("main-method");
System.out.println("x = "+a);
}
}
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
{} is an instance initializer and it is run when an object is constructed (when you invoke Test t = new Test()).
normally you shouldn't use instance initializer in normal classes. Instance initializer have been introduced for anonymous inner class where you can't have explicit constructor. This is the only place where instance initializers should be used...
HIH


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
I believe the purpose of instance initializer is to factor out the common code from all the constructors and place it in one location, i.e. instance initializer. Instance initializer are also useful with anonymous classes since they cannot have constructors. "All" constructors must declare the uncaught checked exceptions from instance initializer(s), if any.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Brian,
if you have multiple constructors in your class you should write them in a way that all constructors call (by means of this() ) only one specific constructor which contains the common code. As far as good design goes, instance initializer should only be used in anonymous inner classes.
Another good thread on this : http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014683
HIH
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Hi Valentin!
Don't you think constructor chaining by means of calling this() in multiple constructor situation is a more expensive operation than using just one initializer block. I did not understand what you meant by pointing me to the link you provided. Corey has given a good example showing one of the uses/benefits of having instance initializer block.
I don't give much credit to statements like these:
"In real programming practice, you would never use an instance initializer in a class, unless as Corey stated, it was in an annonymous class. Put your instance initializations in a constructor. Only use an instance initializer in an annonymous class, since they can't have explicit constructors. In fact, that's why instance initializers were invented."
Sorry Rob no hard feelings. I am not sure if you were involved in the design of Java language or you are in regular touch with the designers of Java language.
No Hard Feelings Valentin too!
Brian
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Brian,
no hard feelings, Javaranch is a friendly place for java greenhorns
I like it when people give their opinions. Yours is legitimate, of course... It's much more a matter of taste than an ultimate design practice.
It is true that chaining constructor will have the effect of growing the stack, but it is much less error-prone to have the code in a constructor somewhere than outside of them in a non-static block as far as debugging is concerned.
Anyway, folks, do it the way you are comfortable with, there is no real proven benefit for one or the other approach.
By the way, the link I provided was not directly directed at you but just to enrich this discussion with another one that happened yesterday on the same topic.
Tarik Makota
Greenhorn

Joined: Jan 29, 2002
Posts: 23
Order of initialization for Object b = new Object(); is
1. final variables are always assigned values first, no matter where they occur. Among themselves, ordering is according to their sequence in code.
2. static and non static blocks : in the order they are written in the code.
3. constructor.
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Okay I am going to take a shot at this one a bit more deeply than I had originally thought.
First things first: Constructor chaining through this() has nothing to do with instance initializer. Unless you can prove me wrong.
When you invoke a different constructor through this() you are either invoking that constructor because you would like to initialize couple of other things besides you just initialized in the current constructor or you do not want to replicate the code from the other constructor in the current one.
Secondly: Assume you have a huge object that needs to "always" initialize certain things no matter in which way the object is constructed (implying you have multiple constructors).
There are two ways to do this:
1. Replicate the common initializing code in all the constructors.
2. Code the initialization sequence/code in a initializer block.
Lets say tomorrow you need to add more or remove some "common" initialization sequence to/from this object. If you go with option no. 2 you just have to modify the code in one place. If you go with option 1 you have to modify the code in multiple places. Option no. 1 is error prone whereas option no. 2 is less error prone.
I cannot guide you to a particular resource or a reasearch study to justify above statements. I believe they are common sense.
Again, you can code the same stuff in different places there is nothing wrong with it. But coding the same stuff in one place "MAY prove" to be less error prone.
Brian
[ February 07, 2002: Message edited by: Brian Lugo ]
mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
just to confirm that final variables are taken care first, be it static or non-static ? between them it would be static final first ?? right ?
Originally posted by Tarik Makota:
Order of initialization for Object b = new Object(); is
1. final variables are always assigned values first, no matter where they occur. Among themselves, ordering is according to their sequence in code.
2. static and non static blocks : in the order they are written in the code.
3. constructor.
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Check out this code Mark!

I believe the class/object initialization sequence is as follows:
1. Initialize static variables and execute static initializer block in the order in which they appear.
2. Initialize instance variables and execute instance initializer block in the order in which they appear.
3. Constructor header i.e. implicit/explicit super() or this().
and then in the end
4. Constructor body.
I believe the above mentioned statements are accurate however, I am still investigating this.
Final has nothing to do with object/static initialization.
If I am wrong please feel free to correct me.
Brian
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: question about code in { }