Which of the following correctly declares and initializes an array of integers named 'numbers' with a size of 5?
int[] numbers = new int(5);
int[] numbers = new int[5];
✓
int numbers[5];
int numbers[] = {0, 0, 0, 0, 0};
Correct Answer
int[] numbers = new int[5];
The correct syntax for declaring an array of a specific size is to use the type followed by square brackets, the array name, an assignment operator, the new keyword, the type again, and then square brackets containing the size. The option 'int[] numbers = new int[5];' correctly follows this syntax. The option 'int numbers[] = {0, 0, 0, 0, 0};' is a valid way to declare and initialize an array, but it explicitly lists initial values rather than just specifying a size. The option 'int numbers[5];' is incorrect because in Java, the size is specified during initialization with 'new type[size]', not during declaration. The option 'int[] numbers = new int(5);' is incorrect because parentheses are used for constructors of objects, not for specifying array size; square brackets are required for array dimensions.
Question 2
Consider the following Java code snippet: int a = 10; int b = a; b = 20; What are the values of 'a' and 'b' after this code executes?
a is 20, b is 20
a is 10, b is 10
a is 10, b is 20
✓
a is 20, b is 10
Correct Answer
a is 10, b is 20
In Java, when primitive types like 'int' are assigned, a copy of the value is made. Initially, 'a' is 10. When 'b = a;' is executed, 'b' also becomes 10, but it holds its own separate copy of the value. When 'b = 20;' is executed, only the value of 'b' is changed to 20; 'a' remains unaffected. Therefore, 'a is 10, b is 20'. The option 'a is 20, b is 20' would be correct if 'a' and 'b' were reference types pointing to the same object or if 'a' was somehow updated when 'b' changed. The option 'a is 10, b is 10' would be correct if 'b' was never updated to 20. The option 'a is 20, b is 10' incorrectly swaps the final values.
Question 3
Which control flow statement is best suited for iterating over elements of an ArrayList when you need to remove elements during the iteration?
A for loop with an index that decrements
✓
A while loop using an Iterator's next() method
A for-each loop
A standard for loop with an index that increments
Correct Answer
A for loop with an index that decrements
When removing elements from an ArrayList during iteration, it is safest to use a for loop with an index that decrements. This approach prevents skipping elements when an item is removed, as subsequent elements shift their indices down. A 'for-each loop' does not allow direct removal of elements and will throw a ConcurrentModificationException if the underlying collection is modified during iteration. A 'while loop using an Iterator's next() method' is generally good for removing elements, but the question asks for a control flow statement, and a decremental for loop is a direct control flow mechanism for this specific scenario. A 'standard for loop with an index that increments' will skip elements if an item is removed at the current index because the next element shifts into the current index and is then passed over when the index increments.
Question 4
A class 'Car' has a private instance variable 'speed'. Which of the following is the best way to allow external code to safely modify the 'speed' of a 'Car' object?
A default (package-private) void updateSpeed(int s) method
A protected void changeSpeed(int delta) method
A public int speed variable
A public void setSpeed(int newSpeed) method
✓
Correct Answer
A public void setSpeed(int newSpeed) method
The best way to allow external code to safely modify a private instance variable like 'speed' is through a public setter method, such as 'public void setSpeed(int newSpeed) method'. This approach, known as encapsulation, allows the class to control how its internal state is modified, potentially including validation logic for 'newSpeed'. A 'public int speed variable' violates encapsulation by exposing the internal state directly, allowing unrestricted and potentially unsafe modification. A 'protected void changeSpeed(int delta) method' would only be accessible within the same package or by subclasses, limiting external modification. A 'default (package-private) void updateSpeed(int s) method' would only be accessible within the same package, also restricting access for general external code.
Question 5
Consider a superclass 'Animal' with a method 'makeSound()' and a subclass 'Dog' that extends 'Animal'. If 'Dog' provides its own implementation of 'makeSound()', what concept is being demonstrated?
Inheritance
Method overriding
✓
Method overloading
Polymorphism
Correct Answer
Method overriding
When a subclass provides its own specific implementation for a method that is already defined in its superclass, it is called method overriding. The option 'Method overriding' correctly describes this scenario. 'Method overloading' involves defining multiple methods with the same name but different parameter lists within the same class. 'Inheritance' is the general concept where a class acquires the properties and behaviors of another class, but it's not the specific term for redefining a superclass method. 'Polymorphism' is a broader concept that allows objects of different classes to be treated as objects of a common type, often enabled by method overriding, but overriding itself is the specific mechanism for providing a new implementation.
Question 6
What is the output of the following Java code? for (int i = 0; i < 3; i++) { System.out.print(i + " "); } System.out.println("Done");
0 1 2 3 Done
Done 0 1 2
0 1 2 Done
✓
1 2 3 Done
Correct Answer
0 1 2 Done
The for loop initializes 'i' to 0. The loop continues as long as 'i' is less than 3. In each iteration, the current value of 'i' is printed followed by a space. This means 0, then 1, then 2 will be printed. When 'i' becomes 3, the condition 'i < 3' is false, and the loop terminates. After the loop, 'System.out.println("Done");' prints "Done" on a new line. Therefore, the output is '0 1 2 Done'. The option '0 1 2 3 Done' is incorrect because the loop condition 'i < 3' means the loop stops before 'i' reaches 3. The option '1 2 3 Done' is incorrect because 'i' starts from 0. The option 'Done 0 1 2' is incorrect because "Done" is printed after the loop completes.
Question 7
Which of the following describes the purpose of a base case in a recursive method?
To declare local variables used within the method
To define the condition under which the method stops calling itself
✓
To specify the initial values for the recursive calls
To handle errors or invalid inputs to the method
Correct Answer
To define the condition under which the method stops calling itself
The base case in a recursive method is the condition that determines when the recursion should stop and a result should be returned without making further recursive calls. It is essential for preventing infinite recursion. The option 'To define the condition under which the method stops calling itself' accurately describes this purpose. The option 'To specify the initial values for the recursive calls' is incorrect; initial values are passed into the first call, not defined by the base case. The option 'To handle errors or invalid inputs to the method' is a concern for robust programming but not the primary purpose of a base case. The option 'To declare local variables used within the method' describes general variable declaration, not the specific role of a base case.
Question 8
What is the result of the expression 10 / 3 + 2 * 5 in Java?
13
✓
21
16
15
Correct Answer
13
Java follows standard order of operations (PEMDAS/BODMAS). Division and multiplication have higher precedence than addition. First, 10 / 3 is integer division, which results in 3. Next, 2 * 5 results in 10. Finally, 3 + 10 results in 13. Therefore, the result is '13'. The option '15' would be incorrect if 10 / 3 was treated as floating-point division or if addition occurred before multiplication. The option '21' would be incorrect if the operations were performed from left to right without respecting precedence (10/3=3, 3+2=5, 5*5=25, or 3+2=5, 5*5=25, not 21). The option '16' is incorrect and might result from a miscalculation like 10/3=3, 2*5=10, 3+10=13, not 16.
Question 9
Given the class public class Point { public int x; public int y; public Point(int xVal, int yVal) { x = xVal; y = yVal; } } and the code: Point p1 = new Point(5, 10); Point p2 = p1; p1.x = 20; What are the values of p1.x and p2.x after this code executes?
p1.x is 20, p2.x is 5
p1.x is 5, p2.x is 10
p1.x is 20, p2.x is 20
✓
p1.x is 5, p2.x is 20
Correct Answer
p1.x is 20, p2.x is 20
When 'Point p2 = p1;' is executed, 'p2' does not create a new 'Point' object; instead, it becomes another reference to the exact same 'Point' object that 'p1' refers to. Both 'p1' and 'p2' point to the same object in memory. Therefore, when 'p1.x = 20;' modifies the 'x' field of the object, this change is visible through both 'p1' and 'p2' because they are accessing the same object. The result is 'p1.x is 20, p2.x is 20'. The option 'p1.x is 5, p2.x is 20' incorrectly suggests that p1 retains its original x value. The option 'p1.x is 20, p2.x is 5' incorrectly suggests that p2 retains its original x value. The option 'p1.x is 5, p2.x is 10' incorrectly suggests that neither reference sees the update and that p2.x is its y value.
Question 10
What will be printed by the following code snippet? int count = 0; while (count < 5) { System.out.print(count + " "); count += 2; }
2 4 6
0 2 4 6
0 1 2 3 4
0 2 4
✓
Correct Answer
0 2 4
The 'while' loop starts with 'count' at 0. The loop condition 'count < 5' is checked. First, 0 is printed, and 'count' becomes 2. Next, 2 is printed, and 'count' becomes 4. Then, 4 is printed, and 'count' becomes 6. At this point, 'count < 5' is false, so the loop terminates. Therefore, the output is '0 2 4 '. The option '0 1 2 3 4 ' would be correct if 'count' incremented by 1 each time. The option '0 2 4 6 ' is incorrect because 6 is not printed as the loop terminates when 'count' becomes 6. The option '2 4 6 ' is incorrect because it misses the initial 0 and incorrectly includes 6.
Question 11
Which statement best describes the concept of encapsulation in object-oriented programming?
Bundling data and methods that operate on the data within a single unit, and restricting direct access to some of the component's internal state
✓
Defining multiple methods with the same name but different parameters in a class
Allowing objects of different classes to be treated as objects of a common type
Creating new classes from existing classes, inheriting their properties and behaviors
Correct Answer
Bundling data and methods that operate on the data within a single unit, and restricting direct access to some of the component's internal state
Encapsulation is the principle of bundling data (attributes) and methods (behaviors) that operate on the data into a single unit, typically a class, and restricting direct access to some of the component's internal state. This is often achieved through access modifiers like 'private' for fields and 'public' for methods. The option 'Bundling data and methods that operate on the data within a single unit, and restricting direct access to some of the component's internal state' accurately defines encapsulation. 'Creating new classes from existing classes, inheriting their properties and behaviors' describes inheritance. 'Allowing objects of different classes to be treated as objects of a common type' describes polymorphism. 'Defining multiple methods with the same name but different parameters in a class' describes method overloading.
Question 12
Given classes 'Vehicle' and 'Car' where 'Car extends Vehicle'. Which of the following assignments demonstrates polymorphism?
Vehicle myVehicle = new Vehicle();
Car myCar = new Car();
Car myCar = new Vehicle();
Vehicle myVehicle = new Car();
✓
Correct Answer
Vehicle myVehicle = new Car();
Polymorphism allows a reference variable of a superclass type to refer to an object of a subclass type. The statement 'Vehicle myVehicle = new Car();' correctly demonstrates this because 'myVehicle' is declared as a 'Vehicle' (superclass) but initialized with a 'Car' object (subclass). The option 'Car myCar = new Vehicle();' is incorrect because a superclass object cannot be assigned to a subclass reference directly without an explicit cast, which would still lead to a ClassCastException at runtime if the object is not actually a Car. The option 'Vehicle myVehicle = new Vehicle();' is a standard object instantiation, not demonstrating polymorphism. The option 'Car myCar = new Car();' is also a standard object instantiation, not demonstrating polymorphism.
Question 13
What is the primary difference between an array and an ArrayList in Java?
Arrays have a fixed size, while ArrayLists can dynamically resize.
✓
Arrays can store objects and primitives, while ArrayLists can only store primitives.
Arrays are always sorted, while ArrayLists are not.
Arrays are part of the Java Collections Framework, while ArrayLists are not.
Correct Answer
Arrays have a fixed size, while ArrayLists can dynamically resize.
The most significant difference between arrays and ArrayLists in Java is their size flexibility. Arrays have a fixed size that is determined at the time of creation and cannot be changed. ArrayLists, on the other hand, are dynamic and can automatically resize as elements are added or removed. Therefore, 'Arrays have a fixed size, while ArrayLists can dynamically resize.' is the correct statement. 'Arrays can store objects and primitives, while ArrayLists can only store primitives' is incorrect; ArrayLists can only store objects (though primitives are autoboxed). 'Arrays are part of the Java Collections Framework, while ArrayLists are not' is incorrect; ArrayLists are part of the Collections Framework, while raw arrays are not. 'Arrays are always sorted, while ArrayLists are not' is incorrect; neither arrays nor ArrayLists are inherently sorted; their elements appear in the order they were inserted or assigned unless explicitly sorted.
Question 14
Consider the following recursive method: public int mystery(int n) { if (n == 0) { return 1; } else { return 2 * mystery(n - 1); } } What is the result of calling mystery(3)?
1
6
2
8
✓
Correct Answer
8
Let's trace the call mystery(3): mystery(3) calls 2 * mystery(2). mystery(2) calls 2 * mystery(1). mystery(1) calls 2 * mystery(0). mystery(0) hits the base case and returns 1. So, mystery(1) returns 2 * 1 = 2. Then, mystery(2) returns 2 * 2 = 4. Finally, mystery(3) returns 2 * 4 = 8. Therefore, the result is '8'. The option '6' would be incorrect and might arise from adding instead of multiplying or a miscalculation. The option '2' would be incorrect and indicates an early termination or miscalculation. The option '1' is the base case return value, not the final result of mystery(3).
Question 15
Which of the following method signatures is syntactically correct for a method named 'calculateSum' that takes two integers and returns their sum?
public void calculateSum(int num1, int num2)
public int calculateSum(int num1, int num2)
✓
int calculateSum(int num1, int num2):
public int calculateSum(num1, num2)
Correct Answer
public int calculateSum(int num1, int num2)
A correct method signature in Java includes an access modifier (like 'public'), a return type (like 'int' for a sum), the method name, and a parameter list enclosed in parentheses, with each parameter specifying its type and name. The option 'public int calculateSum(int num1, int num2)' correctly follows this structure. The option 'public void calculateSum(int num1, int num2)' is incorrect because 'void' indicates no return value, but the method is supposed to return a sum. The option 'public int calculateSum(num1, num2)' is incorrect because it omits the data types for the parameters 'num1' and 'num2' in the parameter list. The option 'int calculateSum(int num1, int num2):' is incorrect because it uses a colon instead of curly braces to denote the start of the method body, and it lacks an access modifier.
Question 16
What is the purpose of the 'final' keyword when applied to a variable in Java?
It makes the variable a constant, meaning its value cannot be changed after initialization.
✓
It restricts the variable's visibility to only the class in which it is declared.
It indicates that the variable is static and shared among all instances of a class.
It allows the variable to be used in a try-with-resources statement.
Correct Answer
It makes the variable a constant, meaning its value cannot be changed after initialization.
When the 'final' keyword is applied to a variable in Java, it makes that variable a constant. This means that once the variable has been initialized, its value cannot be reassigned. The option 'It makes the variable a constant, meaning its value cannot be changed after initialization.' correctly describes this purpose. The option 'It restricts the variable's visibility to only the class in which it is declared.' describes the 'private' access modifier, not 'final'. The option 'It indicates that the variable is static and shared among all instances of a class.' describes the 'static' keyword, not 'final'. The option 'It allows the variable to be used in a try-with-resources statement.' is specific to resources in exception handling and not the general purpose of 'final' for variables.
Question 17
Which of the following code segments will print the numbers from 10 down to 1, each on a new line?
int i = 10; while (i > 0) { System.out.println(i); i++; }
for (int i = 10; i >= 1; i--) { System.out.println(i); }
✓
for (int i = 10; i > 1; i--) { System.out.println(i); }
for (int i = 1; i <= 10; i++) { System.out.println(i); }
Correct Answer
for (int i = 10; i >= 1; i--) { System.out.println(i); }
To print numbers from 10 down to 1, a loop needs to start at 10, decrement in each iteration, and continue as long as the loop variable is greater than or equal to 1. The code 'for (int i = 10; i >= 1; i--) { System.out.println(i); }' correctly implements this logic. The option 'for (int i = 1; i <= 10; i++) { System.out.println(i); }' prints numbers from 1 to 10 in ascending order. The option 'int i = 10; while (i > 0) { System.out.println(i); i++; }' creates an infinite loop because 'i' starts at 10 and keeps incrementing, always staying greater than 0. The option 'for (int i = 10; i > 1; i--) { System.out.println(i); }' prints numbers from 10 down to 2, excluding 1.
Question 18
Given a class 'Counter' with an instance variable 'count' and a static variable 'totalCounters'. Which statement is true?
Each 'Counter' object has its own 'count' and its own 'totalCounters'.
Each 'Counter' object has its own 'count', but all 'Counter' objects share the same 'totalCounters'.
✓
Only one 'Counter' object can exist if 'totalCounters' is declared.
All 'Counter' objects share the same 'count' and the same 'totalCounters'.
Correct Answer
Each 'Counter' object has its own 'count', but all 'Counter' objects share the same 'totalCounters'.
An instance variable, like 'count', belongs to each individual object (instance) of a class, meaning each 'Counter' object will have its own unique 'count' value. A static variable, like 'totalCounters', belongs to the class itself, not to any specific object. All instances of the class share the single copy of the static variable. Therefore, 'Each 'Counter' object has its own 'count', but all 'Counter' objects share the same 'totalCounters'.' is the correct statement. The option 'All 'Counter' objects share the same 'count' and the same 'totalCounters'.' is incorrect because 'count' is an instance variable. The option 'Each 'Counter' object has its own 'count' and its own 'totalCounters'.' is incorrect because 'totalCounters' is static. The option 'Only one 'Counter' object can exist if 'totalCounters' is declared.' is incorrect; static variables do not restrict the number of objects that can be created.
Question 19
Consider a class 'Shape' and a subclass 'Circle' that extends 'Shape'. If 'Shape' has a constructor 'Shape(String name)' and 'Circle' has a constructor 'Circle(String name, double radius)', what must the 'Circle' constructor do?
Explicitly define a default constructor for 'Shape'.
Call 'this(name, radius)' to initialize its own instance variables.
Call 'super(name)' as its first statement to invoke the 'Shape' constructor.
✓
Declare a new 'Shape' object within its body.
Correct Answer
Call 'super(name)' as its first statement to invoke the 'Shape' constructor.
In Java, a subclass constructor must explicitly or implicitly call a superclass constructor. If the superclass does not have a no-argument constructor and the subclass constructor needs to pass arguments to a specific superclass constructor, it must use 'super(...)' as its very first statement. In this case, 'Circle' must call 'super(name)' to initialize the 'name' part inherited from 'Shape'. The option 'Call 'super(name)' as its first statement to invoke the 'Shape' constructor.' correctly describes this requirement. The option 'Call 'this(name, radius)' to initialize its own instance variables.' would be used to call another constructor within the same 'Circle' class, not the superclass constructor. The option 'Declare a new 'Shape' object within its body.' is incorrect; the 'Circle' constructor is constructing a 'Circle' object, not a separate 'Shape' object. The option 'Explicitly define a default constructor for 'Shape'.' is not required; the 'Shape(String name)' constructor already exists and needs to be called.
Question 20
What is the correct way to declare and initialize a 2D array named 'matrix' with 3 rows and 4 columns, all elements initialized to 0?
The correct way to declare and initialize a 2D array of a specific size in Java is to use the type followed by two sets of square brackets, the array name, and then 'new type[rows][columns]'. The option 'int[][] matrix = new int[3][4];' correctly declares a 2D array with 3 rows and 4 columns, and Java automatically initializes all integer elements to 0. The option 'int matrix[][] = new int[4][3];' incorrectly swaps the number of rows and columns. The option 'int[][] matrix = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}};' is a valid way to declare and initialize a 2D array with specific values, but it's not simply specifying the size for default initialization. The option 'int matrix[3][4];' is incorrect Java syntax for array declaration; the size must be specified with 'new' during initialization.
Question 21
Given an ArrayList 'numbers' containing the integers [10, 20, 30, 40]. What will 'numbers' contain after numbers.remove(1); numbers.add(0, 5);?
[5, 20, 30, 40]
[10, 30, 40, 5]
[5, 10, 30, 40]
✓
[10, 5, 30, 40]
Correct Answer
[5, 10, 30, 40]
Initially, 'numbers' is [10, 20, 30, 40]. The call 'numbers.remove(1);' removes the element at index 1, which is 20. The list becomes [10, 30, 40]. Then, 'numbers.add(0, 5);' inserts the integer 5 at index 0, shifting existing elements to the right. The list becomes [5, 10, 30, 40]. Therefore, the final content is '[5, 10, 30, 40]'. The option '[5, 20, 30, 40]' is incorrect because it implies that 20 was not removed. The option '[10, 5, 30, 40]' is incorrect because 5 was added at index 0, not index 1. The option '[10, 30, 40, 5]' is incorrect because 5 was added at index 0, not at the end of the list.
Question 22
An interface 'Drawable' has a method 'draw()'. A class 'Square' implements 'Drawable'. Which statement is true regarding 'Square'?
'Square' can choose to implement 'draw()' or not, depending on its needs.
'Square' must extend the 'Drawable' interface.
'Square' can only implement 'Drawable' if it is an abstract class.
'Square' must provide an implementation for the 'draw()' method.
✓
Correct Answer
'Square' must provide an implementation for the 'draw()' method.
When a concrete class (a non-abstract class) implements an interface, it must provide an implementation for all abstract methods declared in that interface. If it fails to do so, the compiler will report an error. Therefore, 'Square' must provide an implementation for the 'draw()' method. The option ''Square' can choose to implement 'draw()' or not, depending on its needs.' is incorrect; a concrete class has no choice. The option ''Square' must extend the 'Drawable' interface.' is incorrect; classes implement interfaces, they extend other classes. The option ''Square' can only implement 'Drawable' if it is an abstract class.' is incorrect; an abstract class could implement an interface without providing all method implementations, but a concrete class like 'Square' must provide all implementations.