[go: up one dir, main page]

0% found this document useful (0 votes)
48 views52 pages

WIPRO Few Logic Building

Logical

Uploaded by

joysunm82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views52 pages

WIPRO Few Logic Building

Logical

Uploaded by

joysunm82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

DECREASING SEQUENCE

import java.io.*;
import java.util.*;

class DecreasingSequence {
public class Result{
public final int output1;
public final int output2;

public Result(int out1, int out2){


output1 = out1;
output2 = out2;
}
}

public Result decreasingSeq(int[] input1,int input2){


int dcrCount = 0;
int longestLen = 0;
int spikeCount = 0;
boolean flag = false;

for (int i = 0; i < input2 - 1; i++) {


if (input1[i] > input1[i + 1]) {
if (flag == false) {
flag = true;
spikeCount++;
}

dcrCount++;
longestLen = dcrCount > longestLen ? dcrCount : longestLen;
} else {
if (flag == true) {
flag = false;
dcrCount = 0;
}
}
}

if (spikeCount > 0) longestLen++;


return new Result(spikeCount, longestLen);
}
}
ENCODING THREE STRINGS

import java.io.*;
import java.util.*;

class EncodingThreeStrings {
public class Result{
public final String output1;
public final String output2;
public final String output3;

public Result(String out1, String out2, String out3){


output1 = out1;
output2 = out2;
output3 = out3;
}
}

public Result encodeThreeStrings(String input1,String input2,String input3){


String[] ip1parts = new String[3];
String[] ip2parts = new String[3];
String[] ip3parts = new String[3];

ip1parts = getParts(input1);
ip2parts = getParts(input2);
ip3parts = getParts(input3);

StringBuilder output1 = new StringBuilder (ip1parts[0] + ip2parts[0] + ip3parts[0]);


StringBuilder output2 = new StringBuilder (ip1parts[1] + ip2parts[1] + ip3parts[1]);
StringBuilder output3 = new StringBuilder (ip1parts[2] + ip2parts[2] + ip3parts[2]);

for (int i = 0; i < output3.length(); i++) {


if (Character.isLowerCase(output3.charAt(i)))
output3.setCharAt(i, Character.toUpperCase(output3.charAt(i)));
else
output3.setCharAt(i, Character.toLowerCase(output3.charAt(i)));
}
return new Result(output1.toString(), output2.toString(), output3.toString());
}

public static String[] getParts(String str) {


int len = str.length();
String[] parts = new String[3];
int partLen = len / 3;

if (len % 3 == 0) {
parts[0] = str.substring(0, partLen);
parts[1] = str.substring(partLen, 2 * partLen);
parts[2] = str.substring(2 * partLen, len);

} else if (len % 3 == 1) {
parts[0] = str.substring(0, partLen);
parts[1] = str.substring(partLen, 2 * partLen + 1);
parts[2] = str.substring(2 * partLen + 1, len);

} else if (len % 3 == 2) {
parts[0] = str.substring(0, partLen + 1);
parts[1] = str.substring(partLen + 1, 2 * partLen + 1);
parts[2] = str.substring(2 * partLen + 1, len);

}
return parts;
}
}
PASS WORD STABLE OR UNSTABLE
import java.io.*;
import java.util.*;
public class FindPasswordStableUnstable {
public int findPassword(int input1,int input2,int input3,int input4,int input5){
int[] nums = {input1, input2, input3, input4, input5};
int stable = 0, unstable = 0;
for (int num: nums){
if (isStable(num)) stable += num;
else unstable += num;
}
return stable - unstable;
}

public static boolean isStable(int num) {


boolean isStable = true;
int[] freq = new int[10];
String numStr = String.valueOf(num);
for (int i = 0; i < numStr.length(); i++) {
freq[Integer.parseInt(String.valueOf(numStr.charAt(i)))]++;
}
int primFreq = 0;
for (int i = 0; i < 10; i++) {
if (freq[i] > 0) {
primFreq = freq[i];
break;
}
}
for (int i = 0; i < 10; i++) {
if (freq[i] != 0 && freq[i] != primFreq) {
isStable = false;
break;
}
}
return isStable;
}
}
FINDING STRING CODE
import java.io.*;
import java.util.*;
class FindStringCode {
public int findStringCode(String input1){
String[] words = input1.split(" ");
StringBuffer output = new StringBuffer();

for (String word : words) {


int sum = 0;
for (int i = 0; i < (word.length() / 2); i++) {
int j = word.length() - i - 1;
int larger;
int smaller;
if (letterToNo(word.charAt(i)) > letterToNo(word.charAt(j))) {
larger = letterToNo(word.charAt(i));
smaller = letterToNo(word.charAt(j));
} else {
larger = letterToNo(word.charAt(j));
smaller = letterToNo(word.charAt(i));
}
sum += larger - smaller;
}
if (word.length() % 2 == 1) {
sum += letterToNo(word.charAt(word.length() / 2));
}
output.append(sum);
}
return Integer.parseInt(output.toString());
}

public static int letterToNo(char ch) {


if (ch >= 65 && ch <= 90)
return ch - 64;
if (ch >= 97 && ch <= 122)
return ch - 96;
return 0;
}
}
GETCODE THROUGH STRINGS

import java.io.*;
import java.util.*;

