Unit 2 - Practice Quiz
1 Which loop is best suited for scenarios where the number of iterations is known beforehand?
for-each loop
for loop
do-while loop
while loop
2
What is the primary characteristic of a while loop?
3 Which loop structure guarantees that its body will be executed at least once?
enhanced for
for
while
do-while
4
The for-each loop in Java is primarily used for which purpose?
5 How do you correctly declare and initialize an array of 3 integers in a single line in Java?
int arr[] = {10, 20, 30};
int arr = {10, 20, 30};
int arr[3] = {10, 20, 30};
int[] arr = new int(3);
6
If an array is declared as String[] names = new String[10];, what is the valid range of indices for this array?
7 Which of the following correctly declares a 2x3 two-dimensional integer array?
int matrix[][] = new int(2, 3);
int[] matrix = new int[2][3];
int[][] matrix = new int[2][3];
int matrix[2][3] = new int[][];
8 What does the 'varargs' feature in Java allow?
9 Which keyword is used to create an enumeration in Java?
enumeration
enum_class
constants
enum
10
Consider the enum enum Level { LOW, MEDIUM, HIGH }. How would you access the MEDIUM constant?
"MEDIUM"
Level[1]
Level(MEDIUM)
Level.MEDIUM
11 In Java, what is an object?
int or char.
12 What is the main purpose of a constructor in a Java class?
13 What is method overloading?
14 Is it possible to overload constructors in Java?
15
Inside an instance method or a constructor, what does the this keyword refer to?
16 What is an instance initializer block in a Java class?
{} that is executed every time an instance of the class is created.
static keyword.
17
Which of the following is a key characteristic of String objects in Java?
18
Which method of the String class is used to find the number of characters in a string?
length()
getSize()
size()
count()
19
What would "hello".charAt(1) return?
'e'
"e"
'h'
20
When you need to perform many modifications on a sequence of characters, which class is generally more efficient than String?
Char
StringBuilder
StringReader
StringArray
21
What 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);
}
}
22
What 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);
}
}
23
What 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);
}
}
ArrayIndexOutOfBoundsException is thrown.
24
Consider 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 + " ");
}
}
}
25
Which 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);
}
}
26
What 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());
}
}
27
What 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);
}
}
28
What 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);
}
}
29
Predict 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);
}
}
30
What 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();
}
}
31
What 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();
}
}
32
Analyze 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);
}
}
33
What 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);
}
}
34
What 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));
}
}
35
What 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);
}
}
36
What 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]);
}
}
37
How 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("#");
}
}
}
38
What 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);
}
}
39
Given 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);
}
}
40
Which 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; }
41
Analyze 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++;
}
}
42
Consider 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);
}
}
43
Given 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();
ot.process(5, Integer.valueOf(10));
ot.process(new Integer(5), 10);
ot.process(5);
ot.process(5, 10);
44
What 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);
ArrayIndexOutOfBoundsException occurs.
45
What 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();
}
}
46
Analyze 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);
}
}
47
What 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());
48
How 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);
49
What 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 + " ");
}
}
}
ConcurrentModificationException.
50
What 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);
}
}
51
Analyze 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.*
s.length() is 5, sb.capacity() is 12
s.length() is 4, sb.capacity() is 12
s.length() is 4, sb.capacity() is 5
s.length() is 5, sb.capacity() is 5
52
Which statement best describes the primary constraint on using the this() constructor call in Java?
varargs parameter.
53
What 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());
}
}
}
54
Analyze 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);
55
What 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);
}
}
56
What is the output of the following code?
java
String s1 = "abc";
String s2 = new String("abc");
String s3 = "a" + "b" + "c";
System.out.print(s1 == s2);
System.out.print(" ");
System.out.print(s1 == s3);
System.out.print(" ");
System.out.print(s2.intern() == s1);
57
Given 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());
}
}
58
What 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);
}
}
59
What 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;
}