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


How will you search for a specific element in an array?


Download 1.52 Mb.
Pdf ko'rish
bet57/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   53   54   55   56   57   58   59   60   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

How will you search for a specific element in an array?
Answer:
Java provides the java.util.Arrays class as part of the
Collection framework. This has several utility methods. One such
method is the Arrays.binarySearch method which can be
used to search for a specific element in an array. It returns an


148.
149.
integer which specifies the position of the element being
searched if present. Otherwise, it returns–1. The following code
demonstrates the binarySearch() method:
String [] strArr = {“one”, “two”, “four”};
System.out.println(“Search index of one is:
”+Arrays.binarySearch(strArr, “one”));
This code prints the following output:
Search index of one is:0
Since the String one is at position 0, so the binarySearch()
method returns 0.
Which collection would you choose if do not want
duplicates and do not care about the order?
Answer:
HashSet should be used if you want to avoid duplicates and do
not care about the order. HashSet is an implementation of the Set
interface. It is unsorted and unordered. In addition, TreeSet and
LinkedHashSet are also Set implementations. Both of these do
not allow duplicates. However, TreeSet maintains the sorting
order while LinkedHashSet maintains the insertion order.
Explain with a code sample how you can remove the head
of a queue.
Answer:
The interface Queue has a method called poll() which is used
to remove the head of the queue. The following code
demonstrates this:


150.
151.
Queue lList = new LinkedList();
lList.add(100);
lList.add(200);
System.out.println(“Removed– “:lList.poll()); // Line 1
This code creates a Queue and adds two integer values to it. It
then invokes the poll() method. So, this code prints the
following output:
The Element removed is: 100
So, the poll() method always removes the head of the queue
i.e., the first element added in the queue.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   53   54   55   56   57   58   59   60   ...   171




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