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


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

how it can be fixed.
List numbers = List.of(5,10,15); //Line 1
numbers.add(20); //Line 2
System.out.println(numbers); //Line 3
Answer:
Java 9 has added a static method of() to all the Collection
interfaces. The code above uses this method to create an Integer
List at Line 1. The of method creates an immutable List which
cannot be modified. However, Line 2 tries to add a value to the
List which will cause an Exception when the code is executed.
So, in order to fix the code above, you need remove Line 2. So,
you need to re–write the code as follows:
List numbers = List.of(5,10,15,20); //Line 1
System.out.println(numbers); //Line 3


271.
272.
Which Java 9 method can you use to create a Set of String
values?
Answer:
Java 9 has added a static factory method to the Set interface.
You can use this to create a Set with String values. The following
code demonstrates this:
Set months =
Set.of(“January”,”February”,”March”);
This code creates a Set of String values called months. It uses
the String.of() method with the values specified. The
String.of() has several overloaded versions that accept from
0 to 10 arguments as well as a version that accepts varargs.
What will be the output of the following code snippet?
Stream oddNumbers = Stream.iterate(1, num–> num
<= 20, num–> num+2);
oddNumbers.forEach(num–> System.out.print(num+” “));
Answer:
Prior to Java 9, there was a Stream.iterate() method that
created an infinite Stream of values. Java 9 has added an
overloaded version of the Stream.iterate() method that
creates a finite Stream. So, this method accepts an additional
parameter which is a Predicate and stops the stream as soon as
the Predicate is true. So, this code prints the following output:
1 3 5 7 9 11 13 15 17 19




Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   102   103   104   105   106   107   108   109   ...   171




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