Friday, 18 April 2008

Executing code without main method.

Let us look at a cool program. Many times in interview just to check your concepts interviewers like to throw tricky questions one of them is : "Can you write a program without a main method and it should compile and run successfully as well it should not throw main() method not found exception?"

Here goes the answer : It can be done in 2 ways. I know most of you know how to do it by one way I will show you two ways ;-) one of them I learnt today!!

1) Declare main method in a parent class. Extend that class and in subclass not not write a main method. Invoke java ChildClassName and bingo it calls parent class method. Try it once to see the magic.
Simplest code goes here :

Example A)
1: public class Test {
2: public static void main(String[] args) {}
3: }
4:
5: class Test1 extends Test {}

You can execute and run the above code by :
java Test1

(Observe class Test1 is not having main method.)

Liked this one? Want to try a little harder?

Example B)

When you compile and run the following code using
java Test1 what will be output?

01: public class Test {
02: public static void main(String[] args) {
03: System.out.println("void");
04: }
05: }
06:
07: class Test1 extends Test {
08: private static void main(String args) {
09: System.out.println("int");
10: }
11: }

Answer:
Compiles and runs fine printing: void

Think why?

Reason:
In class Test1 we have a main method but it is having different signature.

While compile is interested in public static void main(String[] args) .

Compiler fails to find public static void main(String[] args) so it searches it in the super class and it finds it and so it prints "void".

Liked??

Now lets go to 2nd method How to write code without main method.

2) Another way is by using static blocks. From the static block create the object of that class. And in static block of the class write System.exit(); bigo. You are done.
Note: If you don't write System.exit() it will throw main method not found exception at run time.

Code goes here:

01: public class Test {
02: public Test() {
03: System.out.println("hi");
04: }
05:
06: static {
07: new Test();
08: System.exit(0);
09: }
10: }

This code compiles and runs fine printing:hi
When ever class is loaded its static blocks run first.
And from static block we are creating a new object of the same class.
It will return and exit.

No comments: