Myths about FileName Should be Same as Class Name in Java

This is a very important session for us to know about the myth of File name in Java. When I started to learn Java I got that every book, resources and even most of the web blogs stated that we should keep the “name of Java file as the name of the class.” I wonder why we should do it? Why is everyone asking to follow the weird rule? Why can’t we save java source file as another name (which is not matching with class name)?

Why everywhere it is written that FileName should be same as className. So my friends at the end of this article or better to say after getting outlines of this article we would know the answer of the question “why file name in java should be same as class name.”

Note: We are allowed to use any name for filename only when the class is not public. In the case of public class, we can’t use the different file name.
The filename must have the same name as the public class name in that file, which is the way to tell the JVM(Java Virtual Machine) that this is what the entry point is for you.

Interesting point:- You can keep any name for java file name. It’s not necessary to keep filename as class name but it is strongly recommended that we should keep filename as className.

What is Class

In object-oriented programming class plays a very important role without a single class we cannot imagine of successful execution of the program. the class is a collection of an object where the object may be Method or variable or both.
For Compilation of program, the main Method [Entry Point ] must exist in the class. Without entry point, we can’t imagine the compilation of code.

Program Used 

class ClassA
{
public static void main(String args[])
{
System.out.println(“Hello”);
}
}

This program is written in java language and save as ClassName.java 

Note:- In this program class name is classA and file name is ClassName.java

How to compile it:-
if you are a Java programmer then you already know that how to compile a program but for a beginner who does not know how to compile a java program, take a look and follow the steps as given below:-

  • press  Windkey+r              [it will open run option]
  • write cmd and press Enter  [it will open Command Prompt]

  • now navigate the path  as given below [note in this article program path is set to F:\Java]
  • Type CD command and set the directory where java source code File exists
  • Now you can Compile Java Program where the filename is ClassName.java and javac is a java compiler.
  • After compiling it gives a class known as ClassA.class [because ClassA is name of Class in Program].
  • After getting class you can interpret this class file with java interpreter which is java comes from java.exe
  • To interpret – type java and classfile which is “classA”.
    as:- java ClassA   and Press Enter
  • Take a look of the image given below to successful compilation and interpretAfter going through these all steps you can easily understand that we can save filename with the different name. hence there are no rules to save Filename always with ClassName.  It is not mandatory to say “file name equals to classname”. you can give your own name to your filename [ other than classname ] . at the time of compilation you just give your filename[other than classname]. After compilation, you will get .class file with your class name.[classname.class] . But at the time of loading your program into JVM(Java Virtual Machine) you just have to give the class name. This is possible even with main() is public or private.

 

Now let’s see,

Why it’s recommended that fileName should be same as className

Suppose when you create a program in which more than one class resides. And after compiling Java Source File, it will generate the same number of the .class file as classes reside in your program. In this condition, you will not able to easily identify which class need to interpret by java interpreter and which class containing Entry point (Main Method) for the program. You can take a look at Source code for class Names and then you have to find out classname in which Main Method residing. So it will be very tedious work for anyone. Therefore we are forced to follow the rules to makes finding other classes slightly easier for the compiler in the beginning since it doesn’t have to search all the potentially thousands of class files for a random public class, it can just go to the file.

Best practice – Having multiple public classes in the same file makes things confusing. The purpose of files is to organize the source code, the purpose of folders is to organize the files. If all the classes of a particular package are in a single 100 MB super file then you’ve lost all the advantages and gained none of the benefits of files (plus adding lots of headaches when editing)

It is just the convention set by Sun, the makers of Java and the purpose is organization of programs therefore to find the source and class files needed at compile and runtime becomes fast; the reason is so that everyone who codes in Java will have a consistent way of naming files.

So finally We say this statement that the file name should be same as the class name to make sure there is no confusion while compiling and running the program. 🙂

For more info, you should navigate

