Courseiva

Oracle Java Foundations 1Z0-811 (1Z0-811) — Questions 301375

481 questions total · 7pages · All types, answers revealed

Page 4

Page 5 of 7

Page 6
301
MCQmedium

When using try-with-resources, which interface must the resource implement?

A.Serializable
B.Runnable
C.AutoCloseable
D.Comparable
AnswerC

AutoCloseable (or its subinterface Closeable) is required for try-with-resources.

Why this answer

The try-with-resources statement in Java requires that any resource declared in its parentheses implements the `AutoCloseable` interface (or its subinterface `Closeable`). This interface defines a single `close()` method, which the JVM automatically invokes at the end of the try block, ensuring proper resource management without needing an explicit `finally` block.

Exam trap

Oracle often tests the misconception that any interface with a single method (like `Runnable`) qualifies for try-with-resources, but the key requirement is that the interface must extend `AutoCloseable` and its `close()` method must be the one invoked for cleanup.

How to eliminate wrong answers

Option A is wrong because `Serializable` is a marker interface used for serializing object state to a byte stream, not for resource management. Option B is wrong because `Runnable` is a functional interface designed for thread execution via its `run()` method, not for closing resources. Option D is wrong because `Comparable` is used to define a natural ordering of objects via `compareTo()`, and has no connection to resource cleanup or the try-with-resources mechanism.

302
MCQeasy

A developer wants to iterate over an array of integers named 'numbers'. Which loop declaration will correctly access each element?

A.for (int num : numbers)
B.for (int num = 0; num < numbers.length; num++)
C.for (int num in numbers)
D.for (int num : numbers.length)
AnswerA

Correct enhanced for loop syntax.

Why this answer

It uses the enhanced for-each loop syntax, which is designed specifically for iterating over arrays and collections in Java. The colon (:) separates the element variable declaration from the array name, and each iteration assigns the next element to 'num' automatically, without needing an index or explicit bounds checking.

Exam trap

The trap here is that candidates confuse the for-each syntax with other languages (like Python's 'for x in list') and choose Option C, or they mistakenly think Option B accesses elements directly when it only increments a counter.

How to eliminate wrong answers

Option B is wrong because it uses a traditional indexed for loop with 'num' as the loop counter, not as the element value; to access the element you would need 'numbers[num]', not just 'num'. Option C is wrong because 'in' is not a valid keyword in Java for loop declarations; the correct syntax uses a colon ':', not 'in'. Option D is wrong because 'numbers.length' is an integer representing the array size, not an iterable; the for-each loop requires an array or Iterable object after the colon, not an int.

303
MCQeasy

A junior developer created a class 'BankAccount' with public fields for balance and account number. After deployment, users are able to set negative balances, causing issues. Which OOP principle should have been applied to prevent this?

A.Inheritance
B.Encapsulation
C.Abstraction
D.Polymorphism
AnswerB

Encapsulation allows controlled access through methods with validation.

Why this answer

Encapsulation involves making fields private and providing controlled access via methods. By encapsulating the balance field, a setter method can validate that the balance is not set to a negative value, preventing the issue. Option A (Inheritance) is about code reuse, not data hiding.

Option C (Abstraction) is about hiding complexity, not enforcing validation. Option D (Polymorphism) is about methods behaving differently, not data protection.

304
MCQmedium

A developer writes a method that accepts an array and returns the sum of all elements. Which implementation is correct if the array might be null?

A.public int sum(int[] arr) { if (arr.length==0) return 0; int s=0; for (int n:arr) s+=n; return s; }
B.public int sum(int[] arr) { if (arr == null) return 0; int s=0; for (int n:arr) s+=n; return s; }
C.public int sum(int[] arr) { try { int s=0; for (int n:arr) s+=n; return s; } catch(NullPointerException e) { return -1; } }
D.public int sum(int[] arr) { int s=0; for (int n:arr) s+=n; return s; }
AnswerB

Correctly handles null and empty arrays.

Why this answer

It explicitly checks for a null array before attempting to access its length or iterate over its elements. In Java, accessing `arr.length` or using an enhanced for loop on a null reference throws a `NullPointerException`. By returning 0 for null input, the method gracefully handles the edge case without crashing.

Exam trap

The trap here is that candidates often focus on handling an empty array (length 0) but forget to handle a null array, leading them to choose Option A or D, which fail with a NullPointerException.

How to eliminate wrong answers

Option A is wrong because it checks `arr.length==0` without first checking if `arr` is null, which will throw a `NullPointerException` when `arr` is null. Option C is wrong because catching `NullPointerException` and returning -1 is poor practice; it hides bugs and returns an incorrect sum (0 would be more appropriate for an empty/null array). Option D is wrong because it has no null check at all, so it will throw a `NullPointerException` when `arr` is null.

305
MCQeasy

A method is designed to reverse an array of integers. The method signature is: public static void reverse(int[] arr). The method correctly reverses the array. Which statement is true about the method?

A.It modifies the original array.
B.It returns a new array that is the reverse of the input.
C.It cannot be called with a null array.
D.It uses pass-by-value, so the original array is unchanged.
AnswerA

Since it returns void, the only way to provide the reversed array to the caller is by modifying the input array.

Why this answer

The method receives a reference to the array (pass-by-value of the reference), so any modifications made to the array elements inside the method directly affect the original array object in the caller's scope. Since the method reverses the array in-place by swapping elements, the original array is mutated.

Exam trap

Oracle often tests the misconception that Java uses pass-by-reference for objects; the trap here is that candidates think 'pass-by-value' means the original array cannot be changed, but in reality, the reference is passed by value, allowing mutation of the array's contents.

How to eliminate wrong answers

Option B is wrong because the method has a void return type, so it cannot return a new array; it reverses the array in-place. Option C is wrong because the method can be called with a null array; it would simply throw a NullPointerException at runtime, but the statement says 'it cannot be called' which is false — it can be called, though it will fail. Option D is wrong because Java uses pass-by-value for references, meaning the reference value is copied, but the object (the array) is shared; modifications to the array's elements are visible to the caller, so the original array is changed.

306
MCQeasy

A new developer writes a method that accepts an array and intends to swap the first and last elements. The code is: public static void swapEnds(int[] arr) { int temp = arr[0]; arr[0] = arr[arr.length-1]; arr[arr.length-1] = temp; } What is a potential issue with this method if the array is empty?

A.It will throw a NullPointerException.
B.It will throw an ArrayIndexOutOfBoundsException.
C.It will produce incorrect result because arr.length-1 is negative.
D.It will compile and run correctly.
AnswerB

Accessing index 0 and -1 on an empty array throws this exception.

Why this answer

When the array is empty, `arr.length` is 0, so `arr.length - 1` evaluates to -1. Accessing `arr[-1]` throws an `ArrayIndexOutOfBoundsException` because array indices must be non-negative and less than the array length. The method does not check for an empty array before attempting the swap.

Exam trap

Oracle often tests the distinction between a `null` reference and an empty array, leading candidates to mistakenly think an empty array causes a `NullPointerException` instead of an `ArrayIndexOutOfBoundsException`.

How to eliminate wrong answers

Option A is wrong because a `NullPointerException` occurs only when the array reference itself is `null`, not when the array is empty. Option C is wrong because the method does not produce an incorrect result; it throws an exception before any result can be produced. Option D is wrong because the method does not compile and run correctly for an empty array; it throws an `ArrayIndexOutOfBoundsException` at runtime.

307
Multi-Selecteasy

Which TWO of the following are valid Java identifiers? (Choose 2)

Select 2 answers
A.$value
B.my#var
C.my-var
D._myVar
E.2ndPlace
AnswersA, D

Valid: starts with $.

Why this answer

($value) is correct because Java allows identifiers to begin with a dollar sign ($) or underscore (_), and the rest can include letters, digits, or these special characters. The dollar sign is a valid starting character per the Java Language Specification (JLS §3.8), so $value is a legal identifier.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit and cannot contain special characters like # or -, but candidates may mistakenly think hyphens or hash symbols are allowed because they appear in other programming contexts or variable naming conventions.

308
Multi-Selecthard

Which THREE statements about the final keyword in Java are true?

Select 3 answers
A.A final variable cannot be reassigned after initialization.
B.A final reference variable cannot be made to refer to a different object.
C.A final method can be overridden in a subclass.
D.A final parameter in a method allows the method to modify the argument value.
E.A final class cannot be extended.
AnswersA, B, E

Correct.

Why this answer

A final variable in Java can only be assigned once. After initialization, any attempt to reassign the variable results in a compile-time error. This ensures the variable's value remains constant throughout its scope.

Exam trap

Oracle often tests the distinction between a final reference variable and the immutability of the object it refers to, leading candidates to incorrectly assume that a final reference prevents all changes to the object's state.

309
MCQeasy

A developer writes the following code: int x = 5; int y = x++; What are the values of x and y after execution?

A.x = 5, y = 5
B.x = 5, y = 6
C.x = 6, y = 5
D.x = 6, y = 6
AnswerC

Correct: y=5 (original x), then x increments to 6.

Why this answer

The post-increment operator `x++` returns the original value of `x` (5) before incrementing. Therefore, `y` is assigned 5, and `x` becomes 6 after the increment. This is a fundamental behavior of post-increment in Java.

Exam trap

The trap here is that candidates often confuse post-increment (`x++`) with pre-increment (`++x`), mistakenly thinking the incremented value is assigned to `y`.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes that `x` remains 5 after the post-increment, but `x++` always increments `x` by 1. Option B is wrong because it suggests `y` gets the incremented value (6), which would be the result of pre-increment (`++x`), not post-increment. Option D is wrong because it assumes both `x` and `y` are 6, which would only happen if `y` were assigned the incremented value, but post-increment assigns the original value first.

310
MCQeasy

Refer to the exhibit. Why does the code fail to compile?

A.Animal must be declared as interface
B.The main method is in the wrong class
C.The sound() method is not defined
D.Cannot instantiate an abstract class
AnswerD

Correct. Abstract classes cannot be instantiated directly.

Why this answer

Abstract classes cannot be instantiated. The attempt to create a new Animal() causes a compile-time error because Animal is abstract.

311
MCQmedium

A company is upgrading from Java 8 to Java 11. Which advantage does the module system introduced in Java 9 provide?

A.Better multithreading
B.Faster garbage collection
C.Stronger encapsulation of internal APIs
D.Improved lambda syntax
AnswerC

The module system allows hiding internal packages from external access.

Why this answer

The module system (Project Jigsaw) enforces stronger encapsulation of internal APIs, preventing accidental access. Options A, B, and D are incorrect: multithreading improvements are not provided by the module system, garbage collection enhancements are unrelated, and lambda syntax was introduced in Java 8.

312
MCQmedium

A developer needs to build a SQL query string by concatenating many parts. Which approach is most efficient for repeated concatenation?

A.Using StringBuffer.append()
B.Using StringBuilder.append()
C.Using String concatenation with +=
D.Using String.concat()
AnswerB

StringBuilder.append() uses a mutable buffer without synchronization, making it the most efficient for repeated concatenation.

Why this answer

StringBuilder.append() is efficient for many concatenations as it uses a mutable buffer. StringBuffer is synchronized and slower. String concatenation with '+' creates many intermediate objects.

String.concat() also creates new objects.

313
MCQhard

A developer writes: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); }. What is the output?

A.0123456789
B.13579
C.02468
D.123456789
AnswerB

Correctly prints odd numbers.

Why this answer

The loop iterates from i=0 to i=9. The `continue` statement skips the rest of the loop body when the condition `i%2==0` is true (i.e., when i is even). Therefore, only odd values of i (1, 3, 5, 7, 9) are printed, producing the output '13579'.

Option B is correct.

Exam trap

The trap here is that candidates often confuse the `continue` statement with `break` or misread the condition `i%2==0` as selecting odd numbers, leading them to choose the even-number output (02468) or the full range.

How to eliminate wrong answers

Option A is wrong because it prints all digits 0-9, which would occur only if the `continue` statement were removed or never executed. Option C is wrong because it prints even digits (0,2,4,6,8), which would result from skipping odd numbers (i%2!=0) instead of even numbers. Option D is wrong because it prints 1-9 but omits 0, which would happen if the loop started at i=1 or if the condition checked i%2==1, but the given code starts at i=0 and skips evens, so 0 is skipped and 1-9 are printed only for odds.

314
MCQeasy

Refer to the exhibit. What is the output?

A.int
B.double
C.Runtime error
D.Compilation error
AnswerA

Correct. The argument is an int due to the cast, so the int version is called, printing 'int'.

Why this answer

The code performs an integer division because the double y is cast to int, making both operands int. The result is an int value of 2. The method typeOf(int) is called, which prints the string 'int'.

Exam trap

Candidates often overlook the explicit cast and think the division is between int and double, leading to a double result. However, with the cast, the division is integer, and the method overload resolution selects the int version.

How to eliminate wrong answers

Option A is wrong because the code does not output 'int'; it produces a compilation error due to incompatible types. Option B is wrong because 'double' is not the output; the code fails to compile before any output can occur. Option C is wrong because a runtime error does not happen; the Java compiler catches the type mismatch at compile time.

Option D is correct because the assignment from double to int requires an explicit cast, and since none is provided, the compiler rejects the code.

315
MCQhard

Given: int a = 10; int b = 20; boolean flag = a++ > 10 && ++b > 20; What are the values of a and b after execution?

A.a=10, b=21
B.a=10, b=20
C.a=11, b=21
D.a=11, b=20
AnswerD

Correct: a becomes 11, b remains 20 because the right side of && is not evaluated.

Why this answer

The expression `a++ > 10 && ++b > 20` uses short-circuit evaluation. Since `a++` is post-increment, the comparison uses the original value of `a` (10) before incrementing, so `10 > 10` is false. Because the left operand is false, the `&&` operator short-circuits and the right operand `++b > 20` is never evaluated.

Therefore, `a` is incremented to 11, but `b` remains 20, making option D correct.

Exam trap

The trap here is that candidates often forget that post-increment `a++` uses the original value for the comparison but still increments `a` afterward, and they also overlook short-circuit evaluation, assuming both sides of `&&` are always evaluated.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes `a` remains 10, but post-increment `a++` always increments `a` after the comparison, so `a` becomes 11. Option B is wrong because it assumes both `a` and `b` are unchanged, but `a` is incremented to 11. Option C is wrong because it assumes the right operand `++b` is evaluated, which would make `b` 21, but short-circuit evaluation prevents this since the left operand is false.

316
Multi-Selecthard

Which THREE of the following are valid Java operators?

Select 3 answers
A.::
B.<<
C.instanceof
D.>>>
E.<==
AnswersB, C, D

Shift operator.

Why this answer

(<<) is correct because it is the Java left shift operator, which shifts the bits of an integer or long value to the left by a specified number of positions, filling with zeros. This is a valid bitwise shift operator in Java, defined in the Java Language Specification (JLS §15.19).

Exam trap

Oracle often tests candidates' familiarity with the complete set of Java operators by including plausible but invalid symbols like <== or ::, exploiting the confusion between language constructs and true operators.

317
MCQmedium

Given: int i = 1; int j = i++ + ++i; What is the value of j?

A.3
B.5
C.2
D.4
AnswerD

Correct: i++ = 1, i becomes 2; ++i = 3, i becomes 3; sum 4.

Why this answer

The expression `i++ + ++i` is evaluated as follows: First, `i++` uses the current value of i (1) and then increments i to 2. Then, `++i` increments i from 2 to 3 and uses the new value (3). So, j = 1 + 3 = 4.

Option A (3) incorrectly assumes both operations use the same initial value. Option B (5) incorrectly increments both times before using. Option C (2) incorrectly uses post-increment for both.

318
MCQmedium

Refer to the exhibit. Which action would best resolve this error without changing the code?

A.Compile with -Xlint to get more details.
B.Change the file path to a directory that exists.
C.Use a try-catch to handle FileNotFoundException.
D.Grant read permission on the file.
AnswerD

The error message explicitly says 'Permission denied', so adjusting permissions fixes the issue.

Why this answer

The error is a FileNotFoundException, which occurs when the file does not exist or cannot be opened. Since the code is correct and the file path is valid, the most likely cause is insufficient permissions. Granting read permission on the file resolves the issue without modifying the code, as it allows the JVM to access the file for reading.

Exam trap

The 1Z0-811 exam often tests the distinction between handling an exception (try-catch) and resolving its root cause (e.g., permissions), leading candidates to choose the try-catch option even though it does not fix the underlying issue.

How to eliminate wrong answers

Option A is wrong because -Xlint provides warnings about code issues (e.g., unchecked casts), not runtime file access errors; it cannot fix a FileNotFoundException. Option B is wrong because the file path is already valid (the exhibit shows an existing directory), so changing it would not address a permission issue. Option C is wrong because using a try-catch would handle the exception at runtime but does not resolve the underlying cause (lack of read permission); the question asks for an action that resolves the error without changing the code, and adding a try-catch is a code change.

319
MCQeasy

A method is declared as 'public void printElements(int... numbers)'. Which invocation will cause a compilation error?

A.printElements({1,2,3});
B.printElements(1, 2, 3);
C.printElements();
D.printElements(new int[]{1,2,3});
AnswerA

The provided invocation `printElements({1,2,3});` will cause a compilation error. Array initializer syntax, such as `{1,2,3}`, is exclusively permitted during the declaration of an array (e.g., `int[] arr = {1,2,3};`). It cannot be used directly as a standalone expression or as an argument within a method call. Although the `int... numbers` varargs parameter internally accepts an `int[]`, the compiler requires either individual `int` values or an already instantiated `int[]` object. The given syntax is not a valid way to create an anonymous array for method arguments.

Why this answer

The syntax `{1,2,3}` is an array initializer that can only be used in a variable declaration or as part of an array creation expression (e.g., `new int[]{1,2,3}`). It cannot be passed directly as an argument to a varargs method. The varargs parameter `int... numbers` expects either a sequence of `int` values or an `int[]` array reference, but not an anonymous array initializer.

Exam trap

The trap here is that candidates mistakenly think an array initializer like `{1,2,3}` can be used anywhere an array is expected, but in Java it is only valid in declarations or with `new` — not as a standalone method argument.

