Objects

Java java.util.Objects class consists of class methods for operating on objects. java.util.Objects utilities include null-safe or null-tolerant methods for

  • comparing two objects,
  • computing the hash code of an object,
  • requiring that a reference not be null,
  • returning a string for an object.

System.out.println("Objects.deepEquals(x, y): "+Objects.deepEquals(x, y)); // true

import java.util.Objects;

class Employee {
  private String firstName, lastName;

  Employee(String firstName, String lastName) {
      firstName = Objects.requireNonNull(firstName);
      lastName = Objects.requireNonNull(lastName, "lastName shouldn't be null");
      lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
      this.firstName = firstName;
      this.lastName = lastName;
  }

  String getName() {
    return firstName + " " + lastName;
  }

  public static void main(String[] args) {
    Employee e1 = new Employee(null, "A");
    Employee e2 = new Employee("B", null);
    Employee e3 = new Employee("C", "D");
    System.out.println(e3.getName());
  }
}
Home 
  Java Book 
    Essential Classes