class GetCodeThroughStrings {
public int getCodeThroughStrings(String input1){
String[] words = input1.split(" ");
int pin = 0;

for(String word : words) {


pin += word.length();
}
if (String.valueOf(pin).length() == 1) return pin;

int pin2 = 0;
String pinStr = String.valueOf(pin);
for (int i = 0; i < pinStr.length(); i++) {
pin2 += Integer.parseInt(String.valueOf(pinStr.charAt(i)));
}

return pin2;
}
}
IDENTIFY POSSIBLE WORDS

import java.io.*;
import java.util.*;

class IdentifyPossibleWords {
public String identifyPossibleWords(String input1,String input2){
input1 = input1.toUpperCase();
StringBuffer output = new StringBuffer();
String[] words = input2.split(":");
int underscoreIndex = input1.indexOf('_');

for (int i = 0; i < words.length; i++) {


words[i] = words[i].toUpperCase();

if (words[i].length() >= input1.length() &&


input1.replace('_', words[i].charAt(underscoreIndex)).equals(words[i])) {
output.append(words[i]).append(":");
}
}

if (output.length() == 0) return "ERROR-009";


else return output.toString().substring(0, output.length() - 1);
}
}
MOST FREQUENT DIGIT

import java.util.Arrays;

public class MostFrequentDigit {

public int getMostFrequestDigit(int input1, int input2, int input3, int input4) {

int [] nums = {input1, input2, input3, input4};

int [] freq = new int[10];

Arrays.fill(freq,0);

for (int num : nums){

while (num != 0){

int digit = num % 10;

freq[digit]++;

num /= 10;

int maxFreq = 0;

for (int i = 0; i<= 9; i++){

if (freq[maxFreq] <= freq[i]) maxFreq = i;

return maxFreq;

}
MOST FREQUENTLY OCUURING DIGIT

import java.io.*;
import java.util.*;
class MostFrequentlyOccurringDigit {
public int mostFrequentlyOccurringDigit(int[] input1,int input2){
StringBuilder input = new StringBuilder();
for (int ip : input1) input.append(ip);
int[] freq = new int[10];
for (int j = 0; j < input.length(); j++) {
freq[Integer.parseInt(String.valueOf(input.charAt(j)))]++;
}
int maxFreqIndex = 0;
int maxFreq = 0;
for (int i = 9; i >= 0; i--) {
if (freq[i] > maxFreq) {
maxFreqIndex = i;
maxFreq = freq[i];
}
}
return maxFreqIndex;
}
}
MSG CONTROLLED ROBOT

import java.io.*;
import java.util.*;
public class MsgControlledRobot {
public String moveRobot(int input1,int input2,String input3,String input4){
int X = input1, Y = input2;
String currentPos = input3, msg = input4;

int currX = Integer.parseInt(currentPos.split("-")[0]);


int currY = Integer.parseInt(currentPos.split("-")[1]);
String currD = currentPos.split("-")[2];
String[] instructions = msg.split(" ");
StringBuilder output = new StringBuilder();

for (int i = 0; i < instructions.length; i++) {


if (instructions[i].equals("M")) {
if (currD.equals("E") && (currX + 1 > X )) {
output.append("-ER");
break;
}
if (currD.equals("W") && (currX - 1 < 0 )) {
output.append("-ER");
break;
}
if (currD.equals("N") && (currY + 1 > Y )) {
output.append("-ER");
break;
}
if (currD.equals("S") && (currY - 1 < 0 )) {
output.append("-ER");
break;
}

if (currD.equals("E")) currX++;
else if (currD.equals("W")) currX--;
else if (currD.equals("N")) currY++;
else if (currD.equals("S")) currY--;
} else {
if (currD.equals("E") && instructions[i].equals("L"))
currD = "N";
else if (currD.equals("E") && instructions[i].equals("R"))
currD = "S";
else if (currD.equals("W") && instructions[i].equals("L"))
currD = "S";
else if (currD.equals("W") && instructions[i].equals("R"))
currD = "N";
else if (currD.equals("N") && instructions[i].equals("L"))
currD = "W";
else if (currD.equals("N") && instructions[i].equals("R"))
currD = "E";
else if (currD.equals("S") && instructions[i].equals("L"))
currD = "E";
else if (currD.equals("S") && instructions[i].equals("R"))
currD = "W";
}

output.delete(0, output.length());
output.append(currX + "-" + currY + "-" + currD);
}
return output.toString();
}
}
NAMBER DIGIT CREATING

import java.io.*;
import java.util.*;
public class NambiarNumberGenerator {
public int nnGenerator(String input1){
String mobileNo = input1;
StringBuilder numbiarNo = new StringBuilder();

for (int i = 0; i < mobileNo.length(); i++) {


int digit = Integer.parseInt(String.valueOf(mobileNo.charAt(i)));
int evenOdd = digit % 2 == 0 ? 0 : 1;
int sum = digit;
int j = i + 1;

if (j == mobileNo.length()) {
numbiarNo.append(digit);
break;
}

while (true) {
sum += Integer.parseInt(String.valueOf(mobileNo.charAt(j++)));

if (sum % 2 != evenOdd || j >= mobileNo.length()) {


numbiarNo.append(sum);
i = j - 1;
break;
}
}
}
return Integer.parseInt(numbiarNo.toString());
}
}
NonRepeatedDigitsCount

import java.util.ArrayList;
import java.util.Collections;
public class NonRepeatedDigitsCount {
public static int nonRepeatedDigitsCount(int input1) {
int count = 0;
ArrayList<Integer> nums = new ArrayList<Integer>();

while(input1 != 0){
int digit = input1 % 10;
nums.add(digit);
input1 /= 10;
}

for (int num : nums)


if (Collections.frequency(nums, num) == 1) count++;

return count;
}
}
PinGenerator

public class PinGenerator {


public int pinGenerator(int input1, int input2, int input3) {
int pin = 0;
int ip1, ip2, ip3, min, max;

ip1 = input1 % 10;


ip2 = input2 % 10;
ip3 = input3 % 10;
min = Math.min(ip1, ip2);
min = Math.min(min, ip3);
max = Math.max(ip1, ip2);
max = Math.max(max, ip3);
pin = min;

input1 /= 10;
input2 /= 10;
input3 /= 10;
ip1 = input1 % 10;
ip2 = input2 % 10;
ip3 = input3 % 10;
min = Math.min(ip1, ip2);
min = Math.min(min, ip3);
max = Math.max(max, ip1);
max = Math.max(max, ip2);
max = Math.max(max, ip3);
pin = min * 10 + pin;

input1 /= 10;
input2 /= 10;
input3 /= 10;
ip1 = input1 % 10;
ip2 = input2 % 10;
ip3 = input3 % 10;
min = Math.min(ip1, ip2);
min = Math.min(min, ip3);
max = Math.max(max, ip1);
max = Math.max(max, ip2);
max = Math.max(max, ip3);
pin = min * 100 + pin;
pin = max * 1000 + pin;

return pin;
}
}
REMOVE 1 DIGITFORPALINDROME

import java.io.*;
import java.util.*;
public class Remove1DigitForPalindrome {
public int digitRemove_Palin(int input1){
StringBuilder num = new StringBuilder(String.valueOf(input1));

for (int i = 0; i < num.length(); i++) {


if (isPalindrome(num.toString())) return -1;

char removed = num.charAt(i);


String newNum = num.deleteCharAt(i).toString();

if (isPalindrome(newNum)) {
return Integer.parseInt(String.valueOf(removed));
} else {
num.insert(i, removed);
}
}
return -1;
}

public static boolean isPalindrome(String str) {


str = str.toLowerCase();
int len = str.length();
boolean isPalindrome = true;
int range = len / 2;

if (len % 2 == 0) range--;

for (int i = 0; i <= range; i++) {


if (str.charAt(i) != str.charAt(len - i - 1)) isPalindrome = false;
}
return isPalindrome;
}
}
SECONDWORDINUPPERCASE

public class SecondWordInUppercase {


public String secondWordInUppercase(String input1) {
if (input1.equals("")) return "LESS";
StringBuffer sb = new StringBuffer(input1.trim());

try {
int startIndex = sb.indexOf(" ");
if (startIndex == -1) return "LESS";
try {
int endIndex = sb.indexOf(" ", startIndex+1) + 1;
return sb.substring(startIndex+1, endIndex).toUpperCase().trim();
} catch (StringIndexOutOfBoundsException e) {
return sb.substring(startIndex+1).toUpperCase().trim();
}
} catch (StringIndexOutOfBoundsException e) {
return "LESS";
}
}
}
SIMPLE ENCODED ARRAY

import java.io.*;
import java.util.*;

class SimpleEncodedArray {
public class Result{
public final int output1;
public final int output2;

public Result(int out1, int out2){


output1 = out1;
output2 = out2;
}
}

public Result findOriginalFirstAndSum(int[] input1,int input2){


int[] out = new int[input1.length];
out[out.length - 1] = input1[input1.length - 1];

for (int i = input1.length - 1; i > 0; i--) {


out[i - 1] = input1[i - 1] - out[i];
}

int sum = 0;
for (int item : out)
sum += item;

return new Result(out[0], sum);


}
}
SUM OF POWERS OF DIGITS

import java.io.*;
import java.util.*;

class SumOfPowersOfDigits {
public int sumOfPowerOfDigits(int input1){
if (input1 <= 9) return 0;

String num = String.valueOf(input1);


int sum = 0;

for (int i = 0; i < num.length(); i++) {


if (i == num.length() - 1) {
sum += 1;
System.out.println(num.charAt(i) + " ^ " + 0);
} else {
sum += Math.pow(Integer.parseInt(String.valueOf(num.charAt(i))),
Integer.parseInt(String.valueOf(num.charAt(i + 1))));
}
}
return sum;
}
}
USER ID GENERATION

import java.io.*;
import java.util.*;
public class UserIDGeneration {
public String userIdGeneration(String input1,String input2,int input3,int input4){
String firstName = input1,lastName = input2, longerName, smallerName;
int pin = input3,N = input4;
StringBuilder userId = new StringBuilder();

if (firstName.length() > lastName.length()) {


longerName = firstName;
smallerName = lastName;
} else if (firstName.length() < lastName.length()) {
longerName = lastName;
smallerName = firstName;
} else {
if (firstName.compareTo(lastName) < 1 ) {
longerName = lastName;
smallerName = firstName;
} else {
longerName = firstName;
smallerName = lastName;
}
}

userId.append(smallerName.charAt(smallerName.length() - 1));
userId.append(longerName);
for (int i = 0; i < userId.length(); i++) {
if (Character.isUpperCase(userId.charAt(i)))
userId.setCharAt(i, Character.toLowerCase(userId.charAt(i)));
else
userId.setCharAt(i, Character.toUpperCase(userId.charAt(i)));
}
userId.append(String.valueOf(pin).charAt(N - 1));
userId.append(String.valueOf(pin).charAt(String.valueOf(pin).length() - N));

return userId.toString();
}
}
Which exception will the following
throw?
public class Test {

public static void main(String[] args) {


Object obj = new Integer(3);
String str = (String) obj;
System.out.println(str);
}
}

A. ArrayIndexOutOfBoundsException
B. ClassCastException
C. IllegalArgumentException
D. NumberFormatException
E. None of the above.

Click to View Answer and Explanation

Answer:
B. ClassCastException

Explanation:

The second line tries to cast an Integer to a String. Since String does not extend Integer, this is not allowed and
a ClassCastException is thrown.
9. Which of the following exceptions are thrown by the
JVM? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. ExceptionInInitializerError
C. java.io.IOException
D. NullPointerException
E. NumberFormatException

Click to View Answer and Explanation

Answer:
A, B, D

Explanation:
java.io.IOException is thrown by many methods in the java.io package, but it is always thrown programmatically.
The same is true for NumberFormatException; it is thrown programmatically by the wrapper classes of java.lang. The
other three exceptions are all thrown by the JVM when the corresponding problem arises.

Consider the following program:


public class Test {
public static void main(String[] args) {
String str = null;
System.out.println(str.valueOf(10));
}
}

Which of the following statements correctly describes the behavior of this program?
a) This program will result in a compiler error.
b) This program will throw a NullPointerException.
c) This program will print 10 in the console.
d) This program will print null in the console.