How to eliminate wrong answers

Option B is wrong because `printElements(1, 2, 3)` is a valid invocation — the varargs parameter `int... numbers` automatically packs the three arguments into an array. Option C is wrong because `printElements()` is a valid invocation — varargs allows zero arguments, resulting in an empty array. Option D is wrong because `printElements(new int[]{1,2,3})` is a valid invocation — an explicit array creation expression can be passed directly to a varargs parameter.

320
MCQeasy

A developer writes: int a = 9; int b = 2; double result = a / b; System.out.println(result); What is the output?

A.4
B.4.0
C.Compilation error
D.4.5
AnswerB

Integer division yields 4, stored as double.

Why this answer

(4.0). In Java, when dividing two integers, the result is integer division, which truncates the fractional part. So 9 / 2 yields 4 (int).

This int value is then assigned to a double variable, resulting in 4.0. Option A (4) would be the result of printing an int, but since result is double, it prints 4.0. Option C is incorrect because the code compiles fine.

Option D is incorrect because 4.5 would require at least one operand to be double (e.g., a / (double)b).

321
Drag & Dropmedium

Arrange the steps to use a for loop to iterate over an array in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

First set up the array, then write a for loop with proper syntax, access elements using index, execute body, and consider enhanced for.

322
MCQeasy

Given: int x = 10; int y = 20; What is the output of System.out.println(x + y * 2);?

A.40
B.60
C.30
D.50
AnswerD

Correct: due to operator precedence.

Why this answer

Multiplication has higher precedence than addition: y * 2 = 40, then x + 40 = 50.

323
Multi-Selectmedium

Which THREE are valid ways to declare and initialize a two-dimensional int array in Java?

Select 3 answers
A.int[][] arr = new int[2][2];
B.int[][] arr = new int[2][4];
C.int[][] arr = new int[][2];
D.int[][] arr = new int[2][2]{{1,2},{3,4}};
E.int[][] arr = new int[2][];
.int[][] arr = {{1,2},{3,4}};
AnswersA, B

Correct. This creates a 2x2 int array with all elements defaulting to 0.

Why this answer

`int[][] arr = new int[2][2];` uses the standard syntax for declaring and initializing a two-dimensional int array in Java, where both dimensions are specified at creation time, and all elements default to 0. The first option (null key) is correct because `int[][] arr = {{1,2},{3,4}};` uses an array initializer to declare and initialize the array with specific values in a single statement, which is valid for local variables or fields. Option B is also correct because `int[][] arr = new int[2][4];` declares and initializes a two-dimensional array with dimensions 2 and 4, which is a valid syntax; both dimensions must be positive integers.

Exam trap

Oracle often tests the distinction between valid array initialization syntax and common invalid combinations, such as mixing `new` with an array initializer or omitting the first dimension size without an initializer, which trips up candidates who confuse C-style or other language syntax with Java's rules.

324
MCQmedium

A developer compiles a Java program successfully but gets 'ClassNotFoundException' when running it. What is the most likely cause?

A.The Java version is incompatible
B.The main method signature is incorrect
C.The program has multiple classes
D.The classpath does not include the directory containing the .class file
AnswerD

ClassNotFoundException is thrown when the classpath does not contain the class.

Why this answer

ClassNotFoundException occurs when the JVM cannot find the class definition, typically due to the classpath not including the location of the .class file. Option A is wrong because Java version incompatibility leads to UnsupportedClassVersionError, not ClassNotFoundException. Option B is wrong because an incorrect main method signature causes NoSuchMethodError.

Option C is wrong because having multiple classes does not cause ClassNotFoundException unless one of them is missing from the classpath.

325
MCQeasy

Given the output, which statement is true about this Java installation?

A.It includes a Just-In-Time (JIT) compiler.
B.It runs only in interpreted mode without JIT.
C.It is a debug build of the JVM.
D.It is a Java Micro Edition (Java ME) runtime.
AnswerA

HotSpot VM always includes JIT.

Why this answer

The output shows 'mixed mode', meaning the JVM uses both an interpreter and a Just-In-Time (JIT) compiler. In a standard Java SE installation, HotSpot VM includes a JIT compiler for performance optimization. Option B is incorrect because interpreted-only mode would require the -Xint flag.

Option C is incorrect because a debug build typically includes 'debug' in the version string. Option D is incorrect because Java ME is for embedded devices and would not show a standard HotSpot VM.

326
MCQhard

Consider a method that processes a two-dimensional array (matrix). It uses nested for loops. The inner loop uses a label 'outer' to break out of the outer loop. Under what condition is this label beneficial?

A.When you want to skip the current iteration of the outer loop
B.When you need to exit the outer loop from inside the inner loop
C.When you have a single loop and need to break to a specific point
D.When you want to exit the inner loop only
AnswerB

Labeled break allows jumping out of the outer loop directly.

Why this answer

In Java, a labeled break statement allows you to exit an outer loop from within a nested inner loop. The label 'outer' is placed before the outer loop, and when the break outer; statement executes inside the inner loop, control jumps directly to the statement after the outer loop. This is beneficial specifically when you need to terminate the entire outer loop based on a condition detected inside the inner loop.

Exam trap

Oracle exams often test the distinction between labeled break and labeled continue; the trap here is that candidates confuse 'breaking out of the outer loop' with 'skipping the current iteration of the outer loop,' which is the function of a labeled continue.

How to eliminate wrong answers

Option A is wrong because skipping the current iteration of the outer loop is done with a labeled continue statement, not a labeled break. Option C is wrong because labels are only useful with nested loops; a single loop does not need a label to break—a simple break suffices. Option D is wrong because exiting only the inner loop is the default behavior of an unlabeled break; a label is unnecessary for that purpose.

327
MCQhard

Which of the following statements about the String class is true?

A.Strings can be modified using the '+' operator
B.String objects can be created only with the 'new' keyword
C.Strings are immutable
D.String is a primitive type
AnswerC

Strings in Java are indeed immutable. This means that once a `String` object has been initialised, its sequence of characters cannot be altered. Any operation that appears to modify a string, such as concatenation or substring extraction, actually results in the creation of a *new* `String` object containing the modified value, whilst the original `String` object remains unchanged in memory. This characteristic makes the statement true regarding the `String` class.

Why this answer

String objects in Java are immutable, meaning once a String object is created, its value cannot be changed. Any operation that appears to modify a String, such as concatenation, actually creates a new String object. This immutability is a fundamental design choice that enables String pooling, thread safety, and efficient caching of hash codes.

Exam trap

Oracle often tests the misconception that the '+' operator modifies the original String, leading candidates to choose option A, when in fact it creates a new String object and the original remains unchanged.

How to eliminate wrong answers

Option A is wrong because the '+' operator does not modify the original String; it creates a new String object that is the concatenation of the operands, leaving the original String unchanged. Option B is wrong because String objects can be created using string literals (e.g., "hello") without the 'new' keyword, which leverages the string constant pool. Option D is wrong because String is a reference type (a class in java.lang), not a primitive type like int, double, or boolean.

328
Multi-Selectmedium

Which two statements are true about primitive data types in Java?

Select 2 answers
A.The long data type can store values from -2^63 to 2^63-1.
B.The short data type can store values from -32,768 to 32,767.
C.The float data type is 32-bit and can represent decimal numbers precisely.
D.The boolean data type has a size of 1 bit.
E.The char data type can store only ASCII characters.
AnswersA, B

Correct: long is 64-bit signed two's complement.

Why this answer

Options A and B are correct. The long data type is 64-bit with a range from -2^63 to 2^63-1. The short data type is 16-bit with a range from -32,768 to 32,767.

Option C is false because the float data type is 32-bit and cannot represent decimal numbers precisely; it is an approximate type. Option D is false because the boolean data type's size is not strictly defined; it is typically represented as a byte or word, not a single bit. Option E is false because the char data type stores Unicode characters (16-bit) and can represent a wide range of characters beyond ASCII.

329
Multi-Selectmedium

Which three of the following are valid Java operators that can be used with primitive numeric types?

Select 3 answers
A.&
B.^
C.|
D.||
E.&&
AnswersA, B, C

& is a bitwise AND operator that works on integer types (byte, short, int, long, char).

Why this answer

Options A, B, and C are correct because &, ^, and | are bitwise operators that can be applied to integral primitive numeric types (byte, short, int, long, char). They operate on the binary representations of these types. Note that these operators are not applicable to floating-point types (float, double).

Options D and E (&&, ||) are logical operators that work only with boolean operands, not numeric types.

Exam trap

Oracle often tests the distinction between short-circuit logical operators (&&, ||) and bitwise operators (&, |, ^), trapping candidates who assume that && and || can be used with numeric types because they look similar to & and |.

330
MCQeasy

A developer is writing a method to compute the average of an array of scores. The method should handle edge cases gracefully. The scores array may be empty or contain null values if the collection was interrupted. The scores are stored as primitive doubles. Which implementation is safest and follows best practices?

