Top 10 Java Interview Questions On Main Method: 1.can We Define A Class Without Main Method?
Top 10 Java Interview Questions On Main Method: 1.can We Define A Class Without Main Method?
Method
1.Can we define a class without main method?
1. package com.instanceofjava;
2. public class MainMethod
3. {
4. public static void main(String args[])
5. {
6. }
7. }
No, the return type of main() method must be void only. Any other type is not acceptable.
1. package com.instanceofjava;
2. public class A
3. {
4. public static int main(String[] args)
5. {
6. return 1; //run time error : No main method found
7. }
8. }
4. Why main() method must be static?
1. package com.instanceofjava;
2. public class A
3. {
4. public A(int i)
5. {
6. //Constructor taking one argument
7. }
8. public void main(String[] args)
9. {
10. //main method as non-static
11. }
12.
1. package com.instanceofjava;
2. public class A
3. {
4. public void main(String[] args)
5. {
6. System.out.println("indhu"); //Run time error
7. }
8. }
Yes, We can overload main() method. A Java class can have any number of main()
methods. But to run the java class, class should have main()
method with signature as public static void main(String[] args). If you do any modification
to this signature, compilation will be successful.
But, you cant run the java program. You will get run time error as main method not found.
1. package com.instanceofjava;
2. public class A
3. {
4. public static void main(String[] args)
5. {
6. System.out.println("Indhu");
7. }
8. void main(int args)
9. {
10. System.out.println("Sindhu");
11. }
12. long main(int i, long d)
13. {
14. System.out.println("Saidesh");
15. return d;
16. }
17. }
No, main() method must be public. You cant define main() method as private or protected
or with no access modifier.
This is because to make the main() method accessible to JVM. If you define main() method
other than public, compilation will be successful but you will get run time error as no main
method found.
1. package com.instanceofjava;
2. public class A
3. {
4. private static void main(String[] args)
5. {
6. //Run time error
7. }
8. }
8.Can we override main in Java ?
No you can not override main method in Java, Why because main is static method and in
Java static method is bonded during compile time and you can not
override static method in Java.
you can make main method final in Java. JVM has no issue with that. Unlike any final
method you can not override main in Java.
Yes, main can be synchronized in Java, synchronized modifier is allowed in main signature
and you can make your main method synchronized in Java.