Click to View Answer and Explanation

Answer:
c) This program will print 10 in the console.

Explanation:
The valueOf(int) method is a static method in String that returns the String representation of the integer value that
is passed as its argument. Since calling a static method does not require dereferencing the reference variable on
which it is called, this program does not throw a NullPointerException.

Q3. Consider the following program and


predict the output:
public class Test {
public static void main(String[] args) {
String s = new String("5");
System.out.println(1 + 10 + s + 1 + 10);
}
}

a) 11511
b) 1105110
c) 115110
d) 27

Click to View Answer and Explanation

Answer:
c) 115110

Explanation:
The string concatenation operator works as follows: if both the operands are numbers, it performs the addition;
otherwise, it concatenates the arguments by calling the toString() method if needed. It evaluates from left to right.
Hence, the expression in the program results in the string 115110.
Q4. Consider the following program and predict its
output:
public class Test {
public static void main(String[] args) {
String str = null;
switch (str) { // #1
case "null":
System.out.println("null string"); // #2
break;
}
}
}

a) This program results in a compiler error in statement #1.


b) This program results in a compiler error in statement #2.
c) This program results in throwing a NullPointerException.
d) This program prints the following: null string.

Click to View Answer and Explanation

Answer:
c) This program results in throwing a NullPointerException.

