Java interview questions on main method-part55

Number of View: 1419

271) If we don’t define a main method and execute a class do we get any error?
main() method is not needed for compiling a program but we need it for executing a program.When we try to execute a class without main method we get runtime execution.

272) Can a developer call main method explicitly ?
Since main method is just like other methods we can call.

273) Can we call main method from same class ?
We don’t get compile error but we get stackoverflow error Exception when main method is called within same class.

public class MainTest {
 public static void main(String args[]) {
 main(new String[1]);
 }
 }

We get the following exception when we execute the above program.

Exception in thread “main” java.lang.StackOverflowError

274) Does JVM calls user defined methods with same signature as main with name change?
No JVM calls only main method because it makes explicit call after loading the class so that is the reason main method is called.If we use the same method signature as main with different name JVM does’nt know about our userdefined method.
275) Can we have a overloaded main method in a class? If we have overloaded method which main method does jvm call?

public class MainTest {
 public static void main(String args[]) {
 main(new String[1]);
 }
 public static void main(String args) {
 main(new String[1]);
 }
 }

Yes we can have overloaded main method in a class we don’t get any compilation or runtime exception but jvm calls main method with array of String objects.

276) Can we have multiple classes in a java file with each class having main method?
Yes we can have a different classes with main method in a single java file.
class Main1 {
public static void main(String args[]) {
System.out.println(“Iam in main1 class main method”);
}

}
class Main2
{
public static void main(String[] args) {
System.out.println(“Iam in main2 class main method”);

}
}

Related posts:

  1. Java interview questions on main method -part54

Leave a Reply

Your email address will not be published. Required fields are marked *

*

HTML tags are not allowed.