Sub topic 5
Fully Qualified Names
This chapter assumes you can write and run a basic Java class with a main method, and that you know class, method and field syntax. You should also be able to compile Java from a command line or an IDE. It builds on the previous chapters, where a package declaration puts a class in a package and the source file sits in a matching directory.
What a fully qualified name is
A fully qualified name is the package name, a dot, and the class name. The class Product from the package com.example.shop.model has the fully qualified name com.example.shop.model.Product. The bare name Product is its simple name.
The fully qualified name identifies a class uniquely. Two classes can share a simple name, but two classes in the same package cannot, so the package plus the simple name never collides. This is the main job of a package as a namespace.
You can use a fully qualified name anywhere you would use a simple name, with no import needed:
package com.example.shop;
public class QualifiedUse {
public static void main(String[] args) {
java.util.List<String> names = new java.util.ArrayList<>();
names.add("Pen");
names.add("Notebook");
java.util.Map<String, java.util.List<String>> byShelf = new java.util.HashMap<>();
byShelf.put("A1", names);
com.example.shop.model.Product p = new com.example.shop.model.Product("Pen", 1.5);
System.out.println(byShelf + " " + p.getName());
}
}This program uses the Product class from the earlier chapter. It compiles and runs as long as Product is compiled and on the classpath. The same rule applies to fully qualified names and imports: the class must be public, or in your own package, and the compiler must be able to find it.
The code is correct but hard to read. Imports exist so you can write the short form most of the time. A fully qualified name is the tool you reach for in a few specific situations.
Anatomy of a name
A name such as com.example.shop.model.Product has two parts that the compiler treats differently.
- The package part is
com.example.shop.model. It has no meaning of its own beyond naming a place. - The class part is
Product. For a nested class it continues with more dots, for examplejava.util.Map.Entry.
Packages are not hierarchical in any way the language cares about. java.util and java.util.concurrent look like parent and child, but Java treats them as two unrelated packages. Being able to see java.util.List tells you nothing about access to java.util.concurrent.Executor. Importing one never brings in the other.
Four kinds of name
One class can be written in several ways. The differences matter when you work with reflection, stack traces, and the java command.
| Kind | Example for a nested class | Used for |
|---|---|---|
| Simple name | `Entry` | Code inside the class's scope, or after an import |
| Fully qualified (canonical) name | `java.util.Map.Entry` | Source code, documentation |
| Binary name | `java.util.Map$Entry` | `Class.forName`, class file names, stack traces |
| Package name | `java.util` | `package` and `import` declarations |
For top-level classes the canonical and binary names are the same. For nested classes the canonical name uses a dot, while the binary name uses a $. The compiler also writes a nested class to disk as Map$Entry.class.
You can print all of these from a running program:
package com.example.shop;
import java.util.Map;
public class NamesDemo {
static class Inner {
}
public static void main(String[] args) throws ClassNotFoundException {
Class<?> inner = Inner.class;
System.out.println(inner.getName());
System.out.println(inner.getCanonicalName());
System.out.println(inner.getSimpleName());
System.out.println(inner.getPackageName());
Class<?> entry = Map.Entry.class;
System.out.println(entry.getName());
System.out.println(entry.getCanonicalName());
Class<?> loaded = Class.forName("com.example.shop.NamesDemo$Inner");
System.out.println(loaded == inner);
}
}Save it as src/com/example/shop/NamesDemo.java, then compile and run it:
javac -d out src/com/example/shop/NamesDemo.java
java -cp out com.example.shop.NamesDemoThe output is:
com.example.shop.NamesDemo$Inner
com.example.shop.NamesDemo.Inner
Inner
com.example.shop
java.util.Map$Entry
java.util.Map.Entry
truegetPackageName() exists from Java 9 onward. Class.forName needs the binary name, so "com.example.shop.NamesDemo.Inner" would throw a ClassNotFoundException.
How the compiler reads a dotted name
When the compiler sees a.b.c, it does not know in advance which parts are packages, which are classes, and which are fields. Take java.lang.System.out.println:
javaandjava.langare packages.Systemis a class injava.lang.outis a static field ofSystem.printlnis a method of the object in that field.
The compiler works from the left. It first tries to read the leftmost identifier as a variable, then as a type, then as a package. The first reading that applies wins. This is called obscuring, and it can break a fully qualified name. If a local variable or field named java is in scope, then java.util.List is read as "the util member of the variable java", and the compiler reports cannot find symbol. This is rare in practice, because package names are lowercase and so are variables, but it does happen with variables called com, org, or net in short examples. The fix is to rename the variable.
The diagram shows how a name in source code leads to a class. Qualified names skip the search that simple names need.
The right-hand path is the one the next chapters cover: single-type imports, then wildcard imports, and then conflicts. A fully qualified name avoids all of those rules, which is why it always works when a simple name is ambiguous.
When to write the full name
Use a fully qualified name in these cases:
- Two classes with the same simple name are both needed in one file. You import one and write the other in full, for example
java.sql.Datenext to an importedjava.util.Date. The later chapter on name conflicts covers this. - You use a class once and an import line would be more noise than help.
- You run a program with the
javacommand. The launcher always wants the fully qualified name of the class that holdsmain. - You load a class by string, with
Class.forName, in a configuration file, or in a framework setting. Here you need the binary name. - You write documentation. Javadoc
{@link java.util.List}and@throws java.io.IOExceptionuse full names so that links resolve without an import.
Do not use full names everywhere to avoid imports. Code with long names is slower to read, and tools such as your IDE already add imports for you.
Common errors
These are the mistakes that fully qualified names cause most often.
| Symptom | Cause | Fix |
|---|---|---|
| `package com.example.shop.modle does not exist` | A typo in the package part | Fix the spelling to match the `package` line of the target file |
| `Could not find or load main class com.example.shop.Main.class` | `.class` added to the name | Pass `com.example.shop.Main` without any extension |
| `Could not find or load main class Main`, caused by `NoClassDefFoundError: com/example/shop/Main (wrong name: Main)` | Ran from inside the package directory | Run from the root of the output tree with `-cp out` and the full name |
| `ClassNotFoundException` from `Class.forName("pkg.Outer.Inner")` | Used the canonical name for a nested class | Use `pkg.Outer$Inner` |
| `cannot find symbol` on `java.util.List` | A variable named `java` is in scope | Rename the variable |
| `X is not public in pkg; cannot be accessed from outside package` | The full name was right, but the class is package-private | Make the class `public`, or move the caller into the package |
Fully qualified names and directories
The fully qualified name is also the path to the file, with dots replaced by slashes. com.example.shop.model.Product lives in src/com/example/shop/model/Product.java and compiles to out/com/example/shop/model/Product.class. This mapping is why java -cp out com.example.shop.Main works: the launcher takes the classpath entry out, converts the name to com/example/shop/Main.class, and looks for that file under it.
Exercise
A class Node is nested inside Tree, which is in the package org.demo.data. Give its canonical name and its binary name, and say which one you pass to Class.forName.
Show answer
The canonical name is org.demo.data.Tree.Node and the binary name is org.demo.data.Tree$Node. You pass the binary name to Class.forName.
Exercise
You compiled with javac -d out src/com/example/shop/Main.java. Running java -cp out com/example/shop/Main.class fails. Which command would work, and why does the first one fail?
Show answer
java -cp out com.example.shop.Main works. The launcher expects the fully qualified class name with dots and no file extension, not a file path. With .class added, it looks for a class called Main.class in the package com.example.shop, which does not exist.
Exercise
Why does java.util.List stop compiling if a field named java is declared in the same class?
Show answer
The compiler tries to read the leftmost identifier as a variable before a type or a package. The field java obscures the package, so java.util is read as a member access on that field, and the compiler reports cannot find symbol.