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

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

Page 5

Page 6 of 7

Page 7
376
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

Option B is correct because 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).

377
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

Option C is correct because 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.

378
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

Option D is correct because 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.

379
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

Option D is correct because 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.

380
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

Option B is correct: a*b = 15, then +2 = 17. Option A is wrong (multiplication first). Option C is wrong (assuming parentheses around b+2).

Option D is wrong because no error.

381
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

Option D is correct because 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.

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

383
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

Correct: i=0, i++ gives 0 (i=1), ++i gives 2 (i=2), 0+2=2.

Why this answer

Option D is correct because 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).

384
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 ArithmeticException is an unchecked exception thrown by the JVM when integer division by zero occurs. The stack trace points to line 12 in Calculator.java, which is inside the divide method. The most likely cause is that the divide method does not check if the divisor is zero before performing division.

Option A is incorrect because catching is not mandatory for unchecked exceptions. Option C is incorrect because unchecked exceptions do not need to be declared. Option D is incorrect because the JVM correctly throws the exception; it is not a configuration issue.

385
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

Option B is correct because try-with-resources automatically closes resources declared in the try header in reverse order. Option A is wrong because closing only the outer resource may not close the inner one if wrapped incorrectly. Option C is wrong because closing in the finally block without checking for null can cause NullPointerException if resource creation fails.

Option D is wrong because throwing an exception before close statements prevents cleanup.

386
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

Option B is correct because `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}`).

387
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

Option B is correct because classes inherit default interface methods; Circle inherits the default, Square overrides it. Option A is wrong because Square uses its own version. Option C is wrong because Circle does not cause an error.

Option D is wrong because both compile successfully.

388
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

Option D is correct because 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.

389
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
AnswerA

Correct. Assignment returns int, not boolean.

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 violates the final variable constraint, causing a compilation error due to type mismatch (the assignment is incompatible with the final modifier).

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.

390
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

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

391
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 code prints 2 because the `while` loop condition `x < 3` is checked before each iteration. Initially `x = 0`, then `x++` increments it to 1, and `sum += x` makes `sum = 1`. Next iteration: `x` becomes 2, `sum = 3`.

Next: `x` becomes 3, `sum = 6`. Now `x = 3`, the condition `x < 3` is false, so the loop stops. The final value of `x` is 3, but the question asks for the value printed, which is `sum` — wait, re-evaluating: the code prints `sum`, not `x`.

The loop runs while `x < 3`: after `x` becomes 3, the loop exits, and `sum` is 1+2+3 = 6. However, the correct answer is 2? Let me re-check the question: the answer options are 3, 5, 2, 0. The correct answer is C (2) — this implies the code prints `x` not `sum`, or the loop condition is different.

Actually, the typical trap: if the code prints `x` after the loop, `x` is 3, but answer A is 3. If it prints `sum`, sum is 6, not listed. The only way 2 is correct is if the loop increments `x` before adding, and the condition is `x < 2` or similar.

Given the answer is 2, the likely code is: `int x = 0; int sum = 0; while (x < 2) { x++; sum += x; } System.out.println(x);` — then `x` becomes 1, then 2, loop stops, prints 2. So the explanation: the loop runs while `x < 2`, incrementing `x` each time, so `x` ends at 2.

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.

392
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

Option D correctly 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 Cisco 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).

393
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

Option C is correct because 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.

394
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

Option B is correct because without break, execution falls through to the next case. Option A is wrong because default handles unmatched cases, not fall-through. Option C is wrong because using String in switch is valid.

Option D is wrong because using enum in switch is valid.

395
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

Option A is correct because -XX:+HeapDumpOnOutOfMemoryError creates a heap dump file for analysis. Option B is wrong because -verbose:gc prints GC details but does not capture a heap dump. Option C is wrong because -Xmx sets maximum heap size, which might prevent the error but does not diagnose it.

Option D is wrong because -version prints version info.

396
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

RuntimeException is unchecked, so it does not need to be declared. The method can throw it without a throws clause. Option A is correct.

397
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 have specific meanings in Java.

398
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

Option D is correct because 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.

399
MCQhard

What is the value of y?

A.22
B.20
C.21
D.23
AnswerA

Correct.

Why this answer

The code snippet likely performs an operation such as `int y = 10 + 12;` or similar arithmetic, resulting in y = 22. In Java, primitive integer addition follows standard arithmetic rules, and the value 22 is directly computed without any overflow or type conversion issues.

Exam trap

Oracle often tests the candidate's attention to basic arithmetic with integer literals, where a simple misreading of the operands or operator leads to selecting a plausible but incorrect sum.

How to eliminate wrong answers

Option B is wrong because 20 would result from an incorrect operation like subtracting 2 instead of adding, or misreading the operands. Option C is wrong because 21 would come from a miscalculation such as 10 + 11 or a off-by-one error. Option D is wrong because 23 would require an extra increment or addition of 1 beyond the correct sum.

400
Multi-Selecthard

Which TWO statements about interfaces in Java are true?

Select 2 answers
A.An interface can have instance variables
B.An interface can implement another interface
C.An interface can extend another interface
D.An interface can have final methods
E.An interface can have default methods with a body
AnswersC, E

Interfaces can extend other interfaces.

Why this answer

Interfaces can extend other interfaces and can have default methods with a body.

401
MCQeasy

What is the primary role of the Java Development Kit (JDK) compared to the JRE?

A.JDK provides only a debugger and profiler.
B.JRE includes the JDK and additional libraries.
C.JDK is required to run Java applications, whereas JRE is not.
D.JDK includes compilers and tools for developing Java applications.
AnswerD

JDK contains javac, debugger, etc., which JRE lacks.

Why this answer

Option A is correct because JDK includes development tools like javac, while JRE only provides runtime environment. Option B is wrong because both JDK and JRE support the same platforms. Option C is wrong because JDK includes JRE, not the other way.

Option D is inaccurate because JDK includes debuggers and profilers.

402
MCQhard

A class 'Base' has a method 'public void display() throws IOException'. Subclass 'Derived' overrides display(). Which exception specifications are allowed in the overriding method?

A.public void display() throws SQLException
B.public void display() throws FileNotFoundException
C.public void display() throws Exception
D.public void display() throws Throwable
AnswerB

FileNotFoundException is a subclass of IOException, allowed.

Why this answer

In Java, an overriding method can throw the same exception, a subclass of the exception thrown by the parent method, or no exception at all. The parent method throws IOException, so the overriding method may throw FileNotFoundException (a subclass of IOException). This follows the rule that the overriding method cannot throw a broader checked exception than the overridden method.

Exam trap

Oracle often tests the misconception that an overriding method can throw any exception, but the key is that only the same exception or a subclass of the parent's exception is allowed for checked exceptions.

How to eliminate wrong answers

Option A is wrong because SQLException is not a subclass of IOException; it is a completely unrelated checked exception, and throwing it would violate the rule that an overriding method cannot throw a new or broader checked exception. Option C is wrong because Exception is a superclass of IOException, making it a broader checked exception, which is not allowed in an overriding method. Option D is wrong because Throwable is the root of the entire exception hierarchy and is broader than IOException, so it is not permitted.

403
Multi-Selecthard

Which TWO statements are true about interfaces in Java?

Select 2 answers
A.Interfaces can contain private methods.
B.Interfaces can be instantiated.
C.Interfaces can contain constructors.
D.All interface variables are implicitly public static final.
E.Interfaces cannot have default methods.
AnswersA, D

Since Java 9, interfaces can have private methods for code reuse.

Why this answer

Option A is correct because, since Java 9, interfaces can contain private methods to share common code between default methods or static methods within the interface, without exposing that logic to implementing classes. Option D is correct because all variables declared in an interface are implicitly public, static, and final, meaning they are constants that cannot be changed once assigned.

Exam trap

The trap here is that candidates often forget that interfaces can have private methods (Java 9+) and default methods (Java 8), and mistakenly think interfaces are purely abstract with only public abstract methods and constants.

404
MCQeasy

Given: int x = 3 + 4 * 2; What is x?

A.11
B.11
C.24
D.14
AnswerB

Correct result.

Why this answer

Multiplication has higher precedence, so 4*2=8, then 3+8=11.

405
MCQhard

Why does the code output false?

A.s1 is created with 'new' thus not in string pool, s2 is literal in pool, so different references
B.s1 and s2 refer to different objects in the heap
C.The String class does not override equals
D.The == operator compares value not reference
AnswerA

Correct: this explains the difference in references.

Why this answer

The new keyword forces creation of a new String object in heap. The literal "Java" is interned and may be in the string pool. s1 and s2 refer to different objects, so == returns false.

406
MCQeasy

What is the value of 10 % 3?

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

Correct: 10 ÷ 3 = 3 remainder 1.

Why this answer

The % operator returns remainder of division. 10 divided by 3 is 3 with remainder 1.

407
MCQhard

A developer writes a multi-threaded application that runs on Windows. To ensure the same bytecode runs without modification on Linux and macOS, which Java feature is essential?

A.Bytecode verification
B.Platform independence via JVM
C.Just-in-Time (JIT) compilation
D.Thread synchronization
AnswerB

The JVM abstracts the underlying OS, allowing the same bytecode to run anywhere.

Why this answer

Option D is correct because platform independence via the JVM allows the same bytecode to run on any OS with a compatible JVM. Option A is wrong because thread synchronization is a coding technique, not a cross-platform feature. Option B is wrong because JIT compilation optimizes performance but does not provide OS independence.

Option C is wrong because bytecode verification checks safety, not portability.

408
MCQhard

A financial trading application processes a batch of 10 million trade transactions every night. Each transaction is a String containing trade details such as ID, symbol, quantity, and price. The current implementation uses string concatenation with the += operator in a loop to build a summary report string. The application frequently runs out of memory and takes hours to complete. The server has 16 GB of RAM and runs Java 11. The code cannot be restructured significantly due to regulatory requirements, but performance improvements are allowed. Which course of action will most effectively resolve the performance and memory issues?

A.Replace the String concatenation with StringBuilder.
B.Call intern() on the concatenated result at each iteration.
C.Increase the JVM heap size to 32 GB to accommodate the temporary string objects.
D.Replace the String concatenation with StringBuffer.
AnswerA

StringBuilder is mutable and appends to the same buffer, drastically reducing object creation and improving performance. It is the standard solution for repeated string concatenation.

Why this answer

String concatenation using += inside a loop creates many intermediate String objects, leading to memory waste and slowness. StringBuilder is mutable and designed for efficient string building without creating multiple intermediate objects. Option C is the optimal fix.

Option A (heap increase) only delays the problem. Option B (StringBuffer) is thread-safe but slower due to synchronization, unnecessary in a single-threaded context. Option D (using intern()) does not improve efficiency and can harm performance.

409
Multi-Selecteasy

Which THREE of the following statements about operators in Java are true?

Select 3 answers
A.The instanceof operator can be used to check if an object is an instance of a class.
B.The right shift operator (>>) always fills with zeros.
C.The assignment operator (=) has the lowest precedence.
D.The equality operator (==) compares the content of objects.
E.The conditional operator (&&) short-circuits: if left operand is false, right operand is not evaluated.
AnswersA, C, E

Correct usage.

Why this answer

Option A is correct because the `instanceof` operator in Java is a binary operator used to test whether an object is an instance of a specific class, subclass, or interface. It returns `true` if the object is an instance of the specified type, otherwise `false`, and is commonly used for type checking before casting.

Exam trap

Oracle often tests the misconception that `==` compares object content for reference types, when in fact it compares references, and that `>>` always fills with zeros, confusing it with the unsigned right shift `>>>`.

410
MCQmedium

A developer needs to concatenate several string values in a loop. Which approach is most efficient for performance?

A.Using StringBuilder
B.Using String.concat()
C.Using the '+' operator inside the loop
D.Using StringBuffer
AnswerA

Correct: StringBuilder provides mutable sequence and is optimized for such use.

Why this answer

StringBuilder is the most efficient approach for concatenating strings in a loop because it maintains a mutable sequence of characters, avoiding the creation of intermediate String objects. In contrast, using the '+' operator or String.concat() inside a loop results in the allocation of a new String object for each concatenation, leading to O(n²) time complexity and increased garbage collection overhead.

Exam trap

Oracle often tests the misconception that the '+' operator is always optimized by the compiler, but in a loop it creates a new StringBuilder per iteration, making it far less efficient than using a single StringBuilder outside the loop.

How to eliminate wrong answers

Option B is wrong because String.concat() creates a new String object for each concatenation, which is inefficient in a loop due to repeated object allocation and copying. Option C is wrong because the '+' operator compiles to StringBuilder.append() only when used in a single expression; inside a loop, each iteration creates a new StringBuilder, resulting in the same performance penalty as explicit String concatenation. Option D is wrong because StringBuffer is thread-safe with synchronized methods, which adds unnecessary overhead in a single-threaded context, making it slower than StringBuilder.

411
MCQhard

A developer writes the following code to compare two strings: String s1 = "Java"; String s2 = new String("Java"); if (s1 == s2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } What is the output?

A.Compilation error
B.Not equal
C.Equal
D.Runtime error
AnswerB

== compares references, and they are different.

Why this answer

Option B is correct because the == operator compares object references, not the actual string content. Variable s1 refers to a string literal from the string pool, while s2 is a new String object created on the heap, so they are different objects and the comparison returns false, printing 'Not equal'.

Exam trap

Oracle often tests the distinction between reference equality (==) and value equality (.equals()) with String objects, trapping candidates who assume == compares the actual text content.

How to eliminate wrong answers

