Saturday 31 January 2015

Java - JVM Interview Questions and Answers

6)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.

7)Can the main method be declared final?
Yes, the static void main(String[]) method can be declared final.

8)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 aNoSuchMethodException.

9)How can the static main method use instance variables?
For very simple programs it is possible to write a main method that only uses static variables and methods. For more complex systems, the main method is used to create an instance of itself, or another primary class, as the basis of the application. The primary application object reference uses instance methods to create and interact with other objects, do the work and return when the application terminates.
public class SimpleClass {
  public void doSomething() {
    // Instance method statements
 }
  public static main(final String[] args) {
    SimpleClass instance = new SimpleClass();
    instance.doSomething();
 }
}

10)main method from another class?
Yes, the main method can be called from a separate class. First you must prepare the string array of arguments to pass to the method, then call the method through a static reference to the host class, MaxFactors in the example below.
String[] arguments = new String[] {"123"};
MaxFactors.main(arguments);
More Questions & Answers :-

No comments:

Post a Comment