Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with Statics

 
Randall W. Smith
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic