Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
255 Members
Join this group to post and comment.
Information Technology
11 Feb 2019

Java interview questions on main method?

As we all know that main() method is a special method in java. Because, execution of a java application starts from main() method. In this post, I have collected some interview questions on main() method and have tried to answer them. I hope you guys will find them useful.

Can We Overload main() method?

Yes, We can overload main() method. A Java class can have any number of main() methods. But to run the java class, class should have main() method with signature as “public static void main(String[] args)”. If you do any modification to this signature, compilation will be successful. But, you can’t run the java program. You will get run time error as main method not found.

Can we declare main() method as private or protected or with no access modifier?

No, main() method must be public. You can’t define main() method as private or protected or with no access modifier. This is because to make the main() method accessible to JVM. If you define main() method other than public, compilation will be successful but you will get run time error as no main method found.

Can We Declare main() Method As Non-Static?

No, main() method must be declared as static so that JVM can call main() method without instantiating it’s class. If you remove ‘static’ from main() method signature, compilation will be successful but program fails at run time.

Can we change return type of main() method?

No, the return type of main() method must be void only. Any other type is not acceptable.

Can main() method take an argument other than string array?

No, argument of main() method must be string array. But, from the introduction of var args you can pass var args of string type as an argument to main() method. Again, var args are nothing but the arrays.

Can we run java class without main() method?

No, you can’t run java class without main method. But, there are some scenarios like if super class has main() method, then sub class can be run without defining main() method in it. For example, if you run class B in the below program, you will get 1 as output.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
1mo ago

Thank you for posting the similar questions at one place.