Q5. What will be the output of the below statements?


public class Test {

public static void main(String[] args) {


String s1 = null;
System.out.println(s1); //line 2
System.out.println(s1.toString()); //line 3
}
}

a) null null
b) null NullPointerException
c) NullPointerException NullPointerException
d) None

Click to View Answer and Explanation

Answer:
b) null NullPointerException

Explanation:
Line 2 will print null because the println() method has a null check like below.

if (s == null) {
s = "null";
}
Q6. Select all the classes that extend the
String class
a) StringBuffer
b) StringBuilder
c) StringWriter
d) None
Click to View Answer and Explanation

Answer:
d) None

Explanation:
The String is a final class, so you can't extend it.

Q7. What is the output of the following


program?
public class Test {

public static void main(String[] args) {


String s1 = "hello";
String s2 = new String("hello");

s2 = s2.intern();
System.out.println(s1 == s2);
}
}

a) false
b) true
c) none
Click to View Answer and Explanation

Answer:
b) true

Explanation:
We know that the intern() method will return the String object reference from the string pool since we assign it back
to s2 and now both s1 and s2 are having the same reference. It means that s1 and s2 references point to the same
object.
Q8. What will be the output of the below
statements?
public class Test {

public static void main(String[] args) {


String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
}
}

a) false
b) true
c) ClassCastException at runtime
d) Compile-time error
Click to View Answer and Explanation

Answer:
a) false

Explanation:
It will print false because s2 is not of type String. If you will look at the equals method implementation in the String
class, you will find a check using instanceof operator to check if the type of passed object is String? If not, then
return false.

Q9. What is the result of the following


code?
String s1 = "Java";
String s2 = "Java";
StringBuilder sb1 = new StringBuilder();
sb1.append("Ja").append("va");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(sb1.toString() == s1);
System.out.println(sb1.toString().equals(s1));

A. true is printed out exactly once.


B. true is printed out exactly twice.
C. true is printed out exactly three times.
D. true is printed out exactly four times.
E. The code does not compile.
Click to View Answer and Explanation

Answer:
C. true is printed out exactly three times.
Explanation:
String literals are used from the string pool. This means that s1 and s2 refer to the same object and are equal.
Therefore, the first two print statements print true. The third print statement prints false because toString() uses a
method to compute the value and it is not from the string pool. The final print statement again prints true
because equals() looks at the values of String objects.

Q10. What is the difference between


StringBuilder and StringBuffer in Java?
a) StringBuilder is mutable, while StringBuffer is immutable.
b) StringBuilder is not a thread-safe, while StringBuffer is a thread-safe.
c) StringBuilder is synchronized, while StringBuffer is not synchronized.
d) There is no difference; they can be used interchangeably.
Click to View Answer and Explanation

Answer:
b) StringBuilder is not a thread-safe, while StringBuffer is a thread-safe.

What happens when two String objects


