Originally posted by Girish Nagaraj: Why is it necessary to give file name same as the class name which has main method.
Bcoz we defined the main method as Public static void main(String args).and b'coz of static we call the class without cretae any instance of it.that's y we give the file name same as class name which has main method.
I hope i able to clear ur doubt.Awaiting for comments
The file name needs to match the top-level class name only if that class is public. It has nothing to do with a main method.
You can define a top-level class with default access and place it in a file with an entirely different name. As mentioned above, you compile using the file name, then run (assuming a main method) using the class name.
At the command prompt, use... javac SomeFile.java java SomeClass
Note that if SomeClass were public and you tried to compile it as SomeFile.java, then you would get a compilation error telling you that SomeClass "should be declared in a file named SomeClass.java." And if you try to run "java SomeFile," then you will get the runtime error NoClassDefFoundError. [ May 03, 2006: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
When you have a public class then the file name has to be the name of that public class for the program to compile(that's what most compiler's expect, but its not a language specification.)
But if you don't have a public class in the file then the file name can be different. javac filename.java But while running you have to give the name of the class having the main(). java classname (class having main method)