25 thoughts on “Myths about FileName Should be Same as Class Name in Java”

  1. Lakshmi Kanth Kanth Sandra says:

    I tried having the class name different than the file name. javac fileName.java resulted in an error statement saying that the public class has to be declared with the same filename.

  2. SAIKIRAN says:

    when i try this command ‘java me’ does the jvm search for the .class file named ‘me.class’ in the directory ?

    i have written a program with class ‘me’ containing a valid signatured main function for smooth execution and i compiled (using javac utility program) and a byte code was created in the directory “me.class” and later i executed the file with ‘java me’ , the execution was succesfull.

    as per my knowledge at the execution time on typing this command ‘java me’ the JVM searches for the .class files and checks for the valid signatured main function in the program and then jvm starts execution process.

    WHAT I WANT TO KNOW : does the jvm search for .class file with name ‘me.class’ when i write ‘java me’.
    if so,
    i have done a small operation where i renamed “me.class” to “Me.class” and i tried the command ‘java Me’ , error msg was shown
    further i tried the command ‘ java me’ the program was executed and HOW DID THE JVM FOUND THE .class file with the name ‘me.class’ which doesnt exist as i renamed it to Me.class .

    please correct me if my concepts are wrong

  3. Anuj Singh says:

    it’s very nice article …thanks a lot for explaining this article.

  4. DineshDK says:

    sir great explanation and sir which book you prefer for getting depth knowledge on java…

  5. Sriram E says:

    Wow…How a clear explanation…. Now I’m clear…

  6. Chandra Mani Gupta says:

    No doubt in this that we can have different file name and class name is our class is not declared as public. But when we compile our code, the bytecode (basically .class file) which is generated as the intermediate code has the name of the CLASSNAME rather than FILENAME. And whats the point that you are executing (using java-interpreter) the program on basis of generated CLASSNAME.We can never execute our program in this context with the given FILENAME in anyways.However, its really a bad practice, not industry standard (as you mentioned though) to use the different FILENAME and CLASSNAME (that contains main() method). Anyways nice article.

  7. Vijaya Lakshmi says:

    Thanks a lot for clear explanation…

  8. Ashvinee Kumar says:

    thanks sir … for this article

  9. heenaamb says:

    awsum man thanks a lot for the clarification like this

  10. shubham gupta says:

    if class name is public but does not contain main method,and an another class contain main method but not decleared public,then what will name of file name?

    1. Pragati Naigaonkar says:

      It will throw below Error

      Error: Main method not found in class com.collections.CollectionTest, please define the main method as:
      public static void main(String[] args)

  11. waitingForU says:

    nice artical..thanks a lot

  12. micheal says:

    great article

  13. Chiara Barcelona says:

    Interesting article. Thanks for sharing, but why almost every author of book give focus on using same class name as file name.

    1. Ravi Ranjan Kumar says:

      This is all because it enforces good practices where they make practical sense. it is not just a convention. It serves a purpose: to find the source and class files needed at compile and runtime fast.

  14. sushmita nigam says:

    thanx sir awesome explanation

  15. jitendra rai says:

    Continuing the sehna question if we declare a class name with public specifer then we can’t name the file name other then the class name
    for example-:
    public class A
    {
    public static void main(String arg[])
    {
    System.out.print(“hello”);
    }
    }

    // here we have to name the file name same as the class name other wise it give error try u self

    please clear our doubt

    1. Ravi Ranjan Kumar says:

      Hi Jitendra ! sorry bro for late reply..let me clear the concept, look we are free to use any name for file name only when the class is not public. In case of public class we are bounded to use file name as same as class name means we can not use different file name by anyway. Its a strong methodology of Java.

      Please feel free to revert back in case of any query.

      1. jitendra says:

        sir ji that’s what i want to know the reason behind it .why we have to use the same name if the class is in public

        1. Ravi Ranjan Kumar says:

          Jitendra.. if really some one can answer to this question is Sun-Microsystems because they imposed this weird rule on us. It is just the convention set by the makers and the reason was stated that to find the source and class files needed at compile and runtime fast I don’t know that really it would compile and run slowly when we won’t follow this rule.
          Look some programmer says that this rule simplifies class loading. As being Java learner we better know that we can have only one public classes in one Java file so each public class must be in a file where the FileName matches the ClassName and a package where the Packagename represents the Directory structure. This make compiler able to find the source files and the class loader has to be able to find the implementation. Matching package names and classnames makes this really simple and, more important, fast.
          This rule is not needed in non-public class because non-public classes have a very limited visibility and can only be used within the package where they are defined. complier can easily trace the file when because of limited visibility.
          We all know Java always enforces good practices where they making sense but Java is often critized for putting restricting on the programmer in many ways like this one.

          Jitendra bro.. feel free to revert back in case of any query or discussion.

  16. sneha says:

    if you define the class name as public , you have to give the source file name same as the class name .?
    But then why cant we have a different name in case of public modifier ?

    1. Ravi Ranjan Kumar says:

      In which section of this article you got about these statement ? we are not bounded to public access specifier, using access specifier is depend on condition like how you want to treat your class in your program with other classes and their objects. feel free to use any specifier as per program requirement to accomplish task.

    2. Ravi Ranjan Kumar says:

      Hey! Sneha. check out my answer to Jitendra.

  17. Biswa Ranjan Mohapatra says:

    I do not understand the statement , “This is possible even the main() is public/private”. How could the main function be private which we are expecting to be the entry point of the class.
    Second thing is , the example you have given is a class with default scope, however if you define the class name as public , you have to give the source file name same as the class name .

    1. Ravi Ranjan Kumar says:

      Your Concern is very true that the entry point of your program should be visible and its also said that executing class should contain a ‘public static void method.. but it doesn’t mean that we can’t declare main method as private even we can declare, we can compile and of course we can run but in that case its can’t taken as entry point. we just invoked from somewhere.
      Lets come to your second concern… No need to give source file name as class name and same thing I tried to put in this article. Its a kind of myth to make file name as same as class name.

Leave a Reply