A.public double average(double[] scores) { if (scores == null || scores.length == 0) return 0.0; double sum = 0; for (double s : scores) sum += s; return sum / scores.length; }
B.public double average(double[] scores) { double sum = 0; for (double s : scores) sum += s; return sum / scores.length; }
C.public double average(double[] scores) { try { double sum = 0; for (double s : scores) sum += s; return sum / scores.length; } catch (NullPointerException | ArithmeticException e) { return 0.0; } }
D.public double average(double[] scores) { if (scores == null) return 0.0; double sum = 0; for (double s : scores) sum += s; return scores.length == 0 ? 0.0 : sum / scores.length; }
AnswerD

Explicitly avoids division by zero and handles null.

Why this answer

It explicitly checks for both a null array and an empty array before performing the division. The null check prevents a NullPointerException, and the ternary operator `scores.length == 0 ? 0.0 : sum / scores.length` avoids division by zero when the array is empty. This follows best practices by handling edge cases without relying on exceptions for flow control.

Exam trap

The trap here is that candidates may think catching NullPointerException or using a single check for null is sufficient, but they overlook that an empty array requires a separate check to avoid division by zero, and that double division by zero does not throw an exception.

How to eliminate wrong answers

Option A is wrong because it returns 0.0 for an empty array, but the problem states scores are stored as primitive doubles (not Double objects), so null values in the array are impossible; however, the main flaw is that it does not check for null array, which would cause a NullPointerException if scores is null. Option B is wrong because it lacks any null or empty check, so it will throw a NullPointerException if scores is null and an ArithmeticException (division by zero) if scores.length is 0. Option C is wrong because it uses exception handling for flow control, which is poor practice; also, ArithmeticException is never thrown for double division by zero (it yields Infinity or NaN), so the catch block would not handle the empty array case correctly.

331
Drag & Dropmedium

Arrange the steps to compile and run a Java program from the command line in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

The correct order is to first write the code, then open terminal, navigate to the file location, compile with javac, and run with java.

332
MCQmedium

Refer to the exhibit. Which overloaded methods cause this compilation error?

A.public void print(String s) and public void print(String[] s)
B.public void print(String s) and public void print(String... s)
C.public void print(String[] s) and public void print(String... s)
D.public void print(Object... o) and public void print(String... s)
AnswerC

This combination causes a compilation error because a String array parameter and a String varargs parameter are considered the same after type erasure; the compiler sees them as duplicate methods.

Why this answer

Java does not allow overloading methods that differ only by the use of a varargs parameter and an array parameter of the same type. Both `public void print(String[] s)` and `public void print(String... s)` have the same method signature after erasure — they both accept a `String[]` at the bytecode level — causing a compilation error due to ambiguity.

Exam trap

The trap here is that candidates mistakenly think varargs and arrays are distinct types for overloading, but Java treats them identically after compilation, so defining both `print(String[])` and `print(String...)` causes a duplicate method error.

How to eliminate wrong answers

Option A is wrong because `public void print(String s)` and `public void print(String[] s)` have different parameter types (a single String vs. an array of String), which is a valid overload. Option B is wrong because `public void print(String s)` and `public void print(String... s)` are valid overloads; the compiler can distinguish between a single String argument and a varargs call. Option D is wrong because `public void print(Object... o)` and `public void print(String... s)` have different parameter types (Object varargs vs.

String varargs), so they are valid overloads and do not cause a compilation error.

333
MCQmedium

A team is implementing a search algorithm that iterates over an array of integers. The loop should stop as soon as the target value is found. Which loop construct is most appropriate?

A.While loop with a flag variable
B.Enhanced for loop with continue
C.Do-while loop
D.For loop with break
AnswerD

A for loop with break is the most direct way to iterate and stop on condition.

Why this answer

The most appropriate loop construct for this scenario is a for loop with a break statement. A for loop provides a concise way to iterate over an array by index, and the break statement allows the loop to terminate immediately once the target value is found, avoiding unnecessary iterations. While a while loop with a flag variable could also work, the for loop is more idiomatic and less error-prone.

An enhanced for loop supports break as well, but it lacks access to the loop index, which may be needed. A do-while loop is not suitable because it guarantees at least one iteration even if the array is empty or the target is found early. Therefore, option D is correct.

334
MCQmedium

A scientific application performs calculations with double precision. A specific formula divides two double values: result = a / b; where a and b are calculated from sensor readings. The result is expected to be at most 10 decimal digits of precision. However, the output often shows small rounding errors, e.g., 0.1 + 0.2 = 0.30000000000000004. The application must meet strict accuracy requirements and cannot tolerate these small errors. Which strategy should be used to achieve exact decimal representation?

A.Use BigDecimal with an appropriate scale and rounding mode.
B.Apply Math.round() to the result to reduce decimal places.
C.Use the float data type instead of double to reduce memory usage.
D.Cast the result to int after multiplying by a power of 10.
AnswerA

BigDecimal represents decimal numbers exactly and allows controlling precision and rounding, eliminating floating-point rounding errors.

Why this answer

Floating-point arithmetic (double) inherently has rounding errors due to binary representation, as shown in the example 0.1 + 0.2 = 0.30000000000000004. BigDecimal provides arbitrary-precision decimal arithmetic and allows specifying scale and rounding modes, making it ideal for exact decimal calculations meeting the 10-digit precision requirement. Therefore, Option A (BigDecimal) is the correct approach.

Option B (Math.round) rounds to an integer, losing fractional precision. Option C (float) uses less precision than double, worsening errors. Option D (casting to int after scaling) truncates and risks loss of information.

335
Multi-Selectmedium

Which TWO of the following are valid declarations and initializations of primitive variables?

Select 2 answers
A.double d = 10.5;
B.float f = 10.5;
C.int i = 10;
D.byte b = 200;
E.long l = 123456789012;
AnswersA, C

Valid double initialization.

Why this answer

Options A and C are correct. A: double d = 10.5; is valid because a double literal can be assigned without suffix. C: int i = 10; is valid because 10 fits in an int.

B: float f = 10.5; is invalid because 10.5 is a double literal; must use f suffix. D: byte b = 200; is invalid because 200 is out of byte range (-128 to 127). E: long l = 123456789012; is invalid because the literal exceeds int range and lacks L suffix.

336
MCQeasy

Which primitive type has a default value of 0.0f?

A.float
B.long
C.double
D.int
AnswerA

float default is 0.0f.

Why this answer

In Java, the default value for a float primitive is 0.0f. This is because float is a 32-bit IEEE 754 floating-point type, and its default initialization is 0.0f (with the 'f' suffix to denote a float literal). Option A is correct because it directly matches this specification.

Exam trap

Oracle often tests the distinction between float and double default values, where candidates mistakenly choose double (0.0d) because they overlook the 'f' suffix requirement for float literals.

How to eliminate wrong answers

Option B is wrong because long has a default value of 0L, not 0.0f; long is a 64-bit integer type. Option C is wrong because double has a default value of 0.0d, not 0.0f; double is a 64-bit floating-point type. Option D is wrong because int has a default value of 0, not 0.0f; int is a 32-bit integer type.

337
MCQeasy

Which of the following is a valid Java primitive type?

A.boolean
B.String
C.Integer
D.Char
AnswerA

Correct: boolean is one of the eight primitive types in Java.

Why this answer

`boolean` is one of the eight primitive data types defined in the Java Language Specification (JLS §4.2). It represents a single bit of information with only two possible values: `true` or `false`, and is not an object or a reference type.

Exam trap

The trap here is that candidates confuse case-sensitive naming (e.g., `Char` vs `char`) or mistake commonly used reference types like `String` and `Integer` for primitives because they are frequently used in everyday coding.

How to eliminate wrong answers

Option B is wrong because `String` is a class in the `java.lang` package, not a primitive type; it is an immutable reference type that stores sequences of characters. Option C is wrong because `Integer` is a wrapper class for the primitive `int` type, part of the `java.lang` package, and is a reference type, not a primitive. Option D is wrong because `Char` with a capital 'C' is not a valid Java primitive type; the correct primitive type is `char` (lowercase), which is a 16-bit Unicode character.

338
MCQmedium

A team is developing a Java application for an online store. The application has a class 'Inventory' that maintains an array of 'Product' objects. The method 'public void addProduct(Product p)' is intended to add a product to the array. The current implementation uses a fixed-size array of length 100. However, the business has grown, and the array may exceed its capacity. The team needs a solution that allows dynamic resizing without changing the method signature. Which approach should the team take?

A.Modify the method to use an ArrayList<Product> internally and keep the signature.
B.Change the method signature to accept a Product[] array and copy all elements.
C.Use a Collection<Product> as parameter and convert to array.
D.Change the return type to boolean and return false if array is full.
AnswerA

Allows dynamic resizing with same signature.

Why this answer

Using an ArrayList<Product> internally allows the array to dynamically resize as needed, while keeping the method signature unchanged. The method still accepts a Product parameter, but the internal implementation leverages ArrayList's automatic capacity management, eliminating the fixed-size constraint.

Exam trap

The trap here is that candidates may think changing the return type or parameter type is acceptable, but the question explicitly requires keeping the method signature unchanged, so only internal implementation changes are allowed.

How to eliminate wrong answers

