The main() method in Java is starting point of any standalone core Java application. JVM starts executing Java program from main method and the thread which executes main is called main thread in Java. The main method is also an important topic in Java interviews for 2 to 3 years experienced developer. In this Java article, we will a couple of questions related to the main method in Java. Apart from Why main is static in Java, I see following questions keep coming related to the main method:
- Can we overload the main method in Java? Which main method JVM will call?
- Can we override the main method in Java?
- Can we make main final in Java?
- Can we make main synchronized in Java?
- How to call a nonstatic method from main in Java?
5 Main Method Interview Questions with Answers
Can we overload main in Java?
Yes you can overload the main method in Java, nothing wrong with this but Java will only call your specific main method, i.e. main method with the following signature:
public static void main(String args) or public static void main(String args...) which is the main method as variable argument method and only supported post-Java 5 world.
Can we override main in Java?
No, you can not override the main method in Java, Why? because main is a static method and in Java static method is bonded during compile time and you can not override static method in Java. If you declare a method with same name and signature its called method hiding.
Can we make main final in Java?
Of course, you can make the main method final in Java. JVM has no issue with that. Unlike any final method, you can not override main in Java.
Can we make main synchronized in Java?
Yes, main can be synchronized in Java, synchronized modifier is allowed in the main signature and you can make your main method synchronized in Java.
How to call a nonstatic method from main in Java?
This question applies not only to main but all static methods in Java. Since nonstatic methods can not be called from static context directly, you need to first create an Object as local variable and then you can call nonstatic method using that object, as shown in the following example:
- The main() method is a static method
- You can overload main() method in Java.
- You cannot override main() method in Java
- You can make the main method final in Java
- You can make the main method synchronized in Java.
- You cannot call a non-static method from main in Java.
Other Java Interview questions you may like