Open In App

Myth about the file name and class name in Java

Last Updated : 17 Feb, 2021
Comments
Improve
Suggest changes
102 Likes
Like
Report

The first lecture note given during java class is “In java file name and class name should be the same”. When the above law is violated a compiler error message will appear as below
 

Output: 
 

javac Trial.java
Trial.java:9: error: class Geeks is public, should be
                    declared in a file named Geeks.java
public class Geeks
^
1 error 



But the myth can be violated in such a way to compile the above file. 
 

Step 1: 
 

javac Trial.java



Step 1 will create a Geeks.class (byte code) without any error message since the class is not public.
Step 2: 
 

java Geeks



Now the output will be Hello world
The myth about the file name and class name should be same only when the class is declared in public.
The above program works as follows: 
 

javaex


Now, this .class file can be executed. By the above features, some more miracles can be done. It is possible to have many classes in a java file. For debugging purposes, this approach can be used. Each class can be executed separately to test their functionalities(only on one condition: Inheritance concept should not be used). 
But in general, it is good to follow the myth.
Example 1: 
 

When the above file is compiled as javac Trial.java this will create 2 .class files as ForGeeks.class and GeeksTest.class
Since each class has separate main() stub they can be tested individually. 
 

  • When java ForGeeks is executed the output is For Geeks class.
  • When java GeeksTest is executed the output is Geeks Test class.


Example 2: 
 

Note: There are two classes here, Triangle and Demo. Then which class name must be considered as the file name? 
The class name Demo must be taken as the file name. The reason behind taking Demo as the file name is that it has the main method and execution begins from the main method. 
 

Filename: Demo.java
Compilation: javac Demo.java
Run: java Demo
Output: Area of triangle:65


?list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj


 


Article Tags :
Practice Tags :

Similar Reads