2 min read

Gotchas in Java Packages

Problems that you can encounter when working with Java packages.
Gotchas in Java Packages

Optional Packages

It is optional to put a class in a package. If a class isn't in a package, it will be in the default package. This is not a good idea and it shouldn't be done. You should always explicitly declare a package for every class. Even if you have a project with a single file that isn't used anywhere else, you should still put it in a package.

Classes in a Different Directory

Classes can be in a different directory than the package that is defined in the Java class. Java will not generate a compiler error if this is the case. This will cause you headaches and generally occurs during refactors when you are moving classes around. If you are using an IDE (Integrated Development Environment) to develop, you generally will not run into this problem since the IDE will handle this for you.

Invalid Domain Names in Package Names

The naming standard for packages is to prefix your package names with your internet domain name reversed. An internet domain name doesn't follow the same rules as a Java package. A section in a package name must follow the same rules as variable names.

Invalid Characters for Packages

Internet domain names can contain hyphens. Hyphens are not valid characters in a package name. If you run into a character that isn't valid for a package name, replace it with an underscore.

// Invalid
package com.byte-size.services;

// Valid
package com.byte_size.services

Starting With Numbers

Internet domain names can start with a number. Package names cannot start with a number. To fix this, prefix it with an underscore.

// Invalid
package com.123abc.services;

// Valid
package com._123abc.services;

Java Keywords

If a Java keyword is used in your internet domain name, you can fix this by prefixing it with an underscore.

// Invalid
package com.try.services;

// Valid
package com._try.services;

Conclusion

Packages do not have too many gotchas, but they definitely can occur. Use underscores to fix invalid names; always put a class in a package; and using an IDE will ensure classes are in the corresponding directory of the package they are in.