Exploring java.lang

Simple, practical, book-style explanation of the fundamental java.lang package.

Chapter idea: java.lang is automatically imported into every Java program. It contains fundamental classes and interfaces used throughout Java, including Object, Class, primitive wrappers, String-related types, System, Runtime, ProcessBuilder, Math, StrictMath, Thread, Package, Module, Record, CharSequence, and more.

1. Why java.lang Is Important

The source chapter describes java.lang as Java's most widely used package. It contains classes and interfaces fundamental to virtually all Java programming. Beginning with JDK 9, java.lang is part of the java.base module.

Object model
Object, Class, Enum
Primitive wrappers
Integer, Double, Character, etc.
Text
String, StringBuffer, StringBuilder, CharSequence
Runtime
System, Runtime, Process, ProcessBuilder
Math
Math, StrictMath
Concurrency
Runnable, Thread, ThreadGroup, ThreadLocal
Runtime type information
Class, Package, Module
Modern Java
Record, ClassValue, StackWalker

2. Primitive Type Wrappers

Java has primitive types such as int, char, and double. Sometimes a primitive value needs an object representation—for example, collection classes work with objects. Java therefore provides wrapper classes.

Primitive
Wrapper Object


int → Integer    char → Character    double → Double
boolean → Boolean    byte → Byte    short → Short
long → Long    float → Float

The chapter notes that wrapper classes are value-based beginning with JDK 16 and should not be used for synchronization.

3. Number

Number is an abstract superclass for numeric wrapper classes such as Byte, Short, Integer, Long, Float, and Double.

Number n = Integer.valueOf(100); System.out.println(n.intValue()); System.out.println(n.doubleValue()); System.out.println(n.longValue());
MethodPurpose
byteValue()Returns the value as byte.
shortValue()Returns the value as short.
intValue()Returns the value as int.
longValue()Returns the value as long.
floatValue()Returns the value as float.
doubleValue()Returns the value as double.

4. Integer and Long

Integer and Long provide parsing, conversion, comparison, and radix-related utilities.

int decimal = Integer.parseInt("123"); int binary = Integer.parseInt("1010", 2); System.out.println(decimal); System.out.println(binary);

Common radix values are 2 for binary, 8 for octal, 10 for decimal, and 16 for hexadecimal.

int num = 19648; System.out.println( Integer.toBinaryString(num) ); System.out.println( Integer.toOctalString(num) ); System.out.println( Integer.toHexString(num) );

Output for the example:

100110011000000 46300 4cc0
Modern construction: The source notes that wrapper constructors such as new Integer(...) were deprecated beginning with JDK 9 and deprecated for removal beginning with JDK 16. The strongly recommended alternative is valueOf().

5. Byte and Short

Byte and Short wrap the corresponding primitive types. Like Integer and Long, they provide conversion, parsing, comparison, and unsigned-related utilities where applicable.

Byte b = Byte.valueOf("10"); Short s = Short.valueOf("200"); System.out.println(b); System.out.println(s);

6. Float and Double

Float and Double wrap floating-point values.

Double d1 = Double.valueOf(1 / 0.0); Double d2 = Double.valueOf(0 / 0.0); System.out.println( d1 + ": " + d1.isInfinite() ); System.out.println( d2 + ": " + d2.isNaN() );

Typical output:

Infinity: true NaN: true

The classes provide methods for detecting special floating-point values, converting values, comparing values, and parsing strings.

7. Boolean

Boolean wraps a boolean value and provides conversion, comparison, and logical helper methods.

boolean a = Boolean.parseBoolean("true"); Boolean b = Boolean.valueOf(true); System.out.println(a); System.out.println(b);
MethodPurpose
parseBoolean(String)Converts "true" into true; case is not significant.
valueOf(boolean)Returns Boolean representing the value.
booleanValue()Gets the primitive boolean.
logicalAnd()Logical AND.
logicalOr()Logical OR.
logicalXor()Logical XOR.

8. Character

Character wraps a char. It also provides many methods for testing and converting characters.

