Monday, February 26, 2018

Java main method interview questions and answers

1. Can I write java program without String args[] in main method ?

If you write java program without String args [] like below

public static void main (){
//Some code
}

The code will run. But JVM Can not recognize main method since it will always check main method string array parameter.

2. Difference between System.exit(0) and System.exit(1) ?

Sytem.exit(0) normally terminates the program. System.exit(1) also terminates the program, because It could find some error.

3. Is it possible to call main() from another class ?

Yes, Its possible by calling like Classname.main(). Note here, you should pass string array since main method will expect string array.

4. Can I overload main method ?

public class MainMethodOverloadExample
{
    public static void main(String[] args)
    {
        System.out.println("Execution will be started here");
    }
 
    void main(int args)
    {
        System.out.println("Overloaded main method I");
    }
 
    double main(int i, double d)
    {
        System.out.println("Overloaded main method II");
        //Some code here
    }
}

5. Is it possible change main method access modifier except public ?

No, main() method must be public. Your code will get compile.But Run time Error will happen when you try to run. Because JVM unable to access main method.

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

No, argument of main() method must be string array

7. Can I change main() method to non static ?

No, main() method must be declared as static so that JVM can find and call main() method without instantiating it’s class. Compilation will be successful but program fails at run time.

8.Can we override main method in Java ?

No, you can not override main method in Java, Because main is static method and you can not override static method in Java.

9. Can we make main final in Java?

The Code will compile without any problems but it will throw a run-time exception saying "main method not public".

10. Can we make main method as synchronized in Java?

Yes, main can be synchronized in Java,  synchronized modifier is allowed in main signature.







No comments:

Post a Comment