Java Built-in Classes in java.lang Package
Java’s standard library is vast and powerful, but at the core lies the java.lang package—home to the most essential classes that form the foundation of every Java application. This package is imported automatically, so you can use its classes without needing an import statement.
In this post, we’ll explore the most commonly used java.lang classes with real-world examples, best practices, and usage tips.
Why java.lang Matters
- Automatically available in every Java program.
- Includes classes for object handling, strings, math operations, threads, exceptions, enums, and more.
- Core to writing Java code—understanding this package is a must for all Java developers.
Key Classes in java.lang
1. Object – The Root of All Classes
The Object class in Java, defined in the java.lang package, is the root superclass of all classes. Every class in Java either directly or indirectly inherits from the Object class. This means that all objects in Java have access to the methods defined in it. The Object class provides fundamental methods such as toString(), equals(), hashCode(), clone(), and getClass() that are essential for object comparison, representation, and identity. For example, the toString() method returns a string representation of the object, while equals() is used to compare the contents of two objects. The Object class plays a crucial role in providing a common behavior for all Java objects, supporting polymorphism and enabling generic programming.
Example: Overriding Object methods
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return “Person{name='” + name + “‘}”;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person other = (Person) o;
return this.name.equals(other.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
Tip: Always override equals() and hashCode() together for consistent behavior in collections.
Common Methods of the Object Class in Java
Method | Description | Example Usage |
---|---|---|
toString() | Returns a string representation of the object. By default, it returns the class name followed by the object’s hash code. | obj.toString() → "java.lang.String@2f4d3709" |
equals(Object obj) | Compares two objects for equality. The default implementation checks if both references point to the same object. | obj1.equals(obj2) |
hashCode() | Returns an integer hash code value for the object. It’s used for hashing in collections like HashMap . | obj.hashCode() |
getClass() | Returns the runtime class of the object. Useful for reflection and debugging. | obj.getClass() → class java.lang.String |
clone() | Creates and returns a copy (clone) of the object. The class must implement the Cloneable interface. | obj.clone() |
finalize() | Called by the garbage collector before reclaiming the object’s memory (deprecated in Java 9 and later). | Used internally; rarely overridden. |
notify() | Wakes up a single thread waiting on this object’s monitor. Used in synchronization. | Used with wait() and notifyAll() . |
notifyAll() | Wakes up all threads waiting on this object’s monitor. | Used in multi-threaded environments. |
wait() | Causes the current thread to wait until another thread invokes notify() or notifyAll() . | Used for thread communication. |
2. String – Immutable Text
The String class in Java, part of the java.lang package, is one of the most commonly used and powerful classes for handling text data. A String represents a sequence of characters and is immutable, meaning once a String object is created, its value cannot be changed. Any modification, such as concatenation or replacement, results in the creation of a new String object. The String class provides a wide range of useful methods like length(), charAt(), substring(), toUpperCase(), toLowerCase(), and equals() to perform various text manipulations and comparisons. Strings can be created either using string literals or by using the new keyword.
String greeting = “Hello”;
greeting += ” World”; // Creates a new String object
System.out.println(greeting); // Hello World
Problem: Concatenating strings in a loop is inefficient due to repeated object creation.
Common Methods of the String Class in Java
Method | Description | Example Usage |
---|---|---|
length() | Returns the number of characters in the string. | "Hello".length() → 5 |
charAt(int index) | Returns the character at the specified index (starting from 0). | "Java".charAt(1) → 'a' |
substring(int beginIndex, int endIndex) | Extracts a portion of the string from beginIndex to endIndex - 1 . | "Programming".substring(0, 4) → "Prog" |
toUpperCase() | Converts all characters in the string to uppercase. | "java".toUpperCase() → "JAVA" |
toLowerCase() | Converts all characters in the string to lowercase. | "JAVA".toLowerCase() → "java" |
equals(Object obj) | Compares two strings for content equality (case-sensitive). | "Java".equals("java") → false |
equalsIgnoreCase(String anotherString) | Compares two strings, ignoring case differences. | "Java".equalsIgnoreCase("java") → true |
concat(String str) | Concatenates the specified string to the end of another string. | "Hello".concat(" World") → "Hello World" |
contains(CharSequence s) | Checks if the string contains the given sequence. | "Hello World".contains("World") → true |
replace(char oldChar, char newChar) | Replaces all occurrences of a character with another. | "banana".replace('a', 'o') → "bonono" |
trim() | Removes leading and trailing spaces from the string. | " Java ".trim() → "Java" |
split(String regex) | Splits the string around matches of the given regular expression. | "a,b,c".split(",") → ["a", "b", "c"] |
indexOf(String str) | Returns the index of the first occurrence of the specified substring. | "program".indexOf("gr") → 3 |
isEmpty() | Checks whether the string is empty (length() == 0 ). | "".isEmpty() → true |
3. StringBuilder – Mutable Strings
The StringBuilder class in the java.lang package is used to create mutable (modifiable) sequences of characters. Unlike the String class, whose objects are immutable, StringBuilder allows changes to be made without creating new objects, making it more efficient when performing multiple string modifications such as concatenation, insertion, or deletion. This class is not synchronized, so it offers better performance than StringBuffer in single-threaded environments. Use StringBuilder for efficient string manipulation when building large or dynamic strings. Some commonly used methods include append(), insert(), delete(), reverse(), and toString().
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(“Line “).append(i).append(“\n”);
}
System.out.println(sb.toString());
Tip: Use StringBuilder or StringBuffer (thread-safe) in loops and heavy string concatenation scenarios.
Common Methods of the StringBuilder Class in Java
Method | Description | Example | Output |
---|---|---|---|
append(String str) | Appends the specified string to the end of the current sequence. | new StringBuilder("Java").append(" Rocks") | Java Rocks |
insert(int offset, String str) | Inserts the specified string at the given index. | new StringBuilder("Hello").insert(5, " World") | Hello World |
delete(int start, int end) | Removes the characters in the specified range. | new StringBuilder("Programming").delete(3, 6) | Progming |
deleteCharAt(int index) | Deletes the character at the specified index. | new StringBuilder("Code").deleteCharAt(1) | Cde |
replace(int start, int end, String str) | Replaces characters in the specified range with the given string. | new StringBuilder("Java").replace(1, 3, "AI") | JAIA |
reverse() | Reverses the sequence of characters. | new StringBuilder("ChatGPT").reverse() | TPGtahC |
length() | Returns the number of characters in the sequence. | new StringBuilder("Tech").length() | 4 |
capacity() | Returns the current capacity (storage size) of the StringBuilder . | new StringBuilder("Data").capacity() | 20 (default 16 + length of “Data”) |
setLength(int newLength) | Sets the length of the sequence; truncates or pads with null characters (\u0000 ). | StringBuilder sb = new StringBuilder("Hello"); sb.setLength(3); | Hel |
charAt(int index) | Returns the character at the specified index. | new StringBuilder("Java").charAt(2) | v |
substring(int start, int end) | Returns a substring of the StringBuilder content. | new StringBuilder("StringBuilder").substring(0, 6) | String |
toString() | Converts the StringBuilder object to a String . | new StringBuilder("Learn").toString() | Learn |
4. StringBuffer – Mutable Sequence of Characters
The StringBuffer class in the java.lang package is a mutable sequence of characters, similar to StringBuilder, but with one key difference — it is thread-safe. All its methods are synchronized, making it suitable for use in multi-threaded environments where multiple threads might modify the same string at the same time. Like StringBuilder, it allows modification operations such as appending, inserting, deleting, and reversing strings without creating new objects, improving performance compared to immutable String objects. Common methods include append(), insert(), delete(), reverse(), and toString().
Example:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(“Java”);
sb.append(” Programming”);
sb.insert(0, “Learn “);
sb.replace(6, 10, “Core”);
sb.reverse();
System.out.println(sb);
}
}
Output: gnimmargorP eroC nraeL
In this example, StringBuffer efficiently handles multiple string modifications — appending, inserting, replacing, and reversing — all within the same object.
Common Methods of the StringBuffer Class in Java
Method | Description | Example | Output |
---|---|---|---|
append(String str) | Appends the specified string to the end of the current sequence. | new StringBuffer("Java").append(" Rocks") | Java Rocks |
insert(int offset, String str) | Inserts the specified string at the given index. | new StringBuffer("Hello").insert(5, " World") | Hello World |
delete(int start, int end) | Deletes characters in the specified range. | new StringBuffer("Programming").delete(3, 6) | Progming |
deleteCharAt(int index) | Deletes the character at the specified index. | new StringBuffer("Code").deleteCharAt(1) | Cde |
replace(int start, int end, String str) | Replaces characters in the specified range with the given string. | new StringBuffer("Java").replace(1, 3, "AI") | JAIA |
reverse() | Reverses the sequence of characters. | new StringBuffer("ChatGPT").reverse() | TPGtahC |
length() | Returns the number of characters in the buffer. | new StringBuffer("Tech").length() | 4 |
capacity() | Returns the current capacity (storage size) of the buffer. | new StringBuffer("Data").capacity() | 20 (default 16 + length of “Data”) |
setLength(int newLength) | Sets the buffer length; truncates or pads with null characters (\u0000 ). | StringBuffer sb = new StringBuffer("Hello"); sb.setLength(3); | Hel |
charAt(int index) | Returns the character at the specified index. | new StringBuffer("Java").charAt(2) | v |
substring(int start, int end) | Returns a substring of the buffer content. | new StringBuffer("StringBuffer").substring(0, 6) | String |
toString() | Converts the StringBuffer object to a String . | new StringBuffer("Learn").toString() | Learn |
5. Math – Utility for Mathematical Operations
The Math class in the java.lang package provides a collection of static methods and constants for performing common mathematical operations such as exponentiation, logarithms, trigonometric calculations, rounding, and random number generation. It is a final class, meaning it cannot be subclassed, and all its methods are static, so they can be accessed directly without creating an object. The class includes constants like Math.PI (3.14159…) and Math.E (Euler’s number) for precision-based calculations. Common methods include Math.sqrt(), Math.pow(), Math.abs(), Math.max(), Math.min(), Math.round(), and Math.random().
int max = Math.max(10, 25); // 25
double sqrt = Math.sqrt(49); // 7.0
double pow = Math.pow(2, 8); // 256.0
int abs = Math.abs(-42); // 42
Note: Most methods are static and do not require object creation.
Common Methods of the Math Class in Java
Method | Description | Example | Output |
---|---|---|---|
abs(double a) | Returns the absolute (positive) value of a number. | Math.abs(-10.5) | 10.5 |
max(a, b) | Returns the larger of two values. | Math.max(15, 20) | 20 |
min(a, b) | Returns the smaller of two values. | Math.min(15, 20) | 15 |
sqrt(double a) | Returns the square root of a value. | Math.sqrt(49) | 7.0 |
pow(double a, double b) | Returns the value of a raised to the power of b . | Math.pow(2, 3) | 8.0 |
round(double a) | Rounds the number to the nearest integer. | Math.round(5.6) | 6 |
floor(double a) | Rounds down to the nearest integer. | Math.floor(5.9) | 5.0 |
ceil(double a) | Rounds up to the nearest integer. | Math.ceil(5.1) | 6.0 |
random() | Returns a random number between 0.0 and 1.0 . | Math.random() | (e.g.,) 0.67234 |
exp(double a) | Returns Euler’s number e raised to the power of a . | Math.exp(2) | 7.389056... |
log(double a) | Returns the natural logarithm (base e) of a value. | Math.log(10) | 2.302585... |
log10(double a) | Returns the base-10 logarithm of a value. | Math.log10(100) | 2.0 |
sin(double a) | Returns the sine of an angle in radians. | Math.sin(Math.PI / 2) | 1.0 |
cos(double a) | Returns the cosine of an angle in radians. | Math.cos(0) | 1.0 |
tan(double a) | Returns the tangent of an angle in radians. | Math.tan(Math.PI / 4) | 1.0 |
toDegrees(double a) | Converts radians to degrees. | Math.toDegrees(Math.PI) | 180.0 |
toRadians(double a) | Converts degrees to radians. | Math.toRadians(180) | 3.14159... |
signum(double a) | Returns the sign of the number (-1 , 0 , or 1 ). | Math.signum(-25) | -1.0 |
cbrt(double a) | Returns the cube root of a value. | Math.cbrt(27) | 3.0 |
6. System – Interacting with the JVM
The System class in the java.lang package is one of the most important utility classes in Java, providing access to system-related functionalities such as input/output operations, environment variables, system properties, and time measurement. It cannot be instantiated because all its fields and methods are static, meaning they can be accessed directly using the class name. The System class provides streams like System.in, System.out, and System.err for reading input and printing output. It also offers useful methods such as currentTimeMillis() and nanoTime() for performance measurement, exit() for terminating the JVM, and getProperty() for retrieving system properties.
long start = System.currentTimeMillis();
// some processing
Thread.sleep(100);
long end = System.currentTimeMillis();
System.out.println(“Time taken: ” + (end – start) + “ms”);
System.out.println(“Java Version: ” + System.getProperty(“java.version”));
Tip: The System class is the backbone of Java’s runtime environment — use it for logging, measuring performance, reading system info, and controlling the JVM. However, use methods like exit() and gc() cautiously, as they directly affect the JVM lifecycle and memory management.
Common Methods of the System Class in Java
Method | Description | Example | Output / Effect |
---|---|---|---|
currentTimeMillis() | Returns the current time in milliseconds since January 1, 1970 (Unix epoch). | System.currentTimeMillis() | e.g., 1728981570000 |
nanoTime() | Returns the current time in nanoseconds, useful for measuring elapsed time precisely. | System.nanoTime() | e.g., 2398471290847 |
exit(int status) | Terminates the currently running Java Virtual Machine (JVM). A non-zero status indicates abnormal termination. | System.exit(0) | JVM terminates |
getProperty(String key) | Returns the system property indicated by the specified key. | System.getProperty("os.name") | Windows 10 |
setProperty(String key, String value) | Sets the system property to a given key-value pair. | System.setProperty("env", "production") | Sets property |
getProperties() | Returns all system properties as a Properties object. | System.getProperties() | List of system properties |
getenv(String name) | Returns the value of the specified environment variable. | System.getenv("PATH") | Returns system PATH variable |
arraycopy(Object src, int srcPos, Object dest, int destPos, int length) | Copies elements from one array to another. | System.arraycopy(arr1, 0, arr2, 0, 3) | Copies elements |
identityHashCode(Object obj) | Returns the default hash code for an object (even if hashCode() is overridden). | System.identityHashCode(obj) | e.g., 12345678 |
lineSeparator() | Returns the system-dependent line separator string (e.g., \n on Unix, \r\n on Windows). | System.lineSeparator() | New line character |
gc() | Suggests that the JVM performs garbage collection. | System.gc() | Requests garbage collection |
load(String filename) | Loads a native library (platform-dependent). | System.load("C:\\mylib.dll") | Loads native library |
loadLibrary(String libname) | Loads a library from the system library path. | System.loadLibrary("mylib") | Loads library |
err | Standard error output stream (used for error messages). | System.err.println("Error occurred!") | Prints error message |
out | Standard output stream (used for displaying results). | System.out.println("Hello, World!") | Prints message |
in | Standard input stream (used for reading input from the keyboard). | int data = System.in.read(); | Reads a byte from input |
7. Runtime – Working with the JVM
The Runtime class in the java.lang package provides a direct interface between a Java application and the Java Virtual Machine (JVM), allowing programs to interact with the system at runtime. Unlike most utility classes, Runtime follows the singleton design pattern, meaning only one instance of it exists per JVM, accessible via the Runtime.getRuntime() method. This class enables developers to perform system-level operations such as executing external commands, managing memory, and controlling the JVM’s lifecycle. Common methods include exec() for running system commands, freeMemory(), totalMemory(), and maxMemory() for monitoring memory usage, and exit() for terminating the program.
Runtime runtime = Runtime.getRuntime();
System.out.println(“Available processors: ” + runtime.availableProcessors());
System.out.println(“Free memory: ” + runtime.freeMemory());
System.out.println(“Total Memory: ” + runtime.totalMemory());
runtime.addShutdownHook(new Thread(() -> {
System.out.println(“Application is shutting down…”);
}));
Tip: The Runtime class gives developers direct access to JVM and system resources, making it powerful for performance tuning, monitoring memory usage, and executing system-level tasks. However, use methods like exec() and exit() carefully — improper use can affect system stability or application lifecycle.
Common Methods of the Runtime Class in Java
Method | Description | Example | Output / Effect |
---|---|---|---|
getRuntime() | Returns the current runtime object associated with the JVM (singleton instance). | Runtime runtime = Runtime.getRuntime(); | Returns Runtime instance |
availableProcessors() | Returns the number of available CPU cores for the JVM. | Runtime.getRuntime().availableProcessors() | e.g., 8 |
freeMemory() | Returns the amount of free memory (in bytes) available to the JVM. | Runtime.getRuntime().freeMemory() | e.g., 23456789 |
totalMemory() | Returns the total amount of memory currently available to the JVM. | Runtime.getRuntime().totalMemory() | e.g., 536870912 |
maxMemory() | Returns the maximum memory that the JVM will attempt to use. | Runtime.getRuntime().maxMemory() | e.g., 1073741824 |
gc() | Suggests that the JVM performs garbage collection to free up memory. | Runtime.getRuntime().gc(); | Requests garbage collection |
exit(int status) | Terminates the current Java Virtual Machine. A status code of 0 indicates normal termination. | Runtime.getRuntime().exit(0); | JVM terminates |
exec(String command) | Executes the specified system command in a separate process. | Runtime.getRuntime().exec("notepad"); | Opens Notepad (Windows) |
addShutdownHook(Thread hook) | Registers a thread to be executed when the JVM shuts down. | Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("JVM shutting down..."))); | Prints message before JVM shutdown |
removeShutdownHook(Thread hook) | Removes a previously registered shutdown hook thread. | Runtime.getRuntime().removeShutdownHook(hook); | Removes shutdown hook |
load(String filename) | Loads a dynamic library (e.g., .dll or .so ) specified by an absolute path. | Runtime.getRuntime().load("C:\\libexample.dll"); | Loads native library |
loadLibrary(String libname) | Loads a library from the system library path. | Runtime.getRuntime().loadLibrary("mylib"); | Loads library |
traceInstructions(boolean on) | Enables or disables instruction tracing for debugging (rarely used). | Runtime.getRuntime().traceInstructions(true); | Starts tracing instructions |
traceMethodCalls(boolean on) | Enables or disables method call tracing for debugging. | Runtime.getRuntime().traceMethodCalls(true); | Starts tracing method calls |
8. Thread
The Thread class in the java.lang package is a fundamental part of Java’s multithreading framework. It allows developers to create and manage threads — lightweight subprocesses that enable concurrent execution within a Java program. By using threads, you can perform multiple tasks simultaneously, improving application performance and responsiveness. A thread can be created either by extending the Thread class or by implementing the Runnable interface. The Thread class provides several useful methods such as start(), run(), sleep(), join(), and getName(), which help control and monitor thread behavior.
Example:
class MyThread extends Thread {
public void run() {
System.out.println(“Thread is running: ” + Thread.currentThread().getName());
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread and calls run() method
System.out.println(“Main thread: ” + Thread.currentThread().getName());
}
}
Output:
Main thread: main
Thread is running: Thread-0
In this example, the start() method launches a new thread that executes the run() method concurrently with the main thread. The Thread class is essential for implementing multitasking, background operations, and parallel processing in Java applications.
Common Methods of the Thread Class in Java
Method | Description | Example |
---|---|---|
start() | Starts the execution of a new thread by calling its run() method in a separate call stack. | Thread t = new Thread(() -> System.out.println("Running thread..."));
|
run() | Defines the code that will be executed by the thread when start() is called. | class MyThread extends Thread { |
sleep(long millis) | Makes the currently executing thread pause for the specified time in milliseconds. | Thread.sleep(1000); // Pauses for 1 second |
join() | Waits for a thread to die (i.e., completes its execution) before continuing. | t1.start();
|
getName() | Returns the name of the thread. | System.out.println(t.getName()); |
setName(String name) | Sets a custom name for a thread. | t.setName("WorkerThread"); |
getPriority() | Returns the priority of the thread (default is 5 ). | System.out.println(t.getPriority()); |
setPriority(int newPriority) | Changes the thread’s priority (range: 1–10). | t.setPriority(Thread.MAX_PRIORITY); |
isAlive() | Checks if a thread is still running. | if(t.isAlive()) System.out.println("Still running"); |
currentThread() | Returns a reference to the currently executing thread. | Thread t = Thread.currentThread(); |
interrupt() | Interrupts a thread that is sleeping or waiting. | t.interrupt(); |
isInterrupted() | Tests if the thread has been interrupted. | if(t.isInterrupted()) |
yield() | Pauses the current thread to give other threads a chance to execute. | Thread.yield(); |
9. ThreadGroup
The ThreadGroup class in the java.lang package is used to group multiple threads into a single unit for easier management and control. It allows developers to organize threads hierarchically, where each thread group can contain multiple threads as well as other thread groups. This helps in performing operations—such as setting priorities, interrupting, or listing all threads—on a group rather than managing each thread individually. The ThreadGroup class provides methods like activeCount(), activeGroupCount(), getName(), list(), and interrupt() to monitor and control the threads within a group. Although newer Java applications often prefer higher-level concurrency frameworks (like ExecutorService), ThreadGroup remains useful for debugging and managing thread hierarchies.
Example:
public class ThreadGroupExample {
public static void main(String[] args) {
// Create a new thread group
ThreadGroup group = new ThreadGroup(“MyThreadGroup”);
// Create threads and assign them to the group
Thread t1 = new Thread(group, () -> {
System.out.println(Thread.currentThread().getName() + ” is running”);
}, “Thread-1”);
Thread t2 = new Thread(group, () -> {
System.out.println(Thread.currentThread().getName() + ” is running”);
}, “Thread-2”);
// Start both threads
t1.start();
t2.start();
// Display group information
System.out.println(“Thread Group Name: ” + group.getName());
System.out.println(“Active Threads: ” + group.activeCount());
group.list(); // Lists all threads in the group
}
}
Output:
Thread-1 is running
Thread-2 is running
Thread Group Name: MyThreadGroup
Active Threads: 2
java.lang.ThreadGroup[name=MyThreadGroup,maxpri=10]
Thread[Thread-1,5,MyThreadGroup]
Thread[Thread-2,5,MyThreadGroup]
In this example, two threads are created under the MyThreadGroup group. Using the ThreadGroup object, you can easily retrieve information about all threads, control them collectively, and simplify multi-threaded management in your Java programs.
Common Methods of the ThreadGroup Class in Java
Method | Description | Example |
---|---|---|
getName() | Returns the name of the thread group. | java\nSystem.out.println(group.getName()); |
getParent() | Returns the parent thread group of the current thread group. | java\nThreadGroup parent = group.getParent(); |
activeCount() | Returns the number of active threads in the thread group. | java\nSystem.out.println(group.activeCount()); |
activeGroupCount() | Returns the number of active subgroups within the thread group. | java\nSystem.out.println(group.activeGroupCount()); |
list() | Prints information about the thread group, including threads and subgroups. | java\ngroup.list(); |
isDaemon() | Checks if the thread group is a daemon thread group. | java\nSystem.out.println(group.isDaemon()); |
setDaemon(boolean daemon) | Marks the thread group as a daemon or non-daemon group. | java\ngroup.setDaemon(true); |
getMaxPriority() | Returns the maximum priority that can be assigned to threads in the group. | java\nSystem.out.println(group.getMaxPriority()); |
setMaxPriority(int pri) | Sets the maximum priority for threads in the group. | java\ngroup.setMaxPriority(7); |
interrupt() | Interrupts all threads in the thread group. | java\ngroup.interrupt(); |
enumerate(Thread[] list) | Copies all active threads in the group into the specified array. | java\nThread[] threads = new Thread[group.activeCount()];\ngroup.enumerate(threads); |
parentOf(ThreadGroup g) | Tests if the current thread group is the parent of the specified thread group. | java\nSystem.out.println(parentGroup.parentOf(group)); |
destroy() | Destroys the thread group and all its subgroups (only if all threads have finished). | java\ngroup.destroy(); |
10. Enum – Type-Safe Constants
The Enum class in the java.lang package is the base class for all Java enumerations, introduced in Java 5 as part of the type-safe enum feature. Enums represent a fixed set of constant values, such as days of the week, directions, or user roles, making the code more readable, reliable, and easy to maintain. Every enum in Java implicitly extends the java.lang.Enum class, meaning enums cannot extend any other class but can implement interfaces. The Enum class provides useful methods such as name(), ordinal(), and valueOf() for working with enumeration constants.
Enums represent a fixed set of constants, improving readability and reducing bugs.
enum Status {
NEW, IN_PROGRESS, COMPLETED
}
public class Task {
Status status = Status.NEW;
}
Tip: Enums can have constructors, methods, and fields too.
enum Priority {
LOW(1), MEDIUM(2), HIGH(3);
private final int level;
Priority(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
}
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class EnumExample {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println(“Day: ” + today.name());
System.out.println(“Position: ” + today.ordinal());
System.out.println(“From String: ” + Day.valueOf(“FRIDAY”));
}
}
Tip: The Enum class makes Java enums powerful by providing built-in methods for name, order, comparison, and reflection-based access. Enums improve type safety, code readability, and maintainability, making them ideal for representing fixed sets of constants like statuses, roles, or configuration options in Java applications.
Common Methods of the Enum Class in Java
Method | Description | Example | Output / Effect |
---|---|---|---|
name() | Returns the name of the enum constant exactly as declared. | Day.MONDAY.name() | MONDAY |
ordinal() | Returns the position (index) of the enum constant, starting from 0. | Day.FRIDAY.ordinal() | 5 |
valueOf(Class<T> enumType, String name) | Returns the enum constant of the specified type with the given name. | Enum.valueOf(Day.class, "SUNDAY") | SUNDAY |
compareTo(E o) | Compares the order of two enum constants. | Day.MONDAY.compareTo(Day.WEDNESDAY) | -2 |
equals(Object obj) | Checks if two enum constants are equal. | Day.MONDAY.equals(Day.MONDAY) | true |
hashCode() | Returns the hash code of the enum constant. | Day.SATURDAY.hashCode() | (Integer value) |
toString() | Returns the name of the enum constant (same as name() , but can be overridden). | Day.FRIDAY.toString() | FRIDAY |
getDeclaringClass() | Returns the Class object corresponding to the enum type. | Day.MONDAY.getDeclaringClass() | class Day |
clone() | Throws CloneNotSupportedException since enums cannot be cloned. | Day.MONDAY.clone() | Throws exception |
finalize() | Prevents finalization for enums since they are constants. | (Not directly used) | (N/A) |
11. Class
The Class class in the java.lang package is one of the most powerful components of Java’s reflection mechanism. It represents the metadata of a class or interface that has been loaded into the Java Virtual Machine (JVM). Every class or interface in Java has an associated Class object that provides runtime information about that class — including its name, fields, methods, constructors, superclass, and implemented interfaces. The Class class is especially useful for frameworks, tools, and libraries that need to perform reflection, dynamic loading, or dependency injection at runtime. You can obtain a Class object in three ways: using the .class syntax, calling getClass() on an object, or using Class.forName(“className”).
Example:
public class ClassExample {
public static void main(String[] args) {
// Using .class syntax
Class<String> c1 = String.class;
System.out.println(“Class name: ” + c1.getName());
// Using getClass() method
Integer num = 10;
Class<?> c2 = num.getClass();
System.out.println(“Class name: ” + c2.getName());
// Using Class.forName()
try {
Class<?> c3 = Class.forName(“java.util.ArrayList”);
System.out.println(“Class name: ” + c3.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
Class name: java.lang.String
Class name: java.lang.Integer
Class name: java.util.ArrayList
In this example, the Class object provides runtime information about different Java classes. It serves as the backbone of reflection, enabling dynamic operations like loading classes, creating objects, and invoking methods at runtime — making Java highly flexible and extensible for modern applications.
Common Methods of the Class class in Java
Method | Description | Example |
---|---|---|
getName() | Returns the fully qualified name (package + class name) of the class. | System.out.println(String.class.getName()); // java.lang.String |
getSimpleName() | Returns only the class name without the package. | System.out.println(String.class.getSimpleName()); // String |
getPackage() | Returns the package of the class. | System.out.println(String.class.getPackage()); |
getSuperclass() | Returns the superclass of the current class. | System.out.println(Integer.class.getSuperclass()); // class java.lang.Number |
getInterfaces() | Returns an array of interfaces implemented by the class. | Class<?>[] interfaces = java.util.ArrayList.class.getInterfaces(); for(Class<?> i : interfaces) System.out.println(i.getName()); |
getMethods() | Returns all public methods of the class and its superclasses. | for(Method m : String.class.getMethods()) { |
getDeclaredMethods() | Returns all methods declared in the class (including private ones). | for(Method m : String.class.getDeclaredMethods()) { System.out.println(m.getName()); } |
getFields() | Returns all public fields of the class and its superclasses. | for(Field f : System.class.getFields()) { System.out.println(f.getName()); } |
getDeclaredFields() | Returns all fields declared in the class, including private ones. | for(Field f : System.class.getDeclaredFields()) { |
getConstructors() | Returns all public constructors of the class. | for(Constructor<?> c : String.class.getConstructors()) { System.out.println(c); } |
getDeclaredConstructors() | Returns all constructors declared in the class, including private ones. | for(Constructor<?> c : String.class.getDeclaredConstructors()) { System.out.println(c); } |
newInstance() | Creates a new instance of the class using its no-argument constructor. | Object obj = String.class.newInstance(); |
isInterface() | Checks if the class object represents an interface. | System.out.println(Runnable.class.isInterface()); // true |
isArray() | Checks if the class object represents an array type. | System.out.println(int[].class.isArray()); // true |
isPrimitive() | Checks if the class object represents a primitive type. | System.out.println(int.class.isPrimitive()); // true |
forName(String className) | Loads and returns the Class object associated with the given class name. | Class<?> cls = Class.forName("java.util.Date"); |
11. Throwable, Exception, and Error
These are the base classes for all error handling in Java.
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero!”);
}
Tip: Always catch specific exceptions before catching general Exception.
9. Wrapper Classes – Primitives as Objects
Java provides wrapper classes for all primitive types in the java.lang package.
Primitive Wrapper Class
int Integer
double Double
boolean Boolean
char Character
Integer num = Integer.valueOf(100);
Double pi = Double.parseDouble(“3.14159”);
int a = num.intValue(); // Unboxing
Tip: Autoboxing/unboxing lets you mix primitives and objects easily.
Summary
Class Name | Purpose |
Object | Root of all classes |
String | Immutable text |
StringBuilder | Mutable text |
StringBuffer | Thread-safe mutable text |
Math | Math utilities |
System | System operations |
Runtime | Runtime environment |
Thread | Threads |
ThreadGroup | Thread grouping |
Enum | Base for all enums |
Class | Reflection entry |
Throwable | Base for exceptions/errors |
Exception | Checked exceptions |
RuntimeException | Unchecked exceptions |
Error | JVM/internal errors |
Wrapper Classes: Boolean, Integer, Double, Long, Character, etc. | Object versions of primitive types |
Final Thoughts
The java.lang package provides everything you need to start building robust and efficient Java applications. Mastering these classes gives you a solid foundation and prepares you for more advanced libraries in Java.