Package Naming Conventions Tutorial

This tutorial will discuss recommendations for package naming conventions. The whole idea behind package naming conventions is to maintain unique package.Class names and avoid naming collisions.



Recommendation 1 · Do not name your package java or javax

If the first statement in your class is package java; then you better check your sanity ... or maybe its congrats on your new job at Oracle. The Java class libraries use the java package name. For example, the package java.lang is automatically imported when we create a class. The java.lang provides classes that are fundamental to the design of the Java programming language.

Recommendation 2 · Use lower case

By naming your package lowercase you will prevent conflicts with Class and Interface names.

Recommendation 3 · Name your package the reverse of your internet domain name

My website URL is javacjava.com, so I should name my packages com.javacjava.namespace. For example, com.javacjava.aboutme or com.javacjava.location. I use this technique in real life, but not in my tutorials; I don't need a bunch of com.javacjava packages floating around out there that I didn't write ;)


Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md com
C:\Java>cd com
C:\Java\com>md mywebsite
C:\Java\com>cd mywebsite
C:\Java\com\mywebsite\md mypackage
C:\Java\com\mywebsite\cd mypackage
C:\Java\com\mywebsite\mypackage>Notepad Conventions.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


package com.mywebsite.mypackage;

class Conventions {
    public static void main(String args[]) {
        System.out.println("The package name com.mywebsite.mypackage will minimize the chances ");
        System.out.println("for name collisions ... unless you are part of a large organization.");
    }
}

Now switch back to the command prompt (CMD) and type in cd \Java and press Enter.
Now type in javac com\mywebsite\mypackage\Conventions.java and press Enter.
Now type in java com.mywebsite.mypackage.Conventions and press Enter.


C:\Java>javac com\mywebsite\mypackage\Conventions.java
C:\Java>java com.mywebsite.mypackage.Conventions
The package name com.mywebsite.mypackage will minimize the chances for name collisions ...
unless you are part of a large organization.


Final thoughts

None


Tutorials