Hello learners,
In this post, we'll learn about some basic concepts related to Main method in Java. But before that lets understand what is main method, its importance, how it interacts with JVM etc.
1. What is main method in Java?
Main method is the entry point for every Java program. When you execute certain class that time Java compiler first search for main method for that class, after finding the main method it starts it's execution. Below is the figure for illustrating meaning of every word in declaration of main method.
In the above figure public is a Access Modifier that means the main method is called by JVM from any class, package, subclass etc. static is a Keyword that means we don't need to create objects of main method it can be directly called with the help of class. Void is a return type that means main method does not return any value. main is a method name. And lastly main method can accept one argument of type String Array.
2. What happens to Java program if main method is not present.
It will give byte code verification error as "Main method not found in class". Now, this will be a error and not exception since the program has not started its execution yet. Prior to JDK7 main method declaration was not mandatory but after JDK7 it is mandatory to define method for execution of program.
3. Can we overload main method in Java?
Yes, we can surely do this. We can declare multiple methods with the name as main but the parameters will be different. Let's say we have declare four different main method with different parameters as String array, Single String, Single Integer and with two Integer. And calling the other mains from first main method. Now, since the data type of parameters are different in every case so the main method execution is happening properly.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package javaProgramsforInterview; public class JavaPrograms { public static void main(String[] args) { System.out.println("Main Method-1"); main("my automation lab"); main(50); main(20, 40); } public static void main(String args) { System.out.println("Main Method-2"); } public static void main(int a) { System.out.println("Main Method-3"); } public static void main(int a, int b) { System.out.println("Main Method-4"); } } |
Output:
1 2 3 4 | Main Method-1 Main Method-2 Main Method-3 Main Method-4 |
1 2 3 4 5 6 7 8 9 10 11 |
package javaProgramsforInterview; public class ClassA { public static void main(String[] args) { System.out.println("This is Java Class A"); ClassB.main(args); } } |
1 2 3 4 5 6 7 8 9 10 11 |
package javaProgramsforInterview; public class ClassB { public static void main(String[] args) { System.out.println("This is Java Class B"); } } |
Output:
1 2 | This is Java Class A This is Java Class B |
Nice Article
ReplyDeleteThanks for sharing with us 🙂
/Dental Clinic in Manikonda/