java.lang Package

Core classes that are automatically imported in every Java program.

Object

The root class of all Java classes.

toString

String toString()

Returns a string representation of the object.

equals

boolean equals(Object obj)

Compares this object to another for equality.

hashCode

int hashCode()

Returns a hash code value for the object.

getClass

Class<?> getClass()

Returns the runtime class of this object.

clone

Object clone()

Creates and returns a shallow copy of this object.

String

Immutable sequence of characters.

Length and Access

int length()

Returns the number of characters.

char charAt(int index)

Returns the character at the specified index.

boolean isEmpty()

Returns true if length is 0.

Substring Operations

String substring(int beginIndex)

Returns substring from beginIndex to end.

String substring(int beginIndex, int endIndex)

Returns substring from beginIndex to endIndex (exclusive).

String s = "Hello World";
s.substring(6);      // "World"
s.substring(0, 5);   // "Hello"

Search Operations

int indexOf(String str)

Returns index of first occurrence, or -1 if not found.

int indexOf(String str, int fromIndex)

Returns index starting from specified position.

int lastIndexOf(String str)

Returns index of last occurrence.

boolean contains(CharSequence s)

Returns true if this string contains the sequence.

boolean startsWith(String prefix)

Tests if string starts with the prefix.

boolean endsWith(String suffix)

Tests if string ends with the suffix.

Comparison

boolean equals(Object obj)

Compares content for exact equality.

boolean equalsIgnoreCase(String str)

Compares ignoring case differences.

int compareTo(String str)

Compares lexicographically. Returns negative, zero, or positive.

Transformation

String toUpperCase()

Converts all characters to uppercase.

String toLowerCase()

Converts all characters to lowercase.

String trim()

Removes leading and trailing whitespace.

String replace(char oldChar, char newChar)

Replaces all occurrences of a character.

String replace(CharSequence target, CharSequence replacement)

Replaces all occurrences of a sequence.

String concat(String str)

Concatenates the specified string to the end.

Splitting and Joining

String[] split(String regex)

Splits string around matches of the delimiter.

"a,b,c".split(",");  // ["a", "b", "c"]

Static Methods

static String valueOf(int i)
static String valueOf(long l)
static String valueOf(double d)
static String valueOf(Object obj)

Returns string representation of the argument.

static String format(String format, Object... args)

Returns formatted string. Supports %d, %f, %s, %c, %b, %x, %n.

String.format("Name: %s, Age: %d", "John", 25);

StringBuilder

Mutable sequence of characters for efficient string building.

Constructor

StringBuilder()

Constructs an empty StringBuilder.

Append Methods

StringBuilder append(String str)
StringBuilder append(int i)
StringBuilder append(long l)
StringBuilder append(double d)
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(Object obj)

Appends the string representation to this sequence. Returns this for chaining.

Other Methods

int length()

Returns the current length.

void setLength(int newLength)

Sets the length (truncates if shorter).

StringBuilder reverse()

Reverses the sequence.

String toString()

Returns a String containing the characters.

StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
String result = sb.toString();  // "Hello World"

System

System utilities and standard I/O streams.

Fields

static PrintStream out

Standard output stream.

static PrintStream err

Standard error stream.

PrintStream Methods

void println(String s)
void println(int i)
void println(Object obj)
void println()

Prints with newline.

void print(String s)

Prints without newline.

PrintStream printf(String format, Object... args)

Formatted print.

Time Methods

static long currentTimeMillis()

Returns current time in milliseconds since Unix epoch.

static long nanoTime()

Returns high-resolution time for measuring elapsed time.

Other Methods

static void exit(int status)

Terminates the JVM with the given exit code.

static void gc()

Suggests garbage collection (not guaranteed).

static String getProperty(String key)

Gets a system property.

static String getenv(String name)

Gets an environment variable.

static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Copies array elements from source to destination.

Available System Properties

PropertyValue
java.version"17"
java.vendor"rava2"
os.name"Linux"
line.separator"\n"
file.separator"/"
user.dirCurrent directory

Math

Mathematical functions and constants.

Constants

static final double PI = 3.14159265358979323846
static final double E = 2.71828182845904523536

Basic Operations

static int abs(int a)
static long abs(long a)
static double abs(double a)

Returns the absolute value.

static int max(int a, int b)
static long max(long a, long b)
static double max(double a, double b)

Returns the greater of two values.

static int min(int a, int b)
static long min(long a, long b)
static double min(double a, double b)

Returns the smaller of two values.

Power and Roots

static double pow(double a, double b)

Returns a raised to the power of b.

static double sqrt(double a)

Returns the square root.

static double cbrt(double a)

Returns the cube root.

static double exp(double a)

Returns e raised to the power of a.

Logarithms

static double log(double a)

Returns the natural logarithm (base e).

static double log10(double a)

Returns the base-10 logarithm.

Trigonometry

static double sin(double a)
static double cos(double a)
static double tan(double a)

Trigonometric functions (argument in radians).

static double asin(double a)
static double acos(double a)
static double atan(double a)

Inverse trigonometric functions.

static double atan2(double y, double x)

Returns the angle theta from polar coordinates.

static double toRadians(double degrees)
static double toDegrees(double radians)

Angle unit conversion.

Rounding

static double floor(double a)

Returns largest integer less than or equal to a.

static double ceil(double a)

Returns smallest integer greater than or equal to a.

static long round(double a)
static int round(float a)

Returns the closest integer.

Other

static double random()

Returns a random double between 0.0 (inclusive) and 1.0 (exclusive).

static double signum(double d)

Returns -1.0, 0.0, or 1.0 based on sign.

static double hypot(double x, double y)

Returns sqrt(x² + y²) without overflow.

