Latest JVM Interview Questions and Answers
What is the Java Virtual Machine (JVM)?
The Java Virtual Machine is software that can be ported onto various hardware-based platforms.
What does public static void main(String) mean?
This is a special static method signature that is used to run Java programs from a command line interface (CLI). There is nothing special about the method itself, it is a standard Java method, but the Java interpreter is designed to call this method when a class reference is given on the command line.
Why are command line arguments passed as a String?
Command line arguments are passed to the application’s main method by the Java runtime system before the application class or any supporting objects are instantiated. It would be much more complex to define and construct arbitrary object types to pass to the main method and primitive values alone are not versatile enough to provide the range of input data that strings can. String arguments can be parsed for primitive values and can also be used for arbitrary text input, file and URL references.
Why doesn’t the main method throw an error with no arguments?
When you invoke the Java Virtual Machine on a class without any arguments, the class’ main method receives a String array of zero length. Thus, the method signature is fulfilled. Provided the main method does not make any reference to elements in the array, or checks the array length before doing so, no exception will occur.
Why do we only use the main method to start a program?
The entry point method main is used to the provide a standard convention for starting Java programs. The choice of the method name is somewhat arbitrary, but is partly designed to avoid clashes with the Thread start() and Runnable run() methods, for example.
Can the main method be overloaded?
Yes, any Java method can be overloaded, provided there is no final method with the same signature already. The Java interpreter will only invoke the standard entry point signature for the main method, with a string array argument, but your application can call its own main method as required.
Can the main method be declared final?
Yes, the static void main(String) method can be declared final.
I get an exception if I remove the static modifier from main!
The static void main(String) method is a basic convention of the Java programming language that provides an entry point into the runtime system. The main method must be declared static because no objects exist when you first invoke the Java Virtual Machine (JVM), so there are no references to instance methods. The JVM creates the initial runtime environment in which this static method can be called, if you remove the static modifier, it will throw a NoSuchMethodException.