Option B is wrong because changing the method signature to accept a Product[] array violates the requirement to keep the signature unchanged. Option C is wrong because using a Collection<Product> as a parameter also changes the method signature, which is not allowed. Option D is wrong because changing the return type to boolean and returning false when the array is full does not solve the capacity issue; it merely reports failure without enabling dynamic resizing.

339
MCQhard

Refer to the exhibit. What is the output?

A.Runtime error
B.Compilation error
C.Object
D.String
AnswerD

The more specific overload (String) is chosen.

Why this answer

The code exhibits method overloading with one method accepting an Object parameter and another accepting a String parameter. When a String argument is passed, Java selects the most specific matching method, which is the String version, so the output is 'String'.

Exam trap

The trap here is that candidates may not understand Java's method overloading resolution and assume the method with Object parameter will be called, leading them to choose 'Object', or they might think the code will not compile or will throw a runtime exception.

How to eliminate wrong answers

Option A is wrong because there is no runtime error; the `instanceof` check ensures the cast is safe, and the code compiles and runs without throwing an exception. Option B is wrong because the code compiles successfully; the ternary operator is syntactically valid, and both branches return a `String` type. Option C is wrong because the output is not `Object`; the `instanceof` check evaluates to true for `String`, so the cast to `String` is performed, and the `println` outputs the class name `String`.

340
MCQmedium

Which loop best suits a scenario where the number of iterations is unknown and depends on user input?

A.for loop
B.while loop
C.for-each loop
D.do-while loop
AnswerB

Condition checked before each iteration, suitable for unknown iterations.

Why this answer

The while loop is best when the number of iterations is unknown and depends on user input because it evaluates a boolean condition before each iteration, allowing the loop to continue as long as the condition remains true. This is ideal for scenarios like reading user input until a sentinel value is entered, where the exact number of iterations cannot be predetermined.

Exam trap

The trap here is that candidates often choose the do-while loop thinking it is better for user input because it always runs at least once, but the question specifies the number of iterations is unknown, and the while loop is more appropriate when the loop may need to be skipped entirely based on initial input.

How to eliminate wrong answers

Option A is wrong because a for loop is typically used when the number of iterations is known or can be calculated before the loop begins, such as iterating over a fixed range of values. Option C is wrong because a for-each loop is designed to iterate over all elements in a collection or array, and it does not allow dynamic termination based on user input. Option D is wrong because a do-while loop guarantees at least one execution, which may not be appropriate if the loop should not run at all when the user input immediately satisfies the exit condition.

341
MCQmedium

Refer to the exhibit. What is the output?

A.3
B.6
C.4
D.5
AnswerD

The output '5' arises from correctly evaluating the `length` property of the array presented in the exhibit. Java arrays provide a public `length` field, not a method, which precisely indicates the total number of elements they can hold. This scenario tests the fundamental understanding of array instantiation and how to determine its size, satisfying the constraint of correctly accessing array properties.

Why this answer

The loop iterates i=0,1,2. For i=0: count becomes 1, then 2. For i=1: count becomes 3, continue skips second increment, so count stays 3.

For i=2: count becomes 4, then 5. Output is 5.

342
MCQhard

What likely caused this compilation error?

A.The main method is missing
B.The file is saved with a .txt extension instead of .java
C.The filename does not match the public class name
D.The class name contains a typo
AnswerC

Correct: public class Test must be in Test.java file.

Why this answer

The compilation error occurs because Java requires that the public class name exactly matches the filename (including case) when the class is declared as public. If the filename is different from the public class name, the compiler will fail with an error indicating the class name is incorrect or cannot be found.

Exam trap

Oracle often tests the rule that the public class name must match the filename, and candidates mistakenly think the main method or file extension is the cause of the error.

How to eliminate wrong answers

Option A is wrong because the main method is not required for compilation; it is only required at runtime to execute the program. Option B is wrong because the file extension does not affect compilation; the compiler reads the source code regardless of extension, though .java is conventional. Option D is wrong because a typo in the class name would cause a different error (e.g., 'cannot find symbol') or a mismatch with the filename, but the core issue here is the filename mismatch, not a typo.

343
MCQeasy

A team is designing a Java application that needs to run on different operating systems without modification. Which Java feature makes this possible?

A.The Java Virtual Machine
B.Just-in-time compilation
C.Garbage collection
D.The Java compiler
AnswerA

JVM interprets bytecode on any platform, providing portability.

Why this answer

The Java Virtual Machine (JVM) is the key enabler of Java's 'write once, run anywhere' capability. When you compile Java source code, the Java compiler produces bytecode, which is platform-independent. This bytecode is then executed by the JVM, which is implemented specifically for each operating system (Windows, Linux, macOS, etc.), translating the bytecode into native machine instructions.

Therefore, the same compiled .class file can run on any OS that has a compatible JVM, without requiring any modifications to the application code.

Exam trap

Oracle often tests the misconception that the Java compiler or JIT compilation is responsible for platform independence, but the correct answer is always the JVM because it is the runtime environment that abstracts away the underlying operating system.

How to eliminate wrong answers

Option B is wrong because Just-in-time (JIT) compilation is an optimization technique used by the JVM to improve runtime performance by compiling bytecode into native machine code at runtime; it does not provide platform independence. Option C is wrong because Garbage collection is an automatic memory management feature that reclaims memory from objects no longer in use; it has no role in enabling cross-platform portability. Option D is wrong because The Java compiler (javac) translates Java source code into bytecode, but the bytecode itself is platform-independent only because the JVM interprets it; the compiler does not handle execution or OS-specific adaptation.

344
Matchingmedium

Match each Java collection interface to its characteristics.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Ordered collection allowing duplicates

Collection with no duplicates

Collection for holding elements prior to processing

Key-value pairs, keys unique

Double-ended queue supporting insertion/removal at both ends

Why these pairings

List is ordered and allows duplicates; Set is unordered and no duplicates; Queue is FIFO order; Map maps keys to values with unique keys. Common confusions include swapping List/Set characteristics or misidentifying Map as a collection of single elements.

345
MCQeasy

What is the primary purpose of Java bytecode?

A.To be executed by the Java Virtual Machine on any platform
B.To be compiled into native code once and reused
C.To be human-readable source code
D.To be directly executed by the operating system
AnswerA

Bytecode is platform-independent and executed by JVM.

Why this answer

Java bytecode is designed to be executed by the Java Virtual Machine (JVM), which interprets or compiles it to native code for the underlying platform, enabling platform independence. Option B is incorrect because bytecode is an intermediate representation that is compiled or interpreted at runtime, not compiled once into native code for reuse across platforms. Option C is incorrect because bytecode is not human-readable source code; it is a binary format.

Option D is incorrect because bytecode cannot be directly executed by the operating system; it requires the JVM to run.

346
MCQeasy

A developer writes the following code: if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else { grade = 'D'; } What is the value of grade if score is 75?

A.'B'
B.'C'
C.'D'
D.'A'
AnswerB

score >= 70 is true, so grade is assigned 'C'.

Why this answer

The code uses a cascading if-else-if structure that evaluates conditions from top to bottom. When score is 75, the first condition (score >= 90) is false, the second (score >= 80) is false, and the third (score >= 70) is true, so grade is assigned 'C'. The else block is only reached if all prior conditions are false.

Exam trap

Oracle often tests the candidate's understanding that the else-if chain stops at the first true condition, so a score of 75 correctly falls into the 'C' range, not 'D' or 'B'.

How to eliminate wrong answers

Option A is wrong because 'B' would require score >= 80, but 75 is less than 80, so the second condition fails. Option C is wrong because 'D' is assigned only if all conditions are false (score < 70), but 75 is >= 70, so the third condition is true and grade becomes 'C'. Option D is wrong because 'A' requires score >= 90, but 75 is less than 90, so the first condition fails.

347
MCQhard

A development team is building a modular Java application using Java 17. They have defined a module named com.myapp with a module-info.java that includes 'requires com.thirdparty.lib;'. The com.thirdparty.lib module is a third-party library packaged as a modular JAR with its own module-info.class. The application compiles successfully using javac with the module path pointing to the directory containing the JAR. However, when starting the application with java --module-path <path> --module com.myapp, a NoClassDefFoundError occurs for a class from com.thirdparty.lib. The error message indicates the class is not found. The team has confirmed that the JAR file is present in the specified module path and that the class exists in the JAR. No other errors or warnings are displayed. The team is puzzled because the code compiles without issues. What is the most likely cause of this runtime error?

A.The module path order is incorrect, causing a different version of the library to be loaded.
B.The library is not compatible with Java 17.
C.The application's module requires the wrong version of the library.
D.The module com.thirdparty.lib does not export the package containing the required class in its module-info.java.
AnswerD

Even though the module is on the module path, its packages are not accessible without an 'exports' directive.

Why this answer

In modular Java, a module must explicitly export a package using the 'exports' directive in its module-info.java for that package to be accessible by other modules. If com.thirdparty.lib does not export the package containing the required class, the class is present in the module but not accessible at runtime, leading to a NoClassDefFoundError even though compilation succeeded. Option D is correct because the missing exports directive causes this issue.

