File name: B.java
public class B
{
public static void main(String[] args){}
}
public class A{}
java B.java
runs without errorjavac B.java
gives a compile error: class A needs to be declared in a file A.java
I understand that a java file can not have more than one public class, but why can a java file run without error using the java
command when you get compile errors for the code using javac
?
The javac command is used to compile Java programs, it takes . java file as input and produces bytecode. Following is the syntax of this command. The java command is used to execute the bytecode of java.
Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.
Description. The javac command reads source files that contain module, package and type declarations written in the Java programming language, and compiles them into class files that run on the Java Virtual Machine. The javac command can also process annotations in Java source files and classes.
It means that javac.exe executable file, which exists in bin directory of JDK installation folder is not added to PATH environment variable. You need to add JAVA_HOME/bin folder in your machine's PATH to solve this error. You cannot compile and run Java program until your add Java into your system's PATH variable.
Java-11+ allows launching Single-File Source-Code programs without compiling. You can learn more about it from this article. As per the specification, if the first class in the file has main
, it executes the same without caring for other public
classes in the file. Thus, if you change the order of classes in the file and try java B.java
, it will fail.
My guess, and it is only a guess since I haven't used Java 11 extensively, is that:
The "javac" command produces class files that can be combined into a large program, and thus there could be multiple references to class A "elsewhere" in the program. It is this generality that produces the restriction on one public class per source file (though frankly I don't see why compiling B.java cannot result in A.class and B.class)
The "java" command processes a single source file. From that point of view it is irrelevant whether A is public or not; A can be used from within the single file (same package!) in any case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With