Unit 2 - Practice Quiz

CSE310 59 Questions
0 Correct 0 Wrong 59 Left
0/59

1 Which 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-each loop
B. for loop
C. do-while loop
D. while loop

2 What is the primary characteristic of a while loop?

Working with for loop, while loop, do-while loop and for-each loop Easy
A. It always executes at least once.
B. It can only be used with arrays.
C. It checks the condition before executing the loop body.
D. It requires a counter variable initialized in the loop statement.

3 Which 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. enhanced for
B. for
C. while
D. do-while

4 The 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. Iterating over the elements of an array or collection
B. Creating an infinite loop
C. Executing a loop for a specific number of times
D. Executing a loop body at least once

5 How do you correctly declare and initialize an array of 3 integers in a single line in Java?

Fundamentals about Arrays Easy
A. int arr[] = {10, 20, 30};
B. int arr = {10, 20, 30};
C. int arr[3] = {10, 20, 30};
D. 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?

Array Access and Iterations Easy
A. 0 to 9
B. 1 to 10
C. 1 to 9
D. 0 to 10

7 Which 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 = new int[2][3];
C. int[][] matrix = new int[2][3];
D. int matrix[2][3] = new int[][];

8 What does the 'varargs' feature in Java allow?

Using varargs Easy
A. A class to have a variable number of constructors.
B. A method to accept a variable number of arguments of the same type.
C. A variable to change its data type at runtime.
D. An array to change its size after creation.

9 Which keyword is used to create an enumeration in Java?

Enumerations Easy
A. enumeration
B. enum_class
C. constants
D. enum

10 Consider the enum enum Level { LOW, MEDIUM, HIGH }. How would you access the MEDIUM constant?

Enumerations Easy
A. "MEDIUM"
B. Level[1]
C. Level(MEDIUM)
D. Level.MEDIUM

11 In Java, what is an object?

Basics of class and objects Easy
A. A primitive data type like int or char.
B. An instance of a class.
C. A special type of method.
D. A template or blueprint for creating classes.

12 What 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 initialize a newly created object.
D. To destroy an object and free memory.

13 What 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 and the same parameters.
C. Creating a method that can handle any data type.
D. A class having two methods with the same name but different parameters.

14 Is 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.

15 Inside an instance method or a constructor, what does the this keyword refer to?

this keyword Easy
A. The superclass of the current object.
B. The class itself.
C. A static member of the class.
D. The current object instance.

16 What is an instance initializer block in a Java class?

initializer blocks Easy
A. Another name for a no-argument constructor.
B. A special method used to initialize static variables.
C. A block of code inside {} that is executed every time an instance of the class is created.
D. A block of code prefixed with the static keyword.

17 Which 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 are immutable.
B. They can only store numbers.
C. They are mutable.
D. They have a fixed size of 256 characters.

18 Which 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. length()
B. getSize()
C. size()
D. count()

19 What would "hello".charAt(1) return?

String Class : Constructors and methods of String and String Builder class Easy
A. 'e'
B. 1
C. "e"
D. 'h'

20 When 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. StringBuilder
C. StringReader
D. 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);
}
}

Working with for loop, while loop, do-while loop and for-each loop Medium
A. 4
B. 6
C. 5
D. 3

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);
}
}

Working with for loop, while loop, do-while loop and for-each loop Medium
A. 7
B. 13
C. 10
D. The code will not compile.

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);
}
}

Multi-dimensional arrays Medium
A. 15
B. 13
C. An ArrayIndexOutOfBoundsException is thrown.
D. 9

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 + " ");
}
}
}

Array Access and Iterations Medium
A. 15 25 35
B. 5 5 5
C. 10 20 30
D. The code will not compile.

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);
}
}

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

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());
}
}

Enumerations Medium
A. YELLOW
B. Wait
C. Signal.YELLOW
D. The code will not compile because enums cannot have constructors.

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);
}
}

Basics of class and objects Medium
A. 10 10
B. 10 5
C. 10 20
D. 20 20

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);
}
}

Overloading methods and constructors Medium
A. Method B
B. The code fails to compile due to an ambiguous method call.
C. The code compiles but throws a runtime exception.
D. Method A

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);
}
}

Overloading methods and constructors Medium
A. C1 2023
B. C2 2023
C. C2 C1 2023
D. C1 C2 2023

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();
}
}