are concatenated using the + operator in
Java?
a) A new String object is created.
b) The first String object is modified.
c) The second String object is modified.
d) The original String objects remain unchanged.
Click to View Answer and Explanation

Answer:
a) A new String object is created.

Q13. What is the output of the following


code snippet?
public class Main {
public static void main(String[] args) {
String str = "Java";
str.concat(" Programming");
System.out.println(str);
}
}

a) Java
b) Java Programming
c) Programming
d) Compile-time error
Click to View Answer and Explanation

Answer:
a) Java

Explanation:

The concat() method returns a new string resulting from concatenating the specified string to the original string.
However, in this code, the result of concat() is not assigned back to the str variable. Therefore, the original string
"Java" remains unchanged, and the output is "Java".

Q14. Which of the following methods is


used to compare two strings for equality
in Java?
a) equals()
b) compareTo()
c) contains()
d) concat()
Click to View Answer and Explanation

Answer:
a) equals()

Explanation:
The equals() method is used to compare two strings for equality in Java. It returns true if the two strings have the
same characters in the same order, and false otherwise.
Which method is used to copy one array
into another in Java?
a) copy()

b) clone()

c) System.arraycopy()

d) Arrays.copy()

Click to View Answer and Explanation

Answer:

a) A runtime exception is thrown

Explanation:

The System.arraycopy() method is used to copy one array into another in Java, allowing you to efficiently copy
elements between arrays.

What symbol is used for a varargs method


parameter?
a) ..

b) ...

c) --

d) ---

Click to View Answer and Explanation

Answer:

b) ...
Explanation:

Three dots (...) are the syntax for a method parameter of type varargs. It is treated as an array.

10. How do you determine the number


of elements in an array?
int buses[] = new int[5];

a) buses.length

b) buses.length()

c) buses.size

d) buses.size()

Click to View Answer and Explanation

Answer:
a) buses.length

Explanation:
Arrays use the length variable to determine the number of elements, making Option A correct.

For an ArrayList, Option D would have been the answer.

12. What does this code output?


String[] nums = new String[] { "1", "9", "10" };
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));

a) [1, 9, 10]

b) [1, 10, 9]

c) [10, 1, 9]

d) None of the above


Click to View Answer and Explanation

Answer:
b) [1, 10, 9]

Explanation:
The elements of the array are of type String rather than int. Therefore, we use alphabetical order when sorting.
Character 1 sorts before character 9, alphabetically making Option A incorrect. Shorter strings sort before longer
strings when all the other characters are the same, making Option B the answer.

13. How many of the following are legal


declarations?
String lion [] = new String[] {"lion"};
String tiger [] = new String[1] {"tiger"};
String bear [] = new String[] {};
String cat [] = new String[0] {};

a) None

b) One

c) Two

d) Three

Click to View Answer and Explanation

Answer:
c) Two

Explanation:
When using an array initializer, you are not allowed to specify the size separately. The size is inferred from the number
of elements listed. Therefore, tiger and cat are incorrect. When you’re not using an array initializer, the size is
required. An empty array initializer is allowed. Option C is correct because lion and bear are legal.

16. What is a possible output of the


following code?
String[] strings = new String[2];
System.out.println(strings);
a) [null, null]

b) [,]

c) [Ljava.lang.String;@74a14482

d) None of the above

Click to View Answer and Explanation

Answer:
c) [Ljava.lang.String;@74a14482

Explanation:
Calling toString() on an array doesn’t output the contents of the array, making Option C correct. If you wanted
Option A to be the answer, you’d have to call Arrays.toString(strings).
2. Which of these is not a method defined in the Map interface?
a) put()

b) get()

c) remove()

d) add()

Click to View Answer and Explanation

Answer:
d) add()

Explanation:

The add() method is not defined in the Map interface. Map interface includes methods like put(), get(), and remove()
for manipulating key-value pairs.

3. What is the primary difference between HashSet and TreeSet in Java


Collections?
a) HashSet is ordered, while TreeSet is unordered

b) HashSet is faster than TreeSet

c) TreeSet maintains elements in a sorted order, while HashSet does not

d) TreeSet allows duplicate elements, while HashSet does not

Click to View Answer and Explanation

Answer:
c) TreeSet maintains elements in a sorted order, while HashSet does not

Explanation:

The main difference between HashSet and TreeSet is that TreeSet maintains its elements in a sorted order (either
natural ordering or according to a Comparator) while HashSet does not guarantee any order.

What type of collection does the java.util.Stack class represent?


a) Queue

b) Set

c) List

d) Map
Click to View Answer and Explanation

Answer:
c) List

Explanation:

The Stack class extends Vector and represents a last-in-first-out (LIFO) stack of objects. Despite its name, it is a List
implementation.

5. Which of these interfaces is not part of the Java Collections Framework?


a) List

b) SortedMap

c) SortedSet

d) Sortable

Click to View Answer and Explanation

Answer:
d) Sortable

Explanation:

Sortable is not an interface in the Java Collections Framework. List, SortedMap, and SortedSet are all interfaces within
the framework.

6. Which class is used to create a synchronized version of a Map?


a) ConcurrentHashMap

b) Collections.synchronizedMap()

c) Hashtable

d) SyncMap

Click to View Answer and Explanation

Answer:
b) Collections.synchronizedMap()

Explanation:

Collections.synchronizedMap() method is used to return a synchronized (thread-safe) map backed by the specified
map.
7. What is the purpose of the Comparable interface in Java Collections?
a) To define a natural ordering for objects of each class that implements it

b) To enable objects to be duplicated

