aspose file tools*
The moose likes Beginning Java and the fly likes Simple code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple code" Watch "Simple code" New topic
Author

Simple code

Roberto Diaz
Ranch Hand

Joined: Mar 08, 2002
Posts: 40
public class Simple
{
//4
System.out.println("Here"); //Does not work.!!!
{
System.out.println("Here"); //Works. Why ??
}

public void test()
{
System.out.println("HERE");
}
public static void main(String args[])
{
Simple obj = new Simple() ;
}
}
**********
Above given code will not compile,
but it will work just fine if I enclose the line
//4 within initializer block.
Please enlighten.
Thanks.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
You are not allowed to have normal expressions simply "lying about" in your class. According to the JLS, §8.1.5 Class Body and Member Declarations:

A class body may contain declarations of members of the class, that is, fields (�8.3), classes (�8.5), interfaces (�8.5) and methods (�8.4). A class body may also contain instance initializers (�8.6), static initializers (�8.7), and declarations of constructors (�8.8) for the class.

Therefore, if you want to put that expression in your class, it must go in either a method, an instance initializer, a static initializer, or a constructor.
I hope that helps,
Corey


SCJP Tipline, etc.
Karl Laird
Ranch Hand

Joined: Jul 14, 2001
Posts: 67
In other words the second one works because you have effectively made it into a static block, however the first one will not compile as it is neither static nor enclosed within a method.


The Eagle sneers at the Peacock<p>Systems Administrator<br />OrderWare Solutions Ltd<br /><a href="http://www.orderware.net" target="_blank" rel="nofollow">http://www.orderware.net</a>
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
In other words the second one works because you have effectively made it into a static block
not a static block but an instance initializer.
A static block is declared as follows
static {
...
}


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Ken Manohar
Greenhorn

Joined: Mar 16, 2002
Posts: 4
The statement in question is not an assignment statement or a method signature therefore it cannot exist outside a static or instance block. Such a statement will display "HERE" on a screen, if executed properly, thus it needs to be enclosed within a block (a block is any code or statements found within { } braces).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Simple code
 
Similar Threads
StringBuffer
generating class file without using javac command
Conditional Operator '?'
Synchronization on Threads in Java
Void not allowed here error