• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inside no function or constructor but still compiling/running (Why)  RSS feed

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class ABC
{
{
System.out.println("Inside no funtion ");
}

public static void main(String arg[])
{
ABC a = new ABC();
}

}

The output is ==> Inside no function

1. Why the above code didn't give an error ?
2. and why is it giving the output ? => Inside no function


Sorry for creating an incomplete post "Static Environment"

Regards
 
Hagaya Hatake
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you are using the default constructor, even if you don't write

it will still be created.
 
Arvind Sampath
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Faisal,

The code which outputs "Inside no funtion" to the console in placed in an initializer block. Note that they are placed between two parantheses. The JVM executes the initializer blocks before executing the corresponding class' constructor.

If the word 'static' is placed before the opening paranthesis, then it is a static initializer block. The JVM executes the static initializer blocks when the class is loaded.

Hope i answered you.


Cheers,
Arvind
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the chapter and verse, from the JLS: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6
 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks , I got the point
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!