c) To compare two different collections

d) To create a new type of collection

Click to View Answer and Explanation

Answer:
a) To define a natural ordering for objects of each class that implements it

Explanation:

The Comparable interface is used to define a natural ordering for objects of each class that implements it. It has a
compareTo method used for sorting objects.

9. What is the initial capacity of a HashMap in Java Collections Framework?


a) 10

b) 12

c) 16

d) 20

Click to View Answer and Explanation

Answer:
c) 16

Explanation:

The default initial capacity of a HashMap is 16. This is the number of buckets in the hash table initially.

9. What is the initial capacity of a HashMap in Java Collections Framework?


a) 10

b) 12

c) 16

d) 20

Click to View Answer and Explanation


Answer:
c) 16

Explanation:

The default initial capacity of a HashMap is 16. This is the number of buckets in the hash table initially.

12. What is a major feature of the ConcurrentHashMap class?


a) It does not allow null values

b) It is not thread-safe

c) It allows the modification of the collection while iterating

d) It uses a single lock for the whole map

Click to View Answer and Explanation

Answer:
c) It allows the modification of the collection while iterating

Explanation:

ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them.

14. In which scenario would you use a WeakHashMap?


a) When you need to maintain a mapping for a short duration

b) When you need to store large objects

c) When keys can be garbage collected

d) When you need synchronized access to the map

Click to View Answer and Explanation

Answer:
c) When keys can be garbage collected

Explanation:

WeakHashMap is a hashtable-based implementation where the keys are weak references, allowing the key-value pairs
to be garbage-collected when the key is no longer in ordinary use.
15. What is the purpose of the Collections.unmodifiableCollection()
method?
a) To create a new collection that is a clone of the current collection

b) To create a read-only view of a collection

c) To sort the collection in an unmodifiable order

d) To merge two collections into an unmodifiable collection

Click to View Answer and Explanation

Answer:
b) To create a read-only view of a collection

Explanation:

Collections.unmodifiableCollection() method is used to return an unmodifiable view of the specified collection. This
means that the collection cannot be modified through this view.

16. Which class should be used for a resizable array that provides the ability
to grow or shrink its size dynamically?
a) LinkedList

b) Vector

c) ArrayList

d) ArrayDeque

Click to View Answer and Explanation

Answer:
c) ArrayList

Explanation:

ArrayList is an implementation of the List interface that uses a resizable array, which is expanded or contracted as
needed.

17. What is the primary difference between the offer() and add() methods in
a Queue?
a) offer() throws an exception if the element cannot be added, while add() returns false

b) offer() and add() are identical in functionality

c) offer() returns false if the element cannot be added, while add() throws an exception
d) offer() is used in priority queues, while add() is used in normal queues

Click to View Answer and Explanation

Answer:
c) offer() returns false if the element cannot be added, while add() throws an exception

Explanation:

In Queue, the offer() method is typically preferred over add() as it returns false if the element cannot be added due to
capacity restrictions, while add() throws an IllegalStateException.

18. Which of these classes provides a fail-fast iterator?


a) CopyOnWriteArrayList

b) ConcurrentHashMap

c) ArrayList

d) ConcurrentLinkedQueue

Click to View Answer and Explanation

Answer:
c) ArrayList

Explanation:

ArrayList provides a fail-fast iterator, which means it will throw a ConcurrentModificationException if the collection is
modified after the iterator is created, except through the iterator's own remove method.

9. What is the behavior of the poll() method in a Queue when the Queue is
empty?
a) Throws an exception

b) Returns null

c) Blocks until an element is available

d) Returns a default value

Click to View Answer and Explanation

Answer:
b) Returns null
Explanation:

The poll() method retrieves and removes the head of the queue, or returns null if the queue is empty.
20. What is the key characteristic of a Set in Java Collections?
a) Allows duplicate elements

b) Maintains insertion order

c) Stores elements in key-value pairs

d) Does not allow duplicate elements

Click to View Answer and Explanation

Answer:
d) Does not allow duplicate elements

Explanation:

A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction.

21. Which Java collection class is thread-safe and does not allow null
elements?
a) ConcurrentHashMap

b) CopyOnWriteArrayList

c) Vector

d) Hashtable

Click to View Answer and Explanation

Answer:
d) Hashtable

Explanation:

Hashtable is a legacy class from the original version of Java. It is synchronized (thread-safe) and does not allow null
keys or null values.

22. Which method in the List interface allows to replace an element at a


specific position?
a) set(int index, E element)

b) replace(int index, E element)

c) put(int index, E element)


d) change(int index, E element)

Click to View Answer and Explanation

Answer:
a) set(int index, E element)

Explanation:

The set(int index, E element) method replaces the element at the specified position in the list with the specified
element.

23. What type of collection is returned by Collections.synchronizedList()?


a) An unmodifiable collection

b) A synchronized (thread-safe) collection

c) A sorted collection

d) A collection that supports concurrent modification

Click to View Answer and Explanation

Answer:
b) A synchronized (thread-safe) collection

Explanation:

Collections.synchronizedList() wraps a given List and returns a synchronized (thread-safe) version of it.

24. What is the primary difference between ConcurrentSkipListMap and


TreeMap?
a) ConcurrentSkipListMap is synchronized, whereas TreeMap is not

b) TreeMap is faster than ConcurrentSkipListMap

c) ConcurrentSkipListMap allows null values, but TreeMap does not

d) TreeMap uses a hash table, while ConcurrentSkipListMap uses a skip list

