Tags

,

Ten years ago in an interview I was asked for running result of the following code

public class Main{
public static int main(){
return 1;
} }

At that time I was a Java newbie, I had never been told the main method can be used in this way.I felt crazy.

Regardless the result is what does this code tells us?

1. main is not a reserve word in Java.

2.The main method is nothing but a method, you can overload it.

3.public static void main(String[] args) is a reserved method. Without it you can compile your code, but you can NOT run it.

So far so good? OK let us add one more line into this code.

public class Main{
public static int main(){
return 1;
}
public static void main(String[] args){
System.out.println(main());
}
}

This code can be compiled correctly and run successfully. What does it tell us?

1. The main method has nothing magic inside, it is just a method. You can even trigger it.

2.only static method can be triggered in static method i.e. if you do not put the static key word in front of int main(), you will get a compilation error.

====

main() is a very simple, basic method in Java. But have you ever thought about what is the main method? This post gives you a basic idea.

Advertisements