Optional in Java 8 – JavaDream

Home / Optional in Java 8 – JavaDream

In this post we will see about Optional in Java 8. Optional Class is introduced in Java 8. So before learning about Optional class first we have to know

What is Optional ?

Optional is a container object that is used to contain not-null objects. Optional class introduced in Java 8 to prevent the NullPointerException.

Optional class is present in java.util package.

Just take an example without optional and check if an object contains null or not.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		System.out.println(name[3].toUpperCase());
	}
}

If you try to run the above class you will get the below run time exception.

Exception in thread "main" java.lang.NullPointerException
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:9)

We will get the java.lang.NullPointerException at runtime because we have not any value at index 3 and we try to convert this null value in Uppercase. java.lang.NullPointerException is the very comman problem that every java programmer will face.

Now Try the above example again and use Java 8 Optional class to prevent this null pointer exception at run time.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		Optional<String> myName = Optional.ofNullable(name[3]);
		if(myName.isPresent()) {
			System.out.println(name[3].toUpperCase());
		}else {
			System.out.println("No value find at the given index");
		}
	}
}

Now if you run the above programe you will get the below output.

No value find at the given index

Now you can see that we use ofNullable() and isPresent() method. This method is the static method of Optional class.

ofNullable() function allowed passed parameter to be null.

isPresent() function returns Boolean. This function return true if any value is present and retun false if null value found.

Optional class provide many static methods and they are:

  1. ofNullable() function allowed passed parameter to be null.
  2. of() function do not allow null value. It will throw NullPointerException if passed parameter is null.
  3. ifPresent() function is execute only if the Optional object is not empty.
  4.  isPresent() function returns Boolean. It return true if value is present otherwise it retun false.
  5. hashCode() function return the hashcode.
  6. get() this function returns the value. Value should be present to use this static function.
  7. orElse() function returns the present value. If value is not present than it will return the default passed value.
  8. orElseGet() function return present value. If value is not present it call other method and return the value.
  9. orElseThrow() function return the value. It will throw Exception if value is not present.

Optional.ofNullable() function Example:

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name1);
		System.out.println(op1.isPresent());
	}
}

As you can see we have define name1 as null and name2 as vasu. Now try to pass name1 parameter in ofNullable() function and see the output it will return.

false

Now pass the name2 parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name2);
		System.out.println(op1.isPresent());
	}
}

Output will be

true

Optional.of() function Example.

This function does not allow null if we try to pass the the null parameter than it will throw run time Exception Just take an example.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name1);
		System.out.println(op1.isPresent());
	}
}

If you run this programe it will throw exception because we pass the null parameter. Output will be

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.Optional.<init>(Optional.java:107)
	at java.base/java.util.Optional.of(Optional.java:120)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:10)

Now try to pass not null value as parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name2);
		System.out.println(op1.isPresent());
	}
}

Output

true

Optional.ifPresent() function Example

This function is execute only if the Optional object is not empty Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.empty();
		Optional<String> op2 = Optional.of("My name is vasu");
		
		op1.ifPresent(obj -> System.out.println(obj));
		op2.ifPresent(obj -> System.out.println(obj.toUpperCase()));
	}
}

If you run the above programe you will get the output like

MY NAME IS VASU

This program print op2 object of Optional in Uppercase because op1 object returns the empty Optional object.

Optional.isPresent and Optional.hashCode() Example

Optiona.isPresent() function retuns true if value is presnt and retuns false if value is null. And Optiona.hashCode() function is used to get the hashCode of object.

Look at the below Example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.isPresent());
		System.out.println(op2.isPresent());
		
		System.out.println(op1.hashCode());
		System.out.println(op2.hashCode());
		
	}
}

Output:
false
true
0
3612237

Optional.get() Example

This function return the present value. For using get() method value should be present.

Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.get());	
	}
}

Now run this program and see the output. Output will be a run time exception because we call get() on null.

Output:

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:148)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:16)

Now call get() on op2 object and see the output

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);
		
		System.out.println(op2.get());	
	}
}

Output

vasu

Optional.orElse() , Optional.orElseGet() Example

orElse() and orElseGet() function returns the present value. If value is not present than it will return the default passed value.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.ofNullable("vasu");
		Optional<String> op2 = Optional.empty();
		
		System.out.println(op1.orElse(new String("vishu")));	
		System.out.println(op2.orElse(new String("vishu")));

	}
}

Output

vasu
vishu

You may also like:

Spring Boot Project Using Spring Initializer

Create WAR of Spring Boot Project

Change Running Server Port in Spring Boot

Spring Boot With MySql

How to use multiple database in a single spring boot application

Reference:


Optional (Java Platform SE 8 ) – Oracle Help Center

Help Others, Please Share

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *