wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Java Free Blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Free Blocks" Watch "Java Free Blocks" New topic
Author

Java Free Blocks

Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Can sombody explain me for this answer?

class c {
{ System.out.println("Initializer");}
public static void main(String[] args) {
System.out.println("Main");
c obj = new c();
}}


The answer is: Initializer
Main

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
Are you sure you get that answer ?

Please try to compile and run it again !

The answer must be as follows:
Main
Initializer


unless your code is as follows:


then the answer will be:
Initializer
Main


SCJP 6, SCWCD 5, SCBCD 5
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Very Sorry THe answer is:
Main
Initializer

I know about static free floating blocks in java, But here?
Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
I know about static free floating blocks in java, But here?


May I know what you are trying to ask ?

Here is the statement for you to understand the static initialization (for either static block or static field) , and non-static initialization (for either non-static block or non-static field):

"The order of initialization is statics first, if they haven't already been initialized by a previous object creation, or haven't already been initialized by a previous first invoke of any static method/field of the class. After the initialization for statics complete, only then the turn for non-static"



Try it out and you will understand what I meant.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

My Question is, How can that free block be executed? If a method, then it is invoked by an instance or with the class name(static method). But here it is differnet. Free floating block.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

First, let's post that code in the "Code" tags so it is readable:

Okay, that's better. Now you were asking about the block at line 2? That's an instance initializer. (It isn't preceded by the keyword "static", so it isn't a static initializer as somebody suggested it might be.) Instance initializers are called each time an object of the class is constructed. I don't remember whether they are called before or after the constructors run, but in this case it doesn't matter. When you create a new "c" object at line 5, that instance initializer is called.
Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
Okay , I try to explain the flow, so now follow my explanation




When you issue command "java C", the "public static void main" method of class Run invoke. However before this method invoked, the class loader in JVM will load the class C and initialize all static block and static field (if you refer back to the statement in my previous post, you will understand the flow since this is the first static method invoke for class C), so it print "Initializer". After that, the "public static void main" method continue with "System.out.println("Main");", then only it create the instance of class C.




When you issue command "java C", the "public static void main" method of class Run invoke. However before this method invoked, the class loader in JVM will load the class C and initialize all static block and static field, since no static block or field here, it seems nothing happened. After that, the "public static void main" method continue with "System.out.println("Main");", then only it create the instance of class C. During the object creation of class C, any non-static block/field must be initialize before constructor start, so it will print "Initializer", then only "Construct".

Hope, you get my point.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

So, In order to create the instance/object, all the non-static block/fields must be initialized. It's the part of creating the instance/object. If we don't create any object/instance, then there is no free block initializations. Thanks a lot.
Priety Sharma
Ranch Hand

Joined: Jun 10, 2008
Posts: 156

Ran the code and got the result.
The instance initializers are run before the constcurtor completes.


Priety.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

Paul Clapham wrote:I don't remember whether they are called before or after the constructors run

Actually, in between. The execution order is as follows:
1) the implicit or explicit call to the parent's constructor using super
2) initializer blocks in order of declaration
3) the remainder of the constructor


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Priety Sharma
Ranch Hand

Joined: Jun 10, 2008
Posts: 156

Thanks Rob
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Thanks a lot to all!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
Didn't notice you were a new user: welcome to the Ranch
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
ok i got it..... please tell me what is happening here