Option A is wrong because the code compiles without error; both s1 and s2 are valid String objects. Option C is wrong because == compares references, not values; s1 and s2 are different objects even though they contain the same characters. Option D is wrong because no runtime exception occurs; the comparison simply evaluates to false and the else branch executes normally.

412
Multi-Selectmedium

Which TWO are valid identifiers in Java? (Choose two.)

Select 2 answers
A.$money
B.123abc
C._value
D.2ndPlace
E.my-var
AnswersA, C

$ is allowed.

Why this answer

Option A is correct because in Java, identifiers can begin with a letter, an underscore (_), or a dollar sign ($). The dollar sign is a valid starting character, so '$money' is a legal identifier. This is specified in the Java Language Specification (JLS §3.8).

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit and cannot contain hyphens, while tricking candidates into thinking underscores and dollar signs are invalid or that hyphens are allowed as separators.

413
Matchingmedium

Match each access modifier to its visibility level.

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

Concepts
Matches

Accessible from anywhere

Accessible within same package and subclasses

Accessible only within same package

Accessible only within same class

Why these pairings

Access modifiers control visibility in Java.

414
Multi-Selectmedium

Which THREE of the following expressions evaluate to true? (Assume int a=5, b=10)

Select 3 answers
A.a == b
B.a < b
C.a >= b
D.a != b
E.b > a
AnswersB, D, E

5 < 10 true.

Why this answer

Option B is correct because the expression 'a < b' compares the integer values of a (5) and b (10). Since 5 is less than 10, the relational operator '<' returns the boolean value true.

Exam trap

Oracle often tests the distinction between assignment (=) and equality (==) operators, but here the trap is that candidates may confuse the direction of the comparison or forget that 'a != b' is true when values differ, leading them to incorrectly eliminate correct options like D and E.

415
MCQhard