char[] values = {'a', '5', '?', 'A', ' '}; for (char c : values) { if (Character.isDigit(c)) System.out.println(c + " is digit"); if (Character.isLetter(c)) System.out.println(c + " is letter"); if (Character.isWhitespace(c)) System.out.println(c + " is whitespace"); if (Character.isUpperCase(c)) System.out.println(c + " is uppercase"); }

Useful methods include isDigit(), isLetter(), isWhitespace(), isUpperCase(), isLowerCase(), toUpperCase(), and toLowerCase().

9. String, StringBuffer, and StringBuilder

The chapter's earlier String discussion is extended by the mutable string classes.

Character sequence


↙              ↓               ↘
String
StringBuffer
StringBuilder
ClassMain idea
StringImmutable character sequence.
StringBufferMutable character sequence with synchronization.
StringBuilderMutable character sequence without synchronization; generally faster when external synchronization is unnecessary.

10. Object

Object is the root of Java's class hierarchy. Classes that do not explicitly extend another class ultimately inherit from Object.

class Student { String name = "Ravi"; } Student s = new Student(); System.out.println( s.getClass() ); System.out.println( s.toString() );
MethodPurpose
clone()Creates a copy of the object when cloning is supported.
equals(Object)Tests logical/object equality according to the implementation.
getClass()Returns a Class object describing the object.
hashCode()Returns the object's hash code.
toString()Returns a string representation.
wait()Coordinates waiting between threads.
notify()Notifies one waiting thread.
notifyAll()Notifies waiting threads.

Cloning

The source explains that cloning creates a new object that is initially an exact copy. Reference fields are copied as references, so the clone can still refer to the same underlying objects. This can cause unintended side effects.

Important: clone() is protected in Object and cloning requires appropriate use of Cloneable and/or an overridden clone method.

11. Class — Run-Time Type Information

Class represents classes and interfaces at run time. It lets a program discover information about a type while the program is running.

class X { int a; } X x = new X(); Class<?> c = x.getClass(); System.out.println( c.getName() );
MethodPurpose
getName()Gets the complete class/interface name.
getPackageName()Gets the package name.
getSuperclass()Gets the superclass.
getMethods()Gets public methods.
getConstructors()Gets public constructors.
getFields()Gets public fields.
isInterface()Tests whether the type is an interface.
getModule()Gets the module containing the class.

Loading a class by name

Class<?> c = Class.forName("java.lang.String"); System.out.println( c.getName() );

12. Reflection Connection

The source explains that run-time type information is important for reflection and Java Beans. Reflection can inspect constructors, fields, methods, and modifiers dynamically.

Class<?> c = Class.forName("java.awt.Dimension"); System.out.println("Constructors:"); for (Constructor<?> x : c.getConstructors()) { System.out.println(x); } System.out.println("Fields:"); for (Field x : c.getFields()) { System.out.println(x); } System.out.println("Methods:"); for (Method x : c.getMethods()) { System.out.println(x); }
Mental model: Class tells you what a type is; reflection lets you inspect and work with its members dynamically.

13. System

System contains important static facilities. Standard input, standard output, and standard error are available through System.in, System.out, and System.err.

System.out.println("Hello"); String os = System.getProperty("os.name"); System.out.println(os);
MethodPurpose
arraycopy()Copies elements between arrays.
currentTimeMillis()Current time in milliseconds since January 1, 1970.
getenv()Gets environment variables.
getProperty()Gets a Java system property.
gc()Requests garbage collection.
exit(int)Terminates the JVM with an exit code.
console()Returns the JVM console when available.
lineSeparator()Returns the platform line separator.
getLogger()Gets a system logger.

14. System Properties

System properties provide information about the Java run-time environment and operating system.

System.out.println( System.getProperty("java.version") ); System.out.println( System.getProperty("os.name") ); System.out.println( System.getProperty("user.dir") );
Remember: System properties and environment variables are different concepts. getProperty() accesses Java system properties; getenv() accesses environment variables.

15. Runtime

Runtime represents the run-time environment associated with the Java application. Obtain it using Runtime.getRuntime().