Option A is incorrect because module path order affects module resolution, not accessibility of exported packages; if the module is resolved, the correct JAR is used. Option B is incorrect because if the library were incompatible with Java 17, compilation would typically fail or generate different errors (e.g., UnsupportedClassVersionError). Option C is incorrect because version requirements in 'requires' are optional and generally produce compile-time warnings/errors, not a runtime NoClassDefFoundError for a class that exists.

348
MCQmedium

A developer writes a method that takes an int array and returns the sum of its elements. The method signature is: 'public static int sumArray(int[] arr)'. Which statement correctly calls this method?

A.int result = sumArray(new int[]{1,2,3});
B.int result = sumArray(true);
C.int result = sumArray([1,2,3]);
D.int result = sumArray(5);
AnswerA

This statement correctly invokes the `sumArray` method by providing an `int` array argument, precisely matching the `int[] arr` parameter defined in the method signature. The `new int[]{1,2,3}` syntax creates an anonymous integer array literal, which is then correctly passed to the static method. The method's `int` return value is subsequently assigned to the `int result` variable, ensuring type compatibility. This demonstrates the correct mechanism for passing an array argument to a static method.

Why this answer

It uses the correct syntax for creating and passing an anonymous int array to the sumArray method. The expression `new int[]{1,2,3}` creates an int array object with the specified elements, which matches the method's parameter type `int[]`. The method then returns the sum, which is assigned to the int variable `result`.

Exam trap

Oracle often tests the distinction between array initializer syntax (valid only in declarations) and anonymous array syntax (required when passing an array directly to a method), causing candidates to mistakenly use `[1,2,3]` or a single value instead of the proper `new int[]{...}` form.

How to eliminate wrong answers

Option B is wrong because it passes a boolean value `true` to a method that expects an `int[]` parameter, causing a compilation error due to type mismatch. Option C is wrong because `[1,2,3]` is not valid Java syntax for an array literal; Java requires either `new int[]{1,2,3}` or `{1,2,3}` only in variable declarations. Option D is wrong because it passes a single integer `5` instead of an int array, which does not match the method's parameter type and will cause a compilation error.

349
MCQhard

What is the value of sum printed? int sum = 0; for (int i = 0; i < 3; i++) { sum = sum + i; } System.out.println(sum);

A.6
B.0
C.3
D.1
AnswerC

The value 3 is printed because the code correctly implements an arithmetic operation or a loop that iterates precisely three times. For instance, if a `for` loop is initialised to `i = 0` and its condition is `i < 3`, the loop body will execute for `i = 0, 1, 2`, resulting in three increments to the `sum` variable. This satisfies the constraint of the loop's termination condition accurately determining the final accumulated value.

Why this answer

The loop initializes sum to 0 and iterates i from 0 to 2 inclusive. In the first iteration, sum = 0 + 0 = 0; second iteration, sum = 0 + 1 = 1; third iteration, sum = 1 + 2 = 3. After the loop, sum is printed, so the output is 3.

Option C is correct.

Exam trap

Oracle often tests the off-by-one error where candidates mistakenly include the final value (i=3) or start counting from 1 instead of 0, leading to incorrect sums like 6 or 1.

How to eliminate wrong answers

Option A is wrong because 6 would be the result if the loop ran from i=1 to i=3 inclusive (summing 1+2+3), but the loop starts at i=0 and stops when i<3, so i never reaches 3. Option B is wrong because 0 would be the result if sum was never updated (e.g., if the loop body was empty or sum was reset each iteration), but sum accumulates the values of i. Option D is wrong because 1 would be the result if only the first iteration (i=0) contributed to sum, but the loop runs three times (i=0,1,2) and sum accumulates all three values.

350
Multi-Selectmedium

Which TWO statements are true about passing arrays to methods in Java?

Select 2 answers
A.The method can reassign the original array variable to a new array.
B.The method can modify the elements of the array.
C.The method must return the array to reflect any changes.
D.The method receives a copy of the array reference.
E.The method cannot determine the size of the array.
AnswersB, D

Changes to array elements affect the original array.

Why this answer

Java passes object references by value. When an array is passed to a method, the method receives a copy of the reference to the array object. This copy still points to the same array object in heap memory, so the method can modify the elements of the array through that reference.

These modifications are visible to the caller because they affect the same underlying array object.

Exam trap

The trap here is that candidates often confuse 'pass by reference' with 'pass by value of the reference,' leading them to incorrectly believe that reassigning the parameter inside the method will affect the caller's variable (Option A), or that modifications to array elements require a return value (Option C).

351
Multi-Selecthard

Which two statements about method parameter passing in Java are true? (Choose two.)

Select 2 answers
A.When an array is passed to a method, changes to the array elements inside the method are not reflected in the caller.
B.When an array is reassigned inside a method, the original array in the caller is also reassigned.
C.When a primitive type is passed to a method, a copy of the value is passed.
D.When an object is passed to a method, a reference to the object is passed by value.
E.When a String is passed to a method, the method can modify the original String.
AnswersC, D

Primitives are pass-by-value, so the original variable is not modified.

Why this answer

Java always passes primitive types (like int, double, boolean) by value, meaning a copy of the actual value is made and passed into the method. Any modifications to the parameter inside the method affect only the copy, not the original variable in the caller.

Exam trap

The trap here is that candidates often confuse 'pass-by-reference' with 'pass-by-value of a reference,' leading them to incorrectly believe that reassigning an object parameter inside a method affects the caller's reference, or that primitive types are passed by reference.

352
Multi-Selectmedium

Which TWO statements are true about the finally block in exception handling? (Select exactly 2)

Select 2 answers
A.The finally block is executed only if an exception is thrown.
B.The finally block can be omitted only if the try block does not throw any checked exception.
C.The finally block is executed only if no exception is thrown.
D.The finally block is executed even if the try block contains a return statement.
E.The finally block is executed after the try block and any catch block, but before the method returns.
AnswersD, E

The finally block runs before the return value is passed back, ensuring cleanup.

Why this answer

The finally block is always executed regardless of whether an exception is thrown or caught, and even if the try block contains a return statement. The Java Language Specification (JLS §14.20.2) guarantees that the finally block executes after the try block and any associated catch blocks, but before control is transferred to the caller, ensuring cleanup code runs.

Exam trap

Oracle often tests the misconception that the finally block is optional or conditional based on exception occurrence, but the trap here is that candidates forget the finally block executes even with a return statement in the try block, or they incorrectly think it only runs when no exception occurs.

353
MCQmedium

A developer writes a class 'Vehicle' with a method 'move()' that prints 'Vehicle moves'. A subclass 'Car' overrides 'move()' to print 'Car moves'. Given: Vehicle v = new Car(); v.move(); What is the output?

A.Vehicle moves
B.Runtime exception
C.Compilation fails
D.Car moves
AnswerD

Correct due to polymorphism; the overridden method in Car is called.

Why this answer

Java uses dynamic method dispatch (runtime polymorphism). Even though the reference variable is of type 'Vehicle', the actual object is a 'Car' instance. At runtime, the JVM calls the overridden 'move()' method of the 'Car' class, printing 'Car moves'.

Exam trap

The trap here is that candidates mistakenly apply static binding (thinking the compiler uses the reference type 'Vehicle' to call 'move()'), ignoring Java's runtime polymorphism for overridden instance methods.

How to eliminate wrong answers

Option A is wrong because it assumes static binding (compile-time method resolution based on reference type), but Java resolves overridden instance methods at runtime based on the actual object type. Option B is wrong because no exception occurs; the code compiles and runs successfully. Option C is wrong because the code compiles without error: 'Car' extends 'Vehicle', 'move()' is properly overridden, and the assignment 'Vehicle v = new Car()' is valid upcasting.

354
MCQmedium

Refer to the exhibit. What is the output?

A.Compilation error
B.25
C.17
D.21
AnswerC

Multiplication has higher precedence than addition.

Why this answer

The expression `a * b + 2` follows Java operator precedence: multiplication has higher precedence than addition, so it evaluates as `(a * b) + 2`. Given `a = 3` and `b = 5`, `3 * 5 = 15`, then `15 + 2 = 17`. Therefore, option C is correct.

Option A is wrong because the code compiles successfully (no error). Option B (25) would result from `(a + b) * 2` or similar misinterpretation. Option D (21) would result from `a * (b + 2)`.

Only option C matches the correct calculation.

355
MCQmedium

A company requires a method that accepts an integer and returns true if the integer is even, otherwise false. Which implementation best follows Java conventions?

A.public void isEven(int num) { System.out.println(num%2==0); }
B.public int isEven(int num) { return num % 2; }
C.public boolean evenCheck(int num) { if(num%2==0) return true; else return false; }
D.public boolean isEven(int num) { return num % 2 == 0; }
AnswerD

Correct: boolean return, descriptive name, straightforward logic.

Why this answer

It defines a method with the appropriate return type `boolean`, uses a clear and conventional name `isEven`, and returns the result of the expression `num % 2 == 0` directly. This follows Java naming conventions (camelCase with a verb for boolean methods) and leverages the fact that `%` yields the remainder, which is compared to zero to produce a boolean result.

Exam trap

Oracle often tests the distinction between returning a value versus printing it, and the requirement that a method returning a boolean must have a `boolean` return type, not `int` or `void`; the trap here is that candidates may choose Option C because it 'works' syntactically, overlooking the conventional naming and unnecessarily verbose code.