Given the following try-catch block: try { // some code } catch (IOException | NumberFormatException e) { e = new IOException("wrapper"); // throw e; } Which line causes a compilation error?

A.The multi-catch syntax
B.The assignment to e
C.No error
D.The throw statement
AnswerB

In a multi-catch clause, the exception parameter is implicitly final, so reassignment is not allowed.

Why this answer

In a multi-catch block, the exception parameter `e` is implicitly `final` and cannot be reassigned. The assignment `e = new IOException("wrapper")` violates this rule, causing a compilation error at that line.

Exam trap

The trap here is that candidates assume the multi-catch syntax itself is invalid or that the commented `throw` statement causes the error, overlooking the implicit `final` restriction on the exception parameter.

How to eliminate wrong answers

Option A is wrong because the multi-catch syntax `catch (IOException | NumberFormatException e)` is valid in Java 7+; it correctly catches both exception types. Option C is wrong because there is a compilation error due to the illegal assignment to `e`. Option D is wrong because the `throw e;` statement is commented out, so it does not cause an error; even if uncommented, the error would still be the assignment, not the throw.

416
MCQhard

A developer is building a Java application for a bank that processes account transactions. The application reads transaction amounts from a CSV file provided by a third party. The amounts are in string format, e.g., '1,234.56' or '$5,000.00'. The developer uses Integer.parseInt() to convert these strings to integers for processing. However, many transactions fail with NumberFormatException. The developer adds a try-catch block to catch the exception and log the error. But still, the application fails to process valid transactions because the parsing does not handle the formatting. The development team is considering several approaches to fix this issue. The goal is to parse the string into an integer representing the whole dollar amount (ignoring cents and formatting). Which course of action should the developer take?

A.Use BigDecimal to represent the value and then convert to int using intValue().
B.Use a custom parser that throws a checked exception to enforce proper formatting.
C.Use a Scanner with useDelimiter("[^0-9]") to extract digits.
D.Use String.replaceAll("[^0-9]", "") to remove non-digit characters before parsing.
AnswerD

This removes all non-digit characters, leaving a clean integer string that Integer.parseInt can handle correctly.

Why this answer

The best approach is to remove all non-digit characters before parsing. Using String.replaceAll("[^0-9]", "") strips commas, currency symbols, and decimal points, leaving only digits, which Integer.parseInt can handle. Option B is correct.

Option A (Scanner) is cumbersome for a single string. Option C (BigDecimal) is overkill and still requires cleanup, plus intValue() loses precision. Option D is impractical for formatting issues.

417
MCQmedium

Consider the following code: int[] arr = new int[5]; for (int i = 0; i <= arr.length; i++) { arr[i] = i; } System.out.println(arr[0]); What is the result?

A.0
B.5
C.4
D.An ArrayIndexOutOfBoundsException is thrown.
AnswerD

The loop runs i from 0 to 5 inclusive; when i equals 5, arr[5] is out of bounds, causing the exception.

Why this answer

The correct answer is D because the loop condition `i <= arr.length` causes `i` to iterate from 0 to 5 inclusive. Since `arr` has indices 0 through 4, accessing `arr[5]` throws an `ArrayIndexOutOfBoundsException`. The exception occurs before `arr[0]` can be printed.

Exam trap

The trap here is that candidates often overlook the off-by-one error in the loop condition `i <= arr.length` and assume the loop runs correctly, forgetting that array indices start at 0 and end at `length - 1`.

How to eliminate wrong answers

Option A is wrong because although `arr[0]` would be assigned 0 if the loop completed, the exception halts execution before the print statement. Option B is wrong because `arr.length` is 5, but the loop never assigns 5 to any element; the exception prevents any output. Option C is wrong because 4 is the last valid index, but the loop attempts to access index 5, causing an exception.

418
MCQeasy

What is the result of the following code snippet? int x = 5; int y = 2; double z = x / y; System.out.println(z);

A.3.0
B.2
C.2.0
D.2.5
AnswerC

Correct: integer division yields 2, then assigned to double becomes 2.0.

Why this answer

Option C is correct because in Java, when both operands of the division operator are integers (int), the operation performs integer division, which truncates the fractional part. Here, x / y = 5 / 2 = 2 (integer division), and then the result is implicitly widened to double when assigned to z, producing 2.0.

Exam trap

The trap here is that candidates often forget Java performs integer division when both operands are integers, mistakenly assuming the result will be a floating-point value like 2.5 just because the variable is declared as double.

How to eliminate wrong answers

Option A is wrong because it suggests the result is 3.0, which would only occur if the division were 5 / 1.666... or if rounding occurred, but Java integer division truncates toward zero, not rounds. Option B is wrong because it outputs 2 (an int), but the variable z is declared as double, so the printed value will have a decimal point, i.e., 2.0, not 2. Option D is wrong because it assumes floating-point division occurs, but since both operands are int, integer division is performed first, yielding 2, not 2.5.

419
MCQmedium

A developer writes: String s = "Hello"; s.concat(" World"); System.out.println(s); What is the output?

A.Compilation fails
B.Hello World
C.Hello
D.Hello World
AnswerC

Correct because concat does not modify s.

Why this answer

Option C is correct because strings in Java are immutable. The `concat()` method returns a new string but does not modify the original string `s`. Since the return value is not assigned to any variable, the original string `s` remains unchanged, so `System.out.println(s)` prints "Hello".

Exam trap

The trap here is that candidates often forget that strings are immutable and assume methods like `concat()` modify the original object, leading them to choose "Hello World" instead of "Hello".

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; `concat()` is a valid method on String objects. Option B is wrong because it assumes `concat()` modifies the original string, but strings are immutable in Java. Option D is wrong for the same reason as B — it incorrectly expects the concatenated result to be printed.

420
MCQeasy

Which of the following is the best practice for resource management in Java?

A.Close resources in a finally block without null checks.
B.Rely on garbage collection to close resources.
C.Use try-with-resources statement.
D.Use a try-catch block and close resources in the catch block.
AnswerC

Try-with-resources automatically closes AutoCloseable resources.

Why this answer

Option C is correct because the try-with-resources statement (introduced in Java 7) automatically closes each resource declared in its header when the block exits, whether normally or due to an exception. This eliminates the need for explicit cleanup code and ensures that resources implementing `AutoCloseable` are closed reliably, preventing resource leaks.

Exam trap

Oracle often tests the misconception that garbage collection handles all resource cleanup, but the trap here is that candidates forget external resources (like I/O streams) are not managed by the garbage collector and require explicit closure via try-with-resources or finally blocks.

How to eliminate wrong answers

Option A is wrong because closing resources in a finally block without null checks can cause a `NullPointerException` if the resource variable is null, and it still requires verbose boilerplate code. Option B is wrong because garbage collection only reclaims memory, not external resources like file handles or database connections; relying on it can lead to resource exhaustion. Option D is wrong because closing resources in a catch block only executes if an exception occurs, leaving resources open if the try block completes normally, which defeats the purpose of guaranteed cleanup.

421
MCQmedium

A developer wants to assign the largest possible long value to a variable. Which is correct?

A.long x = (long) 9223372036854775807L;
B.long x = 9223372036854775808L;
C.long x = 9223372036854775807;
D.long x = 9223372036854775807L;
E.long x = Long.MAX_VALUE;
.long x = 9223372036854775807;
.long x = (long) 1e19;
AnswerE

Correct constant.

Why this answer

Option E is correct because Long.MAX_VALUE is a predefined constant in the Java Long wrapper class that holds the maximum possible long value, which is 9223372036854775807. Using this constant ensures portability and avoids hardcoding errors, as the literal value 9223372036854775807 is within the valid long range and must be suffixed with 'L' to be treated as a long literal.

Exam trap

The trap here is that candidates often forget the 'L' suffix for long literals or attempt to assign a value that exceeds the long range, leading them to choose options that cause compilation errors, while the correct answer leverages the Long.MAX_VALUE constant to avoid such pitfalls.

How to eliminate wrong answers

Option A is wrong because the cast (long) is redundant and the literal 9223372036854775807L already has the correct suffix, but the cast does not cause an error; however, the option is not the best practice and is not the correct answer. Option B is wrong because 9223372036854775808L exceeds Long.MAX_VALUE (9223372036854775807) and will cause a compilation error 'integer number too large'. Option C is wrong because the literal 9223372036854775807 lacks the 'L' suffix, so it is treated as an int literal, which is too large for int and causes a compilation error.

Option D is technically correct as a literal assignment, but it is not the best answer because it uses a hardcoded literal rather than the standard constant. Option null (first) is wrong because it is not a valid option. Option null (second) is wrong because (long) 1e19 is a double literal cast to long, which will truncate and produce a value of 9223372036854775807 (due to double precision limits), but it is not the largest possible long value and is a poor practice.

422
MCQeasy

You are a junior developer tasked with generating API documentation for a large Java project. The project uses Javadoc comments extensively, and you need to generate HTML documentation that includes all public and protected classes and methods. You have access to the source files in the `src` directory, and you want the output to be placed in a `docs` folder. Additionally, you want to include a custom header and footer in each generated page. The project uses multiple packages like `com.example.app`, `com.example.util`, and `com.example.data`. You plan to run the javadoc command from the project root. Which command should you use?

A.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src com.example.*
B.javadoc -d docs -private -sourcepath src com.example.app com.example.util com.example.data
C.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src com.example.app com.example.util com.example.data
D.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src -subpackages com.example
AnswerC

Correctly sets output, header, footer, sourcepath, and lists specific packages to document.

Why this answer

Option C is correct because it specifies the exact package names (`com.example.app`, `com.example.util`, `com.example.data`) that contain the public and protected classes and methods required for the documentation, uses `-d docs` to set the output directory, and includes `-header` and `-footer` to add custom header and footer text. This command generates HTML documentation for only the specified packages, meeting all requirements.

Exam trap

Oracle often tests the distinction between `-subpackages` and explicitly listing packages, where candidates mistakenly choose `-subpackages` thinking it is more efficient, but it may include unwanted packages and does not match the requirement to document only the three specified packages.

How to eliminate wrong answers

Option A is wrong because `com.example.*` is not a valid package name for the `javadoc` command; it would be interpreted as a literal package name with an asterisk, causing the tool to fail to find any classes. Option B is wrong because it uses `-private` which includes private members, but the requirement is to include only public and protected classes and methods, and it omits the `-header` and `-footer` options. Option D is wrong because `-subpackages com.example` recursively includes all subpackages (e.g., `com.example.internal`), which may include packages not intended for documentation, and it does not restrict to the three specified packages.

423
MCQmedium

Given the method: public static void modify(int[] data) { data = new int[]{10,20}; } What is the output of: int[] vals = {1,2}; modify(vals); System.out.println(vals[0]);

A.10
B.Compilation error
C.1
D.0
AnswerC

Correct: the original array is unchanged.

Why this answer

In Java, when an object reference (including an array) is passed to a method, the reference itself is passed by value. Inside `modify`, the assignment `data = new int[]{10,20}` reassigns the local variable `data` to a new array object, but this does not affect the original reference `vals` in the caller. Therefore, `vals[0]` remains `1`, making option C correct.

Exam trap

The trap here is that candidates often confuse reassigning a reference with modifying the object's contents, leading them to incorrectly believe the original array is replaced.

How to eliminate wrong answers

Option A is wrong because it assumes the method modifies the original array, but the assignment `data = new int[]{10,20}` only changes the local reference, not the caller's array. Option B is wrong because the code compiles successfully; the method signature matches the call, and no syntax or type errors exist. Option D is wrong because it suggests the array element becomes 0, which would only happen if the original array were modified to contain 0, but no such modification occurs.

424
MCQmedium

What is printed when the main method runs?

A.5
B.0
C.Compilation error: cannot assign new array to parameter
D.100
AnswerA

The original array is not modified; the method reassigned the reference.

Why this answer

Option A is correct because the method `modifyArray` receives a reference to the array, and the assignment `arr = new int[]{100};` changes the local reference `arr` to point to a new array object. The original array in `main` remains unchanged, so `arr[0]` still prints 5. Java passes object references by value, meaning the reference itself is copied, and reassigning the local reference does not affect the caller's reference.

Exam trap

Oracle often tests the distinction between modifying an object's state (which affects the caller) versus reassigning the reference (which does not), and the trap here is that candidates mistakenly think reassigning the parameter changes the original array, leading them to choose option D.

How to eliminate wrong answers

Option B is wrong because the array is initialized with `{5}` and never modified in the calling scope, so `arr[0]` is 5, not 0. Option C is wrong because there is no compilation error; Java allows reassigning a method parameter (the local reference) to a new array, as the parameter is a local variable. Option D is wrong because the new array `{100}` is only assigned to the local reference inside `modifyArray` and does not affect the original array in `main`, so `arr[0]` remains 5, not 100.

425
MCQmedium

class Parent { void show() { System.out.print("Parent"); } } class Child extends Parent { void show() { System.out.print("Child"); } } public class Test { public static void main(String[] args) { Parent p = new Child(); p.show(); } } What is the output?

A.Compilation error
B.No output
C.Parent
D.Child
E.Runtime error
AnswerD

Correct. Although the reference is Parent, the object is Child, and show() is overridden, so Child's version is called.

Why this answer

Although the reference is Parent, the object is Child, and show() is overridden, so Child's version is called.

426
MCQeasy

Which command is used to run a Java application from the command line?

A.jar
B.javac
C.java
D.javadoc
AnswerC

java runs the JVM.

Why this answer

The `java` command is the correct tool to launch a Java application from the command line. It invokes the Java Virtual Machine (JVM) to load and execute the compiled bytecode contained in `.class` files or a JAR file. Without this command, the application cannot run.

Exam trap

Oracle often tests the distinction between compilation (`javac`) and execution (`java`), trapping candidates who confuse the compiler with the runtime launcher.

How to eliminate wrong answers

Option A is wrong because `jar` is used to create, view, or extract Java Archive (JAR) files, not to run applications. Option B is wrong because `javac` is the Java compiler that translates `.java` source files into `.class` bytecode, but it does not execute them. Option D is wrong because `javadoc` generates API documentation from Java source code comments, not run applications.

427
MCQhard

A developer implements a loop that processes a list of transactions. The loop must ensure that at least one transaction is processed even if the list is empty. Which loop construct guarantees this?

A.while loop
B.enhanced for loop
C.do-while loop
D.for loop
AnswerC

do-while executes body once before checking condition, guaranteeing at least one execution.

Why this answer

The do-while loop is the correct choice because it guarantees that the loop body executes at least once, regardless of the condition. In Java, the do-while loop evaluates its boolean condition after executing the loop body, so even if the list is empty (e.g., size 0), the transaction processing code inside the loop will run once before the condition is checked.

Exam trap

Cisco often tests the distinction between entry-controlled (while, for) and exit-controlled (do-while) loops, trapping candidates who assume all loops can guarantee at least one execution without considering when the condition is evaluated.

How to eliminate wrong answers

Option A is wrong because a while loop evaluates its condition before the first iteration; if the list is empty, the condition (e.g., while(index < list.size())) is false initially, so the loop body never executes. Option B is wrong because an enhanced for loop iterates over elements of a collection or array; if the list is empty, there are no elements to iterate over, so the loop body never runs. Option D is wrong because a for loop (traditional) evaluates its condition before each iteration; if the list is empty, the condition (e.g., for(int i=0; i<list.size(); i++)) is false initially, so the loop body never executes.

428
MCQhard

Refer to the exhibit. What is the output?

A.10
B.13
C.12
D.11
AnswerC

Correct. a++ gives 5, ++a gives 7.

Why this answer

The code initializes an integer array with values 1 through 5. The for loop iterates over each element using the enhanced for loop, and the variable 'x' takes on each value in sequence. The loop adds each element to the variable 'sum', which starts at 0.

After processing all five elements (1+2+3+4+5), sum equals 15. Then, the code prints the value of 'sum' minus 3, which is 12. Option C is correct.

Exam trap

The trap here is that candidates may misread the code and think the loop only sums a subset of elements, or they may incorrectly compute the sum (e.g., forgetting to include the last element) or misapply the subtraction, leading to a wrong answer like 10, 11, or 13.

How to eliminate wrong answers

Option A is wrong because 10 would be the result if the loop only summed the first four elements (1+2+3+4) and then subtracted 0, or if a different arithmetic error occurred. Option B is wrong because 13 would be the result if the sum was 16 and then 3 was subtracted, or if the loop incorrectly skipped an element or added an extra value. Option D is wrong because 11 would be the result if the sum was 14 (e.g., missing one element like 5) and then 3 was subtracted, or if the subtraction was misapplied.

429
MCQmedium

A developer wants to prevent a method from being overridden. Which modifier should be used?

A.private
B.abstract
C.final
D.static
AnswerC

Final methods cannot be overridden.

Why this answer

The `final` modifier prevents a method from being overridden in a subclass. When a method is declared as `final`, any attempt to override it in a subclass results in a compile-time error, ensuring the method's implementation remains unchanged.

Exam trap

Oracle often tests the distinction between 'hiding' (for static methods) and 'overriding' (for instance methods), leading candidates to incorrectly choose `static` because they confuse hiding with preventing overriding.

How to eliminate wrong answers

Option A is wrong because `private` methods are not inherited and thus cannot be overridden, but the question asks for preventing overriding of a method that is accessible; `private` methods are hidden, not prevented from overriding. Option B is wrong because `abstract` methods must be overridden by a subclass to provide an implementation, which is the opposite of preventing overriding. Option D is wrong because `static` methods are hidden, not overridden; they belong to the class rather than instances, and a subclass can declare a method with the same signature without overriding the parent's static method.

430
MCQeasy

Which primitive data type should be used to store a single character?

A.int
B.byte
C.char
D.String
AnswerC

char is a 16-bit Unicode character.

Why this answer

Option C is correct because the `char` primitive data type in Java is specifically designed to store a single 16-bit Unicode character, ranging from '\u0000' (0) to '\uffff' (65,535). It can represent any character in the Unicode standard, including letters, digits, and symbols, making it the appropriate choice for a single character value.

Exam trap

Oracle often tests the distinction between primitive and reference types, and the trap here is that candidates confuse `String` (a reference type) with `char` (a primitive type) because both are used for text, leading them to incorrectly select `String` for a single character.

How to eliminate wrong answers

Option A is wrong because `int` is a 32-bit signed integer type used for whole numbers, not for storing characters; while it can hold a character's numeric code point, it is not the primitive type intended for character storage and requires explicit casting to be used as a character. Option B is wrong because `byte` is an 8-bit signed integer type with a range of -128 to 127, which is insufficient to represent the full Unicode character set (0 to 65,535) and cannot store most characters without data loss or overflow. Option D is wrong because `String` is a reference type (a class) that represents a sequence of characters, not a primitive type; it is used for strings of text, not a single character, and using it for a single character introduces unnecessary overhead and violates the requirement for a primitive data type.

431
MCQhard

Consider a Java application that throws a NullPointerException deep inside a library method. The stack trace does not include the caller's line numbers because the library was compiled without debug information. Which approach would best help identify the root cause?

A.Use a debugger to set breakpoints in the library.
B.Recompile the library with -g flag and redeploy.
C.Use logging statements in the application code before and after the call.
D.Add a try-catch around the library call and print the stack trace.
AnswerB

The -g flag generates debugging information including line numbers, making stack traces more informative.

Why this answer

Option B is correct because recompiling the library with the `-g` flag includes debug information (such as line numbers and local variable names) in the class files. This allows the JVM to produce a stack trace with precise line numbers, enabling you to trace the NullPointerException back to the exact source line in the library code, even though the library was originally compiled without debug info.

Exam trap

Oracle often tests the misconception that adding a try-catch or logging around the call site can reveal the internal cause of an exception, when in fact only the library's own debug information (or recompilation with `-g`) can provide the line-level detail needed to trace the root cause.

How to eliminate wrong answers

Option A is wrong because setting breakpoints in the library requires the library to have been compiled with debug information; without it, the debugger cannot map bytecode to source lines, making breakpoints ineffective. Option C is wrong because adding logging statements in the application code only shows when the call is made and returns, but does not reveal where inside the library the NullPointerException occurs, so the root cause remains hidden. Option D is wrong because adding a try-catch around the library call and printing the stack trace will only show the same incomplete stack trace (without line numbers) that was already available; it does not add the missing debug information needed to pinpoint the exact location.

432
MCQeasy

A method that calculates the average of an array of doubles is defined as: public static double average(double[] values) { double sum = 0; for (double v : values) sum += v; return sum / values.length; } Which call is valid?

A.double avg = average(1.0, 2.0);
B.double avg = average(new double[]{1.0, 2.0, 3.0});
C.double avg = average(1.0, 2.0, 3.0);
D.double avg = average({1.0, 2.0, 3.0});
AnswerB

This creates a double array and passes it to the method.

Why this answer

Option B is correct because the method `average(double[] values)` expects a single argument of type `double[]`. The expression `new double[]{1.0, 2.0, 3.0}` creates an anonymous array object that matches the parameter type exactly, so the call compiles and runs correctly.

Exam trap

Oracle often tests the difference between array initializer syntax and anonymous array creation, trapping candidates who think `{1.0, 2.0, 3.0}` can be used as a method argument without the `new double[]` prefix.

How to eliminate wrong answers

Option A is wrong because the method expects a single `double[]` argument, but `1.0, 2.0` are two separate `double` literals, not an array; Java does not support implicit array creation from a comma-separated list in a method call. Option C is wrong for the same reason: three separate `double` literals cannot be passed to a parameter that expects a single `double[]` reference. Option D is wrong because `{1.0, 2.0, 3.0}` is an array initializer syntax that is only valid in a declaration (e.g., `double[] arr = {1.0, 2.0, 3.0};`), not as a standalone expression in a method call.

433
MCQhard

A developer is writing a batch processing application that reads a list of orders and processes each one. The orders are stored in an array of Order objects. The processing logic is complex and involves multiple conditional checks. The developer uses a for-each loop to iterate over the array. However, during testing, the application throws an IndexOutOfBoundsException when processing orders that have a status of "CANCELLED". The developer wants to skip the processing of cancelled orders but still record that the order was skipped in a log. The current code is: for (Order order : orders) { if (order.getStatus().equals("CANCELLED")) { // Skip } // process order process(order); log(order); } The developer considers four options: A. Change the for-each loop to a traditional for loop with an index and increment only when order is not cancelled. B. Add a continue statement inside the if block. C. Change the if condition to check for non-cancelled orders and wrap only the process(order) call inside the if block, leaving log(order) outside. D. Use a while loop with an iterator and remove cancelled orders from the array. Which option best solves the problem without modifying the array and while still logging all orders?

A.Change the if condition to check for non-cancelled orders and wrap only the process(order) call inside the if block, leaving log(order) outside.
B.Change the for-each loop to a traditional for loop with an index and increment only when order is not cancelled.
C.Add a continue statement inside the if block.
D.Use a while loop with an iterator and remove cancelled orders from the array.
AnswerA

This skips processing for cancelled but still logs them, meeting all requirements.

Why this answer

Option C correctly skips only the processing for cancelled orders while still executing the log statement for them. Option A would require index management and still log for cancelled orders, but it changes the loop structure unnecessarily. Option B would skip both process and log for cancelled orders, failing the logging requirement.

Option D modifies the array by removing elements, which is not allowed ('without modifying the array'). Thus C is the best.

434
MCQhard

A developer wants to sort an array of primitive ints in descending order. Which approach will work without using third-party libraries?

A.Arrays.parallelSort(arr);
B.Arrays.sort(arr, Collections.reverseOrder());
C.Arrays.sort(arr); // then reverse the array manually
D.Arrays.sort(arr, (a,b) -> b - a);
AnswerC

Sorts ascending, then reversing yields descending order.

Why this answer

Option C is correct because `Arrays.sort(int[])` sorts the array in ascending order, and then manually reversing the array yields descending order. The other options fail because `Arrays.parallelSort()` also sorts ascending, `Collections.reverseOrder()` requires an array of objects (not primitives), and a custom comparator cannot be used with primitive arrays in Java.

Exam trap

The trap here is that candidates assume `Arrays.sort()` with a comparator works on primitive arrays, but Java's type system prevents this because comparators require object types, leading to a compilation error for `int[]`.

How to eliminate wrong answers

Option A is wrong because `Arrays.parallelSort(int[])` sorts the array in ascending order, not descending. Option B is wrong because `Collections.reverseOrder()` returns a `Comparator<T>` that works only with object arrays (e.g., `Integer[]`), not with primitive `int[]` arrays. Option D is wrong because `Arrays.sort()` for primitive arrays does not accept a `Comparator`; the overload that accepts a comparator works only with object arrays, and using a lambda with primitive arrays causes a compilation error.

435
MCQeasy

Which access modifier allows a member to be accessed only within the same class?

A.static
B.public
C.default (no modifier)
D.protected
E.private
AnswerE

Private members are accessible only within the same class.

Why this answer

Private members are accessible only within the same class.

436
MCQeasy

A developer is maintaining a Java backend service for order processing. The service uses a third-party library that throws a checked PaymentException when a payment fails. The current processOrder method catches Exception generically, logs the error, and returns null. The business requires that when a payment fails, the order status must be updated to 'FAILED' in the database, and a notification must be sent to the customer. However, due to the generic catch, these actions are not performed. The developer must modify the code to meet the business requirements without changing the external API of the class (i.e., the method signature must remain the same and must not throw any exceptions to the caller). Which course of action should the developer take?

A.Catch PaymentException specifically, update the order status and send notification, then throw a new RuntimeException to indicate failure.
B.Remove the try-catch block and declare the method with throws Exception, allowing the caller to handle payment failures.
C.Use a finally block to update the order status and send notification regardless of success or failure.
D.In the catch block, check if the exception is an instance of PaymentException, then update the order status and send notification. Do not rethrow the exception.
AnswerD

This handles the specific exception, performs required actions, and does not propagate any exception, meeting all requirements.

Why this answer

The best course is to catch PaymentException specifically, perform the required business logic (update order status and send notification), and then either not rethrow the exception or rethrow it as an unchecked exception if needed. However, the requirement says 'must not throw any exceptions to the caller', so the method should not propagate any exception. Option A catches PaymentException, handles the business logic, and then rethrows a RuntimeException, which would propagate to the caller, violating the requirement.

Option B removes exception handling, causing checked Exception to be thrown, which also propagates. Option D uses a finally block, which would execute even on success, leading to incorrect notifications. Option C catches Exception, checks if it is PaymentException, handles the business logic, and then does not rethrow the exception, ensuring the method completes normally.

This satisfies the requirement while handling the specific exception.

437
MCQeasy

A developer needs to iterate over an array of integers and compute the sum of its elements. Which loop construct is most appropriate for this task?

A.while loop
B.Enhanced for loop
C.switch statement
D.do-while loop
AnswerB

Simplest and clearest for iterating over all elements.

Why this answer

The enhanced for loop (for-each) is the most appropriate construct for iterating over an array of integers to compute a sum because it provides a concise, read-only traversal without needing an explicit index or iterator. It directly accesses each element in sequence, reducing boilerplate and the risk of off-by-one errors, which is ideal for aggregation operations like summation.

Exam trap

Oracle often tests the misconception that a while or do-while loop is always required for array iteration, leading candidates to overlook the enhanced for loop's suitability for simple, index-free traversal tasks like summation.

How to eliminate wrong answers

Option A is wrong because a while loop requires manual initialization, condition checking, and increment of an index variable, making it more verbose and error-prone for simple array iteration. Option C is wrong because a switch statement is a selection construct for branching based on a single value, not a loop, and cannot iterate over array elements. Option D is wrong because a do-while loop, like the while loop, requires explicit index management and guarantees at least one execution, which is unnecessary overhead when the array may be empty.

438
MCQmedium

Evaluate the following expression: int x = 5; int y = (x > 5) ? 10 : 20; What is y?

A.20
B.5
C.Compilation error
D.10
AnswerA

Condition false, assigns 20.

Why this answer

The ternary operator `(x > 5) ? 10 : 20` evaluates the condition `x > 5`. Since `x` is 5, the condition is false, so the expression returns the value after the colon, which is 20. This value is assigned to `y`, making `y` equal to 20.

Exam trap

Oracle often tests the ternary operator by setting the condition to a borderline value (like equality) to see if candidates mistakenly think the true branch is selected when the condition is false.

How to eliminate wrong answers

Option B is wrong because 5 is the value of `x`, not the result of the ternary expression; the ternary operator does not return the variable itself. Option C is wrong because the ternary operator is a valid Java construct and the code compiles without error; the condition `x > 5` is a valid boolean expression. Option D is wrong because 10 is the value returned only when the condition is true, but here `x > 5` is false, so the false branch (20) is selected.

439
MCQeasy

A developer needs to handle a specific checked exception, FileNotFoundException, but also wants to catch any other IOException that might occur. Which catch block ordering is correct?

A.Use a multi-catch: catch (FileNotFoundException | IOException e).
B.catch (IOException e) first, then catch (FileNotFoundException e).
C.catch (FileNotFoundException e) first, then catch (IOException e).
D.Use a single catch (Exception e).
AnswerC

This is correct because the more specific exception must be caught before the more general one.

Why this answer

Option C is correct because checked exceptions must be caught in order from most specific to most general. FileNotFoundException is a subclass of IOException, so it must be caught first; otherwise, the more specific catch block would be unreachable and cause a compilation error. This ordering ensures that the developer can handle the specific FileNotFoundException separately while still catching any other IOException in the second block.

Exam trap

The trap here is that candidates often think multi-catch can combine any exception types, but the compiler forbids combining a parent and child exception in the same multi-catch clause, and also forbids catching a parent before a child in separate catch blocks.

How to eliminate wrong answers

Option A is wrong because a multi-catch clause cannot contain exception types that are in a parent-child relationship; 'catch (FileNotFoundException | IOException e)' would cause a compilation error since FileNotFoundException is a subclass of IOException. Option B is wrong because catching IOException first makes the subsequent catch for FileNotFoundException unreachable, leading to a compilation error. Option D is wrong because catching Exception is too broad and would catch all exceptions, including unchecked ones like NullPointerException, which defeats the purpose of specifically handling FileNotFoundException and other IOExceptions.

440
MCQeasy

What is the result of the following code? int[] arr = new int[3]; arr[3] = 5; System.out.println(arr[3]);

A.Runtime exception
B.0
C.5
D.Compilation error
AnswerA

ArrayIndexOutOfBoundsException is thrown at runtime.

Why this answer

The code attempts to access index 3 of an array of length 3. Since Java arrays are zero-indexed, valid indices are 0, 1, and 2. Accessing index 3 throws an ArrayIndexOutOfBoundsException at runtime, so option A is correct.

Exam trap

Oracle often tests the distinction between compile-time errors and runtime exceptions, and the trap here is that candidates mistakenly think an invalid array index causes a compilation error, when in fact the compiler only checks syntax and type safety, not index bounds.

How to eliminate wrong answers

Option B is wrong because it suggests the output is 0, but the array element at index 3 was never assigned and the exception prevents any output. Option C is wrong because it assumes the assignment succeeds, but the index is out of bounds, so the assignment never executes. Option D is wrong because the code compiles successfully; the error occurs only at runtime when the invalid index is accessed.

441
MCQmedium

A developer writes a method that takes a variable number of integer arguments and returns the maximum. Which method signature is correct?

A.public int max(int[]... numbers)
B.public int max(int... numbers)
C.public int max(int numbers)
D.public int max(int[] numbers)
AnswerB

Varargs allows zero or more arguments, and inside the method it is treated as an array of int.

Why this answer

Option B is correct because the varargs syntax `int... numbers` allows a method to accept zero or more integer arguments, which are then treated as an array inside the method. This is the standard Java syntax for variable-length argument lists, enabling the developer to pass any number of `int` values and compute the maximum.

Exam trap

Oracle often tests the distinction between varargs (`int...`) and array parameters (`int[]`), trapping candidates who think they are interchangeable without understanding that varargs allows passing individual values directly while an array parameter requires explicit array creation.

How to eliminate wrong answers

Option A is wrong because `int[]... numbers` declares a varargs of `int[]` arrays, meaning it expects an array of integer arrays, not a variable number of individual `int` values. Option C is wrong because `int numbers` is a single integer parameter, which cannot accept multiple arguments. Option D is wrong because `int[] numbers` accepts a single integer array parameter, not a variable number of individual `int` arguments.

442
MCQeasy

In a banking application, a class 'Account' has private field 'balance' and public methods 'getBalance()' and 'setBalance(double)'. This is an example of which OOP principle?

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

Encapsulation bundles data with methods and restricts direct access to fields.

Why this answer

Option D is correct because encapsulation hides internal data and provides controlled access via methods. Option A is wrong because there is no inheritance involved. Option B is wrong because polymorphism is not shown.

Option C is wrong because abstraction is about hiding complexity, not data protection.

443
MCQmedium

Which of the following is a valid Java identifier?

A.2variable
B.class
C._myVar
D.my-var
AnswerC

Underscore allowed.

Why this answer

Option C (_myVar) is a valid Java identifier because it starts with an underscore, which is permitted by the Java Language Specification. Java identifiers must begin with a letter (A-Z, a-z), dollar sign ($), or underscore (_), and cannot start with a digit or contain hyphens. The underscore is explicitly allowed, making _myVar a legal identifier.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit, but the trap here is that candidates may mistakenly think underscores are invalid or that keywords like 'class' can be used as identifiers if they forget Java's reserved word list.

How to eliminate wrong answers

Option A is wrong because 2variable starts with a digit, which violates the Java rule that identifiers cannot begin with a number. Option B is wrong because class is a reserved keyword in Java and cannot be used as an identifier. Option D is wrong because my-var contains a hyphen (-), which is not a valid character in Java identifiers; only letters, digits, dollar signs, and underscores are allowed.

444
MCQhard

Which of the following correctly describes the effect of the method call 'Arrays.sort(myArray)' on an array of objects that do not implement Comparable?

A.The code does not compile because Arrays.sort requires a Comparator.
B.A ClassCastException is thrown at runtime.
C.The array is sorted using the natural order of the elements.
D.The array is sorted using the order defined by the elements' equals method.
AnswerB

Elements must implement Comparable.

Why this answer

When `Arrays.sort(myArray)` is called on an array of objects that do not implement the `Comparable` interface, the method attempts to cast elements to `Comparable` to compare them. Since the objects do not implement `Comparable`, a `ClassCastException` is thrown at runtime. The `Arrays.sort(Object[])` method requires that all elements implement `Comparable`; otherwise, it cannot determine a natural ordering.

Exam trap

The trap here is that candidates assume the code will not compile (Option A) because they think `Comparable` is required at compile time, but the requirement is enforced at runtime via a cast, leading to a `ClassCastException`.

How to eliminate wrong answers

Option A is wrong because `Arrays.sort(Object[])` does not require a `Comparator`; it uses the natural ordering defined by `Comparable`. Option C is wrong because the array cannot be sorted using natural order if the elements do not implement `Comparable`; the method will throw an exception instead. Option D is wrong because `Arrays.sort` does not use the `equals` method for ordering; it uses `compareTo` (from `Comparable`) or a provided `Comparator`.

445
MCQhard

In a nested loop structure, a developer wants to exit completely from the outer loop when a certain condition is met inside the inner loop. Which approach is correct?

A.Use a return statement within the inner loop.
B.Use a continue statement with a label.
C.Use a labeled break statement (e.g., break outerLabel;).
D.Use a break statement inside the inner loop.
AnswerC

Exits the outer loop immediately.

Why this answer

Option C is correct because Java's labeled break statement allows a developer to specify an outer loop label and break out of that loop entirely from within an inner loop. This is the only control flow mechanism designed to exit multiple nested loops at once, as a plain break only exits the innermost loop.

Exam trap

Oracle often tests the distinction between break, continue, and labeled versions, trapping candidates who think a plain break exits all loops or that continue can exit a loop.

How to eliminate wrong answers

Option A is wrong because a return statement would exit the entire method, not just the outer loop, which is too drastic and may leave resources unclosed or skip necessary cleanup. Option B is wrong because a continue statement with a label skips the current iteration of the labeled loop and continues with the next iteration, rather than exiting the loop entirely. Option D is wrong because a plain break statement inside the inner loop only terminates that inner loop, not the outer loop, so the outer loop continues executing.

446
MCQhard

Refer to the exhibit. What is the output?

A.Runtime error
B.No output
C.Compilation error
D.Photo
E.Document
AnswerD

The object is Photo, and print() is overridden, so dynamic binding calls Photo's print method.

Why this answer

The object is Photo, and print() is overridden, so dynamic binding calls Photo's print method.

447
MCQmedium

You are writing a program that processes a list of transactions. Each transaction has a timestamp (long), amount (double), and type (String). The program needs to iterate through the transactions in the order they were added. Which collection should you use to maintain insertion order and allow fast iteration?

A.TreeSet<Transaction>
B.LinkedList<Transaction>
C.HashSet<Transaction>
D.ArrayList<Transaction>
AnswerD

Maintains insertion order, fast iteration.

Why this answer

ArrayList maintains insertion order and provides O(1) random access and fast iteration via index-based traversal. It is the correct choice when you need to preserve the order in which elements were added and iterate over them sequentially without requiring sorting or unique constraints.

Exam trap

Oracle often tests the misconception that LinkedList is the best choice for insertion-order preservation and iteration, but ArrayList is actually faster for iteration due to contiguous memory and lower overhead, while LinkedList is better for frequent insertions/removals at the beginning or middle.

How to eliminate wrong answers

Option A is wrong because TreeSet sorts elements by their natural order or a provided comparator, not by insertion order, and it does not allow duplicates. Option B is wrong because LinkedList maintains insertion order but has slower iteration performance due to node-based traversal and higher memory overhead compared to ArrayList. Option C is wrong because HashSet does not guarantee any order; it uses hash codes to store elements and may reorder them arbitrarily.

448
Multi-Selecthard

Which two statements about passing arrays to methods are correct? (Select two.)

Select 2 answers
A.Passing an array is the same as passing each element individually.
B.The method can change the size of the original array.
C.Modifying the array elements inside the method affects the original array.
D.If the method assigns a new array to the parameter, the original reference is updated outside the method.
E.The array reference is passed by value.
AnswersC, E

Since the method has a reference to the same array object, changes to elements are visible to the caller.

Why this answer

Options A and B are correct. The array reference is passed by value (A), so modifications to the array elements affect the original (B). Option C is false because passing an array is not the same as passing elements individually.

Option D is false because the array size is fixed. Option E is false because assigning a new array to the parameter does not affect the caller's reference.

Page 5

Page 6 of 7

Page 7

All pages