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.
Top comments (2)
It is important to note that the class name and file name must be the same when the class is public.
True. Thanks for the remainder, will edit my post. 👍