• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Java Free Blocks

 
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Very Sorry THe answer is:
Main
Initializer

I know about static free floating blocks in java, But here?
 
Lee Kian Giap
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 28325
96
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 156
Android Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ran the code and got the result.
The instance initializers are run before the constcurtor completes.
 
Sheriff
Posts: 22815
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Priety Sharma
Ranch Hand
Posts: 156
Android Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot to all!
 
Marshal
Posts: 79959
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Didn't notice you were a new user: welcome to the Ranch
 
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Lee Kian Giap
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 504
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
THANK YOU VERY MUCH LEE............that was really quick and a detailed explaination.
 
Ranch Hand
Posts: 137
Hibernate Netbeans IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 79959
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 137
Hibernate Netbeans IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 137
Hibernate Netbeans IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sidharth Pallai wrote:Its sounds goog CampBell.



good was key'd incorrectly as goog. Sorry
 
Campbell Ritchie
Marshal
Posts: 79959
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 137
Hibernate Netbeans IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Feeling to have one.
 
Lee Kian Giap
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Marshal
Posts: 79959
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good point.
 
Don't count your weasels before they've popped. And now for a mulberry bush related tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic