It really depends on how you're compiling and running the program, but ultimately it's your choice.
Let's have a look at some of the different ways you might build your program.
1. Compiling the file with javac
If you're compiling the file using javac
then the package will not matter. It will generate the .class
file the same directory as the source file.
2. Compiling to a JAR File
If you're compiling to a JAR File, then the .class
file will be inside the directories specified in your package name. Although this would not affect how the program is ran.
In both of these cases, I'd say that the package identifier is unnecessary for a single-file program. However, there is an exception.
The exception...
If ever you plan to use the class in a larger program, then adding a relevant package name would be essential.
This is because it would...
Prevent name collisions when other classes in the default packages have the same name.
Help people know whether or not your class is the one they want.
Can you imagine if 20 different developers made a List
class in the default package, and somehow they all ended up in a project? It would be chaos! How would I choose the right List
?
So in the case of writing a class that others will use in their own projects, you should definitely use package names.