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


What is the difference between the orElse and


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

What is the difference between the orElse and
orElseThrow method?
Answer:
Both the orElse() and orElseThrow() are methods on the
Optional class. If a value is present in the Optional, they return
the value. They differ in what happens when a value is not
present in the Optional.
The orElse() method accepts as parameter a value and
returns this value if invoked on an empty Optional. The following
code demonstrates this:
Optional strOptional1 = Optional.empty();
String strValue1 = strOptional1.
orElse(“Default”);
Here, since strOptional1 is an empty Optional, the orElse()
method returns the value Default.
The orElseThrow() method throws an Exception if invoked on
an empty Optional. It accepts as parameter a Supplier


251.
instance that returns an Exception. The following code
demonstrates this:
Optional strOptional2 = Optional.empty();
String strValue2 = strOptional1.orElseThrow(()–> new
IllegalArgumentException());
Here, since strOptional2 is an empty Optional, the
orElseThrow() method throws an
IllegalArgumentException
What will be the output of the following code snippet?
Optional opInt1 = Optional.of(200); //Line 1
Optional opInt2 = opInt.filter(num–> num >
100); //Line 2
System.out.println(opInt2.get()); //Line 3
Answer:
The Optional class has a method called filter() which is used
in the code snippet above. The filter()method accepts as
Predicate and applies the Predicate to the value in the
Optional if present. If the condition in the Predicate is satisfied,
it returns the value in the Optional, otherwise it returns an empty
Optional. In this case, Line 1 creates an Integer Optional with the
value 200. Line 2 invokes the filter() method with a
Predicate that checks if the value in the Optional is greater
than 100. Since this is true, the filter() method returns an
Optional with the value 100 which is assigned to opInt2. So, the
get() method returns this value.
So, this code prints the following output:


100




Download 1.52 Mb.

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




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