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

Every class in Java implicitly extends Object. It defines key methods like toString(), equals(), hashCode(), and clone().

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.

2. String – Immutable Text

Strings are immutable, meaning their values cannot be changed once created.

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.

Converting String to Enum

 

1. Using valueOf()

 
  • Converts a string to an enum constant.
  • The string must match exactly (case-sensitive).

public class EnumValueOfExample {
  enum Direction { NORTH, SOUTH, EAST, WEST }

  public static void main(String[] args) {
    Direction d = Direction.valueOf(“EAST”);
    System.out.println(d); // EAST
  }
}

If the string doesn’t match, it throws IllegalArgumentException.

2. Custom Parsing (Safer)

 

For user input, create a custom method to handle invalid strings gracefully.

public enum Level {
  LOW, MEDIUM, HIGH;

  public static Level fromString(String str) {
    for (Level l : Level.values()) {
      if (l.name().equalsIgnoreCase(str)) {
        return l;
      }
    }
    throw new IllegalArgumentException(“Invalid Level: ” + str);
  }
}

public class EnumParseExample {
  public static void main(String[] args) {
    Level l = Level.fromString(“medium”); // works (case-insensitive)
    System.out.println(l); // MEDIUM
  }
}

Enum Utility Methods

 
  • values() → returns an array of all constants.
  • ordinal() → returns index (position) of the enum constant.

public class EnumUtilityExample {
  enum Size { SMALL, MEDIUM, LARGE }

  public static void main(String[] args) {
    for (Size s : Size.values()) {
      System.out.println(s + ” at index ” + s.ordinal());
    }
  }
}

Best Practices

 
  • Use name() for debugging/logging (guaranteed exact constant name).
  • Override toString() for user-friendly output.
  • Use valueOf() cautiously—wrap it in try-catch or use custom parsing.
  • Avoid relying on ordinal()—values may change if enum order changes.

Conclusion

 

Java provides multiple ways to convert enums to strings and back:

  • name() → exact constant name (safe, fixed).
  • toString() → customizable string representation.
  • valueOf() → converts string back to enum (case-sensitive).

By combining these methods with custom parsing, you can handle enums in a way that’s both robust and user-friendly.

Scroll to Top