Home > database >  IntelliJ error when package name different than the folder name
IntelliJ error when package name different than the folder name

Time:09-29

I was writing a simple class HelloPrinter3.java. It's in directory src/two. Now IntelliJ is giving me an error, saying Package name 'three' does not correspond to the file path 'two'. But it also compiles and runs fine.

enter image description here

I already know that a package name should not necessarily be the folder name. But what I am confused is the error. It cannot be the java error as the file would not have run. But then is it IntelliJ error? How can I differentiate between these two errors while writing code? Thanks in advance.

CodePudding user response:

This IDE inspection detects package statements that do not correspond to the project directory structure. Also, reports classes without package statements if the class is not located directly in source root directory.

While it's not strictly mandated by Java language, it's good to keep classes from package com.example.myapp inside the com/example/myapp directory under the source root. Failure to do this may confuse code readers and make some tools working incorrectly.

You can point the cursor at package three and press Alt Enter to see which fixes the IDE suggest:

enter image description here

Also, you can disable this inspection in the IDE settings if needed:

enter image description here

  • Related