Click to View Answer and Explanation

Answer:
a) ConcurrentSkipListMap is synchronized, whereas TreeMap is not
Explanation:

ConcurrentSkipListMap is a concurrent, thread-safe version of a skip list, while TreeMap is a non-synchronized, sorted
map implementation.

25. What does the iterator of a CopyOnWriteArrayList return when the list is
modified after the iterator is created?
a) The updated list

b) The list at the state it was when the iterator was created

c) A ConcurrentModificationException

d) An UnsupportedOperationException

Click to View Answer and Explanation

Answer:
b) The list at the state it was when the iterator was created

Explanation:

The iterator of a CopyOnWriteArrayList returns a "snapshot" of the list at the point the iterator was created, regardless
of subsequent modifications.

26. Which Java collection is best suited for LIFO (Last-In-First-Out)


operations?
a) ArrayList

b) LinkedList

c) ArrayDeque

d) PriorityQueue

Click to View Answer and Explanation

Answer:
c) ArrayDeque

Explanation:

ArrayDeque is commonly used for stack operations and is more efficient than Stack. It provides a resizable array and
allows null elements, making it suitable for LIFO operations.

27. What is the primary difference between Iterator and ListIterator?


a) Iterator allows traversing in both directions, whereas ListIterator only allows forward traversal
b) ListIterator allows traversing in both directions, whereas Iterator only allows forward traversal

c) Iterator can modify the collection, whereas ListIterator cannot

d) ListIterator can only be used with lists, whereas Iterator can be used with any collection

Click to View Answer and Explanation

Answer:
b) ListIterator allows traversing in both directions, whereas Iterator only allows forward traversal

Explanation:

ListIterator extends Iterator with additional methods that allow bidirectional traversal of a list and the modification of
elements.

28. What is the significance of the BlockingQueue interface in Java


Collections?
a) It automatically sorts elements

b) It allows operations that wait for the queue to become non-empty when retrieving an element and wait for space
to become available in the queue when storing an element

c) It ensures that only unique elements are stored

d) It is used for managing concurrent data access

Click to View Answer and Explanation

Answer:
b) It allows operations that wait for the queue to become non-empty when retrieving an element and wait for space
to become available in the queue when storing an element

Explanation:

BlockingQueue is designed for cases where producers and consumers are different threads. Consumers can wait for
producers to insert items and vice-versa.

29. Which of these is not a feature of the LinkedHashMap class?


a) Maintains insertion order

b) Permits null elements

c) Is not synchronized

d) Consumes less memory than HashMap

Click to View Answer and Explanation


Answer:
d) Consumes less memory than HashMap

Explanation:

LinkedHashMap consumes more memory than HashMap because it maintains a linked list to keep track of insertion
order.

30. What is the behavior of the retainAll() method in the Collection


interface?
a) It removes all the elements from the collection

b) It retains only those elements that are also contained in the specified collection

c) It adds a collection of elements to the existing collection

d) It compares two collections and returns true if they have the same elements

Click to View Answer and Explanation

Answer:
b) It retains only those elements that are also contained in the specified collection

Explanation:

The retainAll() method is used to retain only the elements in the collection that are contained in the specified
collection.

31. Which of these interfaces is typically used for a collection that does not
allow duplicate elements and for which order is not an issue?
a) List

b) Set

c) Map

d) Queue

Click to View Answer and Explanation

Answer:
b) Set

Explanation:

The Set interface models the mathematical set abstraction and is typically used for collections that do not allow
duplicate elements and do not need to maintain any order.
32. What is the difference between the add and offer methods in the Queue
interface?
a) There is no difference, both insert an element into the queue

b) add throws an exception if the element can't be added, while offer returns false

c) add returns false if the element can't be added, while offer throws an exception

d) offer is used in priority queues, while add is used in normal queues

Click to View Answer and Explanation

Answer:
b) add throws an exception if the element can't be added, while offer returns false

Explanation:

In the Queue interface, the add method throws an IllegalStateException if the element cannot be added due to
capacity restrictions, while the offer method returns false in such cases.

33. Which method would you use to obtain the first element of a Set?
a) getFirst()

b) first()

c) It's not possible to get the first element of a Set as it doesn't maintain any order

d) iterator().next()

Click to View Answer and Explanation

Answer:
d) iterator().next()

Explanation:

Sets do not have a method to directly retrieve an element by its position because Sets typically do not guarantee an
order. The iterator().next() method can be used to get the first element if iterating over the Set.

34. What does the Collections.synchronizedSet() method do?


a) Returns a synchronized (thread-safe) set backed by the specified set

b) Creates a new set that is a copy of the existing set

c) Sorts the given set

d) Merges two sets into a new set

Click to View Answer and Explanation


Answer:
a) Returns a synchronized (thread-safe) set backed by the specified set

Explanation:

Collections.synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set.

35. Which class in Java Collections Framework is designed for cases where
high-throughput and thread-safe implementation is required?
a) Vector

b) ArrayList

c) CopyOnWriteArrayList

d) LinkedList

Click to View Answer and Explanation

Answer:
c) CopyOnWriteArrayList

Explanation:

CopyOnWriteArrayList is designed for environments where high-throughput is needed, and the array rarely changes
but is frequently iterated. It provides a thread-safe variant of ArrayList.

36. What is the typical use of a PriorityBlockingQueue?


a) To implement a producer-consumer scenario where elements are processed based on priority

b) For multithreaded applications to sort elements

c) To block elements from entering the queue based on priority

