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


Download 1.52 Mb.
Pdf ko'rish
bet108/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   104   105   106   107   108   109   110   111   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

276.
277.
on which it is invoked is a non–empty Optional, it returns that
Optional, otherwise it returns the Optional generated by the
passed Supplier. In the code snippet above, the or method is
invoked on myDoubleOptional which is an Optional with the
value 10. Since this is a non–empty Optional, the or method
returns this value and not the defaultOptional. So, this code
prints the following output:
10.0
What changes has Java 9 made to the try–with statement?
Answer:
The try–with statement was added by Java 7. It allows
automatically closing resources without an explicit close
statement. So, for example if you are writing a file writing code, if
you use a try–with statement, the FileWriter gets closed
automatically once the try statement completes. The downside of
this was that the resource that needs to be automatically closed
needs to be part of the try statement. So, if a resource is declared
outside the try–with statement, it needs to be declared again as
part of the try–with. Java 9 does away with this restriction. So,
with Java 9, you can use a resource that is declared outside the
try–with statement within the try–with.
What is the use of the stream method added by Java 9 on
the Optional class?
Answer:
The stream() method added by Java 9 on the Optional class
can be used to convert an Optional into a Stream. This allows
applying all the Stream operations on an Optional. The following
code demonstrates this:


278.
a.
b.
c.
d.
279.
Optional str = Optional.of(“Hello”);
Stream strStream = str.stream();
This code defines an Optional called str which has a String value
Hello. It then uses the stream() method. This converts the
Optional to a Stream with one value. So now all Stream
operations like map, filter, etc. can be applied on this stream.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   104   105   106   107   108   109   110   111   ...   171




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