A common fresher interview goes like, Can we overloading main() in Java?
It's a very tricky question on the face of it. But if we just recollect basics, it won't be too hard to answer.
Answer is Yes, we can very much do.
By default we use String args[] as the method argument for main(). We can have multiple mains with different arguments types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OverloadedMain{ | |
public static void main(String args[]){ | |
System.out.println("String args[] main"); | |
main(12); | |
main("JavaOnJava"); | |
main("Java", "OnJava"); | |
} | |
public static void main(int arg){ | |
System.out.println("integer arument main "+ arg); | |
} | |
public static void main(String arg) { | |
System.out.println("One String argument main "+ arg); | |
} | |
public static void main(String arg1, String arg2) { | |
System.out.println("Two String argument main "+ arg1+" "+ arg2 ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String args[] main | |
integer arument main 12 | |
One String argument main JavaOnJava | |
Two String argument main Java OnJava |
Error Cases
1. main(String args[]) is missing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WrongMain{ | |
public static void main(String arg) { | |
System.out.println("One String argument main "+ arg); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Error: Main method not found in class WrongMain, please define the main method as: | |
public static void main(String[] args) |