1Which loop is best suited for scenarios where the number of iterations is known beforehand?
Working with for loop, while loop, do-while loop and for-each loop
Easy
A.for loop
B.for-each loop
C.while loop
D.do-while loop
Correct Answer: for loop
Explanation:
The for loop is ideal for situations where the number of iterations is known, as its structure compactly includes initialization, a condition, and an increment/decrement expression.
Incorrect! Try again.
2What is the primary characteristic of a while loop?
Working with for loop, while loop, do-while loop and for-each loop
Easy
A.It checks the condition before executing the loop body.
B.It can only be used with arrays.
C.It requires a counter variable initialized in the loop statement.
D.It always executes at least once.
Correct Answer: It checks the condition before executing the loop body.
Explanation:
A while loop is a pre-test loop. It evaluates its condition before each iteration. If the condition is false initially, the loop body will not execute at all.
Incorrect! Try again.
3Which loop structure guarantees that its body will be executed at least once?
Working with for loop, while loop, do-while loop and for-each loop
Easy
A.do-while
B.enhanced for
C.for
D.while
Correct Answer: do-while
Explanation:
A do-while loop is a post-test loop. It executes the loop body first and then checks the condition, ensuring at least one execution regardless of whether the condition is initially true or false.
Incorrect! Try again.
4The for-each loop in Java is primarily used for which purpose?
Working with for loop, while loop, do-while loop and for-each loop
Easy
A.Creating an infinite loop
B.Iterating over the elements of an array or collection
C.Executing a loop body at least once
D.Executing a loop for a specific number of times
Correct Answer: Iterating over the elements of an array or collection
Explanation:
The for-each loop (or enhanced for loop) provides a simpler, more readable syntax for iterating through all the elements of an array or a collection without using an index variable.
Incorrect! Try again.
5How do you correctly declare and initialize an array of 3 integers in a single line in Java?
Fundamentals about Arrays
Easy
A.int arr[3] = {10, 20, 30};
B.int[] arr = new int(3);
C.int arr = {10, 20, 30};
D.int arr[] = {10, 20, 30};
Correct Answer: int arr[] = {10, 20, 30};
Explanation:
The correct syntax for declaring and initializing an array in one statement is type[] arrayName = {value1, value2, ...};. The form type arrayName[] is also valid for declaration.
Incorrect! Try again.
6If an array is declared as String[] names = new String[10];, what is the valid range of indices for this array?
Array Access and Iterations
Easy
A.0 to 9
B.0 to 10
C.1 to 10
D.1 to 9
Correct Answer: 0 to 9
Explanation:
Array indexing in Java is 0-based. For an array of size 10, the indices start at 0 and go up to length - 1, which is 9.
Incorrect! Try again.
7Which of the following correctly declares a 2x3 two-dimensional integer array?
Multi-dimensional arrays
Easy
A.int[] matrix = new int[2][3];
B.int matrix[2][3] = new int[][];
C.int matrix[][] = new int(2, 3);
D.int[][] matrix = new int[2][3];
Correct Answer: int[][] matrix = new int[2][3];
Explanation:
The standard syntax to declare and instantiate a multi-dimensional array is type[][] arrayName = new type[rows][columns];.
Incorrect! Try again.
8What does the 'varargs' feature in Java allow?
Using varargs
Easy
A.A method to accept a variable number of arguments of the same type.
B.An array to change its size after creation.
C.A class to have a variable number of constructors.
D.A variable to change its data type at runtime.
Correct Answer: A method to accept a variable number of arguments of the same type.
Explanation:
Varargs (variable-length arguments) allows a method to accept zero or more arguments of a specified type. Inside the method, the varargs are treated as an array of that type.
Incorrect! Try again.
9Which keyword is used to create an enumeration in Java?
Enumerations
Easy
A.enum
B.enumeration
C.enum_class
D.constants
Correct Answer: enum
Explanation:
An enumeration is a special data type that represents a set of predefined constants. It is defined using the enum keyword.
Incorrect! Try again.
10Consider the enum enum Level { LOW, MEDIUM, HIGH }. How would you access the MEDIUM constant?
Enumerations
Easy
A.Level(MEDIUM)
B.Level[1]
C.Level.MEDIUM
D."MEDIUM"
Correct Answer: Level.MEDIUM
Explanation:
Enum constants are accessed statically using the enum's name, followed by a dot, and then the constant's name, like Level.MEDIUM.
Incorrect! Try again.
11In Java, what is an object?
Basics of class and objects
Easy
A.An instance of a class.
B.A primitive data type like int or char.
C.A special type of method.
D.A template or blueprint for creating classes.
Correct Answer: An instance of a class.
Explanation:
A class is a blueprint, and an object is a concrete instance created from that blueprint. It has state (fields) and behavior (methods) as defined by its class.
Incorrect! Try again.
12What is the main purpose of a constructor in a Java class?
Writing constructors and methods
Easy
A.To return a value to the calling code.
B.To define all the static methods of a class.
C.To destroy an object and free memory.
D.To initialize a newly created object.
Correct Answer: To initialize a newly created object.
Explanation:
A constructor is a special method called when an object is instantiated. Its primary role is to initialize the state (instance variables) of the new object.
Incorrect! Try again.
13What is method overloading?
Overloading methods and constructors
Easy
A.A child class defining a method with the same name as a method in its parent class.
B.A class having two methods with the same name but different parameters.
C.Creating a method that can handle any data type.
D.A class having two methods with the same name and the same parameters.
Correct Answer: A class having two methods with the same name but different parameters.
Explanation:
Method overloading allows multiple methods in the same class to share the same name, as long as their parameter lists (number, type, or order of parameters) are different.
Incorrect! Try again.
14Is it possible to overload constructors in Java?
Overloading methods and constructors
Easy
A.No, a class can only have one constructor.
B.Yes, as long as each constructor has a different parameter list.
C.No, this concept only applies to methods, not constructors.
D.Yes, but only in abstract classes.
Correct Answer: Yes, as long as each constructor has a different parameter list.
Explanation:
Just like methods, constructors can be overloaded. This allows you to create objects in different ways by providing different sets of initial values.
Incorrect! Try again.
15Inside an instance method or a constructor, what does the this keyword refer to?
this keyword
Easy
A.The class itself.
B.A static member of the class.
C.The superclass of the current object.
D.The current object instance.
Correct Answer: The current object instance.
Explanation:
The this keyword is a reference to the current object—the object whose method or constructor is being called. It is often used to disambiguate between instance variables and parameters.
Incorrect! Try again.
16What is an instance initializer block in a Java class?
initializer blocks
Easy
A.A special method used to initialize static variables.
B.A block of code inside {} that is executed every time an instance of the class is created.
C.Another name for a no-argument constructor.
D.A block of code prefixed with the static keyword.
Correct Answer: A block of code inside {} that is executed every time an instance of the class is created.
Explanation:
An instance initializer block is a set of curly braces {} defined at the class level. Its code is run before the constructor every time a new object is created.
Incorrect! Try again.
17Which of the following is a key characteristic of String objects in Java?
String Class : Constructors and methods of String and String Builder class
Easy
A.They can only store numbers.
B.They are mutable.
C.They are immutable.
D.They have a fixed size of 256 characters.
Correct Answer: They are immutable.
Explanation:
String objects in Java are immutable, which means once a String object is created, its value cannot be changed. Any operation that appears to modify a string actually creates a new String object.
Incorrect! Try again.
18Which method of the String class is used to find the number of characters in a string?
String Class : Constructors and methods of String and String Builder class
Easy
A.count()
B.size()
C.length()
D.getSize()
Correct Answer: length()
Explanation:
The length() method in the java.lang.String class returns the length of the string, which is the count of its characters.
Incorrect! Try again.
19What would "hello".charAt(1) return?
String Class : Constructors and methods of String and String Builder class
Easy
A."e"
B.'h'
C.1
D.'e'
Correct Answer: 'e'
Explanation:
The charAt(int index) method returns the character at the specified index. Since strings are 0-indexed, index 1 corresponds to the second character, which is 'e'. The return type is char.
Incorrect! Try again.
20When you need to perform many modifications on a sequence of characters, which class is generally more efficient than String?
String Class : Constructors and methods of String and String Builder class
Easy
A.Char
B.StringArray
C.StringBuilder
D.StringReader
Correct Answer: StringBuilder
Explanation:
StringBuilder is designed for creating and manipulating mutable sequences of characters. It is more performance-efficient than String for operations involving frequent changes because it does not create a new object for every modification.
Incorrect! Try again.
21What is the output of the following Java code snippet?
JAVA
public class LoopTest {
public static void main(String[] args) {
int count = 0;
OUTER: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j > 0) {
break OUTER;
}
if (i == 2) {
continue OUTER;
}
count++;
}
}
System.out.println(count);
}
}
Working with for loop, while loop, do-while loop and for-each loop
Medium
A.3
B.6
C.5
D.4
Correct Answer: 4
Explanation:
The outer loop runs for i = 0, i = 1, and i = 2.
When i = 0, the inner loop runs for j = 0, 1, 2. count becomes 3.
When i = 1, the inner loop runs for j = 0. count becomes 4. When j becomes 1, the condition i == 1 && j > 0 is true, and the break OUTER; statement terminates the entire outer loop.
The loop for i = 2 is never reached.
Thus, the final value of count is 4.
Incorrect! Try again.
22What will be printed to the console after executing the following code?
JAVA
public class DoWhileTest {
public static void main(String[] args) {
int x = 10;
do {
x -= 3;
} while (x > 10);
System.out.println(x);
}
}
Working with for loop, while loop, do-while loop and for-each loop
Medium
A.13
B.7
C.The code will not compile.
D.10
Correct Answer: 7
Explanation:
A do-while loop always executes its body at least once. In the first iteration, x is 10. The body x -= 3; executes, and x becomes 7. Then, the condition while (x > 10); is checked. Since 7 is not greater than 10, the condition is false, and the loop terminates. The final value of x, which is 7, is printed.
Incorrect! Try again.
23What is the output of the following code snippet that works with a ragged 2D array?
JAVA
public class RaggedArray {
public static void main(String[] args) {
int[][] arr = new int[3][];
arr[0] = new int[]{1, 2};
arr[1] = new int[]{3, 4, 5};
arr[2] = new int[]{6};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i][arr[i].length - 1];
}
System.out.println(sum);
}
}
Multi-dimensional arrays
Medium
A.15
B.9
C.An ArrayIndexOutOfBoundsException is thrown.
D.13
Correct Answer: 13
Explanation:
The code iterates through a ragged 2D array and sums the last element of each inner array.
For i = 0, arr[0].length is 2. The last element is arr[0][1], which is 2. sum is 2.
For i = 1, arr[1].length is 3. The last element is arr[1][2], which is 5. sum is 2 + 5 = 7.
For i = 2, arr[2].length is 1. The last element is arr[2][0], which is 6. sum is 7 + 6 = 13.
The final sum printed is 13.
Incorrect! Try again.
24Consider the following code using a for-each loop. What is the output?
JAVA
public class ForEachTest {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int x : numbers) {
x = x + 5;
}
for (int x : numbers) {
System.out.print(x + " ");
}
}
}
Array Access and Iterations
Medium
A.10 20 30
B.The code will not compile.
C.5 5 5
D.15 25 35
Correct Answer: 10 20 30
Explanation:
In a for-each loop with primitive types (like int), the loop variable x is a copy of the array element's value, not a reference to the element itself. Therefore, modifying x inside the first loop (x = x + 5;) does not change the original values in the numbers array. The second loop iterates over the unchanged array and prints its original elements: 10 20 30.
Incorrect! Try again.
25Which method is called by test(10, 20) and what is the output?
JAVA
public class VarargsTest {
static void test(int... v) {
System.out.print("varargs");
}
static void test(int x, int y) {
System.out.print("int, int");
}
public static void main(String[] args) {
test(10, 20);
}
}
Using varargs
Medium
A.int, int
B.The code runs but produces no output.
C.The code results in a compilation error due to ambiguity.
D.varargs
Correct Answer: int, int
Explanation:
Java's method overloading resolution prefers a specific match over a varargs match. When test(10, 20) is called, the compiler finds a method signature test(int x, int y) that is an exact match for the arguments provided. The varargs method test(int... v) is only chosen if no more specific method signature is available. Therefore, the test(int x, int y) method is invoked, and it prints "int, int".
Incorrect! Try again.
26What is the output of the following Java program?
JAVA
enum Signal {
GREEN("Go"), YELLOW("Wait"), RED("Stop");
private String action;
Signal(String action) {
this.action = action;
}
public String getAction() {
return this.action;
}
}
public class Main {
public static void main(String[] args) {
Signal current = Signal.YELLOW;
System.out.println(current.getAction());
}
}
Enumerations
Medium
A.Wait
B.YELLOW
C.Signal.YELLOW
D.The code will not compile because enums cannot have constructors.
Correct Answer: Wait
Explanation:
Enums in Java can have constructors, fields, and methods. In this example, the Signal enum has a constructor that takes a String and assigns it to the action field. When the enum constants GREEN, YELLOW, and RED are created, their respective constructors are called with the provided strings. The line Signal current = Signal.YELLOW; assigns the YELLOW constant to the current variable. Calling current.getAction() invokes the getAction method on the YELLOW instance, which returns the value of its action field, initialized to "Wait".
Incorrect! Try again.
27What is the output of the following code?
JAVA
class Box {
int size = 10;
void updateSize(Box b, int newSize) {
b.size = newSize;
b = new Box();
b.size = 5;
}
}
public class Main {
public static void main(String[] args) {
Box box1 = new Box();
Box box2 = new Box();
box1.updateSize(box2, 20);
System.out.println(box1.size + " " + box2.size);
}
}
Basics of class and objects
Medium
A.10 5
B.10 10
C.10 20
D.20 20
Correct Answer: 10 20
Explanation:
In Java, object references are passed by value.
box1 and box2 are created, both with size = 10.
box1.updateSize(box2, 20) is called. Inside the method, the parameter b is a copy of the reference to box2.
b.size = newSize; changes the size of the object that b (and box2) points to. So, box2.size becomes 20.
b = new Box(); reassigns the local parameter b to point to a new Box object. This does not affect the original box2 reference in main.
b.size = 5; changes the size of this new Box object, which is local to the method and is discarded when the method ends.
The updateSize method does not modify box1 at all.
Therefore, the output is the size of box1 (10) and the modified size of box2 (20).
Incorrect! Try again.
28What is the output of the code below?
JAVA
class Calculator {
public void add(int a, double b) {
System.out.println("Method A");
}
public void add(double a, int b) {
System.out.println("Method B");
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(10, 20);
}
}
Overloading methods and constructors
Medium
A.Method B
B.The code compiles but throws a runtime exception.
C.Method A
D.The code fails to compile due to an ambiguous method call.
Correct Answer: The code fails to compile due to an ambiguous method call.
Explanation:
The method call calc.add(10, 20) provides two integer literals. The compiler looks for a matching add(int, int) method. Since one doesn't exist, it looks for methods that can be called via type promotion (widening conversion).
add(int a, double b) is a potential match because the second argument 20 (int) can be promoted to a double.
add(double a, int b) is also a potential match because the first argument 10 (int) can be promoted to a double.
Since both methods are equally applicable after one promotion, the compiler cannot decide which one to choose. This results in a compilation error for an ambiguous method call.
Incorrect! Try again.
29Predict the output of the following Java program.
JAVA
class Car {
String model;
int year;
Car(String model) {
this(model, 2023);
System.out.print("C1 ");
}
Car(String model, int year) {
this.model = model;
this.year = year;
System.out.print("C2 ");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Sedan");
System.out.print(myCar.year);
}
}
Overloading methods and constructors
Medium
A.C1 C2 2023
B.C1 2023
C.C2 C1 2023
D.C2 2023
Correct Answer: C2 C1 2023
Explanation:
new Car("Sedan") calls the first constructor Car(String model).
The first line in this constructor is this(model, 2023), which is a call to another constructor in the same class (constructor chaining). This call must be the very first statement.
The second constructor Car(String model, int year) is executed. It initializes this.model and this.year, and then prints "C2 ".
After the second constructor finishes, control returns to the first constructor.
The first constructor then executes its next statement, System.out.print("C1 ");.
Finally, in the main method, System.out.print(myCar.year); prints the value of year, which was set to 2023.
The final output is "C2 C1 2023".
Incorrect! Try again.
30What is printed by the following code?
JAVA
class Point {
int x, y;
Point(int x, int y) {
x = x;
this.y = y;
}
void print() {
System.out.println("x=" + x + ", y=" + y);
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(10, 20);
p.print();
}
}
this keyword
Medium
A.x=0, y=20
B.x=10, y=0
C.x=0, y=0
D.x=10, y=20
Correct Answer: x=0, y=20
Explanation:
In the constructor Point(int x, int y), the statement x = x; refers to the local parameter x on both sides of the assignment. It is assigning the value of the parameter x (which is 10) to itself. The instance variable this.x is never assigned a value, so it retains its default value for an int, which is 0. The statement this.y = y; correctly uses the this keyword to distinguish the instance variable this.y from the parameter y, so the instance variable y is correctly assigned the value 20. Therefore, the output is "x=0, y=20".
Incorrect! Try again.
31What is the sequence of output when the following Java code is executed?
JAVA
class MyClass {
static { System.out.print("S"); }
{ System.out.print("I"); }
public MyClass() {
System.out.print("C");
}
}
public class Main {
public static void main(String[] args) {
new MyClass();
new MyClass();
}
}
Initializer blocks
Medium
A.S I C I C
B.S C I C I
C.S I C S I C
D.I C I C S
Correct Answer: S I C I C
Explanation:
The order of execution is as follows:
Static initializer block: Runs only once when the class is first loaded into the JVM. This prints "S".
First object creation (new MyClass()):
a. The instance initializer block runs. This prints "I".
b. The constructor runs. This prints "C".
Second object creation (new MyClass()):
a. The static block does not run again.
b. The instance initializer block runs again for the new object. This prints "I".
c. The constructor runs again for the new object. This prints "C".
Combining these steps, the final output is "S I C I C".
Incorrect! Try again.
32Analyze the following code. What will be printed to the console?
JAVA
public class StringTest {
public static void main(String[] args) {
String s1 = "hello";
String s2 = s1.concat(" world");
s1.toUpperCase();
System.out.println(s1 + " " + s2);
}
}
String Class : Constructors and methods of String and String Builder class
Medium
A.HELLO HELLO WORLD
B.hello hello world
C.hello HELLO WORLD
D.HELLO hello world
Correct Answer: hello hello world
Explanation:
The key concept here is the immutability of the String class in Java. When methods like concat() or toUpperCase() are called on a String object, they do not modify the original string. Instead, they return a new String object with the result.
s1 is initialized to "hello".
s1.concat(" world") creates a new string "hello world" which is assigned to s2.
s1.toUpperCase() creates a new string "HELLO", but its return value is not assigned to any variable. s1 itself remains unchanged.
Therefore, s1 is still "hello" and s2 is "hello world". The output is "hello hello world".
Incorrect! Try again.
33What is the output of the following code involving StringBuilder?
JAVA
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("start");
sb.append("le");
sb.insert(5, "t");
sb.delete(1, 4);
System.out.println(sb);
}
}
String Class : Constructors and methods of String and String Builder class
Medium
A.stle
B.sle
C.sttle
D.startle
Correct Answer: stle
Explanation:
StringBuilder is mutable, so its methods modify the object in place.
sb is initialized to "start".
sb.append("le"): sb becomes "startle".
sb.insert(5, "t"): The character 't' is inserted at index 5. sb becomes "starttle".
sb.delete(1, 4): Deletes characters from the starting index 1 (inclusive) to the ending index 4 (exclusive). It deletes 't', 'a', and 'r'. sb becomes "stle".
Finally, "stle" is printed.
Incorrect! Try again.
34What does the following code print?
JAVA
public class StringCompare {
public static void main(String[] args) {
String s1 = "Java";
String s2 = new String("Java");
String s3 = "Java";
System.out.print(s1 == s2);
System.out.print(", ");
System.out.print(s1 == s3);
System.out.print(", ");
System.out.print(s1.equals(s2));
}
}
String Class : Constructors and methods of String and String Builder class
Medium
A.true, true, true
B.true, false, true
C.false, false, true
D.false, true, true
Correct Answer: false, true, true
Explanation:
s1 == s2: s1 is a string literal from the string pool. s2 is created using new, so it's a new object on the heap. The == operator compares object references (memory addresses), which are different. So, this is false.
s1 == s3: Both s1 and s3 are string literals with the same value. Java's string pool reuses this literal, so both variables point to the same object in memory. This is true.
s1.equals(s2): The .equals() method compares the actual character sequences of the strings. Since both strings contain "Java", this is true.
Therefore, the output is "false, true, true".
Incorrect! Try again.
35What is the output of the following code, which demonstrates method chaining?
JAVA
class Calculator {
private int result = 0;
public Calculator add(int num) {
this.result += num;
return this;
}
public Calculator subtract(int num) {
this.result -= num;
return this;
}
public int getResult() {
return this.result;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int finalResult = calc.add(10).subtract(3).add(5).getResult();
System.out.println(finalResult);
}
}
this keyword
Medium
A.The code will not compile.
B.12
C.7
D.10
Correct Answer: 12
Explanation:
This code demonstrates method chaining, which is possible because the add and subtract methods return this (a reference to the current object).
calc.add(10): result becomes 10. The method returns the calc object.
.subtract(3) is called on the returned calc object. result becomes 10 - 3 = 7. The method returns the calc object again.
.add(5) is called on the returned calc object. result becomes 7 + 5 = 12. The method returns the calc object.
.getResult() is called on the calc object, which returns the final value of result, which is 12.
This value is then printed to the console.
Incorrect! Try again.
36What is the result of executing the following Java code?
JAVA
public class ArrayReference {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = a;
boolean check1 = (a == b);
boolean check2 = (a == c);
c[1] = 5;
System.out.println(check1 + ", " + check2 + ", " + a[1]);
}
}
Fundamentals about Arrays
Medium
A.false, true, 2
B.true, true, 5
C.true, false, 2
D.false, true, 5
Correct Answer: false, true, 5
Explanation:
In Java, array variables are references.
int[] a = {1, 2, 3}; creates an array object and a holds its memory address.
int[] b = {1, 2, 3}; creates a new, separate array object with the same content. b holds a different memory address.
int[] c = a; makes the reference c point to the same array object as a.
check1 = (a == b): Compares the memory addresses of a and b. Since they are different objects, this is false.
check2 = (a == c): Compares the memory addresses of a and c. Since they point to the same object, this is true.
c[1] = 5;: Modifies the second element of the array that both c and a are pointing to. Therefore, a[1] also becomes 5.
The output is false, true, 5.
Incorrect! Try again.
37How many times will the character '#' be printed by the following code?
JAVA
public class LoopCounter {
public static void main(String[] args) {
int i = 0, j = 10;
int count = 0;
while (i < j) {
i++;
j--;
System.out.print("#");
}
}
}
Working with for loop, while loop, do-while loop and for-each loop
Medium
A.4
B.10
C.6
D.5
Correct Answer: 5
Explanation:
Let's trace the values of i and j in each iteration of the while loop.
The loop continues as long as i < j.
Start:i=0, j=10. Condition 0 < 10 is true.
Iter 1:i becomes 1, j becomes 9. Prints '#'. Condition 1 < 9 is true.
Iter 2:i becomes 2, j becomes 8. Prints '#'. Condition 2 < 8 is true.
Iter 3:i becomes 3, j becomes 7. Prints '#'. Condition 3 < 7 is true.
Iter 4:i becomes 4, j becomes 6. Prints '#'. Condition 4 < 6 is true.
Iter 5:i becomes 5, j becomes 5. Prints '#'. Condition 5 < 5 is now false.
The loop terminates. The character '#' was printed 5 times.
Incorrect! Try again.
38What is the value of len and cap after executing this code?
JAVA
public class SBCapacity {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(5);
sb.append("Java");
sb.append(" is fun");
int len = sb.length();
int cap = sb.capacity();
System.out.println("Length: " + len + ", Capacity: " + cap);
}
}
String Class : Constructors and methods of String and String Builder class
Medium
A.Length: 11, Capacity: 5
B.Length: 12, Capacity: 12
C.Length: 11, Capacity: 11
D.Length: 11, Capacity: 12
Correct Answer: Length: 11, Capacity: 12
Explanation:
StringBuilder sb = new StringBuilder(5); creates a StringBuilder with an initial capacity of 5.
sb.append("Java"); adds a 4-character string. The length is now 4, capacity is 5.
sb.append(" is fun"); attempts to add a 7-character string. The total required length is 4 + 7 = 11. Since this exceeds the current capacity of 5, the StringBuilder must expand its internal array. The new capacity is typically calculated as (old_capacity * 2) + 2. So, new capacity becomes (5 * 2) + 2 = 12.
The final string is "Java is fun", which has a length of 11.
The final capacity is 12. So, len is 11 and cap is 12.
Incorrect! Try again.
39Given the Book class, what will the following code snippet print?
JAVA
class Book {
String title;
public Book(String t) {
this.title = t;
}
}
public class Main {
public static void changeTitle(Book book) {
book.title = "The Great Gatsby";
book = new Book("Moby Dick");
book.title = "1984";
}
public static void main(String[] args) {
Book myBook = new Book("A Tale of Two Cities");
changeTitle(myBook);
System.out.println(myBook.title);
}
}
Writing constructors and methods
Medium
A.1984
B.A Tale of Two Cities
C.The Great Gatsby
D.Moby Dick
Correct Answer: The Great Gatsby
Explanation:
Java passes object references by value.
In main, myBook is created, pointing to a Book object with title "A Tale of Two Cities".
changeTitle(myBook) is called. The parameter book inside the method receives a copy of the reference from myBook. Both myBook and book now point to the same object.
book.title = "The Great Gatsby";: This line modifies the title field of the object that both references are pointing to. So, myBook.title is now "The Great Gatsby".
book = new Book("Moby Dick");: This reassigns the local reference book to a brand new Book object. This action does not affect the myBook reference in main, which still points to the original object.
book.title = "1984";: This modifies the title of the new, local object. This change is lost when the method ends.
Back in main, System.out.println(myBook.title); prints the title of the original object, which was last changed to "The Great Gatsby".
Incorrect! Try again.
40Which of the following code snippets will fail to compile?
JAVA
// Snippet A
enum Color { RED, GREEN, BLUE; }
// Snippet B
enum Size {
SMALL, MEDIUM, LARGE;
public Size() {} // Constructor
}
// Snippet C
enum Priority {
HIGH, MEDIUM, LOW;
private Priority() {}
}
// Snippet D
public enum Day { MONDAY, TUESDAY; }
Enumerations
Medium
A.Snippet B
B.Snippet D
C.Snippet A
D.Snippet C
Correct Answer: Snippet B
Explanation:
Constructors for enums must be private (or package-private, which is the default). They cannot be declared public or protected. The reason is that only the JVM can construct enum instances; you cannot create them manually using new. Snippet B attempts to declare a public constructor public Size() {}, which is a compilation error. Snippet C is valid because it explicitly declares a private constructor. Snippet A is valid because the compiler provides a default private constructor. Snippet D is a valid basic enum declaration.
Incorrect! Try again.
41Analyze the following Java code snippet. What will be the final value of the count variable after the loops complete?
JAVA
int count = 0;
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
continue outer;
}
if (i > 1) {
break outer;
}
count++;
}
}
Working with for loop
Hard
A.4
B.6
C.3
D.2
Correct Answer: 2
Explanation:
Let's trace the execution:
i = 0:
j = 0:i == j is true. continue outer; is executed. The inner loop terminates
Incorrect! Try again.
42Consider the following Java class. What is the output when new Demo(10); is executed?
JAVA
class Demo {
static String s1 = "Static";
String s2 = "Instance";
{
s2 = "Block";
}
static {
System.out.print(s1 + " ");
}
Demo() {
System.out.print(s2 + " ");
}
Demo(int x) {
this();
System.out.print(s1 + "-" + x + " ");
}
}
public class Main {
public static void main(String[] args) {
new Demo(10);
}
}
initializer blocks
Hard
A.Static Block Block Static-10
B.Static Instance Block Static-10
C.Static Block Instance-10
D.Block Static Instance Static-10
Correct Answer: Static Block Block Static-10
Explanation:
The order of execution is critical:
Static Initialization (once, when class is loaded):
a. The static variable s1 is initialized to "Static".
b. The static initializer block is executed. It prints "Static ".
Object Creation (new Demo(10);):
a. The constructor Demo(int x) is called.
b. Instance Initialization begins: The instance variable s2 is initialized to "Instance".
c. The instance initializer block { s2 = "Block"; } is executed. s2 is now "Block".
d. The body of Demo(int x) starts. It first calls this(), which invokes the no-argument constructor.
e. The no-argument constructor Demo() is executed. It prints the current value of s2, which is "Block ".
f. Control returns to the Demo(int x) constructor. It prints s1 + "-" + x, which is "Static-10 ".
Combining the print statements in order gives: Static Block Static-10.
Incorrect! Try again.
43Given the following methods in a class, which call will result in a compile-time error due to ambiguity?
JAVA
class OverloadTest {
void process(Integer i, int j) {
System.out.println("Integer, int");
}
void process(int i, Integer j) {
System.out.println("int, Integer");
}
void process(int... i) {
System.out.println("varargs");
}
}
// In some other method:
OverloadTest ot = new OverloadTest();
Overloading methods and constructors
Hard
A.ot.process(5);
B.ot.process(new Integer(5), 10);
C.ot.process(5, 10);
D.ot.process(5, Integer.valueOf(10));
Correct Answer: ot.process(5, 10);
Explanation:
Java's overloading resolution rules are tested here.
ot.process(5, Integer.valueOf(10)); perfectly matches process(int i, Integer j). No ambiguity.
ot.process(new Integer(5), 10); perfectly matches process(Integer i, int j). No ambiguity.
ot.process(5); does not match the two-argument methods. It matches the varargs method process(int... i). No ambiguity.
ot.process(5, 10); is ambiguous. The compiler needs to decide between process(Integer i, int j) and process(int i, Integer j). To match the first, it would need to autobox the first argument (5 to Integer). To match the second, it would need to autobox the second argument (10 to Integer). Since both options require one level of conversion (autoboxing) and neither is more specific than the other, the compiler cannot choose and reports an 'ambiguous method call' error.
Incorrect! Try again.
44What is the output of the following Java code that manipulates a jagged array?
JAVA
int[][] matrix = new int[3][];
matrix[0] = new int[]{1, 2};
matrix[1] = new int[]{3, 4, 5};
matrix[2] = matrix[0];
matrix[1][1] = 9;
matrix[2][0] = 7;
int sum = matrix[0][0] + matrix[0][1] + matrix[2][1];
System.out.println(sum);
This question tests the understanding that arrays are objects and array variables are references.
matrix[0] points to the array {1, 2}.
matrix[1] points to the array {3, 4, 5}.
matrix[2] = matrix[0]; makes matrix[2] point to the same array object as matrix[0]. They are now aliases.
matrix[1][1] = 9; changes the second array to {3, 9, 5}. This does not affect matrix[0] or matrix[2].
matrix[2][0] = 7; modifies the array pointed to by matrix[2]. Since matrix[0] points to the same array, the array is now {7, 2}. This change is visible via both matrix[0] and matrix[2].
The sum is calculated:
matrix[0][0] is now 7.
matrix[0][1] is 2.
matrix[2][1] is also 2 (since matrix[2] is the same as matrix[0]).
The final sum is 7 + 2 + 2 = 11.
Incorrect! Try again.
45What is the output of the following program?
JAVA
class Point {
int x, y;
Point(int x) {
this(x, x + 10);
this.x = x * 2;
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
void print() {
System.out.println("x=" + x + ", y=" + y);
}
}
public class Main {
public static void main(String[] args) {
new Point(5).print();
}
}
this keyword
Hard
A.x=5, y=10
B.x=10, y=15
C.x=5, y=15
D.x=10, y=10
Correct Answer: x=10, y=15
Explanation:
The key is the order of operations in the constructors due to the this() call.
new Point(5) calls the Point(int x) constructor.
The first statement in this constructor is this(x, x + 10), which is this(5, 15). This call must be the very first statement.
The Point(int x, int y) constructor is executed. It sets this.x = 5 and this.y = 15.
After the Point(int x, int y) constructor finishes, control returns to the Point(int x) constructor.
The next line in Point(int x) is this.x = x * 2;. Here, x is the parameter passed to this constructor, which is 5. So, this.x is set to 5 * 2 = 10. The value of this.x is overwritten from 5 to 10.
The y coordinate remains 15.
Finally, print() is called on the newly created object, which prints x=10, y=15.
Incorrect! Try again.
46Analyze the Java enum below. What is printed to the console?
JAVA
public enum Element {
HELIUM("He", 2) {
@Override
public boolean isReactive() { return false; }
},
SODIUM("Na", 11) {
@Override
public boolean isReactive() { return true; }
};
private final String symbol;
private final int atomicNumber;
Element(String symbol, int atomicNumber) {
this.symbol = symbol;
this.atomicNumber = atomicNumber;
System.out.print(symbol + " ");
}
public abstract boolean isReactive();
public static void main(String[] args) {
System.out.print(SODIUM.isReactive() + " ");
System.out.print(HELIUM.atomicNumber);
}
}
Enumerations
Hard
A.He Na SODIUM true 2
B.true 2
C.Na He true 2
D.He Na true 2
Correct Answer: He Na true 2
Explanation:
This question tests advanced enum features: constructors, abstract methods, and initialization order.
When the Element enum class is loaded, its constants are initialized in the order they are declared.
The HELIUM constant is created first. Its constructor Element("He", 2) is called, which prints "He ".
The SODIUM constant is created next. Its constructor Element("Na", 11) is called, which prints "Na ".
This static initialization phase happens before main is executed. So the output so far is "He Na ".
The main method starts.
System.out.print(SODIUM.isReactive() + " "); calls the overridden isReactive method for SODIUM, which returns true. This prints "true ".
System.out.print(HELIUM.atomicNumber); accesses the atomicNumber field of the HELIUM constant, which is 2. This prints "2".
The final combined output is He Na true 2.
Incorrect! Try again.
47What is the output of this code snippet involving String and StringBuilder?
JAVA
StringBuilder sb = new StringBuilder("race");
sb.append("car");
sb.reverse();
String s = sb.substring(0, 4);
s.toUpperCase();
System.out.println(s + "-" + sb.length());
String Class : Constructors and methods of String and String Builder class
Hard
A.race-7
B.ECAR-4
C.ecar-7
D.ECAR-7
Correct Answer: ecar-7
Explanation:
This question tests the difference between StringBuilder's mutable nature and String's immutability, along with method behaviors.
StringBuilder sb = new StringBuilder("race"); -> sb contains "race".
sb.append("car"); -> sb is modified to "racecar".
sb.reverse(); -> sb is modified to "racecar".
String s = sb.substring(0, 4); -> A newString object s is created with the content "ecar". The StringBuildersb remains unchanged ("racecar").
s.toUpperCase(); -> This method call returns a new String object "ECAR", but this returned value is not assigned to any variable. The original Strings is immutable and remains "ecar".
System.out.println(s + "-" + sb.length()); -> This prints the value of s ("ecar"), a hyphen, and the length of the StringBuildersb ("racecar"), which is 7.
The final output is ecar-7.
Incorrect! Try again.
48How many times will the character 'X' be printed by the following code?
JAVA
int a = 2;
int b = 20;
do {
b /= a;
System.out.print("X");
} while (b > a-- && b > 0);
Working with do-while loop
Hard
A.2
B.The loop runs infinitely.
C.1
D.3
Correct Answer: 2
Explanation:
This requires careful tracing of the loop condition
Incorrect! Try again.
49What happens when the following Java code is executed?
JAVA
public class Test {
static class Box {
int val;
Box(int v) { this.val = v; }
}
public static void main(String[] args) {
Box[] boxes = {new Box(10), new Box(20), new Box(30)};
for (Box b : boxes) {
b.val += 5;
b = new Box(0);
}
for (Box b : boxes) {
System.out.print(b.val + " ");
}
}
}
Array Access and Iterations
Hard
A.10 20 30
B.15 25 35
C.0 0 0
D.The code will throw a ConcurrentModificationException.
Correct Answer: 15 25 35
Explanation:
This question tests the behavior of the for-each loop with object references.
Box[] boxes is an array of references to three Box objects.
The first for-each loop starts. The loop variable b is a local copy of the reference from the array.
Iteration 1:b points to the same Box object as boxes[0].
b.val += 5; modifies the val field of the original object in the array. boxes[0].val is now 15.
b = new Box(0); reassigns the local loop variableb to point to a new Box object. This has no effect on the original boxes array.
Iteration 2:b points to the same Box object as boxes[1].
b.val += 5; modifies the original object. boxes[1].val is now 25.
b = new Box(0); reassigns the local b again.
Iteration 3:b points to the same Box object as boxes[2].
b.val += 5; modifies the original object. boxes[2].val is now 35.
b = new Box(0); reassigns the local b.
The second loop iterates through the boxes array, which still contains references to the original (but modified) objects. It prints the val of each, resulting in 15 25 35.
Incorrect! Try again.
50What is the result of compiling and running the following code?
JAVA
public class VarargsTest {
static void go(int x, int... y) {
System.out.print("A");
}
static void go(long x, long... y) {
System.out.print("B");
}
static void go(byte... b) {
System.out.print("C");
}
public static void main(String[] args) {
byte b = 5;
go(b, b);
}
}
Using varargs
Hard
A.C
B.A
C.B
D.A compile-time error occurs.
Correct Answer: A
Explanation:
This is a tricky overload resolution problem involving varargs, autoboxing, and widening.
The call is go(b, b), where b is a byte. So the signature is go(byte, byte).
The compiler looks for a matching method.
go(byte... b): This is a potential match. It's a varargs match.
go(int x, int... y): To match this, both byte arguments must be widened to int. This is a valid conversion (widening primitive conversion).
go(long x, long... y): To match this, both byte arguments must be widened to long. This is also a valid conversion.
Java's resolution rules prefer widening over varargs. Therefore, go(byte... b) is eliminated from consideration first.
Now the compiler must choose between go(int x, int... y) and go(long x, long... y). Both are applicable through widening.
The rule is to choose the most specific method. Widening from byte to int is a "smaller" jump than widening from byte to long. Therefore, go(int, int...) is more specific than go(long, long...).
The compiler selects go(int x, int... y). The program compiles and prints 'A'.
Incorrect! Try again.
51Analyze the following code. What are the final values of s.length() and sb.capacity()?
JAVA
StringBuilder sb = new StringBuilder(5);
sb.append("12345");
sb.insert(2, "ABC");
sb.delete(1, 4);
String s = sb.toString();
sb.append("XYZ");
*Note: The default `StringBuilder` growth strategy is typically (old_capacity * 2) + 2.*
String Builder class
Hard
A.s.length() is 5, sb.capacity() is 12
B.s.length() is 5, sb.capacity() is 5
C.s.length() is 4, sb.capacity() is 12
D.s.length() is 4, sb.capacity() is 5
Correct Answer: s.length() is 4, sb.capacity() is 12
Explanation:
This question requires a step-by-step trace of StringBuilder's state
Incorrect! Try again.
52Which statement best describes the primary constraint on using the this() constructor call in Java?
OOP Concepts : this keyword
A.It can only be used in a constructor with at least one argument.
B.It must be the first statement in the constructor's body.
C.It can only call a constructor with a less-specific access modifier (e.g., a public constructor cannot call a private one).
D.It cannot be used to call a constructor that has a varargs parameter.
Correct Answer: It must be the first statement in the constructor's body.
Explanation:
This question tests a fundamental rule of constructor chaining. The this() call is used to invoke another constructor within the same class. The Java language specification mandates that if it is used, it must be the very first statement in the constructor. This ensures that the object is properly initialized by the chained constructor before any other logic in the calling constructor is executed. The other options are incorrect: this() can be used in no-arg constructors, it can call constructors with varargs, and it can call any other constructor in the same class regardless of access modifier.
Incorrect! Try again.
53What is the result of executing the following Java code?
JAVA
public class ArrayTest {
public static void main(String[] args) {
try {
Object[] objArray = new String[5];
objArray[0] = "Hello";
objArray[1] = 100; // Autoboxed to Integer
System.out.println("Success");
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
Multi-dimensional arrays
Hard
A.ArrayStoreException
B.ClassCastException
C.Success
D.A compile-time error occurs.
Correct Answer: ArrayStoreException
Explanation:
This question addresses the concept of array covariance in Java. Because String is a subclass of Object, an array of String (String[]) can be assigned to a variable of type Object[]. This is syntactically valid and compiles without error. However, at runtime, the object is still fundamentally a String array. The line objArray[1] = 100; attempts to store an Integer object into this String array. The JVM's type system knows the actual type of the array object and prevents this, throwing an ArrayStoreException at runtime. It's not a ClassCastException because no explicit casting is performed, and it's not a compile-time error because of array covariance rules.
Incorrect! Try again.
54Analyze the following for loop. What will be the final value of j printed to the console?
JAVA
int j = 10;
for (int i = 0; i < 100; i++, j--) {
if (i == j) {
break;
}
}
System.out.println(j);
Wait, this is too easy. Let's make it harder.
New Question: What will be printed by the following code?
java
int result = 0;
for (int i = 1, j = 10; i < j; i += 2, j--) {
result += (j - i);
}
System.out.println(result);
Working with for loop
Hard
A.18
B.15
C.21
D.25
Correct Answer: 18
Explanation:
This question tests the tracking of multiple variables within a for loop's declaration and update sections.
Let's trace the loop iterations:
Body: result += (9 - 3); result becomes 9 + 6 = 15.
Update: i becomes 3 + 2 = 5, j becomes 9 - 1 = 8.
Iteration 3:
Condition: i < j (5 < 8) is true.
Body: result += (8 - 5); result becomes 15 + 3 = 18.
Update: i becomes 5 + 2 = 7, j becomes 8 - 1 = 7.
Iteration 4:
Condition: i < j (7 < 7) is false.
The loop terminates. The final value of result printed is 18.
Incorrect! Try again.
55What is the output of the following Java program?
JAVA
class OverloadPriority {
void method(int i) {
System.out.print("A");
}
void method(long l) {
System.out.print("B");
}
void method(Integer i) {
System.out.print("C");
}
void method(Object o) {
System.out.print("D");
}
public static void main(String[] args) {
OverloadPriority op = new OverloadPriority();
short s = 10;
op.method(s);
}
}
Overloading methods and constructors
Hard
A.C
B.D
C.B
D.A
Correct Answer: A
Explanation:
This question tests the overload resolution priority: Widening beats Boxing, which beats Varargs.
The argument is a short primitive s.
The compiler looks for the best match for a short argument.
Exact Match: There is no method(short s).
Widening Primitive Conversion:short can be widened to int, long, float, or double. The method(int i) and method(long l) are both applicable via widening. Between these two, int is a "smaller" or more specific conversion than long, so method(int i) is preferred over method(long l).
Autoboxing: The shorts could be autoboxed to a Short object. Then, this Short object could be passed to a method that takes a superclass, like method(Object o). There is no method(Short s).
Boxing then Widening: The shorts could be autoboxed to Short, and then the reference could be widened to Object. This matches method(Object o).
Resolution Rule: The compiler strictly prefers widening of primitives over autoboxing. Since method(int i) is available via widening, it is chosen without ever considering the boxing options (method(Integer i) or method(Object o)). Therefore, method(int i) is called, and 'A' is printed.
String Class : Constructors and methods of String and String Builder class
Hard
A.true true true
B.false true false
C.false false true
D.false true true
Correct Answer: false true true
Explanation:
This question dives deep into the String pool and the difference between string literals and new String().
s1 == s2: s1 refers to the string "abc" in the string constant pool. s2 is created using new, which explicitly creates a new object on the heap, separate from the pool. Therefore, their references are different, and the result is false.
s1 == s3: s3 is initialized with a constant expression "a" + "b" + "c". The Java compiler is smart enough to evaluate this at compile time to the single string literal "abc". Therefore, s3 will also point to the same object in the string pool as s1. The result is true.
s2.intern() == s1: The intern() method checks the string pool for a string with the same value as s2. It finds the existing string ("abc", referenced by s1). It then returns the reference to that string from the pool. So, this comparison becomes s1 == s1, which is true.
Incorrect! Try again.
57Given the following enum, what is the output of the main method?
JAVA
enum TrafficLight {
RED(30), AMBER(10), GREEN(30);
private int duration;
private TrafficLight(int duration) {
this.duration = duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getDuration() {
return this.duration;
}
public static void main(String[] args) {
TrafficLight light = TrafficLight.RED;
light.setDuration(45);
System.out.println(TrafficLight.RED.getDuration());
}
}
Enumerations
Hard
A.30
B.A runtime exception occurs.
C.A compile-time error occurs because enums cannot have setters.
D.45
Correct Answer: 45
Explanation:
This question reveals a crucial concept: enum constants are singleton instances.
RED, AMBER, and GREEN are the only three instances of the TrafficLight enum that will ever exist in the JVM.
TrafficLight light = TrafficLight.RED; creates a reference light that points to the single RED instance.
light.setDuration(45); calls the setter method on the object that light refers to. This is the one and only RED instance. This action modifies the internal state (duration field) of that singleton RED object from 30 to 45.
System.out.println(TrafficLight.RED.getDuration()); accesses the same singleton RED instance and calls its getter. Since its state was just modified, it will return the new value, 45.
This demonstrates that while enum constants are fixed, their internal state can be mutable if they are designed with mutable fields and setters, which is generally considered a poor design practice for enums.
Incorrect! Try again.
58What is the output of the following code snippet?
JAVA
class InitOrder {
private final String name;
{
System.out.print("Block 1 -> ");
// System.out.println(name); // This would be a compile error
}
InitOrder() {
name = "Default";
System.out.print("Constructor -> ");
}
{
System.out.print("Block 2 -> ");
}
public static void main(String[] args) {
InitOrder io = new InitOrder();
System.out.print(io.name);
}
}
This question tests the precise execution order of instance initializer blocks and the constructor, especially in relation to a final instance variable.
When new InitOrder() is called, the instance initialization process begins before the constructor body is executed.
Instance initializer blocks are executed in the order they appear in the source code.
First, Block 1 executes, printing "Block 1 -> ".
Second, Block 2 executes, printing "Block 2 -> ".
After all instance initializers are complete, the constructor body is executed. It initializes the final variable name to "Default" and then prints "Constructor -> ".
Finally, back in main, System.out.print(io.name) prints the value of the now-initialized name field, which is "Default".
The final output is the concatenation of these print statements: Block 1 -> Block 2 -> Constructor -> Default.
Incorrect! Try again.
59What is the final value of the sum variable?
JAVA
int x = 12345;
int sum = 0;
int k = 10000;
while (k > 0) {
sum += (x / k) % 10;
k /= 10;
}
Working with while loop
Hard
A.10
B.1
C.5
D.15
Correct Answer: 10
Explanation:
This loop seems to be summing digits
Incorrect! Try again.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill.
The rest comes out of a student's own pocket: the domain, the storage,
and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason.
to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it.
What it pays for →