Runtime rt = Runtime.getRuntime(); System.out.println( rt.totalMemory() ); System.out.println( rt.freeMemory() ); System.out.println( rt.version() );
MethodPurpose
getRuntime()Returns the current Runtime object.
totalMemory()Approximate total memory available to the program.
freeMemory()Approximate free memory available.
gc()Initiates garbage collection.
exec()Starts another operating-system process.
addShutdownHook()Registers a thread to run during JVM termination.
removeShutdownHook()Removes a shutdown hook.
version()Returns Java runtime version information.

16. Runtime and External Processes

Java can execute other programs through Runtime's exec(). It returns a Process object that can be used to interact with the subprocess.

Runtime r = Runtime.getRuntime(); Process p = null; try { p = r.exec("program-name"); p.waitFor(); System.out.println( p.exitValue() ); } catch (Exception e) { System.out.println(e); }

The chapter describes destroy(), waitFor(), and exitValue(), plus streams/readers used to communicate with a subprocess.

17. ProcessBuilder

ProcessBuilder provides another way to create and configure operating-system processes. It accepts the program name and command-line arguments.

ProcessBuilder pb = new ProcessBuilder( "program-name", "arg1" ); Process p = pb.start();
MethodPurpose
command()Gets or sets the program and arguments.
directory()Gets or sets the working directory.
environment()Gets environment variables.
inheritIO()Uses the same standard I/O as the current process.
redirectInput()Redirects standard input.
redirectOutput()Redirects standard output.
redirectError()Redirects standard error.
redirectErrorStream()Merges standard error into standard output.
start()Starts the configured process.

18. Math

Math provides mathematical functions and constants.

double radians = Math.toRadians(120.0); double degrees = Math.toDegrees(1.312); System.out.println(radians); System.out.println(degrees);
CategoryExamples
Absolute valueabs()
Maximum/minimummax(), min()
Power/rootpow(), sqrt(), cbrt()
Trigonometrysin(), cos(), tan()
Logarithmslog(), log10()
Roundingceil(), floor(), round()
Randomrandom()
AnglestoRadians(), toDegrees()

19. StrictMath

StrictMath provides a mathematical API parallel to Math. The source explains that StrictMath historically emphasized precisely identical results across Java implementations, while Math allowed more implementation latitude for performance. It also notes that beginning with JDK 17, all math computations are strict.

20. Runnable

Runnable defines the entry point for a separate thread of execution. It has one abstract method: run().

class MyTask implements Runnable { public void run() { System.out.println( "Running in another thread" ); } }

21. Thread

Thread creates and controls a thread of execution. It implements Runnable.

Thread t = new Thread( () -> System.out.println( "Hello from thread" ) ); t.start();
MethodPurpose
start()Starts thread execution.
run()Contains the thread's work.
currentThread()Returns the current Thread.
getName()Gets the thread name.
getPriority()Gets priority.
setPriority()Sets priority.
getState()Gets thread state.
getStackTrace()Gets stack trace information.
Deprecated thread methods: The source identifies methods such as stop(), suspend(), and resume() as deprecated because of their unsafe behavior.

22. ThreadGroup

ThreadGroup groups threads together. A newly created thread normally belongs to the same thread group as its parent unless another group is specified.

23. ThreadLocal

ThreadLocal provides thread-local storage: each thread can have its own independent value associated with the same ThreadLocal variable.

ThreadLocal<Integer> value = new ThreadLocal<>(); value.set(100); System.out.println( value.get() );

24. ProcessHandle

ProcessHandle provides information and control over operating-system processes. The source discusses process identification and the ability to determine whether a process is still alive.

ProcessHandle current = ProcessHandle.current(); System.out.println( current.pid() ); System.out.println( current.isAlive() );

ProcessHandle.Info provides process information such as command and CPU-duration information.

25. Package

Package represents information about a Java package.

