NullPointerExceptions
, indicating exactly which variable or operation was null.Before Java 17:
Before, whenever you accidentally caused a null pointer exception, you wouldn’t get many clues as to exactly where it happened.
String firstName = "James"; String lastName = null; if (firstName.length() + lastName.length() < 10) { System.out.println("Your name is super short!"); }
In earlier Java versions, this would throw a generic NullPointerException
without indicating that lastName
is null.
After Java 17:
Now, the exception message would include “Cannot invoke “String.length()” because “lastName” is null”, pointing directly to the null reference.
String firstName = "James"; String lastName = null; if (firstName.length() + lastName.length() < 10) { System.out.println("Your name is super short!"); }
Person
-class and PersonApp
-class.public class Person { private String fullName; private List<String> hobbies; public Person(String fullName) { this.fullName = fullName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public void addHobby(String hobby) { hobbies.add(hobby); } }
public class PersonApp { public static void main(String[] args) { Person person = new Person("James Barnes"); person.addHobby("reading"); person.addHobby("sleeping"); System.out.printf("%s's hobbies are: %s\n", person.getFullName(), person.getHobbies()); } }
public void addHobby(String hobby) { if (hobbies == null) { hobbies = new ArrayList<>(); } hobbies.add(hobby); }