This week's book giveaway is in the HTML/CSS/JavaScript forum.
We're giving away four copies of Practical SVG and have Chris Coyier on-line!
See this thread for details.
Win a copy of Practical SVG this week in the HTML/CSS/JavaScript 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.
 
Always! Wait. Never. Shut up. Look at this tiny ad.
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!