d) To create a queue that holds elements of a single type

Click to View Answer and Explanation

Answer:
a) To implement a producer-consumer scenario where elements are processed based on priority

Explanation:

PriorityBlockingQueue is a thread-safe priority queue implementation. It is used in scenarios where multi-threaded


tasks need to process elements based on their priorities.
37. In Java Collections, what is the main difference between a HashMap and
a Hashtable?
a) HashMap is synchronized, whereas Hashtable is not

b) Hashtable allows one null key, but HashMap does not

c) HashMap allows null keys and values, but Hashtable does not

d) There is no significant difference

Click to View Answer and Explanation

Answer:
c) HashMap allows null keys and values, but Hashtable does not

Explanation:

HashMap allows null keys and null values, whereas Hashtable does not allow null keys or values and is synchronized.

8. Which interface should be used when you need a map and you wish to
preserve the order of elements?
a) SortedMap

b) LinkedHashMap

c) TreeMap

d) ConcurrentHashMap

Click to View Answer and Explanation

Answer:
b) LinkedHashMap

Explanation:

LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were inserted. This linked
list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-
order).

39. What is a key characteristic of the ConcurrentLinkedQueue class?


a) It is not thread-safe

b) It uses a linked list that allows insertion and removal at both ends

c) It allows concurrent modification from multiple threads without locking


d) It maintains the elements in natural order

Click to View Answer and Explanation

Answer:
c) It allows concurrent modification from multiple threads without locking

Explanation:

ConcurrentLinkedQueue is a thread-safe queue based on linked nodes and supports concurrent access from multiple
threads without locking.

40. What does the Collections.emptySet() method return?


a) A new, empty set instance

b) A null pointer

c) A set containing a single null element

d) An immutable empty set

Click to View Answer and Explanation

Answer:
d) An immutable empty set

Explanation:

Collections.emptySet() returns a special immutable empty set. This set is serializable and no elements can be added to
it.

1. In Java Collections, what is the difference between the poll() and


remove() methods of Queue interface?
a) poll() retrieves and removes the head of the queue, remove() only retrieves but does not remove

b) poll() returns null if the queue is empty, remove() throws an exception

c) There is no difference, both methods do the same thing

d) remove() returns null if the queue is empty, poll() throws an exception

Click to View Answer and Explanation

Answer:
b) poll() returns null if the queue is empty, remove() throws an exception
Explanation:

In Queue interface, poll() retrieves and removes the head of the queue, returning null if the queue is empty, whereas
remove() retrieves and removes the head of the queue but throws an exception if the queue is empty.

42. What will happen if you try to sort a List that contains a null element?
a) NullPointerException

b) The list will be sorted and the null element will be placed at the beginning

c) The null element will be ignored during sorting

d) The list will be sorted and the null element will be placed at the end

Click to View Answer and Explanation

Answer:
a) NullPointerException

Explanation:

Attempting to sort a list containing null elements will result in a NullPointerException because null cannot be
compared with non-null elements.

44. Which class is best suited for a FIFO (First-In-First-Out) queue


implementation?
a) LinkedList

b) PriorityQueue

c) ArrayDeque

d) Stack

Click to View Answer and Explanation

Answer:
c) ArrayDeque

Explanation:

ArrayDeque is more efficient than LinkedList for new standard FIFO (first-in-first-out) queue operations.

45. Which method in the Map interface is used to retrieve all keys contained
in the map?
a) values()
b) keySet()

c) entrySet()

d) getAllKeys()

Click to View Answer and Explanation

Answer:
b) keySet()

Explanation:

The keySet() method in the Map interface is used to return a Set view of the keys contained in the map.

46. What is the difference between the size and capacity of an ArrayList?
a) Size and capacity are the same in an ArrayList

b) Size is the number of elements in the ArrayList, and capacity is the size of the array buffer

c) Size is the size of the array buffer, and capacity is the number of elements it can hold

d) There is no concept of capacity in an ArrayList

Click to View Answer and Explanation

Answer:
b) Size is the number of elements in the ArrayList, and capacity is the size of the array buffer

Explanation:

In an ArrayList, the size is the number of elements currently in the list, while the capacity is the size of the array buffer
inside the ArrayList, which can potentially hold more elements than the current size.

47. Which of these classes is synchronized and is designed for use in


multithreaded contexts?
a) ArrayList

b) HashMap

c) ConcurrentHashMap

d) LinkedList

Click to View Answer and Explanation

Answer:
c) ConcurrentHashMap
Explanation:

ConcurrentHashMap is a concurrent collection class that allows multiple threads to read and write concurrently and is
designed to be used in multithreaded contexts.

48. What will Collections.max() return when applied to a Collection of


Strings?
a) The first string in the collection

b) The string with the most characters

c) The string that comes last in lexicographical order

d) The string that comes first in lexicographical order

Click to View Answer and Explanation

Answer:
c) The string that comes last in lexicographical order

Explanation:

Collections.max() returns the maximum element of the given collection, according to the natural ordering of its
elements. For a string, it would be the one that comes last in lexicographical order.

50. Which method do you need to implement when creating a class that can
be used as a key in a HashMap?
a) compareTo()

b) equals() and hashCode()

c) clone()

d) toString()

Click to View Answer and Explanation

Answer:
b) equals() and hashCode()

Explanation:

When creating a class that can be used as a key in a HashMap, it is crucial to properly override both equals() and
hashCode() methods to ensure that duplicate keys are not allowed and the hashcode contract is maintained.

You might also like