Thread

Thread of execution in a program.

Constants

static final int MIN_PRIORITY = 1
static final int NORM_PRIORITY = 5
static final int MAX_PRIORITY = 10

Constructor

Thread(Runnable target)

Creates a thread with the given runnable task.

Instance Methods

void start()

Starts the thread execution.

void join()

Waits for this thread to complete.

boolean isAlive()

Tests if the thread is still running.

String getName()
void setName(String name)

Gets/sets the thread name.

int getPriority()
void setPriority(int priority)

Gets/sets the thread priority.

Static Methods

static void sleep(long millis)

Pauses execution for the specified milliseconds.

static void yield()

Hints that the thread is willing to yield its current use of a processor.

static Thread currentThread()

Returns a reference to the currently executing thread.

Thread t = new Thread(() -> {
    System.out.println("Running in thread");
    Thread.sleep(1000);
    System.out.println("Done");
});
t.start();
t.join();  // Wait for completion

Wrapper Classes

Integer

static final int MAX_VALUE = 2147483647
static final int MIN_VALUE = -2147483648
static int parseInt(String s)
static int parseInt(String s, int radix)

Parses a string as an integer.

static Integer valueOf(int i)

Returns an Integer instance.

int intValue()

Returns the int value.

Byte

static final byte MAX_VALUE = 127
static final byte MIN_VALUE = -128
static byte parseByte(String s)
static byte parseByte(String s, int radix)

Parses a string as a byte.

static Byte valueOf(byte b)

Returns a Byte instance.

byte byteValue()

Returns the byte value.

Short

static final short MAX_VALUE = 32767
static final short MIN_VALUE = -32768
static short parseShort(String s)
static short parseShort(String s, int radix)

Parses a string as a short.

static Short valueOf(short s)

Returns a Short instance.

short shortValue()

Returns the short value.

Long

static final long MAX_VALUE
static final long MIN_VALUE
static long parseLong(String s)
static long parseLong(String s, int radix)

Parses a string as a long.

static Long valueOf(long l)

Returns a Long instance.

long longValue()

Returns the long value.

Float

static final float MAX_VALUE
static final float MIN_VALUE
static final float POSITIVE_INFINITY
static final float NEGATIVE_INFINITY
static final float NaN
static float parseFloat(String s)

Parses a string as a float.

static Float valueOf(float f)

Returns a Float instance.

static boolean isNaN(float v)
static boolean isInfinite(float v)

Tests for special float values.

float floatValue()

Returns the float value.

Double

static final double MAX_VALUE
static final double MIN_VALUE
static final double POSITIVE_INFINITY
static final double NEGATIVE_INFINITY
static final double NaN
static double parseDouble(String s)

Parses a string as a double.

static boolean isNaN(double v)
static boolean isInfinite(double v)

Tests for special values.

double doubleValue()

Returns the double value.

Boolean

static final Boolean TRUE
static final Boolean FALSE
static boolean parseBoolean(String s)

Parses "true" (case-insensitive) as true, anything else as false.

boolean booleanValue()

Returns the boolean value.

Character

static boolean isLetter(char c)
static boolean isDigit(char c)
static boolean isWhitespace(char c)
static boolean isUpperCase(char c)
static boolean isLowerCase(char c)

Character classification methods.

static char toUpperCase(char c)
static char toLowerCase(char c)

Case conversion methods.

Throwable and Exceptions

Throwable

String getMessage()

Returns the detail message.

Throwable getCause()

Returns the cause of this throwable.

void printStackTrace()

Prints the stack trace to standard error.

Exception Hierarchy

  • Throwable
    • Exception
      • RuntimeException
        • NullPointerException
        • ArrayIndexOutOfBoundsException
        • IllegalArgumentException
          • NumberFormatException
        • IllegalStateException
        • ArithmeticException
        • ClassCastException
      • IOException
      • ClassNotFoundException
    • Error

Common Runtime Exceptions

NullPointerException

Thrown when an application attempts to use null where an object is required.

String s = null;
s.length();  // Throws NullPointerException

ArrayIndexOutOfBoundsException

Thrown when accessing an array with an illegal index (negative or >= length).

int[] arr = new int[5];
arr[10] = 1;  // Throws ArrayIndexOutOfBoundsException

ArithmeticException

Thrown when an exceptional arithmetic condition occurs, such as integer division by zero.

int result = 10 / 0;  // Throws ArithmeticException: / by zero

try {
    int x = 100 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
}

ClassCastException

Thrown when an object is cast to a type of which it is not an instance.

Object obj = "Hello";
Integer num = (Integer) obj;  // Throws ClassCastException

try {
    Object value = new ArrayList<>();
    String str = (String) value;
} catch (ClassCastException e) {
    System.out.println("Invalid cast: " + e.getMessage());
}

IllegalArgumentException

Thrown when a method receives an argument that is inappropriate.

public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
}

IllegalStateException

Thrown when a method is invoked at an illegal or inappropriate time.

public void start() {
    if (started) {
        throw new IllegalStateException("Already started");
    }
    started = true;
}

NumberFormatException

Thrown when attempting to convert a string to a numeric type but the string does not have the appropriate format.

int num = Integer.parseInt("abc");  // Throws NumberFormatException

try {
    int value = Integer.parseInt("12.5");
} catch (NumberFormatException e) {
    System.out.println("Invalid number format");
}

Class

Represents classes and interfaces at runtime.

String getName()

Returns the fully qualified name.

String getSimpleName()

Returns the simple name without package.

Class<?> getSuperclass()

Returns the superclass.

boolean isInterface()
boolean isArray()

Type checking methods.

Object newInstance()

Creates a new instance using the default constructor.