No, File Name and Class Name do NOT need to be same in Java. Here’s How.
Ashutosh Dubey
Posted on August 5, 2021
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");
}
}
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.
🔴🚫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.
Posted on August 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024