How to eliminate wrong answers

Option A is wrong because the method returns `void` and prints the result instead of returning it, which does not satisfy the requirement to return `true` or `false`. Option B is wrong because it returns an `int` (the remainder) rather than a `boolean`, and a non-zero remainder does not directly represent `true` or `false` in a boolean context. Option C is wrong because although it returns a `boolean`, the method name `evenCheck` is not conventional; Java conventions favor `isEven` for boolean-returning methods, and the redundant `if-else` block is unnecessary when a direct expression suffices.

356
MCQhard

Refer to the exhibit. What is the potential issue with this singleton implementation in a multithreaded environment?

A.The getInstance() method should be non-static
B.Compilation error because the constructor is private
C.Memory leak because instances are never garbage collected
D.Not thread-safe; two threads could simultaneously create different instances
AnswerD

Correct. The check-then-act sequence is not synchronized.

Why this answer

The if-check and instantiation are not atomic. Two threads could both see instance == null and create separate instances, violating the singleton guarantee.

357
MCQmedium

What is the output of the following code? int i = 0; i = i++ + ++i; System.out.println(i);

A.3
B.0
C.1
D.2
AnswerD

The output is 2 because Java evaluates the right-hand side of the assignment `i = i++ + ++i;` from left to right. First, `i++` uses the current value of `i` (0) for the sum, then increments `i` to 1. Next, `++i` pre-increments `i` to 2, then uses this new value (2) for the sum. The addition becomes `0 + 2`, resulting in 2, which is then assigned back to `i`. This demonstrates the precise order of operator precedence and side effects in Java's expression evaluation.

Why this answer

The expression `i = i++ + ++i` evaluates as follows: initially `i = 0`. In `i++`, the post-increment operator returns the current value (0) and then increments `i` to 1. Then `++i` pre-increments `i` from 1 to 2 and returns 2.

The sum is 0 + 2 = 2, which is assigned to `i`, overwriting the intermediate increments. Thus, the final output is 2.

Exam trap

The trap here is that candidates often misapply operator precedence or confuse the order of evaluation with the order of side effects, specifically forgetting that post-increment returns the original value before the increment, while pre-increment returns the value after the increment.

How to eliminate wrong answers

Option A is wrong because 3 would result from incorrectly assuming both increments happen before the addition (e.g., i becomes 1 then 2, then 1+2=3, but the post-increment returns the original value, not the incremented one). Option B is wrong because 0 would result from mistakenly thinking the assignment uses the original value of i (0) and ignores the increments entirely. Option C is wrong because 1 would result from a common error of only counting one increment or misordering the operations (e.g., thinking i++ increments first, then ++i adds 1 to the already incremented value, yielding 1+1=2 but then assigning incorrectly).

358
MCQhard

Refer to the exhibit. A developer encounters this exception when running the application. The method divide is intended to handle division by zero. What is the most likely cause of the exception?

A.The divide method does not catch ArithmeticException.
B.The JVM is not configured to handle arithmetic exceptions.
C.The divide method uses integer division without checking the divisor.
D.The Main class does not declare throws ArithmeticException.
AnswerC

Integer division by zero throws ArithmeticException. The method should check if the divisor is zero before performing division.

Why this answer

The exception is ArithmeticException, which occurs when integer division by zero is performed. The stack trace points to line 12 inside the divide method, indicating that the method did not check whether the divisor is zero before performing the division. Option C is correct because using integer division without checking the divisor is the direct cause.

Option A is incorrect because ArithmeticException is an unchecked exception, so catching it is not mandatory. Option B is incorrect because the JVM correctly throws the exception; it is not a configuration issue. Option D is incorrect because unchecked exceptions do not need to be declared in a throws clause.

359
MCQmedium

A developer writes a method that reads a file and processes its contents. The method uses a BufferedReader wrapped around a FileReader. Which of the following approaches ensures that both resources are properly closed even if an exception occurs?

A.Close both resources in a finally block using separate try-catch for each close.
B.Use try-with-resources with both resources declared in the try header.
C.Close only the BufferedReader in a finally block.
D.Throw a custom exception after closing resources in the catch block.
AnswerB

try-with-resources ensures that each resource is closed automatically, in reverse order, even if an exception occurs.

Why this answer

Try-with-resources ensures that both the BufferedReader and FileReader are automatically closed in reverse order, even if an exception occurs. Option A is wrong because while it attempts to close both resources in separate try-catch blocks within a finally block, this approach is verbose and error-prone; if an exception occurs during the first close, the second close may be skipped unless handled carefully, and it does not guarantee resource closure as reliably as try-with-resources. Option C is wrong because closing only the BufferedReader may close the underlying FileReader due to chaining, but this approach lacks null-safety—if resource creation fails, a NullPointerException occurs when calling close, and it does not demonstrate proper exception handling or best practices.

Option D is wrong because throwing a custom exception after closing resources does not ensure both are closed; it adds unnecessary complexity and may leave resources open if close methods throw exceptions.

360
Multi-Selecthard

Which THREE of the following are primitive data types in Java?

Select 3 answers
A.String
B.double
C.int
D.array
E.boolean
AnswersB, C, E

Primitive type.

Why this answer

`double` is one of the eight primitive data types in Java, used to store floating-point numbers with double precision (64-bit IEEE 754). It is a fundamental type that holds a numeric value directly, not an object reference.

Exam trap

Oracle often tests the distinction between primitive types and reference types, trapping candidates who mistakenly think `String` or `array` are primitives because they are commonly used and have literal syntax (e.g., `"hello"` or `{1,2,3}`).

361
MCQhard

A Java application uses an interface 'Drawable' with a default method 'draw()'. A class 'Circle' implements Drawable but does not override draw(). Another class 'Square' implements Drawable and overrides draw(). Which statement is true about calling draw() on instances of Circle and Square?

A.Circle will use the default, Square will use its own
B.Square will use the default, Circle will cause a compilation error
C.Both will use the default implementation
D.Both will cause a compilation error
AnswerA

If a class does not override a default method, it inherits the default.

Why this answer

When a class implements an interface with a default method, the class inherits the default implementation unless it overrides the method. Circle does not override draw(), so it uses the default implementation from the Drawable interface. Square overrides draw(), so it uses its own version.

Option B is incorrect because Square uses its own method, not the default. Option C is incorrect because Square does not use the default. Option D is incorrect because both classes compile successfully.

362
MCQmedium

Which method invocation is ambiguous given these overloaded methods? public void process(int[] a) and public void process(int... a)

A.process(1, 2);
B.process((int[]) null);
C.process();
D.process(new int[]{1, 2});
AnswerD

Both methods accept an int array, causing ambiguity.

Why this answer

When you call process(new int[]{1, 2}), the compiler cannot determine whether to use the method with an int[] parameter or the varargs method (int... a). Both methods have the same signature after type erasure, and the argument is an int array, which matches both exactly, causing an ambiguity error.

Exam trap

The trap here is that candidates think varargs and array parameters are distinct, but they are not; the compiler treats them as identical when the argument is an array, leading to ambiguity.

How to eliminate wrong answers

Option A is wrong because process(1, 2) passes two int arguments, which unambiguously matches the varargs method (int... a) since the array method requires a single int[] argument. Option B is wrong because process((int[]) null) explicitly casts null to int[], which unambiguously matches the array method (int[] a) and not the varargs method. Option C is wrong because process() with no arguments unambiguously matches the varargs method (int... a) with an empty array, and does not match the array method which requires an int[] argument.

363
MCQmedium

Refer to the exhibit. What happens when you compile this code?

A.Compilation fails because of type mismatch
B.Compilation fails because num is final
C.Prints "Five"
D.Prints nothing
AnswerB

Incorrect. Although `num` is final, the specific error is a type mismatch because assigning to a final variable is illegal. The option's phrasing is too vague.

Why this answer

The code fails to compile because the variable `num` is declared as `final`, meaning its value cannot be changed after initialization. The switch statement attempts to assign a new value to `num` in each case label (e.g., `case 1: num = 5;`), which results in a compilation error: cannot assign a value to a final variable. This is not a type mismatch; it is a violation of the final constraint.

Exam trap

Oracle often tests the distinction between using a final variable in a switch expression (allowed) versus attempting to reassign it inside the switch body (not allowed), leading candidates to incorrectly assume that final variables can be modified in any context.

How to eliminate wrong answers

Option B is wrong because the compilation fails due to the attempt to reassign a final variable, not because the variable is final itself (final variables are allowed in switch statements as long as they are not modified). Option C is wrong because the code never compiles, so no output is produced, let alone 'Five'. Option D is wrong because the code does not compile, so nothing is printed, but the correct outcome is a compilation failure, not a silent runtime behavior.

364
Multi-Selectmedium

Which THREE of the following are valid types that can be used as a switch expression in Java (as of Java 8)?

Select 3 answers
A.long
B.String
C.char
D.int
E.boolean
AnswersB, C, D

String is valid since Java 7.

Why this answer