this keyword Medium
A. x=10, y=20
B. x=0, y=0
C. x=10, y=0
D. x=0, y=20

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();
}
}

Initializer blocks Medium
A. S I C S I C
B. I C I C S
C. S C I C I
D. S I C I C

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);
}
}

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

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);
}
}

String Class : Constructors and methods of String and String Builder class Medium
A. stle
B. startle
C. sle
D. sttle

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));
}
}

String Class : Constructors and methods of String and String Builder class Medium
A. false, false, true
B. false, true, true
C. true, false, true
D. true, true, true

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);
}
}

this keyword Medium
A. The code will not compile.
B. 12
C. 10
D. 7

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]);
}
}

Fundamentals about Arrays Medium
A. false, true, 5
B. true, false, 2
C. false, true, 2
D. true, true, 5

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("#");
}
}
}

Working with for loop, while loop, do-while loop and for-each loop Medium
A. 6
B. 5
C. 10
D. 4

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);
}
}

String Class : Constructors and methods of String and String Builder class Medium
A. Length: 12, Capacity: 12
B. Length: 11, Capacity: 5
C. Length: 11, Capacity: 12
D. Length: 11, Capacity: 11

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);
}
}

Writing constructors and methods Medium
A. The Great Gatsby
B. 1984
C. A Tale of Two Cities
D. Moby Dick

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; }

Enumerations Medium
A. Snippet C
B. Snippet A
C. Snippet B
D. Snippet D

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++;
}
}

Working with for loop Hard
A. 6
B. 3
C. 2
D. 4

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);
}
}

initializer blocks Hard
A. Block Static Instance Static-10
B. Static Block Instance-10
C. Static Block Block Static-10
D. Static Instance Block Static-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();

Overloading methods and constructors Hard
A. ot.process(5, Integer.valueOf(10));
B. ot.process(new Integer(5), 10);
C. ot.process(5);
D. 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);

Multi-dimensional arrays Hard
A. 11
B. 12
C. A runtime ArrayIndexOutOfBoundsException occurs.
D. 10

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();
}
}

this keyword Hard
A. x=5, y=15
B. x=5, y=10
C. x=10, y=15
D. x=10, y=10

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);
}
}

Enumerations Hard
A. Na He true 2
B. true 2
C. He Na SODIUM true 2
D. He Na true 2

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());

String Class : Constructors and methods of String and String Builder class Hard
A. ECAR-4
B. ecar-7
C. ECAR-7
D. race-7

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);

Working with do-while loop Hard
A. 3
B. 2
C. 1
D. The loop runs infinitely.

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 + " ");
}
}
}

Array Access and Iterations Hard
A. The code will throw a ConcurrentModificationException.
B. 0 0 0
C. 10 20 30
D. 15 25 35

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);
}
}

Using varargs Hard
A. C
B. A compile-time error occurs.
C. B
D. A

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.*

String Builder class Hard
A. s.length() is 5, sb.capacity() is 12
B. s.length() is 4, sb.capacity() is 12
C. s.length() is 4, sb.capacity() is 5
D. s.length() is 5, sb.capacity() is 5

52 Which 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 can only call a constructor with a less-specific access modifier (e.g., a public constructor cannot call a private one).
C. It cannot be used to call a constructor that has a varargs parameter.
D. It must be the first statement in the constructor's body.

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());
}
}
}

Multi-dimensional arrays Hard
A. ClassCastException
B. ArrayStoreException
C. A compile-time error occurs.
D. Success

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);

Working with for loop Hard
A. 18
B. 15
C. 25
D. 21

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);
}
}

Overloading methods and constructors Hard
A. C
B. D
C. B
D. A

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);

String Class : Constructors and methods of String and String Builder class Hard
A. false true true
B. false true false
C. true true true
D. false false true

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());
}
}

Enumerations Hard
A. A compile-time error occurs because enums cannot have setters.
B. 30
C. A runtime exception occurs.
D. 45

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);
}
}

initializer blocks Hard
A. Block 1 -> Block 2 -> Constructor -> Default
B. The code will not compile.
C. Constructor -> Block 1 -> Block 2 -> Default
D. Block 1 -> Constructor -> Block 2 -> Default

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;
}

Working with while loop Hard
A. 1
B. 15
C. 10
D. 5