Basic Java Questions and Answer for Interview

11. What if the main() method is declared as private?
The program compiles properly but at runtime it will give "main() method not public." message.

12. What if the static modifier is removed from the signature of the main() method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

13. What if I write static public void instead of public static void?
Program compiles and runs properly.

14. What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".

15. What is the first argument of the String array in main() method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

16. If I do not provide any arguments on the command line, then the String array of main() method will be empty or null?
It is empty. But not null.

17. How can one prove that the array is not null but empty using one line of code?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

18. What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.

19. Can an application have multiple classes having main() method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned.
Hence there is not conflict amongst the multiple classes having main() method.

20. Can I have multiple main() methods in the same class?
No the program fails to compile. The compiler says that the main() method is already defined in the class.

User Answer ( 1 )

  1. user
    Arvind Gupta
    7 years ago
    constructor is not used to create objects of class ,it is used to initialized the instance member of the class

Basic Java Questions and Answer for Interview