Continuing our discussion from the previous post on the main method.
6. Multiple classes can contain the main method in a source file
6. Multiple classes can contain the main method in a source file
public class HelloWorld {
public static void main(String[] args) {
System.out.println("No. of arguments passed: " + args.length);
if(args.length != 0){
System.out.println("Arguments passed: ");
for(int i=0; i<args.length; i++){
System.out.println(i + ": " + args[i]);
}
}
}
}
class SomeClass1{
public static void main(String[] args){
System.out.println("main() in SomeClass");
}
}
class SomeClass2{
public static void main(String[] args){
System.out.println("main() in SomeClass2");
}
}
Output:
C:\Dropbox\practice\blog>javac HelloWorld.java
C:\Dropbox\practice\blog>java HelloWorld
No. of arguments passed: 0
C:\Dropbox\practice\blog>java HelloWorld 0 1 2
No. of arguments passed: 3
Arguments passed:
0: 0
1: 1
2: 2
C:\Dropbox\practice\blog>java SomeClass1
main() in SomeClass
C:\Dropbox\practice\blog>java SomeClass2
main() in SomeClass2
C:\Dropbox\practice\blog>
7. The class with the main method may or may not be public.
8. There can be only one public class in a source file.
9. The source file must be named EXACTLY as the public class. If there is no public class present, then the source file may be named anything.
The source file containing the above code above MUST be named HelloWorld.java (as the HelloWorld class is public). If the public modifier is removed then the file may be named anything (eg MyClasses.java, Anything.java etc.). You cannot apply public modifier to SomeClass1 (or SomeClass2) while HelloWorld is public.
10. There can be any number of classes/interfaces in a single source file.
This completes discussion on the main() method.
No comments :
Post a Comment