In Java 8, a switch expression can use `String`, `char`, and `int` as valid types. `String` was added in Java 7, and `char` and `int` are among the original primitive types supported. `long` and `boolean` are not allowed because `long` is a 64-bit type not supported by the switch statement's underlying `tableswitch` or `lookupswitch` bytecode instructions, and `boolean` has only two values, making it unsuitable for switch's multi-branch logic.

Exam trap

The 1Z0-811 exam often tests the misconception that `long` is a valid switch type because it is a numeric primitive, but the JVM's switch bytecode only supports 32-bit integer types, making `long` invalid.

365
MCQhard

What is the value printed?

A.3
B.5
C.2
D.0
AnswerC

Only i=1 and i=3 increment count.

Why this answer

The while loop condition is `x < 2`, so the loop executes while x is less than 2. Initially x=0. In the first iteration, x becomes 1; in the second, x becomes 2.

After the second iteration, x=2, the condition `2 < 2` is false, so the loop stops. The code prints the value of x, which is 2 after the loop exits.

Exam trap

Oracle often tests the off-by-one error where candidates miscount loop iterations or confuse the final value of the loop variable with the sum, leading them to pick 3 (the value after the loop exits) instead of 2 (the value when the condition fails).

How to eliminate wrong answers

Option A (3) is wrong because if the loop condition were `x < 3`, `x` would become 3 after the third iteration, but the loop stops when `x` is 3, so printing `x` would give 3, but the correct answer is 2, meaning the condition is `x < 2`. Option B (5) is wrong because it might result from incorrectly summing values (e.g., 1+2+2) or misreading the loop bounds. Option D (0) is wrong because the loop executes at least once (since `x` starts at 0 and the condition `x < 2` is true), so `x` is incremented and printed as 2, not 0.

366
MCQmedium

A method 'public static int findMax(int[] numbers)' returns the maximum value in the array. Which implementation correctly handles an empty array by returning 0?

A.int max = 0; for(int n: numbers) if(n > max) max = n; return max;
B.int max = numbers[0]; for(int i=1; i<numbers.length; i++) if(numbers[i] > max) max = numbers[i]; return max;
C.if(numbers.length == 0) return 0; int max = 0; for(int n: numbers) if(n > max) max = n; return max;
D.if(numbers.length == 0) return 0; int max = numbers[0]; for(int i=1; i<numbers.length; i++) if(numbers[i] > max) max = numbers[i]; return max;
AnswerD

Correctly handles empty and non-empty arrays.

Why this answer

Ly handles an empty array by checking `numbers.length == 0` and returning 0 before attempting to access `numbers[0]`, which would throw an `ArrayIndexOutOfBoundsException` on an empty array. It then initializes `max` to the first element and iterates from index 1, ensuring all elements are compared correctly even if all numbers are negative.

Exam trap

The trap here is that candidates often choose Option C because they see the empty check but overlook that initializing `max` to 0 instead of the first element causes incorrect results for arrays with all negative numbers, which the exam frequently uses to test understanding of edge cases and initialization logic.

How to eliminate wrong answers

Option A is wrong because it initializes `max = 0`, which fails if all array elements are negative (returns 0 instead of the actual maximum negative value) and does not handle an empty array (returns 0 but without explicit check, which is acceptable only if the spec requires returning 0 for empty arrays, but the lack of check is a design flaw). Option B is wrong because it accesses `numbers[0]` without checking if the array is empty, causing an `ArrayIndexOutOfBoundsException` at runtime. Option C is wrong because it initializes `max = 0` after the empty check, so it still fails for arrays with all negative numbers (returns 0 instead of the correct negative maximum).

367
MCQmedium

Refer to the exhibit. What is the most likely cause?

A.The array has 6 elements.
B.The code tries to access index 4 of a 5-element array.
C.The code tries to access index 5 of a 5-element array.
D.The code has a syntax error.
AnswerC

Indices 0-4 are valid; index 5 is out of bounds.

Why this answer

Java arrays are zero-indexed, meaning a 5-element array has valid indices 0 through 4. Accessing index 5 attempts to read beyond the array bounds, causing an ArrayIndexOutOfBoundsException at runtime. This is a classic off-by-one error where the code mistakenly uses the array length as the index.

Exam trap

Oracle often tests the off-by-one error where candidates mistakenly think the last valid index is the array length (e.g., 5) instead of length-1 (e.g., 4), leading them to choose option B or misidentify the array size.

How to eliminate wrong answers

Option A is wrong because stating 'the array has 6 elements' is a misinterpretation of the error; the array actually has 5 elements, and the problem is not about the count but about accessing an invalid index. Option B is wrong because accessing index 4 of a 5-element array is perfectly valid (indices 0-4), so that would not cause an exception. Option D is wrong because the code compiles successfully; the error is a runtime exception, not a syntax error.

368
MCQmedium

A company's application uses a switch statement to handle different user roles. The code currently has a bug where after processing one role, it unintentionally executes the next role's logic. Which concept is being misused?

A.Missing break statements causing fall-through
B.Incorrect default case
C.Using enum in switch
D.Using string in switch (Java 7+)
AnswerA

Missing break allows execution to continue into subsequent cases.

Why this answer

In Java, a switch statement without break statements causes fall-through, where execution continues into subsequent case blocks even after a match is found. This is exactly the bug described: after processing one role, the code unintentionally executes the next role's logic because no break terminates the case.

Exam trap

The trap here is that candidates may confuse the cause of fall-through with other switch features, such as the default case or valid types, when the core issue is simply the absence of break statements.

How to eliminate wrong answers

Option B is wrong because an incorrect default case would affect only unmatched values, not cause fall-through between matched cases. Option C is wrong because using an enum in a switch is valid and does not inherently cause fall-through; the bug is independent of the type used. Option D is wrong because using a String in a switch (introduced in Java 7) is also valid and does not cause fall-through; the issue is missing break statements, not the data type.

369
MCQeasy

An application throws 'java.lang.OutOfMemoryError: Java heap space'. Which JVM option can help generate diagnostic information to identify the cause?

A.-version
B.-verbose:gc
C.-XX:+HeapDumpOnOutOfMemoryError
D.-Xmx
AnswerC

This option produces a heap dump when OutOfMemoryError occurs, useful for analysis.

Why this answer

XX:+HeapDumpOnOutOfMemoryError instructs the JVM to generate a heap dump file when an OutOfMemoryError occurs, which can be analyzed to identify memory leaks or other causes. Option A (-version) prints the Java version and does not help with diagnostics. Option B (-verbose:gc) prints garbage collection details but does not produce a heap dump at the time of failure.

Option D (-Xmx) sets the maximum heap size, which may delay or prevent the error but does not provide diagnostic information about the cause.

370
MCQhard

Given a method that catches Exception and then throws a RuntimeException, what is the effect?

A.The RuntimeException will not propagate if caught.
B.The method can throw RuntimeException without declaring it.
C.The method must declare throws RuntimeException.
D.The catch block cannot throw a RuntimeException because it is caught as Exception.
AnswerB

RuntimeException is unchecked, no throws required.

Why this answer

In Java, RuntimeException is an unchecked exception, meaning it does not need to be declared in a method's throws clause. The catch block catches Exception (which includes RuntimeException), and then throws a new RuntimeException. Since RuntimeException is unchecked, the method can throw it without declaring it, making option B correct.

Exam trap

The trap here is that candidates mistakenly think any exception thrown from a catch block must be declared, forgetting that RuntimeException and its subclasses are unchecked and exempt from the throws requirement.

How to eliminate wrong answers

Option A is wrong because the RuntimeException is thrown after being caught, so it will propagate up the call stack unless caught again by an outer handler. Option C is wrong because RuntimeException is an unchecked exception, so the method is not required to declare it in a throws clause. Option D is wrong because a catch block can throw any exception, including RuntimeException, even if the caught exception is of type Exception; there is no restriction preventing this.

371
Matchingmedium

Match each Java keyword to its use.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Prevents modification: variable constant, method override, class inheritance

Belongs to the class rather than instances

Cannot be instantiated; used for classes and methods

Ensures mutual exclusion in multithreading

Marks field to be ignored during serialization

Why these pairings

Keywords in Java have specific meanings. Static members are class-level, final prevents modification, abstract requires subclassing, and synchronized controls thread access. Distractors confuse static with final.

372
MCQhard

A method returns a String. The team debates using == vs equals(). Which correctly describes String comparison in Java?

A.== compares the content of two Strings.
B.== always returns false for different String objects, even if content is same.
C.equals() compares the memory addresses.
D.== may return true for two different references if they point to the same interned string.
AnswerD

String literals are interned; == can be true for same literal.

Why this answer

The == operator in Java compares object references, not content. However, due to string interning, two different String variables that reference the same interned string literal will have the same memory reference, causing == to return true. This is a special case that can mislead developers into thinking == compares content.

Exam trap

The trap here is that candidates often assume == always compares references and never returns true for equal content, but they forget about string interning, which can cause == to return true for two different references pointing to the same interned string.

How to eliminate wrong answers

Option A is wrong because == compares memory addresses (references), not the content of Strings. Option B is wrong because == can return true for different String objects if they are interned and point to the same memory location. Option C is wrong because equals() compares the actual character content of the Strings, not memory addresses.

Page 4

Page 5 of 7

Page 6

All pages