wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes What does this code do? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What does this code do?" Watch "What does this code do?" New topic
Author

What does this code do?

abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
code
-------------
public class Top {
{
System.out.println("hi");
}

}
----------------------
code

Why compiler is not showing any error in this code?Why dont this piece of code require a function to compile properly?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

The code is in an "instance initializer" which is executed during the construction process -- after the super() of the contructor has completed, but before the rest of the constructor has executed.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
I didnt get what you trying to say
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

Here is the link to the relevant chapter in the Sun Java tutorial.

http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

Maybe you can start there...

Henry
abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
but why
code
--------------
class Alpha {
int over=1;
}
--------------
is allowed where as

code
--------------
class Alpha {
System.out.println("hi");
}
----------------

is not allowed
ravikdcs dixit
Greenhorn

Joined: Aug 27, 2008
Posts: 3
this code compiles fine
but not results in any output
since there is no public static void main() method
the statement in the main() method are only executed by the interpreter or JVM
abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
code
--------------
class Alpha {
System.out.println("hi");
}
----------------

this will not compile
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
Originally posted by abin joy:
but why
code
--------------
class Alpha {
int over=1;
}
--------------
is allowed where as

code
--------------
class Alpha {
System.out.println("hi");
}
----------------is not allowed
int over = 1; is a declaration and initialisation, not an ordinary statement.
System.out.println("hi"); is an ordinary statement. No ordinary statements allowed outside methods and initialisers.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

Also, did you read the tutorial page that I linked to? This follow-up question is explained too.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What does this code do?
 
Similar Threads
JPanel only displays one component
JTables again
Code compilation error
Please Help, why this servlet is not working on mycgiserver
Integer.valueOf