Package p = String.class.getPackage(); System.out.println( p.getName() );
MethodPurpose
getName()Gets package name.
getImplementationTitle()Gets implementation title.
getImplementationVendor()Gets implementation vendor.
getImplementationVersion()Gets implementation version.
getSpecificationTitle()Gets specification title.
getSpecificationVendor()Gets specification vendor.
getSpecificationVersion()Gets specification version.
isSealed()Tests whether the package is sealed.

26. Module

Added by JDK 9, Module encapsulates a Java module. It can provide information about module access and packages and can participate in module relationships.

Module m = MyClass.class.getModule(); System.out.println( m.getName() ); for (String pkg : m.getPackages()) { System.out.println(pkg); }
MethodPurpose
getName()Gets module name.
getPackages()Gets packages in the module.
getDescriptor()Gets module descriptor information.
isNamed()Checks whether module is named.
isExported()Checks whether a package is exported.
isOpen()Checks whether a package is open.
canRead()Checks module readability.
canUse()Checks service usage.

27. ModuleLayer

ModuleLayer, added by JDK 9, represents a module layer. Its nested Controller class controls a module layer. The source describes these as specialized facilities.

28. StackTraceElement

StackTraceElement describes one frame in a stack trace. A frame identifies an execution point and can include class name, method name, source file, source line number, and module information.

try { int x = 10 / 0; } catch (ArithmeticException e) { for (StackTraceElement frame : e.getStackTrace()) { System.out.println(frame); } }

Normally, you obtain StackTraceElement objects through methods such as Throwable.getStackTrace() or Thread.getStackTrace().

29. Record

Added by JDK 16, Record is the superclass for all Java records. Records automatically inherit from Record, and Record provides/overrides object-level behavior such as equals(), hashCode(), and toString().

record Student( String name, int age ) {} Student s = new Student("Ravi", 20); System.out.println(s.name()); System.out.println(s.age()); System.out.println(s);

30. ClassValue

ClassValue<T> associates a value with a type. The source describes it as a specialized facility rather than something normally needed in everyday programming.

31. CharSequence

CharSequence defines read-only access to a sequence of characters. It is implemented by types including String, StringBuffer, and StringBuilder.

CharSequence text = "Java"; System.out.println( text.length() ); System.out.println( text.charAt(0) ); System.out.println( text.subSequence(1, 4) );
MethodPurpose
charAt(int)Returns a character at an index.
compare(CharSequence, CharSequence)Compares two character sequences.
chars()Returns an IntStream of characters.
codePoints()Returns an IntStream of code points.
isEmpty()Tests whether the sequence has no characters.
length()Returns the number of characters.
subSequence()Returns a subsequence.
toString()Returns a String representation.

32. Runtime Version

Runtime.Version encapsulates version information for the Java environment. The source notes that it was added by JDK 9 and changed substantially with JDK 10 to accommodate the newer release cadence.

Runtime.Version v = Runtime.version(); System.out.println(v);

33. SecurityManager and RuntimePermission

RuntimePermission relates to Java's security mechanism. The source also notes that SecurityManager has been deprecated for removal beginning with JDK 17.

34. Compiler

Compiler supports environments where Java bytecode can be compiled into executable code rather than interpreted. The source describes it as not intended for normal programming use and deprecated for removal.

35. java.lang Mental Map

java.lang | +-- Object model | +-- Object | +-- Class | +-- Enum | +-- Record | +-- Primitive wrappers | +-- Boolean | +-- Character | +-- Byte | +-- Short | +-- Integer | +-- Long | +-- Float | +-- Double | +-- Text | +-- String | +-- StringBuffer | +-- StringBuilder | +-- CharSequence | +-- Runtime | +-- System | +-- Runtime | +-- Process | +-- ProcessBuilder | +-- ProcessHandle | +-- Math | +-- Math | +-- StrictMath | +-- Threads | +-- Runnable | +-- Thread | +-- ThreadGroup | +-- ThreadLocal | +-- Type / module information +-- Package +-- Module +-- ModuleLayer +-- StackTraceElement

36. Which java.lang Class Should I Think Of?

