aspose file tools*
The moose likes Beginning Java and the fly likes Help with Statics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with Statics" Watch "Help with Statics" New topic
Author

Help with Statics

Randall W. Smith
Greenhorn

Joined: Jul 28, 2001
Posts: 9
//java:rws: junk.java
public class junk {
static int x = prt("asdf");
//public static void main(String[] args) {
//}

static int prt(String s){
System.out.println(s);
return (47);
}

}

If you save and run, the "asdf" will print right before you get an error message about not having a main method. From my reading, Statics are supposed to be initialized in textual order. As you can see my method prt is defined after it is called. I'm also surprised that I'm able to get output without a main method.
Of course, if you don't comment out the main method it will run without errors but how is it able to load the prt method given the "textual order?"
Here's the output:
C:\java>java junk
asdf
Exception in thread "main" java.lang.NoSuchMethodError: main
Nura Horne
Ranch Hand

Joined: Jul 26, 2001
Posts: 40
As far a s I know it doesn't matter where your methods are defined in Java code so the fact that it is after main does not matter.
Chad McGowan
Ranch Hand

Joined: May 10, 2001
Posts: 265
When junk.class is loaded, static variables are initialized first. Since the initialization of static variable x calls the prt method, this method is executed before the main() is called. Next main() is attempted, which throws a NoSuchMethodException.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help with Statics