C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This method is used for parameter validation, as in constructor bodies. Please see the next example.
Java program that uses Objects.requireNonNull
import java.util.Objects;
public class Program {
public static void main(String[] args) {
// Ensure an object is not null.
String value = null;
Objects.requireNonNull(value);
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Unknown Source)
at program.Program.main(Program.java:11)
Note: In main we test the constructor. When called with a String like "Andrew" it works with no error. But null causes an Exception.
Java program that validates in constructor
import java.util.Objects;
class Test {
public Test(String name) {
Objects.requireNonNull(name, "name cannot be null");
}
}
public class Program {
public static void main(String[] args) {
// This is safe.
Test t = new Test("Andrew");
// This will cause an exception.
Test t2 = new Test(null);
}
}
Output
Exception in thread "main" java.lang.NullPointerException: name cannot be null
at java.util.Objects.requireNonNull(Unknown Source)
at program.Test.<init>(Program.java:8)
at program.Program.main(Program.java:18)
Here: We implement hashCode on the Test class. The hash for Test is based on two parameters: the X and Y fields.
Tip: This is a convenience method. When we have just one object to base a hash code on, using hashCode directly is clearer.
Java program that uses Objects.hash
import java.util.Objects;
class Test {
int x;
int y;
public Test(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return Objects.hash(this.x, this.y);
}
}
public class Program {
public static void main(String[] args) {
// Get hash code for these objects.
Test t = new Test(1, 10);
System.out.println(t.hashCode());
Test t2 = new Test(2, 20);
System.out.println(t2.hashCode());
}
}
Output
1002
1043