File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to print message without main and static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to print message without main and static" Watch "How to print message without main and static" New topic

How to print message without main and static

skpradeep kumar

Joined: Jul 06, 2008
Posts: 1
how to print a message to console without using main()
function?(do not use even static blocks also.)
Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
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

Joined: Oct 13, 2005
Posts: 46437
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

Joined: Mar 05, 2008
Posts: 3028

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

Joined: Mar 22, 2005
Posts: 42965
This recent discussion added a couple more twists.
marc weber

Joined: Aug 31, 2004
Posts: 11343

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).

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: How to print message without main and static
It's not a secret anymore!