I have been coding in java for about a year now and I discovered something strange. Consider the following project structure-
Project
|
|--src
|
|--Test
|
|--Class1.java
Class1.java
public class Class1 {
public static void main(String[] args) {
System.out.println("Woah no package statement!");
}
}
As you can see Class1
has no package statement and Intellij actually gives an error -
Missing package statement: 'Class1'
I can compile and execute the main method through the command line as follows-
/Project/src/Test $ javac Class1.java
/Project/src/Test $ java Class1
Woah no package statement!
Now I know that when I try to run it through sources root, I will get an exception-
/Project/src $ javac Test/Class1.java
/Project/src $ java Test.Class1
Error: Could not find or load main class Test.Class1
Caused by: java.lang.NoClassDefFoundError: Class1 (wrong name: Test/Class1)
Now I want to know the reason behind having such a design, why doesn't java straight away give a compile-time error if the package statement is missing and the class is not present in the default package.
Is there any use case for such type of design?
CodePudding user response:
Answering this with the suggestions from the comments to get it out of the unanswered questions queue:
javac
can't know that you want Class1
to be in a package if you compile it with
/Project/src/Test $ javac Class1.java
But Intellij will sure argue about that, given the folder structure you gave.