DEV Community

Ashutosh Dubey
Ashutosh Dubey

Posted on • Edited on

No, File Name and Class Name do NOT need to be same in Java. Here’s How.

The very first thing I was told in my java class was that the names of the .java file and the Class in java need to be same. But soon I learned it is actually a good practice to do so, but not mandatory at all.
Let us create a simple Hello world Java program.

class Main{
    public static void main(String[] args){
        System.out.println("Hello World");
        }
}
Enter fullscreen mode Exit fullscreen mode

Save the file as “Hello.java” (Class name is Main).
Now, open your terminal and give command to compile as you would normally:
javac Hello.java
and then when you want to execute, instead of typing:
java Hello
we need to type:
java Main
As you would see, our program got executed easily.
Screenshot of Terminal

🔴🚫EDIT🔴🚫 - As mentioned by @wldomiciano, if you declare the class as public, then it is mandatory to name both the class and file name exactly same.

Conclusion

At the time of execution, we just need to mention class name. Therefore, it is always advised to name the file and class alike, to not create any confusion. But as you saw, it is not a mandatory thing.

Top comments (2)

Collapse
 
wldomiciano profile image
Wellington Domiciano

It is important to note that the class name and file name must be the same when the class is public.

Collapse
 
ashutoshdubey133 profile image
Ashutosh Dubey

True. Thanks for the remainder, will edit my post. 👍