RequirementUseful type
Object's common behaviorObject
Inspect a type at runtimeClass
Wrap a primitiveInteger, Double, Boolean, Character, etc.
Parse integer textInteger / Long
Character classificationCharacter
Mutable textStringBuffer / StringBuilder
System properties/environmentSystem
JVM runtime informationRuntime
Start an external processRuntime / ProcessBuilder
Mathematical operationsMath / StrictMath
Create a threadThread / Runnable
Per-thread valueThreadLocal
Process informationProcessHandle
Package informationPackage
Module informationModule
Stack frame informationStackTraceElement
Read-only character abstractionCharSequence

37. Key Rules to Remember

  • java.lang is automatically imported.
  • Object is the root of the Java class hierarchy.
  • Class provides run-time type information.
  • Wrapper classes provide object representations of primitive values.
  • valueOf() is preferred over the old wrapper constructors.
  • Integer/Long provide parsing and radix conversions.
  • Character provides character classification and case conversion.
  • System provides standard I/O, system properties, environment access, and other JVM-level utilities.
  • Runtime represents the current Java run-time environment.
  • ProcessBuilder provides configurable external process creation.
  • Math and StrictMath provide mathematical operations.
  • Runnable defines the work of a thread; Thread represents the executing thread.
  • ThreadLocal gives each thread its own associated value.
  • Module provides run-time module information and access-related operations.
  • StackTraceElement represents one stack frame.
  • Record is the superclass of Java records.
  • CharSequence is a common read-only character-sequence abstraction.

38. Final Perspective

This chapter is about the building blocks underneath everyday Java code.

When you write Java, you constantly use Object, wrapper classes, String, System, Class, and thread-related types—even when you do not explicitly think about java.lang.

The best way to learn this chapter is to connect each class with its job:

Object → common object behavior
Class → run-time type information
Integer/Double/etc. → primitive wrappers
System → JVM/system facilities
Runtime → run-time environment
ProcessBuilder → external processes
Math → mathematical operations
Thread/Runnable → concurrent execution
Module/Package → program structure metadata
CharSequence → common character-sequence abstraction

39. Summary

This chapter explores the fundamental java.lang package. It covers primitive wrappers, Object, Class and run-time type information, System, Runtime, Process and ProcessBuilder, Math and StrictMath, threading classes/interfaces, process handles, packages and modules, stack traces, records, ClassValue, and CharSequence. Understanding these APIs gives you a strong foundation for the Java platform itself.

Inheritance Hierarchy of Important java.lang Classes

The following tree gives a quick visual view of the major inheritance relationships discussed in this chapter. Remember that Boolean and Character are wrapper classes but do not extend Number.

Object
│
├── Number
│   │
│   ├── Byte
│   ├── Short
│   ├── Integer
│   ├── Long
│   ├── Float
│   └── Double
│
├── Boolean
│
├── Character
│
├── String
│
├── StringBuffer
│
├── StringBuilder
│
├── Thread
│
└── Throwable
    │
    ├── Exception
    │   ├── RuntimeException
    │   └── ...
    │
    └── Error
        ├── ThreadDeath
        └── ...
Important: The wrapper hierarchy is especially easy to remember as: Object → Number → Byte, Short, Integer, Long, Float, Double. Boolean and Character directly extend Object.

Java.lang Class Hierarchy — Quick Visual Map

This hierarchy gives you a quick picture of the important relationships between the java.lang classes discussed in this chapter.

  • java.lang
    • Object
      • Class
      • Enum
      • Throwable
        • Exception
        • Error
      • Thread
    • Number
      • Byte
      • Short
      • Integer
      • Long
      • Float
      • Double
    • CharSequence
      • String
      • StringBuffer
      • StringBuilder
    • Other important java.lang types
      • Boolean
      • Character
      • System
      • Runtime
      • Math
      • StrictMath
      • Runnable
      • ThreadGroup
      • ThreadLocal
      • ProcessHandle
      • Package
      • Module
      • ModuleLayer
      • Record
      • ClassValue
Important: This is a learning map, not a complete inheritance diagram. Some types shown here are interfaces, while others are classes. The purpose is to remember the major groups and relationships discussed in the chapter.