Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

un-named block of code

 
Jitendra Jha
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while reading i came across this block of code

public class unspec
{
{
System.out.println("Hello");
}
unspec()
{
System.out.println("Hello World");
}
public static void main(String args[])
{
unspec us=new unspec();
}
}


this block of code compiles and the unnamed block is executed first,even before constructor.
What is this block and what is its purpose.

please guide me
 
Henry Wong
author
Marshal
Pie
Posts: 21128
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That "block of code" ...



is called an instance initializer. It is executed along with the initialization of your instance variables. In terms of when, it is executed after the super constructor, but before the constructor.

Henry
 
Jitendra Jha
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With due respect Henry,it still is not very clear.would you or anyone else please explain it.sorry and thanks for the trouble
 
Henry Wong
author
Marshal
Pie
Posts: 21128
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jitendra Jha:
With due respect Henry,it still is not very clear.would you or anyone else please explain it.sorry and thanks for the trouble


With due respect, can you tell us what you are not clear with? We can't read your mind, and just repeating ourselves with different words or examples, is not a very efficient.

Henry
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at http://java.sun.com/developer/JDCTechTips/2004/tt0406.html#2

Googling for "instance initializer", it was the first hit.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15288
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try searching for "java instance initializer" with Google, and you'll find a number of pages that explain what it is. Maybe these are useful:

The Essence of OOP using Java, Instance Initializers
The Java Tutorial - Initializing Fields (see the bottom of the page)
JavaWorld: Object initialization in Java
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic