Yes, the main() method in java can be overloaded.
Given below is the sample code snippet where main() method has been overloaded twice. If you want you can experiment by overloading main() as per your choice and requirement.
To prove our point that main() can be overloaded, below code is sufficient. Have a look,
Source File: MainOverloading.java
OUTPUT:
Overloaded methods will not be executed here
---------------------------------------------------------------------------------------------------
In the above code snippet JVM searches for public static void main(String[] args) type signature as regular. And anything inside public static void main(String[] args) will be executed first. So if you want your overloaded main() method to get executed, you need to call it from inside actual main() which is entry point for all java program.
---------------------------------------------------------------------------------------------------
Source File: MainOverloading.java
OUTPUT:
You may also like to read:
Given below is the sample code snippet where main() method has been overloaded twice. If you want you can experiment by overloading main() as per your choice and requirement.
To prove our point that main() can be overloaded, below code is sufficient. Have a look,
Source File: MainOverloading.java
package basic;
public class MainOverloading
{
public static void main(String[] args) {
System.out.println("Overloaded methods will not be executed here");
}
public static void main(int x){
System.out.println("x="+ x);
main(5,54);
}
public static void main(int a, int b){
System.out.println("a="+ a);
System.out.println("b="+ b);
}
}
Given below is modified version of above code snippet. Here overloaded main() is executed. Have a look,
package basic;
public class MainOverloading {
public static void main(String[] args) {
main(1); //calling overloaded main
}
public static void main(int x){
System.out.println("x="+ x);
main(5,54);
}
public static void main(int a, int b){
System.out.println("a="+ a);
System.out.println("b="+ b);
}
}
x=1 //output of main(int x)
a=5 //output of main(int a, int b)
b=54
You may also like to read:
No comments:
Post a Comment