# Optional





```java
import java.util.Optional;

class Emp {
	private long id;
	private String name;

	public Emp(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + "]";
	}

}

public class Optional1 {
	public static void main(String[] args) {

		Emp emp = getSomeData();
		Optional<Emp> emp1 = getSomeDataJava8();
		if (emp1.isPresent()) {
			System.out.println(emp1.get());
		} else {
			System.out.println(emp1.orElse(new Emp(23, "Test")));
		}
		System.out.println(emp.getName());
	}

	private static Optional<Emp> getSomeDataJava8() {
		// return Optional.ofNullable(null);
		return Optional.of(new Emp(12, "test"));
	}

	private static Emp getSomeData() {
		return null;
	}

}

```



### Readings:

1\)

{% embed url="https://howtodoinjava.com/java8/java-8-optionals-complete-reference/" %}

