File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to print message without main and static

 
skpradeep kumar
Greenhorn
Posts: 1
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to print a message to console without using main()
function?(do not use even static blocks also.)
 
Preeti Yarla
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If that class is the only class in your application and if it does not have the public static void main() method the program will not run. JVM throws a run time exception since it cannot find the main(). So what is it you are trying to do?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47216
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

I presume you want that as a party trick (it isn't suitable for real-life use). I know how you can start an app with a static initialiser and no main() method, but I can't see it being possible without both.
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is nearly equivalent to using a static initializer - but it's not a static initializer.

I guess another way to do this might be by writing a Servlet, JSP, Applet, or other object that relies of a framework of some sort to invoke it. Except that in the case of Servlets and JSPs at least, there really is a main() method for the server. It's just not in code that you write - it's kind of hidden from view. For an Applet, I'm not sure. I suspect there's probably a main() method being used there too, but I don't know where it is offhand. I agree with Campbell - this doesn't seem like a very useful question for real-life use.
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This recent discussion added a couple more twists.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the intent of these types of parlor tricks... uh, I mean, questions is to get you to think about what happens when a class is initialized. In particular, understand that static blocks are executed and static fields are initialized before main is invoked. (Note: You can avoid the NoSuchMethodError by inserting a System.exit(0) at the appropriate place.)

But once this lightbulb has gone on, you should also recognize this for what it is (and isn't).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic