Hi guys, I'm playing around ith optionals a little, but I'm not surewhether this is the correct behavious as I'm getting a null pointer exeption (I thought the point of Optionals was not to get a null pointer.)
SO I'm setting an object to null and before calling toString on it I'm using isPresent() on it. Here is the code:
package optional_test;
import java.util.Optional;
public class Optional_test {
public static void main(String[] args) {
Optional<Customer> customer1 = Optional.ofNullable(new Customer("John", "Doe"));
Optional<Customer> customer2 = null;
if(customer1.isPresent()){
System.out.println(customer1.get());
}
if(customer2.isPresent()){
System.out.println(customer2.orElse(new Customer("Unknown", "Unknown")));
}
}
}
And the cCustomer class:
package optional_test;
import java.util.Optional;
public class Customer {
private String name;
private String surname;
public Customer(String name, String surname) {
this.name = name;
this.surname = surname;
}
public Optional<String> getName() {
return Optional.ofNullable(this.name);
}
public void setName(String name) {
this.name = name;
}
public Optional<String> getSurname() {
return Optional.ofNullable(this.surname);
}
public void setSurname(String surname) {
this.surname = surname;
}
@Override
public String toString(){
return "Name: " + getName() + ". Surname: " + getSurname();
}
}