Utilities
Objects Utility Class
When implementing equals(), hashCode(), or handling potentially null values, manual null checks are error-prone and verbose. The Objects utility class provides null-safe methods for these common operations, making defensive programming cleaner and more reliable.
Objects class
A utility class in java.util providing null-safe static methods for common object operations.
Null-Safe Equality
Compare objects without risking NullPointerException.
Equals.java
Replay: real traced execution (multi-file project)
// Objects.equals examples
import java.util.Objects;
public class Equals {
public static void main(String[] args) {
System.out.println("Basic equals:");
String s1 = "hello";
String s2 = "hello";
String s3 = "world";
String s4 = null;
System.out.println("s1.equals(s2): " + s1.equals(s2));
System.out.println("Objects.equals(s1, s2): " + Objects.equals(s1, s2));
System.out.println("Objects.equals(s1, s3): " + Objects.equals(s1, s3));
System.out.println("\nNull-safe equals:");
System.out.println("Objects.equals(s1, null): " + Objects.equals(s1, null));
System.out.println("Objects.equals(null, s1): " + Objects.equals(null, s1));
System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));
// This would throw NullPointerException:
// System.out.println(s4.equals(s1));
System.out.println("\nDeep equals:");
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
int[] arr3 = arr1;
System.out.println("arr1 == arr2: " + (arr1 == arr2));
System.out.println("arr1.equals(arr2): " + arr1.equals(arr2));
System.out.println("Objects.equals(arr1, arr2): " + Objects.equals(arr1, arr2));
System.out.println("Objects.deepEquals(arr1, arr2): " + Objects.deepEquals(arr1, arr2));
System.out.println("Objects.deepEquals(arr1, arr3): " + Objects.deepEquals(arr1, arr3));
System.out.println("\nCustom class equals:");
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
Person p3 = new Person("Bob", 25);
Person p4 = null;
System.out.println("p1.equals(p2): " + p1.equals(p2));
System.out.println("Objects.equals(p1, p2): " + Objects.equals(p1, p2));
System.out.println("Objects.equals(p1, p3): " + Objects.equals(p1, p3));
System.out.println("Objects.equals(p1, null): " + Objects.equals(p1, null));
System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));
System.out.println("\nComparing arrays:");
String[] names1 = {"Alice", "Bob"};
String[] names2 = {"Alice", "Bob"};
System.out.println("Arrays equal (==): " + (names1 == names2));
System.out.println("Arrays equal (equals): " + names1.equals(names2));
System.out.println("Arrays equal (Objects.equals): " + Objects.equals(names1, names2));
System.out.println("Arrays equal (Objects.deepEquals): " + Objects.deepEquals(names1, names2));
System.out.println("\n2D arrays:");
int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{1, 2}, {3, 4}};
System.out.println("Matrix equal (Objects.equals): " + Objects.equals(matrix1, matrix2));
System.out.println("Matrix equal (Objects.deepEquals): " + Objects.deepEquals(matrix1, matrix2));
System.out.println("\nIn collections:");
java.util.List<String> list1 = java.util.Arrays.asList("a", "b", "c");
java.util.List<String> list2 = java.util.Arrays.asList("a", "b", "c");
java.util.List<String> list3 = null;
System.out.println("Lists equal: " + Objects.equals(list1, list2));
System.out.println("List vs null: " + Objects.equals(list1, null));
System.out.println("Null lists: " + Objects.equals(list3, null));
}
static class Person {
String name;
int age;
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 other = (Person) obj;
return age == other.age && Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
}
s1 ← hello, s2 ← hello, s3 ← world, s4 ← null
5public class Equals {6 public static void main(String[] args) {7 System.out.println("Basic equals:");89 String s1→ hello = "hello";10 String s2→ hello = "hello";11 String s3→ world = "world";12 String s4→ null = null;1314 System.out.println("s1.equals(s2): " + s1.equals(s2hello));15 System.out.println("Objects.equals(s1, s2): " + Objects.equals(s1hello, s2hello));16 System.out.println("Objects.equals(s1, s3): " + Objects.equals(s1hello, s3world));17 System.out.println("\nNull-safe equals:");1819 System.out.println("Objects.equals(s1, null): " + Objects.equals(s1hello, null));20 System.out.println("Objects.equals(null, s1): " + Objects.equals(null, s1hello));21 System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));2223 // This would throw NullPointerException:24 // System.out.println(s4.equals(s1));25 System.out.println("\nDeep equals:");2627 int[] arr1 = {1, 2, 3};28 int[] arr2 = {1, 2, 3};29 int[] arr3 = arr1;3031 System.out.println("arr1 == arr2: " + (arr1 == arr2));32 System.out.println("arr1.equals(arr2): " + arr1.equals(arr2));33 System.out.println("Objects.equals(arr1, arr2): " + Objects.equals(arr1, arr2));34 System.out.println("Objects.deepEquals(arr1, arr2): " + Objects.deepEquals(arr1, arr2));35 System.out.println("Objects.deepEquals(arr1, arr3): " + Objects.deepEquals(arr1, arr3));36 System.out.println("\nCustom class equals:");3738 Person p1 = new Person("Alice", 30);39 Person p2 = new Person("Alice", 30);outputBasic equals: s1.equals(s2): true Objects.equals(s1, s2): true Objects.equals(s1, s3): false Null-safe equals: Objects.equals(s1, null): false Objects.equals(null, s1): false Objects.equals(null, null): true Deep equals: arr1 == arr2: false arr1.equals(arr2): false Objects.equals(arr1, arr2): false Objects.deepEquals(arr1, arr2): true Objects.deepEquals(arr1, arr3): true Custom class equals:this.name ← Alice, this.age ← 30, p1 ← ⟨Equals$Person A⟩
pass 1 of 338 Person p1→ ⟨Equals$Person A⟩ = new Person("Alice", 30);39 Person p2 = new Person("Alice", 30);40 Person p3 = new Person("Bob", 25);41 Person p4 = null;4243 System.out.println("p1.equals(p2): " + p1.equals(p2));44 System.out.println("Objects.equals(p1, p2): " + Objects.equals(p1, p2));45 System.out.println("Objects.equals(p1, p3): " + Objects.equals(p1, p3));46 System.out.println("Objects.equals(p1, null): " + Objects.equals(p1, null));47 System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));48 System.out.println("\nComparing arrays:");4950 String[] names1 = {"Alice", "Bob"};51 String[] names2 = {"Alice", "Bob"};5253 System.out.println("Arrays equal (==): " + (names1 == names2));54 System.out.println("Arrays equal (equals): " + names1.equals(names2));55 System.out.println("Arrays equal (Objects.equals): " + Objects.equals(names1, names2));56 System.out.println("Arrays equal (Objects.deepEquals): " + Objects.deepEquals(names1, names2));57 System.out.println("\n2D arrays:");5859 int[][] matrix1 = {{1, 2}, {3, 4}};60 int[][] matrix2 = {{1, 2}, {3, 4}};6162 System.out.println("Matrix equal (Objects.equals): " + Objects.equals(matrix1, matrix2));63 System.out.println("Matrix equal (Objects.deepEquals): " + Objects.deepEquals(matrix1, matrix2));64 System.out.println("\nIn collections:");6566 java.util.List<String> list1 = java.util.Arrays.asList("a", "b", "c");67 java.util.List<String> list2 = java.util.Arrays.asList("a", "b", "c");68 java.util.List<String> list3 = null;6970 System.out.println("Lists equal: " + Objects.equals(list1, list2));71 System.out.println("List vs null: " + Objects.equals(list1, null));72 System.out.println("Null lists: " + Objects.equals(list3, null));73}7475static class Person {76 String name;77 int age;7879 Person(String nameAlice, int age30) {80 this.name→ Alice = nameAlice;81 this.age→ 30 = age30;82 }All 3 passes — pass 1 is the card above pass nameagethis.namethis.agep1p2p3p4list1list2list31 Alice 30 Alice 30 ⟨Equals$Person A⟩ — — — — — — 2 Alice 30 Alice 30 — ⟨Equals$Person A⟩ — — — — — 3 Bob 25 Bob 25 ⟨Equals$Person A⟩ ⟨Equals$Person A⟩ ⟨Equals$Person B⟩ null [a, b, c] [a, b, c] null
Null-safe comparison
Objects.equals(a, b) handles null values gracefully, returning true if both are null and false if only one is null.
Hash Code Generation
Generate consistent hash codes for multiple fields.
Hash.java
Replay: real traced execution (multi-file project)
// Objects.hash examples
import java.util.Objects;
import java.util.Arrays;
public class Hash {
public static void main(String[] args) {
System.out.println("Basic hash:");
String s1 = "hello";
String s2 = "world";
System.out.println("s1.hashCode(): " + s1.hashCode());
System.out.println("Objects.hashCode(s1): " + Objects.hashCode(s1));
System.out.println("Objects.hashCode(null): " + Objects.hashCode(null));
System.out.println("\nMultiple values:");
int hash1 = Objects.hash("Alice", 30);
int hash2 = Objects.hash("Alice", 30);
int hash3 = Objects.hash("Bob", 30);
int hash4 = Objects.hash("Alice", 25);
System.out.println("hash('Alice', 30): " + hash1);
System.out.println("hash('Alice', 30): " + hash2);
System.out.println("Same? " + (hash1 == hash2));
System.out.println("hash('Bob', 30): " + hash3);
System.out.println("hash('Alice', 25): " + hash4);
System.out.println("\nCustom class:");
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
Person p3 = new Person("Bob", 25);
System.out.println("p1.hashCode(): " + p1.hashCode());
System.out.println("p2.hashCode(): " + p2.hashCode());
System.out.println("p3.hashCode(): " + p3.hashCode());
System.out.println("p1 == p2 hashCode? " + (p1.hashCode() == p2.hashCode()));
System.out.println("\nIn HashMap:");
java.util.Map<Person, String> map = new java.util.HashMap<>();
map.put(new Person("Alice", 30), "Engineer");
map.put(new Person("Bob", 25), "Designer");
System.out.println("Get Alice: " + map.get(new Person("Alice", 30)));
System.out.println("Get Bob: " + map.get(new Person("Bob", 25)));
System.out.println("\nHash with nulls:");
int h1 = Objects.hash("Alice", null, 30);
int h2 = Objects.hash("Alice", null, 30);
int h3 = Objects.hash(null, null, null);
System.out.println("hash('Alice', null, 30): " + h1);
System.out.println("hash('Alice', null, 30): " + h2);
System.out.println("Same? " + (h1 == h2));
System.out.println("hash(null, null, null): " + h3);
System.out.println("\nPoint class:");
Point pt1 = new Point(10, 20);
Point pt2 = new Point(10, 20);
Point pt3 = new Point(20, 10);
System.out.println("pt1: " + pt1 + " hash=" + pt1.hashCode());
System.out.println("pt2: " + pt2 + " hash=" + pt2.hashCode());
System.out.println("pt3: " + pt3 + " hash=" + pt3.hashCode());
System.out.println("\nHashSet usage:");
java.util.Set<Point> points = new java.util.HashSet<>();
points.add(new Point(1, 2));
points.add(new Point(3, 4));
points.add(new Point(1, 2)); // Duplicate
System.out.println("Set size: " + points.size());
System.out.println("Contains (1,2)? " + points.contains(new Point(1, 2)));
System.out.println("\nRecord class:");
Rectangle r1 = new Rectangle(10, 20);
Rectangle r2 = new Rectangle(10, 20);
Rectangle r3 = new Rectangle(20, 10);
System.out.println("r1 hash: " + r1.hashCode());
System.out.println("r2 hash: " + r2.hashCode());
System.out.println("r3 hash: " + r3.hashCode());
System.out.println("r1.equals(r2)? " + r1.equals(r2));
}
static class Person {
String name;
int age;
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 other = (Person) obj;
return age == other.age && Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Point)) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
static class Rectangle {
int width, height;
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Rectangle)) return false;
Rectangle r = (Rectangle) obj;
return width == r.width && height == r.height;
}
@Override
public int hashCode() {
return Objects.hash(width, height);
}
}
}
s1 ← hello, s2 ← world, hash1 ← 1963862399, hash2 ← 1963862399
6public class Hash {7 public static void main(String[] args) {8 System.out.println("Basic hash:");910 String s1→ hello = "hello";11 String s2→ world = "world";1213 System.out.println("s1.hashCode(): " + s1.hashCode());14 System.out.println("Objects.hashCode(s1): " + Objects.hashCode(s1hello));15 System.out.println("Objects.hashCode(null): " + Objects.hashCode(null));16 System.out.println("\nMultiple values:");1718 int hash1→ 1963862399 = Objects.hash("Alice", 30);19 int hash2→ 1963862399 = Objects.hash("Alice", 30);20 int hash3→ 2076906 = Objects.hash("Bob", 30);21 int hash4→ 1963862394 = Objects.hash("Alice", 25);2223 System.out.println("hash('Alice', 30): " + hash11963862399);24 System.out.println("hash('Alice', 30): " + hash21963862399);25 System.out.println("Same? " + (hash11963862399 == hash21963862399));26 System.out.println("hash('Bob', 30): " + hash32076906);27 System.out.println("hash('Alice', 25): " + hash41963862394);28 System.out.println("\nCustom class:");2930 Person p1 = new Person("Alice", 30);31 Person p2 = new Person("Alice", 30);outputBasic hash: s1.hashCode(): 99162322 Objects.hashCode(s1): 99162322 Objects.hashCode(null): 0 Multiple values: hash('Alice', 30): 1963862399 hash('Alice', 30): 1963862399 Same? true hash('Bob', 30): 2076906 hash('Alice', 25): 1963862394 Custom class:this.name ← Alice, this.age ← 30, p1 ← ⟨Hash$Person A⟩
pass 1 of 730 Person p1→ ⟨Hash$Person A⟩ = new Person("Alice", 30);31 Person p2 = new Person("Alice", 30);32 Person p3 = new Person("Bob", 25);3334 System.out.println("p1.hashCode(): " + p1.hashCode());35 System.out.println("p2.hashCode(): " + p2.hashCode());36 System.out.println("p3.hashCode(): " + p3.hashCode());37 System.out.println("p1 == p2 hashCode? " + (p1.hashCode() == p2.hashCode()));38 System.out.println("\nIn HashMap:");3940 java.util.Map<Person, String> map = new java.util.HashMap<>();4142 map.put(new Person("Alice", 30), "Engineer");43 map.put(new Person("Bob", 25), "Designer");4445 System.out.println("Get Alice: " + map.get(new Person("Alice", 30)));46 System.out.println("Get Bob: " + map.get(new Person("Bob", 25)));47 System.out.println("\nHash with nulls:");4849 int h1 = Objects.hash("Alice", null, 30);50 int h2 = Objects.hash("Alice", null, 30);51 int h3 = Objects.hash(null, null, null);5253 System.out.println("hash('Alice', null, 30): " + h1);54 System.out.println("hash('Alice', null, 30): " + h2);55 System.out.println("Same? " + (h1 == h2));56 System.out.println("hash(null, null, null): " + h3);57 System.out.println("\nPoint class:");5859 Point pt1 = new Point(10, 20);60 Point pt2 = new Point(10, 20);61 Point pt3 = new Point(20, 10);6263 System.out.println("pt1: " + pt1 + " hash=" + pt1.hashCode());64 System.out.println("pt2: " + pt2 + " hash=" + pt2.hashCode());65 System.out.println("pt3: " + pt3 + " hash=" + pt3.hashCode());66 System.out.println("\nHashSet usage:");6768 java.util.Set<Point> points = new java.util.HashSet<>();69 points.add(new Point(1, 2));70 points.add(new Point(3, 4));71 points.add(new Point(1, 2)); // Duplicate7273 System.out.println("Set size: " + points.size());74 System.out.println("Contains (1,2)? " + points.contains(new Point(1, 2)));75 System.out.println("\nRecord class:");7677 Rectangle r1 = new Rectangle(10, 20);78 Rectangle r2 = new Rectangle(10, 20);79 Rectangle r3 = new Rectangle(20, 10);8081 System.out.println("r1 hash: " + r1.hashCode());82 System.out.println("r2 hash: " + r2.hashCode());83 System.out.println("r3 hash: " + r3.hashCode());84 System.out.println("r1.equals(r2)? " + r1.equals(r2));85}8687static class Person {88 String name;89 int age;9091 Person(String nameAlice, int age30) {92 this.name→ Alice = nameAlice;93 this.age→ 30 = age30;94 }All 7 passes — pass 1 is the card above pass nameagethis.namethis.agep1p2p3maph1h2h31 Alice 30 Alice 30 ⟨Hash$Person A⟩ — — — — — — 2 Alice 30 Alice 30 — ⟨Hash$Person A⟩ — — — — — 3 Bob 25 Bob 25 — — ⟨Hash$Person B⟩ {} — — — 4 Alice 30 Alice 30 — — — — — — — 5 Bob 25 Bob 25 — — — — — — — 6 Alice 30 Alice 30 — — — — — — — 7 Bob 25 Bob 25 — — — — 750191325 750191325 29791 this.x ← 10, this.y ← 20, pt1 ← (10,20)
pass 1 of 759 Point pt1→ (10,20) = new Point(10, 20);60 Point pt2 = new Point(10, 20);61 Point pt3 = new Point(20, 10);6263 System.out.println("pt1: " + pt1 + " hash=" + pt1.hashCode());64 System.out.println("pt2: " + pt2 + " hash=" + pt2.hashCode());65 System.out.println("pt3: " + pt3 + " hash=" + pt3.hashCode());66 System.out.println("\nHashSet usage:");6768 java.util.Set<Point> points = new java.util.HashSet<>();69 points.add(new Point(1, 2));70 points.add(new Point(3, 4));71 points.add(new Point(1, 2)); // Duplicate7273 System.out.println("Set size: " + points.size());74 System.out.println("Contains (1,2)? " + points.contains(new Point(1, 2)));75 System.out.println("\nRecord class:");7677 Rectangle r1 = new Rectangle(10, 20);78 Rectangle r2 = new Rectangle(10, 20);79 Rectangle r3 = new Rectangle(20, 10);8081 System.out.println("r1 hash: " + r1.hashCode());82 System.out.println("r2 hash: " + r2.hashCode());83 System.out.println("r3 hash: " + r3.hashCode());84 System.out.println("r1.equals(r2)? " + r1.equals(r2));85}8687static class Person {88 String name;89 int age;9091 Person(String name, int age) {92 this.name = name;93 this.age = age;94 }9596 @Override97 public boolean equals(Object obj) {98 if (this == obj) return true;99 if (obj == null || getClass() != obj.getClass()) return false;100 Person other = (Person) obj;101 return age == other.age && Objects.equals(name, other.name);102 }103104 @Override105 public int hashCode() {106 return Objects.hash(name, age);107 }108}109110static class Point {111 int x, y;112113 Point(int x10, int y20) {114 this.x→ 10 = x10;115 this.y→ 20 = y20;116 }All 7 passes — pass 1 is the card above pass xythis.xthis.ypt1pt2pt3points1 10 20 10 20 (10,20) — — — 2 10 20 10 20 — (10,20) — — 3 20 10 20 10 (10,20) (10,20) (20,10) [] 4 1 2 1 2 — — — — 5 3 4 3 4 — — — — 6 1 2 1 2 — — — — 7 1 2 1 2 — — — — this.width ← 10, this.height ← 20, r1 ← Hash$Rectangle@50b
pass 1 of 377 Rectangle r1→ Hash$Rectangle@50b = new Rectangle(10, 20);78 Rectangle r2 = new Rectangle(10, 20);79 Rectangle r3 = new Rectangle(20, 10);8081 System.out.println("r1 hash: " + r1.hashCode());82 System.out.println("r2 hash: " + r2.hashCode());83 System.out.println("r3 hash: " + r3.hashCode());84 System.out.println("r1.equals(r2)? " + r1.equals(r2));85}8687static class Person {88 String name;89 int age;9091 Person(String name, int age) {92 this.name = name;93 this.age = age;94 }9596 @Override97 public boolean equals(Object obj) {98 if (this == obj) return true;99 if (obj == null || getClass() != obj.getClass()) return false;100 Person other = (Person) obj;101 return age == other.age && Objects.equals(name, other.name);102 }103104 @Override105 public int hashCode() {106 return Objects.hash(name, age);107 }108}109110static class Point {111 int x, y;112113 Point(int x, int y) {114 this.x = x;115 this.y = y;116 }117118 @Override119 public boolean equals(Object obj) {120 if (this == obj) return true;121 if (!(obj instanceof Point)) return false;122 Point other = (Point) obj;123 return x == other.x && y == other.y;124 }125126 @Override127 public int hashCode() {128 return Objects.hash(x, y);129 }130131 @Override132 public String toString() {133 return "(" + x + "," + y + ")";134 }135}136137static class Rectangle {138 int width, height;139140 Rectangle(int width10, int height20) {141 this.width→ 10 = width10;142 this.height→ 20 = height20;143 }All 3 passes — pass 1 is the card above pass widthheightthis.widththis.heightr1r2r31 10 20 10 20 Hash$Rectangle@50b — — 2 10 20 10 20 — Hash$Rectangle@50b — 3 20 10 20 10 — Hash$Rectangle@50b Hash$Rectangle@637
Combined hash
Objects.hash() combines multiple fields into a single hash code, ideal for implementing hashCode() in classes with multiple fields.
Null Validation
Enforce non-null requirements with clear error messages.
Require.java
Replay: real traced execution (multi-file project)
// Objects.requireNonNull examples
import java.util.Objects;
public class Require {
public static void main(String[] args) {
System.out.println("Basic requireNonNull:");
String valid = "hello";
String invalid = null;
String result = Objects.requireNonNull(valid);
System.out.println("Valid: " + result);
try {
Objects.requireNonNull(invalid);
} catch (NullPointerException e) {
System.out.println("Caught NPE: " + e.getMessage());
}
System.out.println("\nWith message:");
try {
Objects.requireNonNull(null, "Value must not be null");
} catch (NullPointerException e) {
System.out.println("Message: " + e.getMessage());
}
System.out.println("\nConstructor validation:");
try {
Person p1 = new Person("Alice", 30);
System.out.println("Created: " + p1);
Person p2 = new Person(null, 25);
} catch (NullPointerException e) {
System.out.println("Constructor failed: " + e.getMessage());
}
System.out.println("\nMethod parameters:");
EmailSender sender = new EmailSender();
try {
sender.send("user@example.com", "Hello", "Welcome!");
System.out.println("Email sent successfully");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
try {
sender.send(null, "Hello", "Welcome!");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
System.out.println("\nSupplier message:");
String userId = null;
try {
Objects.requireNonNull(userId, () ->
"User ID is required but was null in this request");
System.out.println("User ID: " + userId);
} catch (NullPointerException e) {
System.out.println("Lazy message: " + e.getMessage());
}
System.out.println("\nChain validation:");
Config config = new Config("localhost", 8080, "/api");
System.out.println("Config: " + config);
try {
new Config(null, 8080, "/api");
} catch (NullPointerException e) {
System.out.println("Host required: " + e.getMessage());
}
System.out.println("\nReturn value validation:");
UserService service = new UserService();
User user = service.findUser("alice");
System.out.println("Found: " + user);
try {
service.findUser("unknown");
} catch (NullPointerException e) {
System.out.println("Not found: " + e.getMessage());
}
System.out.println("\nDefensive copy:");
String[] items = {"a", "b", "c"};
Container c1 = new Container(items);
System.out.println("Container: " + c1);
try {
new Container(null);
} catch (NullPointerException e) {
System.out.println("Null array: " + e.getMessage());
}
}
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = Objects.requireNonNull(name, "Name must not be null");
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
static class EmailSender {
void send(String to, String subject, String body) {
Objects.requireNonNull(to, "Recipient must not be null");
Objects.requireNonNull(subject, "Subject must not be null");
Objects.requireNonNull(body, "Body must not be null");
// Send email...
}
}
static class Config {
String host;
int port;
String path;
Config(String host, int port, String path) {
this.host = Objects.requireNonNull(host, "Host required");
this.port = port;
this.path = Objects.requireNonNull(path, "Path required");
}
@Override
public String toString() {
return host + ":" + port + path;
}
}
static class UserService {
User findUser(String id) {
Objects.requireNonNull(id, "User ID required");
if ("alice".equals(id)) {
return new User("alice", "Alice");
}
throw new NullPointerException("User not found: " + id);
}
}
static class User {
String id;
String name;
User(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return name + " (id=" + id + ")";
}
}
static class Container {
String[] items;
Container(String[] items) {
this.items = Objects.requireNonNull(items, "Items array required")
.clone(); // Defensive copy
}
@Override
public String toString() {
return java.util.Arrays.toString(items);
}
}
}
// Objects.requireNonNull examples
import java.util.Objects;
public class Require {
public static void main(String[] args) {
System.out.println("Basic requireNonNull:");
String valid = "hello";
String invalid = null;
String result = Objects.requireNonNull(valid);
System.out.println("Valid: " + result);
try {
Objects.requireNonNull(invalid);
} catch (NullPointerException e) {
System.out.println("Caught NPE: " + e.getMessage());
}
System.out.println("\nWith message:");
try {
Objects.requireNonNull(null, "Value must not be null");
} catch (NullPointerException e) {
System.out.println("Message: " + e.getMessage());
}
System.out.println("\nConstructor validation:");
try {
Person p1 = new Person("Alice", 30);
System.out.println("Created: " + p1);
Person p2 = new Person(null, 25);
} catch (NullPointerException e) {
System.out.println("Constructor failed: " + e.getMessage());
}
System.out.println("\nMethod parameters:");
EmailSender sender = new EmailSender();
try {
sender.send("user@example.com", "Hello", "Welcome!");
System.out.println("Email sent successfully");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
try {
sender.send(null, "Hello", "Welcome!");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
System.out.println("\nSupplier message:");
String userId = "alice";
try {
Objects.requireNonNull(userId, () ->
"User ID is required but was null in this request");
System.out.println("User ID: " + userId);
} catch (NullPointerException e) {
System.out.println("Lazy message: " + e.getMessage());
}
System.out.println("\nChain validation:");
Config config = new Config("localhost", 8080, "/api");
System.out.println("Config: " + config);
try {
new Config(null, 8080, "/api");
} catch (NullPointerException e) {
System.out.println("Host required: " + e.getMessage());
}
System.out.println("\nReturn value validation:");
UserService service = new UserService();
User user = service.findUser("alice");
System.out.println("Found: " + user);
try {
service.findUser("unknown");
} catch (NullPointerException e) {
System.out.println("Not found: " + e.getMessage());
}
System.out.println("\nDefensive copy:");
String[] items = {"a", "b", "c"};
Container c1 = new Container(items);
System.out.println("Container: " + c1);
try {
new Container(null);
} catch (NullPointerException e) {
System.out.println("Null array: " + e.getMessage());
}
}
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = Objects.requireNonNull(name, "Name must not be null");
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
static class EmailSender {
void send(String to, String subject, String body) {
Objects.requireNonNull(to, "Recipient must not be null");
Objects.requireNonNull(subject, "Subject must not be null");
Objects.requireNonNull(body, "Body must not be null");
// Send email...
}
}
static class Config {
String host;
int port;
String path;
Config(String host, int port, String path) {
this.host = Objects.requireNonNull(host, "Host required");
this.port = port;
this.path = Objects.requireNonNull(path, "Path required");
}
@Override
public String toString() {
return host + ":" + port + path;
}
}
static class UserService {
User findUser(String id) {
Objects.requireNonNull(id, "User ID required");
if ("alice".equals(id)) {
return new User("alice", "Alice");
}
throw new NullPointerException("User not found: " + id);
}
}
static class User {
String id;
String name;
User(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return name + " (id=" + id + ")";
}
}
static class Container {
String[] items;
Container(String[] items) {
this.items = Objects.requireNonNull(items, "Items array required")
.clone(); // Defensive copy
}
@Override
public String toString() {
return java.util.Arrays.toString(items);
}
}
}
// Objects.requireNonNull examples
import java.util.Objects;
public class Require {
public static void main(String[] args) {
System.out.println("Basic requireNonNull:");
String valid = "hello";
String invalid = null;
String result = Objects.requireNonNull(valid);
System.out.println("Valid: " + result);
try {
Objects.requireNonNull(invalid);
} catch (NullPointerException e) {
System.out.println("Caught NPE: " + e.getMessage());
}
System.out.println("\nWith message:");
try {
Objects.requireNonNull(null, "Value must not be null");
} catch (NullPointerException e) {
System.out.println("Message: " + e.getMessage());
}
System.out.println("\nConstructor validation:");
try {
Person p1 = new Person("Alice", 30);
System.out.println("Created: " + p1);
Person p2 = new Person(null, 25);
} catch (NullPointerException e) {
System.out.println("Constructor failed: " + e.getMessage());
}
System.out.println("\nMethod parameters:");
EmailSender sender = new EmailSender();
try {
sender.send("user@example.com", "Hello", "Welcome!");
System.out.println("Email sent successfully");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
try {
sender.send(null, "Hello", "Welcome!");
} catch (NullPointerException e) {
System.out.println("Failed: " + e.getMessage());
}
System.out.println("\nSupplier message:");
String userId = "guest";
try {
Objects.requireNonNull(userId, () ->
"User ID is required but was null in this request");
System.out.println("User ID: " + userId);
} catch (NullPointerException e) {
System.out.println("Lazy message: " + e.getMessage());
}
System.out.println("\nChain validation:");
Config config = new Config("localhost", 8080, "/api");
System.out.println("Config: " + config);
try {
new Config(null, 8080, "/api");
} catch (NullPointerException e) {
System.out.println("Host required: " + e.getMessage());
}
System.out.println("\nReturn value validation:");
UserService service = new UserService();
User user = service.findUser("alice");
System.out.println("Found: " + user);
try {
service.findUser("unknown");
} catch (NullPointerException e) {
System.out.println("Not found: " + e.getMessage());
}
System.out.println("\nDefensive copy:");
String[] items = {"a", "b", "c"};
Container c1 = new Container(items);
System.out.println("Container: " + c1);
try {
new Container(null);
} catch (NullPointerException e) {
System.out.println("Null array: " + e.getMessage());
}
}
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = Objects.requireNonNull(name, "Name must not be null");
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
static class EmailSender {
void send(String to, String subject, String body) {
Objects.requireNonNull(to, "Recipient must not be null");
Objects.requireNonNull(subject, "Subject must not be null");
Objects.requireNonNull(body, "Body must not be null");
// Send email...
}
}
static class Config {
String host;
int port;
String path;
Config(String host, int port, String path) {
this.host = Objects.requireNonNull(host, "Host required");
this.port = port;
this.path = Objects.requireNonNull(path, "Path required");
}
@Override
public String toString() {
return host + ":" + port + path;
}
}
static class UserService {
User findUser(String id) {
Objects.requireNonNull(id, "User ID required");
if ("alice".equals(id)) {
return new User("alice", "Alice");
}
throw new NullPointerException("User not found: " + id);
}
}
static class User {
String id;
String name;
User(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return name + " (id=" + id + ")";
}
}
static class Container {
String[] items;
Container(String[] items) {
this.items = Objects.requireNonNull(items, "Items array required")
.clone(); // Defensive copy
}
@Override
public String toString() {
return java.util.Arrays.toString(items);
}
}
}
valid ← hello, invalid ← null, result ← hello
5public class Require {6 public static void main(String[] args) {7 System.out.println("Basic requireNonNull:");89 String valid→ hello = "hello";10 String invalid→ null = null;1112 String result→ hello = Objects.requireNonNull(validhello);13 System.out.println("Valid: " + resulthello);outputBasic requireNonNull: Valid: hellotry
15try {16 Objects.requireNonNull(invalidnull);17} catch (NullPointerException e) {catch (NullPointerException e)
16 Objects.requireNonNull(invalid);17} catch (NullPointerException ejava.lang.NullPointerException) {18 System.out.println("Caught NPE: " + e.getMessage());19}outputCaught NPE: nullSystem.out.println(" With message:");
19}20System.out.println("\nWith message:");output With message:catch (NullPointerException e)
23 Objects.requireNonNull(null, "Value must not be null");24} catch (NullPointerException ejava.lang.NullPointerException: Value must not be null) {25 System.out.println("Message: " + e.getMessage());26}outputMessage: Value must not be nullSystem.out.println(" Constructor validation:");
26}27System.out.println("\nConstructor validation:");output Constructor validation:this.name ← Alice, this.age ← 30, p1 ← Alice (30)
pass 1 of 229 try {30 Person p1→ Alice (30) = new Person("Alice", 30);31 System.out.println("Created: " + p1Alice (30));3233 Person p2 = new Person(null, 25);34 } catch (NullPointerException e) {35 System.out.println("Constructor failed: " + e.getMessage());36 }37 System.out.println("\nMethod parameters:");3839 EmailSender sender = new EmailSender();4041 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = null; //@userId="alice", "guest"5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String nameAlice, int age30) {104 this.name→ Alice = Objects.requireNonNull(nameAlice, "Name must not be null");105 this.age→ 30 = age30;106 }outputCreated: Alice (30)Person(String name, int age)
pass 2 of 2103Person(String namenull, int age25) {104 this.name = Objects.requireNonNull(namenull, "Name must not be null");105 this.age = age;catch (NullPointerException e)
33 Person p2 = new Person(null, 25);34} catch (NullPointerException ejava.lang.NullPointerException: Name must not be null) {35 System.out.println("Constructor failed: " + e.getMessage());36}outputConstructor failed: Name must not be nullsender ← ⟨Require$EmailSender A⟩
36}37System.out.println("\nMethod parameters:");3839EmailSender sender→ ⟨Require$EmailSender A⟩ = new EmailSender();output Method parameters:void send(String to, String subject, String body)
pass 1 of 241 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = null; //@userId="alice", "guest"5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(touser@example.com, "Recipient must not be null");117 Objects.requireNonNull(subjectHello, "Subject must not be null");118 Objects.requireNonNull(bodyWelcome!, "Body must not be null");119 // Send email...outputEmail sent successfullyvoid send(String to, String subject, String body)
pass 2 of 2114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(tonull, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");catch (NullPointerException e)
49 sender.send(null, "Hello", "Welcome!");50} catch (NullPointerException ejava.lang.NullPointerException: Recipient must not be null) {51 System.out.println("Failed: " + e.getMessage());52}outputFailed: Recipient must not be nulluserId ← null
52}53System.out.println("\nSupplier message:");5455String userId→ null = null; //@userId="alice", "guest"output Supplier message:try
57try {58 Objects.requireNonNull(userIdnull, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);catch (NullPointerException e)
60 System.out.println("User ID: " + userId);61} catch (NullPointerException ejava.lang.NullPointerException: User ID is required but was null in this request) {62 System.out.println("Lazy message: " + e.getMessage());63}outputLazy message: User ID is required but was null in this requestSystem.out.println(" Chain validation:");
63}64System.out.println("\nChain validation:");6566Config config = new Config("localhost", 8080, "/api");67System.out.println("Config: " + config);output Chain validation:this.host ← localhost, this.port ← 8080, this.path ← /api, config ← localhost:8080/api
pass 1 of 266 Config config→ localhost:8080/api = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + configlocalhost:8080/api);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String hostlocalhost, int port8080, String path/api) {129 this.host→ localhost = Objects.requireNonNull(hostlocalhost, "Host required");130 this.port→ 8080 = port8080;131 this.path→ /api = Objects.requireNonNull(path/api, "Path required");132 }outputConfig: localhost:8080/apiConfig(String host, int port, String path)
pass 2 of 2128Config(String hostnull, int port8080, String path/api) {129 this.host = Objects.requireNonNull(hostnull, "Host required");130 this.port = port;catch (NullPointerException e)
70 new Config(null, 8080, "/api");71} catch (NullPointerException ejava.lang.NullPointerException: Host required) {72 System.out.println("Host required: " + e.getMessage());73}outputHost required: Host requiredservice ← ⟨Require$UserService B⟩
73}74System.out.println("\nReturn value validation:");7576UserService service→ ⟨Require$UserService B⟩ = new UserService();7778User user = service.findUser("alice");79System.out.println("Found: " + user);output Return value validation:User findUser(String id)
pass 1 of 2140static class UserService {141 User findUser(String idalice) {142 Objects.requireNonNull(idalice, "User ID required");if ("alice".equals(id))
144if ("alice".equals(idalice)) {145 return new User("alice", "Alice");146}this.id ← alice, this.name ← Alice, user ← Alice (id=alice)
78 User user→ Alice (id=alice) = service.findUser("alice");79 System.out.println("Found: " + userAlice (id=alice));8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String idalice, String nameAlice) {157 this.id→ alice = idalice;158 this.name→ Alice = nameAlice;159 }outputFound: Alice (id=alice)User findUser(String id)
pass 2 of 2140static class UserService {141 User findUser(String idunknown) {142 Objects.requireNonNull(idunknown, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }catch (NullPointerException e)
82 service.findUser("unknown");83} catch (NullPointerException ejava.lang.NullPointerException: User not found: unknown) {84 System.out.println("Not found: " + e.getMessage());85}outputNot found: User not found: unknownString[] items = {"a", "b", "c"};
85}86System.out.println("\nDefensive copy:");8788String[] items = {"a", "b", "c"};89Container c1 = new Container(items);90System.out.println("Container: " + c1);output Defensive copy:c1 ← [a, b, c]
pass 1 of 288 String[] items = {"a", "b", "c"};89 Container c1→ [a, b, c] = new Container(items);90 System.out.println("Container: " + c1[a, b, c]);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String id, String name) {157 this.id = id;158 this.name = name;159 }160161 @Override162 public String toString() {163 return name + " (id=" + id + ")";164 }165}166167static class Container {168 String[] items;169170 Container(String[] items) {171 this.items = Objects.requireNonNull(items, "Items array required")172 .clone(); // Defensive copy173 }outputContainer: [a, b, c]Container(String[] items)
pass 2 of 2170Container(String[] itemsnull) {171 this.items = Objects.requireNonNull(itemsnull, "Items array required")172 .clone(); // Defensive copy173}catch (NullPointerException e)
93 new Container(null);94} catch (NullPointerException ejava.lang.NullPointerException: Items array required) {95 System.out.println("Null array: " + e.getMessage());96}outputNull array: Items array required
valid ← hello, invalid ← null, result ← hello
5public class Require {6 public static void main(String[] args) {7 System.out.println("Basic requireNonNull:");89 String valid→ hello = "hello";10 String invalid→ null = null;1112 String result→ hello = Objects.requireNonNull(validhello);13 System.out.println("Valid: " + resulthello);outputBasic requireNonNull: Valid: hellotry
15try {16 Objects.requireNonNull(invalidnull);17} catch (NullPointerException e) {catch (NullPointerException e)
16 Objects.requireNonNull(invalid);17} catch (NullPointerException ejava.lang.NullPointerException) {18 System.out.println("Caught NPE: " + e.getMessage());19}outputCaught NPE: nullSystem.out.println(" With message:");
19}20System.out.println("\nWith message:");output With message:catch (NullPointerException e)
23 Objects.requireNonNull(null, "Value must not be null");24} catch (NullPointerException ejava.lang.NullPointerException: Value must not be null) {25 System.out.println("Message: " + e.getMessage());26}outputMessage: Value must not be nullSystem.out.println(" Constructor validation:");
26}27System.out.println("\nConstructor validation:");output Constructor validation:this.name ← Alice, this.age ← 30, p1 ← Alice (30)
pass 1 of 229 try {30 Person p1→ Alice (30) = new Person("Alice", 30);31 System.out.println("Created: " + p1Alice (30));3233 Person p2 = new Person(null, 25);34 } catch (NullPointerException e) {35 System.out.println("Constructor failed: " + e.getMessage());36 }37 System.out.println("\nMethod parameters:");3839 EmailSender sender = new EmailSender();4041 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = "alice";5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String nameAlice, int age30) {104 this.name→ Alice = Objects.requireNonNull(nameAlice, "Name must not be null");105 this.age→ 30 = age30;106 }outputCreated: Alice (30)Person(String name, int age)
pass 2 of 2103Person(String namenull, int age25) {104 this.name = Objects.requireNonNull(namenull, "Name must not be null");105 this.age = age;catch (NullPointerException e)
33 Person p2 = new Person(null, 25);34} catch (NullPointerException ejava.lang.NullPointerException: Name must not be null) {35 System.out.println("Constructor failed: " + e.getMessage());36}outputConstructor failed: Name must not be nullsender ← ⟨Require$EmailSender A⟩
36}37System.out.println("\nMethod parameters:");3839EmailSender sender→ ⟨Require$EmailSender A⟩ = new EmailSender();output Method parameters:void send(String to, String subject, String body)
pass 1 of 241 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = "alice";5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(touser@example.com, "Recipient must not be null");117 Objects.requireNonNull(subjectHello, "Subject must not be null");118 Objects.requireNonNull(bodyWelcome!, "Body must not be null");119 // Send email...outputEmail sent successfullyvoid send(String to, String subject, String body)
pass 2 of 2114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(tonull, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");catch (NullPointerException e)
49 sender.send(null, "Hello", "Welcome!");50} catch (NullPointerException ejava.lang.NullPointerException: Recipient must not be null) {51 System.out.println("Failed: " + e.getMessage());52}outputFailed: Recipient must not be nulluserId ← alice
52}53System.out.println("\nSupplier message:");5455String userId→ alice = "alice";output Supplier message:try
57try {58 Objects.requireNonNull(userIdalice, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userIdalice);61} catch (NullPointerException e) {outputUser ID: aliceSystem.out.println(" Chain validation:");
63}64System.out.println("\nChain validation:");6566Config config = new Config("localhost", 8080, "/api");67System.out.println("Config: " + config);output Chain validation:this.host ← localhost, this.port ← 8080, this.path ← /api, config ← localhost:8080/api
pass 1 of 266 Config config→ localhost:8080/api = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + configlocalhost:8080/api);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String hostlocalhost, int port8080, String path/api) {129 this.host→ localhost = Objects.requireNonNull(hostlocalhost, "Host required");130 this.port→ 8080 = port8080;131 this.path→ /api = Objects.requireNonNull(path/api, "Path required");132 }outputConfig: localhost:8080/apiConfig(String host, int port, String path)
pass 2 of 2128Config(String hostnull, int port8080, String path/api) {129 this.host = Objects.requireNonNull(hostnull, "Host required");130 this.port = port;catch (NullPointerException e)
70 new Config(null, 8080, "/api");71} catch (NullPointerException ejava.lang.NullPointerException: Host required) {72 System.out.println("Host required: " + e.getMessage());73}outputHost required: Host requiredservice ← ⟨Require$UserService B⟩
73}74System.out.println("\nReturn value validation:");7576UserService service→ ⟨Require$UserService B⟩ = new UserService();7778User user = service.findUser("alice");79System.out.println("Found: " + user);output Return value validation:User findUser(String id)
pass 1 of 2140static class UserService {141 User findUser(String idalice) {142 Objects.requireNonNull(idalice, "User ID required");if ("alice".equals(id))
144if ("alice".equals(idalice)) {145 return new User("alice", "Alice");146}this.id ← alice, this.name ← Alice, user ← Alice (id=alice)
78 User user→ Alice (id=alice) = service.findUser("alice");79 System.out.println("Found: " + userAlice (id=alice));8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String idalice, String nameAlice) {157 this.id→ alice = idalice;158 this.name→ Alice = nameAlice;159 }outputFound: Alice (id=alice)User findUser(String id)
pass 2 of 2140static class UserService {141 User findUser(String idunknown) {142 Objects.requireNonNull(idunknown, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }catch (NullPointerException e)
82 service.findUser("unknown");83} catch (NullPointerException ejava.lang.NullPointerException: User not found: unknown) {84 System.out.println("Not found: " + e.getMessage());85}outputNot found: User not found: unknownString[] items = {"a", "b", "c"};
85}86System.out.println("\nDefensive copy:");8788String[] items = {"a", "b", "c"};89Container c1 = new Container(items);90System.out.println("Container: " + c1);output Defensive copy:c1 ← [a, b, c]
pass 1 of 288 String[] items = {"a", "b", "c"};89 Container c1→ [a, b, c] = new Container(items);90 System.out.println("Container: " + c1[a, b, c]);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String id, String name) {157 this.id = id;158 this.name = name;159 }160161 @Override162 public String toString() {163 return name + " (id=" + id + ")";164 }165}166167static class Container {168 String[] items;169170 Container(String[] items) {171 this.items = Objects.requireNonNull(items, "Items array required")172 .clone(); // Defensive copy173 }outputContainer: [a, b, c]Container(String[] items)
pass 2 of 2170Container(String[] itemsnull) {171 this.items = Objects.requireNonNull(itemsnull, "Items array required")172 .clone(); // Defensive copy173}catch (NullPointerException e)
93 new Container(null);94} catch (NullPointerException ejava.lang.NullPointerException: Items array required) {95 System.out.println("Null array: " + e.getMessage());96}outputNull array: Items array required
valid ← hello, invalid ← null, result ← hello
5public class Require {6 public static void main(String[] args) {7 System.out.println("Basic requireNonNull:");89 String valid→ hello = "hello";10 String invalid→ null = null;1112 String result→ hello = Objects.requireNonNull(validhello);13 System.out.println("Valid: " + resulthello);outputBasic requireNonNull: Valid: hellotry
15try {16 Objects.requireNonNull(invalidnull);17} catch (NullPointerException e) {catch (NullPointerException e)
16 Objects.requireNonNull(invalid);17} catch (NullPointerException ejava.lang.NullPointerException) {18 System.out.println("Caught NPE: " + e.getMessage());19}outputCaught NPE: nullSystem.out.println(" With message:");
19}20System.out.println("\nWith message:");output With message:catch (NullPointerException e)
23 Objects.requireNonNull(null, "Value must not be null");24} catch (NullPointerException ejava.lang.NullPointerException: Value must not be null) {25 System.out.println("Message: " + e.getMessage());26}outputMessage: Value must not be nullSystem.out.println(" Constructor validation:");
26}27System.out.println("\nConstructor validation:");output Constructor validation:this.name ← Alice, this.age ← 30, p1 ← Alice (30)
pass 1 of 229 try {30 Person p1→ Alice (30) = new Person("Alice", 30);31 System.out.println("Created: " + p1Alice (30));3233 Person p2 = new Person(null, 25);34 } catch (NullPointerException e) {35 System.out.println("Constructor failed: " + e.getMessage());36 }37 System.out.println("\nMethod parameters:");3839 EmailSender sender = new EmailSender();4041 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = "guest";5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String nameAlice, int age30) {104 this.name→ Alice = Objects.requireNonNull(nameAlice, "Name must not be null");105 this.age→ 30 = age30;106 }outputCreated: Alice (30)Person(String name, int age)
pass 2 of 2103Person(String namenull, int age25) {104 this.name = Objects.requireNonNull(namenull, "Name must not be null");105 this.age = age;catch (NullPointerException e)
33 Person p2 = new Person(null, 25);34} catch (NullPointerException ejava.lang.NullPointerException: Name must not be null) {35 System.out.println("Constructor failed: " + e.getMessage());36}outputConstructor failed: Name must not be nullsender ← ⟨Require$EmailSender A⟩
36}37System.out.println("\nMethod parameters:");3839EmailSender sender→ ⟨Require$EmailSender A⟩ = new EmailSender();output Method parameters:void send(String to, String subject, String body)
pass 1 of 241 try {42 sender.send("user@example.com", "Hello", "Welcome!");43 System.out.println("Email sent successfully");44 } catch (NullPointerException e) {45 System.out.println("Failed: " + e.getMessage());46 }4748 try {49 sender.send(null, "Hello", "Welcome!");50 } catch (NullPointerException e) {51 System.out.println("Failed: " + e.getMessage());52 }53 System.out.println("\nSupplier message:");5455 String userId = "guest";5657 try {58 Objects.requireNonNull(userId, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userId);61 } catch (NullPointerException e) {62 System.out.println("Lazy message: " + e.getMessage());63 }64 System.out.println("\nChain validation:");6566 Config config = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + config);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(touser@example.com, "Recipient must not be null");117 Objects.requireNonNull(subjectHello, "Subject must not be null");118 Objects.requireNonNull(bodyWelcome!, "Body must not be null");119 // Send email...outputEmail sent successfullyvoid send(String to, String subject, String body)
pass 2 of 2114static class EmailSender {115 void send(String to, String subjectHello, String bodyWelcome!) {116 Objects.requireNonNull(tonull, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");catch (NullPointerException e)
49 sender.send(null, "Hello", "Welcome!");50} catch (NullPointerException ejava.lang.NullPointerException: Recipient must not be null) {51 System.out.println("Failed: " + e.getMessage());52}outputFailed: Recipient must not be nulluserId ← guest
52}53System.out.println("\nSupplier message:");5455String userId→ guest = "guest";output Supplier message:try
57try {58 Objects.requireNonNull(userIdguest, () ->59 "User ID is required but was null in this request");60 System.out.println("User ID: " + userIdguest);61} catch (NullPointerException e) {outputUser ID: guestSystem.out.println(" Chain validation:");
63}64System.out.println("\nChain validation:");6566Config config = new Config("localhost", 8080, "/api");67System.out.println("Config: " + config);output Chain validation:this.host ← localhost, this.port ← 8080, this.path ← /api, config ← localhost:8080/api
pass 1 of 266 Config config→ localhost:8080/api = new Config("localhost", 8080, "/api");67 System.out.println("Config: " + configlocalhost:8080/api);6869 try {70 new Config(null, 8080, "/api");71 } catch (NullPointerException e) {72 System.out.println("Host required: " + e.getMessage());73 }74 System.out.println("\nReturn value validation:");7576 UserService service = new UserService();7778 User user = service.findUser("alice");79 System.out.println("Found: " + user);8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String hostlocalhost, int port8080, String path/api) {129 this.host→ localhost = Objects.requireNonNull(hostlocalhost, "Host required");130 this.port→ 8080 = port8080;131 this.path→ /api = Objects.requireNonNull(path/api, "Path required");132 }outputConfig: localhost:8080/apiConfig(String host, int port, String path)
pass 2 of 2128Config(String hostnull, int port8080, String path/api) {129 this.host = Objects.requireNonNull(hostnull, "Host required");130 this.port = port;catch (NullPointerException e)
70 new Config(null, 8080, "/api");71} catch (NullPointerException ejava.lang.NullPointerException: Host required) {72 System.out.println("Host required: " + e.getMessage());73}outputHost required: Host requiredservice ← ⟨Require$UserService B⟩
73}74System.out.println("\nReturn value validation:");7576UserService service→ ⟨Require$UserService B⟩ = new UserService();7778User user = service.findUser("alice");79System.out.println("Found: " + user);output Return value validation:User findUser(String id)
pass 1 of 2140static class UserService {141 User findUser(String idalice) {142 Objects.requireNonNull(idalice, "User ID required");if ("alice".equals(id))
144if ("alice".equals(idalice)) {145 return new User("alice", "Alice");146}this.id ← alice, this.name ← Alice, user ← Alice (id=alice)
78 User user→ Alice (id=alice) = service.findUser("alice");79 System.out.println("Found: " + userAlice (id=alice));8081 try {82 service.findUser("unknown");83 } catch (NullPointerException e) {84 System.out.println("Not found: " + e.getMessage());85 }86 System.out.println("\nDefensive copy:");8788 String[] items = {"a", "b", "c"};89 Container c1 = new Container(items);90 System.out.println("Container: " + c1);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String idalice, String nameAlice) {157 this.id→ alice = idalice;158 this.name→ Alice = nameAlice;159 }outputFound: Alice (id=alice)User findUser(String id)
pass 2 of 2140static class UserService {141 User findUser(String idunknown) {142 Objects.requireNonNull(idunknown, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }catch (NullPointerException e)
82 service.findUser("unknown");83} catch (NullPointerException ejava.lang.NullPointerException: User not found: unknown) {84 System.out.println("Not found: " + e.getMessage());85}outputNot found: User not found: unknownString[] items = {"a", "b", "c"};
85}86System.out.println("\nDefensive copy:");8788String[] items = {"a", "b", "c"};89Container c1 = new Container(items);90System.out.println("Container: " + c1);output Defensive copy:c1 ← [a, b, c]
pass 1 of 288 String[] items = {"a", "b", "c"};89 Container c1→ [a, b, c] = new Container(items);90 System.out.println("Container: " + c1[a, b, c]);9192 try {93 new Container(null);94 } catch (NullPointerException e) {95 System.out.println("Null array: " + e.getMessage());96 }97}9899static class Person {100 String name;101 int age;102103 Person(String name, int age) {104 this.name = Objects.requireNonNull(name, "Name must not be null");105 this.age = age;106 }107108 @Override109 public String toString() {110 return name + " (" + age + ")";111 }112}113114static class EmailSender {115 void send(String to, String subject, String body) {116 Objects.requireNonNull(to, "Recipient must not be null");117 Objects.requireNonNull(subject, "Subject must not be null");118 Objects.requireNonNull(body, "Body must not be null");119 // Send email...120 }121}122123static class Config {124 String host;125 int port;126 String path;127128 Config(String host, int port, String path) {129 this.host = Objects.requireNonNull(host, "Host required");130 this.port = port;131 this.path = Objects.requireNonNull(path, "Path required");132 }133134 @Override135 public String toString() {136 return host + ":" + port + path;137 }138}139140static class UserService {141 User findUser(String id) {142 Objects.requireNonNull(id, "User ID required");143144 if ("alice".equals(id)) {145 return new User("alice", "Alice");146 }147148 throw new NullPointerException("User not found: " + id);149 }150}151152static class User {153 String id;154 String name;155156 User(String id, String name) {157 this.id = id;158 this.name = name;159 }160161 @Override162 public String toString() {163 return name + " (id=" + id + ")";164 }165}166167static class Container {168 String[] items;169170 Container(String[] items) {171 this.items = Objects.requireNonNull(items, "Items array required")172 .clone(); // Defensive copy173 }outputContainer: [a, b, c]Container(String[] items)
pass 2 of 2170Container(String[] itemsnull) {171 this.items = Objects.requireNonNull(itemsnull, "Items array required")172 .clone(); // Defensive copy173}catch (NullPointerException e)
93 new Container(null);94} catch (NullPointerException ejava.lang.NullPointerException: Items array required) {95 System.out.println("Null array: " + e.getMessage());96}outputNull array: Items array required
Fail-fast validation
Objects.requireNonNull() throws NullPointerException immediately with a descriptive message, catching bugs early.
String Conversion
Convert objects to strings safely.
Tostring.java
Replay: real traced execution (multi-file project)
// Objects.toString examples
import java.util.Objects;
public class Tostring {
public static void main(String[] args) {
System.out.println("Basic toString:");
String s1 = "hello";
String s2 = null;
System.out.println("s1.toString(): " + s1.toString());
System.out.println("Objects.toString(s1): " + Objects.toString(s1));
System.out.println("Objects.toString(null): " + Objects.toString(s2));
// This would throw NPE:
// System.out.println(s2.toString());
System.out.println("\nWith default:");
String name = null;
String result = Objects.toString(name, "Unknown");
System.out.println("Name: " + result);
Integer age = null;
String ageStr = Objects.toString(age, "N/A");
System.out.println("Age: " + ageStr);
System.out.println("\nArray toString:");
int[] numbers = {1, 2, 3, 4, 5};
int[] empty = null;
System.out.println("Array: " + Objects.toString(numbers));
System.out.println("Null array: " + Objects.toString(empty, "[]"));
// Better for arrays:
System.out.println("Arrays.toString: " + java.util.Arrays.toString(numbers));
System.out.println("\nCustom objects:");
Person p1 = new Person("Alice", 30);
Person p2 = null;
System.out.println("Person: " + Objects.toString(p1));
System.out.println("Null person: " + Objects.toString(p2, "No person"));
System.out.println("\nCollections:");
java.util.List<String> list = java.util.Arrays.asList("a", "b", "c");
java.util.List<String> nullList = null;
System.out.println("List: " + Objects.toString(list));
System.out.println("Null list: " + Objects.toString(nullList, "[]"));
System.out.println("\nFormatting output:");
String username = "alice";
String email = null;
String phone = "555-1234";
System.out.println("Username: " + Objects.toString(username, "N/A"));
System.out.println("Email: " + Objects.toString(email, "N/A"));
System.out.println("Phone: " + Objects.toString(phone, "N/A"));
System.out.println("\nIn logging:");
Config config = new Config();
config.host = "localhost";
config.port = 8080;
config.database = null;
System.out.println("Config:");
System.out.println(" Host: " + Objects.toString(config.host, "default"));
System.out.println(" Port: " + config.port);
System.out.println(" DB: " + Objects.toString(config.database, "not configured"));
System.out.println("\nOptional values:");
Integer count = getCount();
String status = getStatus();
System.out.println("Count: " + Objects.toString(count, "0"));
System.out.println("Status: " + Objects.toString(status, "unknown"));
System.out.println("\nDebug output:");
Object obj1 = "hello";
Object obj2 = 123;
Object obj3 = null;
Object obj4 = new Person("Bob", 25);
printDebug("obj1", obj1);
printDebug("obj2", obj2);
printDebug("obj3", obj3);
printDebug("obj4", obj4);
}
static Integer getCount() {
return null; // Simulate optional value
}
static String getStatus() {
return null; // Simulate optional value
}
static void printDebug(String name, Object value) {
System.out.println(name + " = " + Objects.toString(value, "<null>"));
}
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
static class Config {
String host;
int port;
String database;
}
}
s1 ← hello, s2 ← null, name ← null, result ← Unknown, age ← null
5public class Tostring {6 public static void main(String[] args) {7 System.out.println("Basic toString:");89 String s1→ hello = "hello";10 String s2→ null = null;1112 System.out.println("s1.toString(): " + s1.toString());13 System.out.println("Objects.toString(s1): " + Objects.toString(s1hello));14 System.out.println("Objects.toString(null): " + Objects.toString(s2null));1516 // This would throw NPE:17 // System.out.println(s2.toString());18 System.out.println("\nWith default:");1920 String name→ null = null;21 String result→ Unknown = Objects.toString(namenull, "Unknown");22 System.out.println("Name: " + resultUnknown);2324 Integer age→ null = null;25 String ageStr→ N/A = Objects.toString(agenull, "N/A");26 System.out.println("Age: " + ageStrN/A);27 System.out.println("\nArray toString:");2829 int[] numbers = {1, 2, 3, 4, 5};30 int[] empty→ null = null;3132 System.out.println("Array: " + Objects.toString(numbers));33 System.out.println("Null array: " + Objects.toString(emptynull, "[]"));3435 // Better for arrays:36 System.out.println("Arrays.toString: " + java.util.Arrays.toString(numbers));37 System.out.println("\nCustom objects:");3839 Person p1 = new Person("Alice", 30);40 Person p2 = null;outputBasic toString: s1.toString(): hello Objects.toString(s1): hello Objects.toString(null): null With default: Name: Unknown Age: N/A Array toString: Array: ⟨int[] A⟩ Null array: [] Arrays.toString: [1, 2, 3, 4, 5] Custom objects:this.name ← Alice, this.age ← 30, p1 ← Person{name='Alice', age=30}
pass 1 of 239 Person p1→ Person{name='Alice', age=30} = new Person("Alice", 30);40 Person p2→ null = null;4142 System.out.println("Person: " + Objects.toString(p1Person{name='Alice', age=30}));43 System.out.println("Null person: " + Objects.toString(p2null, "No person"));44 System.out.println("\nCollections:");4546 java.util.List<String> list→ [a, b, c] = java.util.Arrays.asList("a", "b", "c");47 java.util.List<String> nullList→ null = null;4849 System.out.println("List: " + Objects.toString(list[a, b, c]));50 System.out.println("Null list: " + Objects.toString(nullListnull, "[]"));51 System.out.println("\nFormatting output:");5253 String username→ alice = "alice";54 String email→ null = null;55 String phone→ 555-1234 = "555-1234";5657 System.out.println("Username: " + Objects.toString(usernamealice, "N/A"));58 System.out.println("Email: " + Objects.toString(emailnull, "N/A"));59 System.out.println("Phone: " + Objects.toString(phone555-1234, "N/A"));60 System.out.println("\nIn logging:");6162 Config config→ ⟨Tostring$Config B⟩ = new Config();63 config.host→ localhost = "localhost";64 config.port→ 8080 = 8080;65 config.database→ null = null;6667 System.out.println("Config:");68 System.out.println(" Host: " + Objects.toString(config.hostlocalhost, "default"));69 System.out.println(" Port: " + config.port8080);70 System.out.println(" DB: " + Objects.toString(config.databasenull, "not configured"));71 System.out.println("\nOptional values:");7273 Integer count = getCount();74 String status = getStatus();7576 System.out.println("Count: " + Objects.toString(count, "0"));77 System.out.println("Status: " + Objects.toString(status, "unknown"));78 System.out.println("\nDebug output:");7980 Object obj1 = "hello";81 Object obj2 = 123;82 Object obj3 = null;83 Object obj4 = new Person("Bob", 25);8485 printDebug("obj1", obj1);86 printDebug("obj2", obj2);87 printDebug("obj3", obj3);88 printDebug("obj4", obj4);89}9091static Integer getCount() {92 return null; // Simulate optional value93}9495static String getStatus() {96 return null; // Simulate optional value97}9899static void printDebug(String name, Object value) {100 System.out.println(name + " = " + Objects.toString(value, "<null>"));101}102103static class Person {104 String name;105 int age;106107 Person(String nameAlice, int age30) {108 this.name→ Alice = nameAlice;109 this.age→ 30 = age30;110 }outputPerson: Person{name='Alice', age=30} Null person: No person Collections: List: [a, b, c] Null list: [] Formatting output: Username: alice Email: N/A Phone: 555-1234 In logging: Config: Host: localhost Port: 8080 DB: not configured Optional values:count ← null
73Integer count→ null = getCount();74String status = getStatus();status ← null, obj1 ← hello, obj2 ← 123, obj3 ← null
73Integer count = getCount();74String status→ null = getStatus();7576System.out.println("Count: " + Objects.toString(countnull, "0"));77System.out.println("Status: " + Objects.toString(statusnull, "unknown"));78System.out.println("\nDebug output:");7980Object obj1→ hello = "hello";81Object obj2→ 123 = 123;82Object obj3→ null = null;83Object obj4 = new Person("Bob", 25);outputCount: 0 Status: unknown Debug output:this.name ← Bob, this.age ← 25, obj4 ← Person{name='Bob', age=25}
pass 2 of 282 Object obj3 = null;83 Object obj4→ Person{name='Bob', age=25} = new Person("Bob", 25);8485 printDebug("obj1", obj1hello);86 printDebug("obj2", obj2);87 printDebug("obj3", obj3);88 printDebug("obj4", obj4);89}9091static Integer getCount() {92 return null; // Simulate optional value93}9495static String getStatus() {96 return null; // Simulate optional value97}9899static void printDebug(String name, Object value) {100 System.out.println(name + " = " + Objects.toString(value, "<null>"));101}102103static class Person {104 String name;105 int age;106107 Person(String nameBob, int age25) {108 this.name→ Bob = nameBob;109 this.age→ 25 = age25;110 }static void printDebug(String name, Object value)
pass 1 of 485 printDebug("obj1", obj1hello);86 printDebug("obj2", obj2123);87 printDebug("obj3", obj3);88 printDebug("obj4", obj4);89}9091static Integer getCount() {92 return null; // Simulate optional value93}9495static String getStatus() {96 return null; // Simulate optional value97}9899static void printDebug(String nameobj1, Object valuehello) {100 System.out.println(nameobj1 + " = " + Objects.toString(valuehello, "<null>"));101}outputobj1 = helloAll 4 passes — pass 1 is the card above pass namevalueobj1obj2obj3obj41 obj1 hello hello 123 — — 2 obj2 123 — 123 null — 3 obj3 null — — null Person{name='Bob', age=25} 4 obj4 Person{name='Bob', age=25} — — — Person{name='Bob', age=25}
Comparison Operations
Compare objects with null handling.
Compare.java
Replay: real traced execution (multi-file project)
// Objects.compare examples
import java.util.Objects;
import java.util.Comparator;
public class Compare {
public static void main(String[] args) {
System.out.println("Basic compare:");
String s1 = "apple";
String s2 = "banana";
String s3 = "apple";
int result = Objects.compare(s1, s2, String::compareTo);
System.out.println("compare('apple', 'banana'): " + result);
result = Objects.compare(s1, s3, String::compareTo);
System.out.println("compare('apple', 'apple'): " + result);
System.out.println("\nWith nulls:");
String n1 = null;
String n2 = "hello";
// Nulls-first comparator
Comparator<String> nullsFirst = Comparator.nullsFirst(String::compareTo);
result = Objects.compare(n1, n2, nullsFirst);
System.out.println("compare(null, 'hello', nullsFirst): " + result);
result = Objects.compare(n2, n1, nullsFirst);
System.out.println("compare('hello', null, nullsFirst): " + result);
result = Objects.compare(n1, n1, nullsFirst);
System.out.println("compare(null, null, nullsFirst): " + result);
System.out.println("\nNulls-last:");
Comparator<String> nullsLast = Comparator.nullsLast(String::compareTo);
result = Objects.compare(null, "hello", nullsLast);
System.out.println("compare(null, 'hello', nullsLast): " + result);
result = Objects.compare("hello", null, nullsLast);
System.out.println("compare('hello', null, nullsLast): " + result);
System.out.println("\nNumbers:");
Integer i1 = 10;
Integer i2 = 20;
Integer i3 = null;
result = Objects.compare(i1, i2, Integer::compareTo);
System.out.println("compare(10, 20): " + result);
result = Objects.compare(i1, i3, Comparator.nullsLast(Integer::compareTo));
System.out.println("compare(10, null): " + result);
System.out.println("\nCustom objects:");
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Bob", 25);
Person p3 = new Person("Charlie", 30);
// Compare by age
result = Objects.compare(p1, p2, Comparator.comparing(p -> p.age));
System.out.println("Alice vs Bob (by age): " + result);
result = Objects.compare(p1, p3, Comparator.comparing(p -> p.age));
System.out.println("Alice vs Charlie (by age): " + result);
// Compare by name
result = Objects.compare(p1, p2, Comparator.comparing(p -> p.name));
System.out.println("Alice vs Bob (by name): " + result);
System.out.println("\nSorting:");
java.util.List<Person> people = new java.util.ArrayList<>();
people.add(new Person("Charlie", 30));
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 35));
System.out.println("Before sort:");
people.forEach(System.out::println);
people.sort((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.name)));
System.out.println("\nAfter sort by name:");
people.forEach(System.out::println);
System.out.println("\nMultiple criteria:");
java.util.List<Person> students = new java.util.ArrayList<>();
students.add(new Person("Alice", 30));
students.add(new Person("Bob", 25));
students.add(new Person("Charlie", 30));
students.add(new Person("Alice", 25));
Comparator<Person> byAgeThenName =
Comparator.comparing((Person p) -> p.age)
.thenComparing(p -> p.name);
students.sort((a, b) -> Objects.compare(a, b, byAgeThenName));
System.out.println("Sorted by age then name:");
students.forEach(System.out::println);
System.out.println("\nMin/Max:");
Person youngest = people.stream()
.min((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.age)))
.orElse(null);
Person oldest = people.stream()
.max((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.age)))
.orElse(null);
System.out.println("Youngest: " + youngest);
System.out.println("Oldest: " + oldest);
}
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
}
s1 ← apple, s2 ← banana, s3 ← apple, result ← -1, n1 ← null, n2 ← hello
6public class Compare {7 public static void main(String[] args) {8 System.out.println("Basic compare:");910 String s1→ apple = "apple";11 String s2→ banana = "banana";12 String s3→ apple = "apple";1314 int result→ -1 = Objects.compare(s1apple, s2banana, String::compareTo);15 System.out.println("compare('apple', 'banana'): " + result-1);1617 result→ 0 = Objects.compare(s1apple, s3apple, String::compareTo);18 System.out.println("compare('apple', 'apple'): " + result0);19 System.out.println("\nWith nulls:");2021 String n1→ null = null;22 String n2→ hello = "hello";2324 // Nulls-first comparator25 Comparator<String> nullsFirst→ ⟨Comparators$NullComparator A⟩ = Comparator.nullsFirst(String::compareTo);2627 result→ -1 = Objects.compare(n1null, n2hello, nullsFirst⟨Comparators$NullComparator A⟩);28 System.out.println("compare(null, 'hello', nullsFirst): " + result-1);2930 result→ 1 = Objects.compare(n2hello, n1null, nullsFirst⟨Comparators$NullComparator A⟩);31 System.out.println("compare('hello', null, nullsFirst): " + result1);3233 result→ 0 = Objects.compare(n1null, n1, nullsFirst⟨Comparators$NullComparator A⟩);34 System.out.println("compare(null, null, nullsFirst): " + result0);35 System.out.println("\nNulls-last:");3637 Comparator<String> nullsLast→ ⟨Comparators$NullComparator B⟩ = Comparator.nullsLast(String::compareTo);3839 result→ 1 = Objects.compare(null, "hello", nullsLast⟨Comparators$NullComparator B⟩);40 System.out.println("compare(null, 'hello', nullsLast): " + result1);4142 result→ -1 = Objects.compare("hello", null, nullsLast⟨Comparators$NullComparator B⟩);43 System.out.println("compare('hello', null, nullsLast): " + result-1);44 System.out.println("\nNumbers:");4546 Integer i1→ 10 = 10;47 Integer i2→ 20 = 20;48 Integer i3→ null = null;4950 result→ -1 = Objects.compare(i110, i220, Integer::compareTo);51 System.out.println("compare(10, 20): " + result-1);5253 result→ -1 = Objects.compare(i110, i3null, Comparator.nullsLast(Integer::compareTo));54 System.out.println("compare(10, null): " + result-1);55 System.out.println("\nCustom objects:");5657 Person p1 = new Person("Alice", 30);58 Person p2 = new Person("Bob", 25);outputBasic compare: compare('apple', 'banana'): -1 compare('apple', 'apple'): 0 With nulls: compare(null, 'hello', nullsFirst): -1 compare('hello', null, nullsFirst): 1 compare(null, null, nullsFirst): 0 Nulls-last: compare(null, 'hello', nullsLast): 1 compare('hello', null, nullsLast): -1 Numbers: compare(10, 20): -1 compare(10, null): -1 Custom objects:this.name ← Alice, this.age ← 30, p1 ← Alice (30)
pass 1 of 1057 Person p1→ Alice (30) = new Person("Alice", 30);58 Person p2 = new Person("Bob", 25);59 Person p3 = new Person("Charlie", 30);6061 // Compare by age62 result = Objects.compare(p1, p2, Comparator.comparing(p -> p.age));63 System.out.println("Alice vs Bob (by age): " + result);6465 result = Objects.compare(p1, p3, Comparator.comparing(p -> p.age));66 System.out.println("Alice vs Charlie (by age): " + result);6768 // Compare by name69 result = Objects.compare(p1, p2, Comparator.comparing(p -> p.name));70 System.out.println("Alice vs Bob (by name): " + result);71 System.out.println("\nSorting:");7273 java.util.List<Person> people = new java.util.ArrayList<>();74 people.add(new Person("Charlie", 30));75 people.add(new Person("Alice", 25));76 people.add(new Person("Bob", 35));7778 System.out.println("Before sort:");79 people.forEach(System.out::println);8081 people.sort((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.name)));8283 System.out.println("\nAfter sort by name:");84 people.forEach(System.out::println);85 System.out.println("\nMultiple criteria:");8687 java.util.List<Person> students = new java.util.ArrayList<>();88 students.add(new Person("Alice", 30));89 students.add(new Person("Bob", 25));90 students.add(new Person("Charlie", 30));91 students.add(new Person("Alice", 25));9293 Comparator<Person> byAgeThenName =94 Comparator.comparing((Person p) -> p.age)95 .thenComparing(p -> p.name);9697 students.sort((a, b) -> Objects.compare(a, b, byAgeThenName));9899 System.out.println("Sorted by age then name:");100 students.forEach(System.out::println);101 System.out.println("\nMin/Max:");102103 Person youngest = people.stream()104 .min((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.age)))105 .orElse(null);106107 Person oldest = people.stream()108 .max((a, b) -> Objects.compare(a, b, Comparator.comparing(p -> p.age)))109 .orElse(null);110111 System.out.println("Youngest: " + youngest);112 System.out.println("Oldest: " + oldest);113}114115static class Person {116 String name;117 int age;118119 Person(String nameAlice, int age30) {120 this.name→ Alice = nameAlice;121 this.age→ 30 = age30;122 }All 10 passes — pass 1 is the card above pass nameagethis.namethis.agep1p2p3resultpeoplestudentsbyAgeThenNameyoungestoldest1 Alice 30 Alice 30 Alice (30) — — — — — — — — 2 Bob 25 Bob 25 — Bob (25) — — — — — — — 3 Charlie 30 Charlie 30 Alice (30) Bob (25) Charlie (30) 1 [] — — — — 4 Charlie 30 Charlie 30 — — — — — — — — — 5 Alice 25 Alice 25 — — — — — — — — — 6 Bob 35 Bob 35 — — — — — [] — — — 7 Alice 30 Alice 30 — — — — — — — — — 8 Bob 25 Bob 25 — — — — — — — — — 9 Charlie 30 Charlie 30 — — — — — — — — — 10 Alice 25 Alice 25 — — — — — — ⟨Comparator lambda C⟩ Alice (25) Bob (35)
@seealso collections_util
Exercise: Practical.java
Implement equals and hashCode for a Product class using Objects methods