Sub topic 7
What java.lang gives you for free
This chapter assumes you can write and compile a Java class with a main method, that you know the package declaration, and that you have seen import statements. It explains the one package you never have to import, what that includes, and where the convenience stops.
The implicit import
Every Java source file behaves as if its first import line were this one:
import java.lang.*;You never write it. The compiler adds it to every compilation unit (a single .java file). That is why the following program compiles with no imports at all:
public class FreeStuff {
public static void main(String[] args) {
String greeting = "hello";
StringBuilder sb = new StringBuilder(greeting);
sb.append(", ").append(Math.max(3, 7));
Integer boxed = 42;
System.out.println(sb + " " + boxed);
Thread.currentThread().setName("main-worker");
System.out.println(Thread.currentThread().getName());
}
}String, StringBuilder, Math, Integer, System and Thread all live in java.lang. The program prints hello, 7 42 and then main-worker.
The implicit import is an on-demand import (a wildcard import). That detail decides what happens when names collide, as covered below.
What is in java.lang
java.lang holds the types the language itself depends on. The table groups the ones you meet most often.
| Group | Examples |
|---|---|
| Root and core types | `Object`, `Class`, `Enum`, `Record`, `String`, `CharSequence` |
| Wrapper types | `Integer`, `Long`, `Double`, `Boolean`, `Character`, `Byte`, `Short`, `Float`, `Number` |
| Utilities | `Math`, `StrictMath`, `System`, `StringBuilder`, `Runtime` |
| Concurrency | `Thread`, `Runnable`, `ThreadLocal` |
| Interfaces used by language features | `Comparable`, `Iterable`, `AutoCloseable`, `Cloneable` |
| Throwables | `Throwable`, `Exception`, `RuntimeException`, `Error`, `IllegalArgumentException`, `NullPointerException`, `StackOverflowError` |
| Standard annotations | `Override`, `Deprecated`, `SuppressWarnings`, `FunctionalInterface`, `SafeVarargs` |
There is a reason these types are always available. The compiler needs some of them to define the language. Every class extends Object, string literals are String objects, for-each loops need Iterable, and try-with-resources needs AutoCloseable. Requiring an import for those would be pointless.
What you still have to import
Many types you use daily are not in java.lang. These all need an import:
- Collections:
List,ArrayList,Map,HashMap,Set(injava.util) Scanner,Optional,Random,Date(injava.util)BigDecimalandBigInteger(injava.math)Path,Files(injava.nio.file)LocalDateandDuration(injava.time)
If you forget, javac reports an error like this:
FreeStuff.java:3: error: cannot find symbol
List<String> names = new ArrayList<>();
^
symbol: class List
location: class FreeStuffThe message says the symbol is unknown, not that a package is missing. The fix is import java.util.List; and import java.util.ArrayList;, or import java.util.*;.
Subpackages are not included
The * in java.lang.* covers only the types directly in java.lang. Java has no real package hierarchy. java.lang.reflect is a separate package that happens to share a name prefix, so importing the parent never brings in its children. The same applies to java.lang.annotation, java.lang.invoke and java.lang.ref. They need explicit imports:
import java.lang.reflect.Method;
public class ReflectDemo {
public static void main(String[] args) throws Exception {
Method m = String.class.getMethod("length");
System.out.println(m.getName());
}
}This prints length. String and Class (the type of String.class) are free, but Method is in java.lang.reflect, so removing the import line breaks compilation. Likewise, import java.util.*; does not give you java.util.function.Function or java.util.stream.Stream.
Static members are not free either
The implicit import covers type names only. It does not import static members. Math is available, but a bare max(3, 7) is not. You need Math.max(3, 7) or an explicit import static java.lang.Math.max;. The same holds for System.out. You write System.out.println, and out alone means nothing. Static imports are covered in their own chapter.
Redundant imports are legal
You can write import java.lang.String; or import java.lang.*; yourself. The compiler accepts both and ignores the redundancy. Some tools and style checkers flag them as unused. Remove them.
Name resolution order and shadowing
Because java.lang.* is an on-demand import, it has the lowest precedence when the compiler resolves a simple name like Math. Anything more specific wins:
- A type declared in the same file, or named in a single-type import.
- A type in the same package.
- Types from on-demand imports, including
java.lang.*.
So a class in your own package can hide a java.lang class of the same name. This is a gotcha. Here is a runnable example with two files.
src/com/example/shadow/Math.java:
package com.example.shadow;
public class Math {
public static String name() {
return "my own Math";
}
}src/com/example/shadow/Main.java:
package com.example.shadow;
public class Main {
public static void main(String[] args) {
System.out.println(Math.name());
System.out.println(java.lang.Math.max(3, 7));
}
}Compile and run it:
javac -d out src/com/example/shadow/Math.java src/com/example/shadow/Main.java
java -cp out com.example.shadow.MainThe output is my own Math, then 7. In Main, the simple name Math finds the same-package class first, so java.lang.Math is never considered. To reach the real one, use its fully qualified name. If you had written Math.max(3, 7) in Main, it would have failed with cannot find symbol, because your Math has no max method. The compiler does not fall back to java.lang.Math.
Shadowing is legal, but it confuses readers and breaks code that expects the standard class. Avoid naming your own classes String, Object, Math, Thread, Error, Record, Number or similar.
Ambiguity between on-demand imports
Since java.lang.* is an on-demand import, it can collide with another wildcard import. Suppose a library package com.acme.model contains a class named Record. This file compiles against Java 15 and fails against Java 16:
import com.acme.model.*;
public class Reports {
Record latest;
}Java 16 added java.lang.Record. Now Record matches in two on-demand imports, and javac reports reference to Record is ambiguous. The code did not change, but the JDK did. A single-type import avoids the problem, because it has higher precedence:
import com.acme.model.Record;This is a concrete reason to prefer single-type imports for classes whose names are generic. It is also why a JDK upgrade can break a build that uses wildcard imports. The next chapters on wildcard imports and name conflicts return to this trade-off.
Where java.lang lives
In Java 9 and later, java.lang belongs to the java.base module. Every module reads java.base automatically, which matches the "free for everyone" behavior at the module level. You can ignore this until you reach the chapter on JARs and modules.
Summary of the rules
- Every compilation unit gets
import java.lang.*;automatically. - Only types directly in
java.langare covered. Subpackages such asjava.lang.reflectneed imports. - Static members need
import staticor a class-name prefix. - Same-package classes and single-type imports shadow
java.langtypes. - Another on-demand import that supplies the same simple name makes the reference ambiguous.
Exercise
A file contains import java.util.*; and uses Stream.of(1, 2, 3) and Math.abs(-4) with no other imports. Which of the two names compiles, and why? What would you add to fix the other?
Show answer
Math.abs(-4) compiles because Math is in java.lang, which is imported implicitly. Stream is in java.util.stream, a separate package, so java.util.* does not cover it and javac reports cannot find symbol. Add import java.util.stream.Stream; (or import java.util.stream.*;).
Exercise
In package com.example.shadow, you have a class named Integer with a method static int parse(String s). A class App in the same package, with no imports, calls Integer.parseInt("12"). Does it compile? How could App reach the standard parsing method?
Show answer
It does not compile. The simple name Integer resolves to the same-package class, which shadows the on-demand java.lang.* import, and the local class has no parseInt method, so javac reports cannot find symbol. App can call java.lang.Integer.parseInt("12") using the fully qualified name. The better fix is to rename the local class.
Exercise
Your project compiles on Java 11 but fails on Java 17 with reference to Record is ambiguous. The file has import com.acme.model.*; and uses Record. Explain the cause and give two fixes.
Show answer
Java 16 added java.lang.Record, which the implicit java.lang.* on-demand import supplies. com.acme.model.* is also an on-demand import containing a class named Record, so the simple name matches both. Fix it with a single-type import, import com.acme.model.Record;, which takes precedence. Or write the name fully qualified, com.acme.model.Record.