class Bird {
{ System.out.print("bl "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

What is the result?

1. pre b1 b2 r3 r2 hawk
2. pre b2 b1 r2 r3 hawk
3. pre b2 b1 r2 r3 hawk r1 r4
4. r1 r4 pre b1 b2 r3 r2 hawk
5. r1 r4 pre b2 b1 r2 r3 hawk
6. pre r1 r4 b1 b2 r3 r2 hawk
7. pre r1 r4 b2 b1 r2 r3 hawk
8. The order of output cannot be predicted.
9. Compilation fails.

the question is from 3rd chapter of r&b correct answer is 4.

i just want to know that why the line --- System.out.print("pre "); is not executed first and print pre before anything else as it comes before the call to hawk constructor.

thanks


SCJP 1.6 96%
Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
Okay, this is the case of inheritance involve in initialization

Before I explain, I try to make the code indentation looked nicer




Here, the first thing that happens when you run Java on Hawk (i.e. java Hawk) is that you try to access main() which is the first static method. According to the rules that stated in this post, the class loader will find and load the Hawk.class because the following situation was met
"class haven't already been loaded and initialized, and will be loaded and initialize on first object creation of that class OR first invoke of any static method/field of that class OR that class is inherited by other class"

In the process of loading Hawk, class loader found out that Hawk has a base class which is Raptor, so class loader will first find and load the Raptor.class before any static block/field of class Hawk can be initialized.

In the process of loading Raptor, class loader again found out that Raptor has a base class which is Bird, so class loader will again first find and load the Bird.class before any static block/field of class Raptor can be initialized.

Now is in the process of loading Bird, nothing seems happens here because there is no any static block/field in class Bird.
After completed loading Bird, class loader continue with Raptor, so now it print "r1" and "r4" which is the two static block in Raptor.
After completed loading Raptor, class loader again continue with Hawk, so nothing seems happens since there is no any static block/field in class Hawk.

So, here it continue with the main() method which print "pre" ... ...

After that, comes the instantiation of Hawk (remember here, since class already loaded previously because of first static method, all static block/field already initialized, so all the static block/field will not be run second time ... the remaining initialization is for non-static)
Constructor of every class will call a super() before any code in the constructor execute, so the non-static initialization start from Bird, then Raptor, then Hawk.
And any method or constructor can only be run after all non-static block/field completely initialized.
Therefore, it print "b1", "b2", "r3", "r2", "hawk".

Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
THANK YOU VERY MUCH LEE............that was really quick and a detailed explaination.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Very Interesitng!!.

Lee and Paul made "instance initializer" understood with better instances. Anyway i would like to know , when & where "instance initializer" could be made useful.


Thanks & Regards
Sidharth Pallai
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
Sidharth Pallai wrote:Very Interesitng!!.

Lee and Paul made "instance initializer" understood with better instances.
Yes, they did: well done
Anyway i would like to know , when & where "instance initializer" could be made useful.
So would I Anything an instance initialiser can do, a constructor or a factory method can do too. You can put all your initialisations into constructors and factory methods and never need an instance initialiser block.

Static initialisers are probably much more useful, however.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Its sounds goog CampBell.

But there could be some reason they have been incorporated in to JAVA. I think as we cannot talk to the block with arguments as we could do with constructors or methods.

Generally , the more "curious" i am is , its getting called before a constructor but at the same am "confused" that it gets called every time i instanciate.

Can this block be useful to check for Singleton nature of a class.
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Sidharth Pallai wrote:Its sounds goog CampBell.


good was key'd incorrectly as goog. Sorry
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
Sidharth Pallai wrote:
Sidharth Pallai wrote:Its sounds goog CampBell.


good was key'd incorrectly as goog. Sorry
A gottle of geer will sort that out
Sidharth Pallai
Ranch Hand

Joined: Apr 21, 2008
Posts: 134

Feeling to have one.
Lee Kian Giap
Ranch Hand

Joined: Jan 23, 2008
Posts: 213
Campbell Ritchie wrote:
So would I Anything an instance initialiser can do, a constructor or a factory method can do too. You can put all your initialisations into constructors and factory methods and never need an instance initialiser block.

Static initialisers are probably much more useful, however.


Sidharth Pallai wrote:
But there could be some reason they have been incorporated in to JAVA. I think as we cannot talk to the block with arguments as we could do with constructors or methods.


Yes, right ~! I feel so excited to be in this forum !

Here is the usage of instance initializer, we will need it when come to design when we are using anonymous inner class.
Why ? annonymous inner class (instantiated with name "SomeClass ") when instantiated is the object of the subclass (i.e. a subclass of "SomeClass "), which means the subclass of SomeClass have no name. Therefore without a class name, you can't use normal constructor, and here is the place where instance initializer show up and play a role as constructor !!!

Here some code to demonstrate it.



The above code is to show how instance initializer can be used as constructor,
now where will anonymous class be used ... yeah, find it out yourself ...
one of it is when you want to create special iterator() method from the Iterable interface.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
Good point.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java Free Blocks
 
Similar Threads
same wiht super
Return Statement..
Order of Execution(Interesting)-:)
same with super
output of this program?