In scjp book its given that if there is no public class in file then file name does not match any class name i have tried this code class Shikha { public static void main(String[] args) {System.out.println("Hello"); } } and saved it as Shikha.java.its giving me output Hello.no error.
If there are no top level public class in a file, then you can name the file with any name, which is not matching any of the non-public class names. It will compile and run fine. That is why you are getting the Output.
Originally posted by Amitji Sharma: If there is only one class in the file filename must match with that class name irrespective of its either public,private etc.
if there is two or more classes in a file and no one is public then you can choose any class name as file name
example - if two classes in a file
you can give that file name either Sikha.java or SikhaSuper.java
Just a slight correction in Amit's statement. If you have more than one non-public class in a file, then the file name can be anything i.e., it can have the name same as any of the non-public class (as Amit mentioned) or it can have any other name which is not same as any of the non-public class.
If there is only one class in the file filename must match with that class name irrespective of its either public,private etc.
It is not necessary to have the filename same as the name of the non-public class even if it contains a single class. E.g.
This would compile fine. But it is not possible to run this file. Reason for it is that the JVM serches for <FileName>.main method when you try to run the file. And here since we have not created any class with name "Test", it will not run.
ok i understand if there is one or more classes in a file with default modifier then file can have any name either class or any other name.if its given class name it will compile and run but if given other name it will not run.
ok i understand if there is one or more classes in a file with default modifier then file can have any name either class or any other name.
Yes you are correct here.
if its given class name it will compile and run but if given other name it will not run.
For this its necessary that the class which you have used to name the file contains the main method. Say your file had 3 classes A,B and C. And you named the file A.java. Then "C:\>java A" will run only if class A has "main" method as JVM will be searching for A.main to run.