Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet95/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   91   92   93   94   95   96   97   98   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

How can an Optional be created?
Answer:
There are some static methods on the Optional class which can
be used to create an Optional. These are as follows:


a.
b.
c.
249.
Optional.isEmpty– This creates an empty Optional, that
is an Optional without a value as shown below:
Optional number = Optional.empty();
Optional.of– This creates an Optional with a particular
value as shown below:
Optional number = Optional.of(10); //creates
Optional with the value 10
Optional.ofNullable– This creates an Optional with
either a null or a non–null value as shown below:
Optional number = Optional.ofNullable(10);
//creates Optional with the value 10
It can also be used to create an Optional with a null value as
follows:
Optional number = Optional.ofNullable(null);
Explain the Optional.ifPresent method with a code
sample.
Answer:
The Optional.ifPresent method performs an operation on
the value in the Optional if it is present. The operation to be
performed is specified as a Consumer instance. If the Optional is
empty, it does not do anything. The following code demonstrates
this:
Optional strOptional = Optional.of(“Test”);


250.
strOptional.ifPresent(str–>
System.out.println(str.toUpperCase()));
This code creates an Optional strOptional corresponding to
the value Test. The ifPresent method is then invoked with a
lambda expression that converts the value in the Optional to
uppercase and prints it. So, this code prints the following output:
TEST
In case, the input Optional is empty, the ifPresent() method
does not do anything.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   91   92   93   94   95   96   97   98   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling