-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalExample.java
More file actions
41 lines (35 loc) · 873 Bytes
/
Copy pathOptionalExample.java
File metadata and controls
41 lines (35 loc) · 873 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
*
*/
package com.java8.optional;
import java.util.Optional;
/**
* @author Atul Sharma
*
* https://github.com/sourac
*/
public class OptionalExample {
/*
* introduced in java-8, used to deal with NullPointerException in java. it's in
* the util package.
*/
public static void main(String[] args) {
String[] str = new String[10];
// when the value is not present
Optional<String> opt = Optional.ofNullable(str[1]);
if (opt.isPresent()) {
System.out.println("value is present...");
} else {
System.out.println("value is not present...");
}
//when the value is present.
String[] str1 = new String[10];
str1[1] = "Hello world";
Optional<String> opt1 = Optional.ofNullable(str1[1]);
if(opt1.isPresent()) {
System.out.println("value present...");
}else {
System.out.println("value is not present...");
}
}
}