Skip to main content

Overview

The java.lang package provides classes fundamental to the design of the Java programming language. This package is automatically imported into every Java source file (import java.lang.* is implicit).

Core Classes

Object Class

The root of the Java class hierarchy. Every class has Object as a superclass.
getClass()
Class<?>
Returns the runtime class of this object.
Object obj = "Hello";
Class<?> clazz = obj.getClass(); // Returns String.class
hashCode()
int
Returns a hash code value for the object. Objects that are equal according to equals() must have the same hash code.
String s = "example";
int hash = s.hashCode();
equals(Object obj)
boolean
Indicates whether some other object is “equal to” this one. The default implementation compares object references.
String s1 = new String("test");
String s2 = new String("test");
boolean equal = s1.equals(s2); // true
toString()
String
Returns a string representation of the object. The default implementation returns getClass().getName() + "@" + Integer.toHexString(hashCode()).
Object obj = new Object();
String str = obj.toString(); // "java.lang.Object@1a2b3c4d"
clone()
Object
Creates and returns a copy of this object. Requires implementing Cloneable interface.
class Person implements Cloneable {
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
wait()
void
Causes current thread to wait until another thread invokes notify() or notifyAll() on this object.
synchronized (obj) {
    while (!condition) {
        obj.wait();
    }
    // Perform action
}
wait(long timeoutMillis)
void
Waits for at most the specified number of milliseconds.
notify()
void
Wakes up a single thread waiting on this object’s monitor.
notifyAll()
void
Wakes up all threads waiting on this object’s monitor.

String Class

Represents immutable character strings. All string literals are instances of this class.
public final class String
    implements Serializable, Comparable<String>, CharSequence,
               Constable, ConstantDesc
Strings are immutable - their values cannot be changed after creation.
// String literals
String str1 = "abc";

// Constructor
char[] data = {'a', 'b', 'c'};
String str2 = new String(data);

// Concatenation
String result = "Hello" + " " + "World";
String objects are immutable and can be shared. String literals are interned in the string pool.
length()
int
Returns the number of characters in the string.
"hello".length(); // Returns 5
charAt(int index)
char
Returns the character at the specified index.
"hello".charAt(1); // Returns 'e'
substring(int beginIndex, int endIndex)
String
Returns a substring from beginIndex (inclusive) to endIndex (exclusive).
"hello world".substring(0, 5); // Returns "hello"
contains(CharSequence s)
boolean
Returns true if the string contains the specified sequence.
"hello world".contains("world"); // true
startsWith(String prefix)
boolean
Tests if the string starts with the specified prefix.
endsWith(String suffix)
boolean
Tests if the string ends with the specified suffix.
indexOf(String str)
int
Returns the index of the first occurrence of the specified substring, or -1 if not found.
toLowerCase()
String
Converts all characters to lowercase.
toUpperCase()
String
Converts all characters to uppercase.
trim()
String
Returns a string with leading and trailing whitespace removed.
replace(char oldChar, char newChar)
String
Returns a string with all occurrences of oldChar replaced by newChar.
split(String regex)
String[]
Splits the string around matches of the given regular expression.
String[] parts = "a,b,c".split(","); // ["a", "b", "c"]
Java provides multiple ways to compare strings:
equals(Object obj)
boolean
Exact content equality - checks identical char sequence (case-sensitive).
"hello".equals("hello"); // true
"hello".equals("Hello"); // false
equalsIgnoreCase(String str)
boolean
Simple case-insensitive equality check.
"hello".equalsIgnoreCase("HELLO"); // true
compareTo(String str)
int
Lexicographically compares two strings. Returns negative if this string is less than the argument, zero if equal, positive if greater.
"apple".compareTo("banana"); // negative number
"banana".compareTo("apple"); // positive number
"apple".compareTo("apple");  // 0

Class Class

Instances of Class represent classes and interfaces in a running Java application.
public final class Class<T>
    implements Serializable, GenericDeclaration, Type, AnnotatedElement,
               TypeDescriptor.OfField<Class<?>>, Constable
// Using class literal
Class<String> clazz1 = String.class;

// Using Object.getClass()
String str = "example";
Class<?> clazz2 = str.getClass();

// Using Class.forName()
Class<?> clazz3 = Class.forName("java.lang.String");
getName()
String
Returns the fully qualified name of the class.
String.class.getName(); // "java.lang.String"
getSimpleName()
String
Returns the simple name of the class.
String.class.getSimpleName(); // "String"
getSuperclass()
Class<? super T>
Returns the superclass of this class.
getInterfaces()
Class<?>[]
Returns an array of interfaces implemented by this class.
getMethods()
Method[]
Returns all public methods of this class and its superclasses.
getFields()
Field[]
Returns all public fields of this class and its superclasses.
newInstance()
T
Creates a new instance of the class (deprecated - use Constructor.newInstance() instead).
isInstance(Object obj)
boolean
Determines if the specified object is assignment-compatible with this Class.

System Class

Provides access to system facilities including standard I/O streams, environment variables, and system properties.
public final class System
in
InputStream
The standard input stream, typically connected to keyboard input.
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
out
PrintStream
The standard output stream, typically connected to console output.
System.out.println("Hello, World!");
System.out.printf("Value: %d%n", 42);
err
PrintStream
The standard error output stream for error messages.
System.err.println("Error occurred!");
currentTimeMillis()
long
Returns current time in milliseconds since Unix epoch (January 1, 1970 00:00:00 UTC).
long now = System.currentTimeMillis();
nanoTime()
long
Returns the current value of the running JVM’s high-resolution time source, in nanoseconds. Used for measuring elapsed time.
long start = System.nanoTime();
// ... operation ...
long elapsed = System.nanoTime() - start;
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
void
Copies an array from the specified source array to the destination array.
int[] source = {1, 2, 3, 4, 5};
int[] dest = new int[5];
System.arraycopy(source, 0, dest, 0, 5);
getProperty(String key)
String
Gets the system property indicated by the specified key.
String javaVersion = System.getProperty("java.version");
String userHome = System.getProperty("user.home");
String osName = System.getProperty("os.name");
getenv(String name)
String
Gets the value of the specified environment variable.
String path = System.getenv("PATH");
exit(int status)
void
Terminates the currently running JVM. Status code 0 indicates normal termination.
System.exit(0); // Normal termination
System.exit(1); // Error termination
gc()
void
Suggests that the JVM run the garbage collector (not guaranteed to run immediately).

Primitive Wrapper Classes

Wrapper class for primitive int type.
// Autoboxing and unboxing
Integer obj = 42;          // autoboxing
int value = obj;           // unboxing

// Parsing
int num = Integer.parseInt("123");
Integer obj2 = Integer.valueOf("456");

// Constants
int max = Integer.MAX_VALUE;  // 2147483647
int min = Integer.MIN_VALUE;  // -2147483648

// Conversion
String str = Integer.toString(123);
String hex = Integer.toHexString(255); // "ff"
String binary = Integer.toBinaryString(8); // "1000"

Exception Classes

The java.lang package defines the exception hierarchy:
Throwable
├── Error (unchecked)
│   ├── OutOfMemoryError
│   ├── StackOverflowError
│   └── ...
└── Exception
    ├── RuntimeException (unchecked)
    │   ├── NullPointerException
    │   ├── IllegalArgumentException
    │   ├── IndexOutOfBoundsException
    │   ├── ClassCastException
    │   └── ...
    └── Checked Exceptions
        ├── InterruptedException
        ├── CloneNotSupportedException
        └── ...

Other Important Classes

Mathematical functions and constants.
// Constants
double pi = Math.PI;      // 3.141592653589793
double e = Math.E;        // 2.718281828459045

// Basic operations
int max = Math.max(10, 20);           // 20
int min = Math.min(10, 20);           // 10
int abs = Math.abs(-10);              // 10

// Rounding
long rounded = Math.round(3.7);       // 4
double ceil = Math.ceil(3.2);         // 4.0
double floor = Math.floor(3.9);       // 3.0

// Power and roots
double pow = Math.pow(2, 8);          // 256.0
double sqrt = Math.sqrt(16);          // 4.0
double cbrt = Math.cbrt(27);          // 3.0

// Trigonometry
double sin = Math.sin(Math.PI / 2);   // 1.0
double cos = Math.cos(0);             // 1.0
double tan = Math.tan(Math.PI / 4);   // ~1.0

// Random
double random = Math.random();        // [0.0, 1.0)
Represents a thread of execution in a program.
// Creating threads
Thread thread = new Thread(() -> {
    System.out.println("Running in thread");
});
thread.start();

// Thread operations
Thread.currentThread();        // Get current thread
Thread.sleep(1000);            // Sleep for 1 second
thread.join();                 // Wait for thread to complete
thread.interrupt();            // Interrupt the thread

// Thread properties
thread.setName("MyThread");
String name = thread.getName();
thread.setPriority(Thread.MAX_PRIORITY);
boolean alive = thread.isAlive();
Mutable sequences of characters.
// StringBuilder (not thread-safe, faster)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.insert(5, ",");
sb.delete(0, 6);
String result = sb.toString();

// StringBuffer (thread-safe, synchronized)
StringBuffer buffer = new StringBuffer("Initial");
buffer.append(" text");

Usage Examples

Working with Objects

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && 
               Objects.equals(name, person.name);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
    
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

String Manipulation

String text = "  Hello, World!  ";

// Basic operations
String trimmed = text.trim();           // "Hello, World!"
String upper = trimmed.toUpperCase();   // "HELLO, WORLD!"
String replaced = upper.replace("WORLD", "JAVA");

// Searching
boolean contains = text.contains("World");  // true
int index = text.indexOf("World");          // 9

// Splitting
String csv = "apple,banana,cherry";
String[] fruits = csv.split(",");

// Building strings efficiently
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    builder.append(i).append(",");
}
String numbers = builder.toString();
The java.lang package is automatically imported. You never need to write import java.lang.*.

Build docs developers (and LLMs) love