Courseiva

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

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

Page 3

Page 4 of 7

Page 5
226
MCQmedium

Which primitive type can store a single character?

A.String
B.byte
C.short
D.char
AnswerD

Correct.

Why this answer

The `char` primitive type in Java is specifically designed to store a single 16-bit Unicode character, ranging from '\u0000' (0) to '\uffff' (65535). It is the only primitive type that directly represents a character value, making it the appropriate choice for storing a single character.

Exam trap

Oracle often tests the distinction between primitive types and reference types, and the trap here is that candidates mistakenly choose `String` because they associate it with characters, forgetting that `String` is not a primitive type and is designed for sequences, not single characters.

How to eliminate wrong answers

Option A is wrong because `String` is a reference type (a class in Java), not a primitive type, and it is used to store a sequence of characters, not a single character. Option B is wrong because `byte` is an 8-bit signed integer primitive type that stores numeric values from -128 to 127, not characters. Option C is wrong because `short` is a 16-bit signed integer primitive type that stores numeric values from -32,768 to 32,767, not characters.

227
MCQmedium

You are responsible for deploying a Java desktop application that uses JavaFX and various third-party libraries. The application is modular and uses JPMS. To reduce the footprint and startup time, you decide to use jlink to create a custom runtime image that includes only the required modules. The application has a main module `com.myapp` that requires `javafx.controls`, `javafx.base`, and some other modules. After creating the runtime image using the command `jlink --module-path $JAVA_HOME/jmods:lib --add-modules com.myapp --output myapp-image`, you test the image on a development machine, and it works. However, when deploying to a customer's machine, the application fails to start with an error: "Error: Could not find or load main class com.myapp.Main". The customer's machine has no Java installed. The runtime image includes the `com.myapp` module. You verify that the `myapp-image/bin/java` launcher exists. The main class is correctly declared in the module-info.java of `com.myapp`. What is the most likely cause of this error?

A.Use the `--add-modules` option to include `javafx.controls` and other required modules in the command.
B.Use the `--launcher` option in jlink to create a launcher script that automatically runs the main class with the correct module.
C.Add the `--bind-services` option to jlink to automatically include service provider modules.
D.Ensure that the `com.myapp` module reads all required modules by adding `requires` directives in module-info.java.
AnswerB

The `--launcher` option generates a platform-specific script (e.g., myapp.sh or myapp.bat) that invokes the JVM with the correct module and main class, avoiding the need to specify them manually.

Why this answer

The `jlink` tool does not automatically create a launcher script that specifies the main class for the runtime image. Without the `--launcher` option, the generated `java` launcher does not know which module and main class to execute, leading to the 'Could not find or load main class' error when no Java is installed on the customer's machine. Using `--launcher` creates a custom script (e.g., `myapp`) that invokes `java --module com.myapp/com.myapp.Main`, ensuring the correct entry point is used.

Exam trap

The trap here is that candidates assume the `java` launcher in the runtime image will automatically find the main class from the module descriptor, but in reality, without `--launcher`, the launcher requires explicit module and main class arguments, mimicking the standard `java` command behavior.

How to eliminate wrong answers

Option A is wrong because the `--add-modules` option is already used in the command to include `com.myapp` and its dependencies; the issue is not about missing modules but about the launcher not specifying the main class. Option C is wrong because `--bind-services` adds service provider modules automatically, which is unrelated to the main class resolution error; the error occurs because no launcher is configured to run the main class. Option D is wrong because the `requires` directives in `module-info.java` are already correctly declared (the app works on the dev machine), so the problem is not about missing module dependencies but about the runtime image lacking a launcher that specifies the main class.

228
MCQeasy

Refer to the exhibit. What is the output?

A.false
B.true
C.NullPointerException
D.Compilation error: invalid operator
AnswerB

!a false, b && false false, a || false true.

Why this answer

The expression evaluates to true. Operator precedence: ! highest, then &&, then ||. Given typical values (a=false, b=true), !a=true, then b && !a = true && true = true, then a || (b && !a) = false || true = true.

Thus output is true. Option A is incorrect because the expression yields true, not false. Option C and D are incorrect as there is no exception or compilation error.

229
MCQeasy

A junior developer wrote the following code to calculate the sum of an array: int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 1; i <= numbers.length; i++) { sum += numbers[i]; } System.out.println("Sum: " + sum); The developer expects the output to be 15, but the program throws an exception. What is the root cause and the correct fix?

A.Change to enhanced for loop: for (int num : numbers) sum += num;
B.Change to: for (int i = 0; i < numbers.length; i++)
C.Change to: for (int i = 1; i < numbers.length; i += 2)
D.Change to: for (int i = 0; i <= numbers.length; i++)
AnswerB

Correct start and condition.

Why this answer

The loop starts at index 1 instead of 0, and goes up to index numbers.length (which is 5), but valid indices are 0-4. So accessing numbers[5] throws ArrayIndexOutOfBoundsException. The correct fix is to start at i=0 and continue while i < numbers.length, which is option B.

Option A uses an enhanced for loop, which is also a valid fix but changes the loop style; however, the question asks for the root cause and correct fix, and option B directly corrects the indexing. Option C changes the step to 2 and starts at 1, still wrong. Option D uses i <= numbers.length, which still causes out-of-bounds.

230
MCQeasy

A banking application stores daily transaction amounts in an array. Which declaration correctly creates an array of 31 double values?

A.double[] transactions = new double[31];
B.double transactions[] = new double[30];
C.int[] transactions = new int[31];
D.double[] transactions = new double[];
AnswerA

Correct syntax: declares array and allocates 31 elements.

Why this answer

It uses the proper syntax to declare an array of double values and initializes it with a size of 31, which allocates memory for 31 double elements, each defaulting to 0.0. In Java, the array size must be specified when using the 'new' keyword, and the index range is 0 to 30, accommodating exactly 31 daily transaction amounts.

Exam trap

Oracle often tests the distinction between array size and index range, tricking candidates into choosing an array of size 30 (index 0-29) when 31 elements are needed, or confusing the data type (int vs double) for monetary values.

How to eliminate wrong answers

Option B is wrong because it declares an array of 30 elements (size 30), not 31, which would not store all 31 daily transaction amounts. Option C is wrong because it declares an array of int values, not double values, so it cannot store fractional transaction amounts. Option D is wrong because it omits the array size in the initialization expression; in Java, 'new double[]' without a size is invalid syntax and will cause a compilation error.

231
MCQmedium

Given: String s1 = "Java"; String s2 = new String("Java"); What does (s1 == s2) evaluate to?

A.true if interned, false otherwise
B.false
C.true
D.Compilation error
AnswerB

Different objects, == checks references.

Why this answer

S1 is a string literal which is interned, while s2 is created using the 'new' keyword, resulting in a different object in heap memory. The '==' operator compares object references, so it returns false. Option A is incorrect because 'true if interned' is misleading; s1 is interned, but the comparison is false because s2 is a separate object.

Option C ('true') is wrong because references differ. Option D ('Compilation error') is incorrect; the code compiles and runs without error.

232
MCQmedium

A team is developing a library management system. They have a base class 'Item' with a method 'getTitle()' that returns the title. They also have a subclass 'Book' that overrides 'getTitle()'. In some places, they have a method that accepts an Item reference but actually receives a Book object. They want to call a method specific to Book, such as 'getISBN()', that is not in Item. They attempt to cast the parameter: ((Book) item).getISBN(). However, occasionally the program crashes with ClassCastException. What is the best practice to avoid this exception?

A.Use if (item instanceof Book) before casting.
B.Create a separate method for Book objects.
C.Catch ClassCastException and handle it.
D.Change the parameter type to Object and then cast to Book.
AnswerA

instanceof check prevents ClassCastException.

Why this answer

Using `instanceof` before casting ensures the object is actually an instance of `Book`, preventing a `ClassCastException` at runtime. This is the standard Java practice for safe downcasting when the object type is not guaranteed.

Exam trap

Oracle often tests the misconception that catching `ClassCastException` is an acceptable way to handle invalid casts, when in fact the best practice is to use `instanceof` to prevent the exception entirely.

How to eliminate wrong answers

Option B is wrong because creating a separate method for `Book` objects does not solve the core problem of safely downcasting from a parent reference; it merely avoids the cast but may lead to code duplication or loss of polymorphism. Option C is wrong because catching `ClassCastException` is a poor practice—it hides programming errors and violates the principle of fail-fast, as the exception indicates a design flaw that should be prevented rather than handled reactively. Option D is wrong because changing the parameter type to `Object` and then casting to `Book` is even less safe; it removes compile-time type checking and still risks a `ClassCastException` if the actual object is not a `Book`.

233
Multi-Selecteasy

Which TWO of the following are valid loop constructs in Java? (Choose two.)

Select 2 answers
A.do {} while (false);
B.while (true)
C.for each (int i : array) {}
D.loop (int i = 0; i < 10; i++) {}
E.for (int i = 0; i < 10; i++) {}
AnswersA, E

Correct do-while loop syntax, including the required semicolon.

Why this answer

A valid do-while loop; the semicolon after the condition is required. Option E is a standard for loop. Option B is invalid because 'while (true)' lacks a loop body (statement or block).

Option C uses incorrect syntax: 'for each' is not Java; the correct syntax is 'for (int i : array)'. Option D uses 'loop' which is not a Java keyword; the correct keyword is 'for'.

234
MCQeasy

A company develops a payroll system in Java with a hierarchy: Employee, Manager (extends Employee), and Director (extends Manager). Each class overrides a method getDetails() that returns a string with employee information. Employee's getDetails() returns name and ID. Manager's getDetails() adds department. Director's getDetails() adds division. The system uses a single method printDetails(Employee e) that calls e.getDetails(). After a recent deployment, the system prints only the name and ID for all employees, even for managers and directors. The code review reveals that Employee's getDetails() is declared with default (package-private) access, while the overridden versions in Manager and Director are public. The printDetails method and the Manager/Director classes are in different packages. What is the most likely cause and the correct solution?

A.Change the access modifier of getDetails() in Employee to public (or protected).
B.Modify printDetails() to accept Manager or Director objects instead of Employee.
C.Add @Override annotation to the overridden methods in Manager and Director.
D.Declare getDetails() in Employee as final to ensure consistent behavior.
AnswerA

A is correct: default access prevents overriding from different packages; changing to public enables proper polymorphism.

Why this answer

In Java, a default-access method is not visible to subclasses in different packages, so Manager and Director cannot override it; their getDetails() methods are new methods, not overriding Employee's. Making Employee's getDetails() public (or protected) allows proper overriding and polymorphic behavior. Option B is wrong because it bypasses polymorphism.

Option C is wrong because @Override only helps catch errors, but the access issue remains. Option D is wrong because making the method final would prevent overriding entirely.

235
MCQhard

An integer counter variable is incremented in a loop that runs 3 billion times. Initially counter = 0. After the loop, the value is printed. Which code snippet correctly handles potential overflow?

A.int counter = 0; for(int i=0; i<3000000000L; i++) counter++; System.out.println(counter);
B.int counter = 0; for(int i=0; i<3000000000L; i++) counter += 1; System.out.println(counter);
C.int counter = 0; for(int i=0; i<3000000000L; i++) counter = Math.addExact(counter, 1); System.out.println(counter);
D.long counter = 0; for(long i=0; i<3000000000L; i++) counter++; System.out.println(counter);
AnswerD

long can hold 3e9 without overflow.

Why this answer

Uses a long variable, which can hold the value up to 9e18, avoiding overflow. Options A and B use int and will silently overflow because 3e9 exceeds Integer.MAX_VALUE (2.147e9). Option C uses Math.addExact, which throws an ArithmeticException on overflow; while this detects overflow, the question asks for handling it gracefully, and using a long is the proper approach.

236
Multi-Selectmedium

Which TWO are valid ways to handle a checked exception in a method?

Select 2 answers
A.Catch the exception within the method
B.Ignore the exception by doing nothing
C.Declare the exception in the throws clause
D.Use assert to suppress the exception
E.Convert it to a runtime exception by throwing a new RuntimeException
AnswersA, C

Catching is the primary way to handle.

Why this answer

Catching a checked exception within the method using a try-catch block is a valid way to handle it. The Java compiler enforces that checked exceptions (subclasses of Exception but not RuntimeException) must be either caught or declared, so catching the exception satisfies the compiler's requirement.

Exam trap

Oracle often tests the misconception that converting a checked exception to a RuntimeException (option E) is a valid way to handle it within the method, but the conversion itself requires the original exception to be caught or declared, so it is not a standalone handling mechanism.

237
MCQmedium

A developer tries to compile a modular Java application using the command shown in the exhibit. The compilation fails with the error shown. What is the most likely cause?

A.The `-d out` flag is incorrectly specified; it should point to the source directory.
B.The `-m` option should be `--module` instead.
C.The import statement should use the fully qualified class name instead of importing.
D.The `--module-source-path` does not include the location of the utility module.
AnswerD

The module source path must point to the directory that contains all module source directories; if missing, dependent modules cannot be resolved.

Why this answer

The error indicates that the compiler cannot find the utility module referenced in the `requires` directive. The `--module-source-path` option must list all directories containing module source code. Since the utility module's source is not included in the specified path, the compilation fails.

Option D correctly identifies this missing path as the cause.

Exam trap

Oracle often tests the distinction between module path and module source path, trapping candidates who confuse `-d` (output directory) with source path or who think import syntax is the issue when the real problem is a missing module source location.

How to eliminate wrong answers

Option A is wrong because `-d out` specifies the destination directory for compiled classes, not the source directory; it is correctly used here. Option B is wrong because `-m` is the correct short form for specifying the main module; `--module` is the long form but not required. Option C is wrong because the import statement is syntactically correct and does not cause a compilation error; the error is about a missing module, not about import resolution.

238
MCQmedium

Refer to the exhibit. A developer runs the command java -version on a system. Which statement about this Java installation is correct?

A.This is a Java SE 17 installation.
B.This is a Java Runtime Environment (JRE) installation.
C.This is a Java SE 8 installation.
D.This is a Java Development Kit (JDK) installation.
AnswerB

The output explicitly says 'Runtime Environment' and lacks compiler information.

Why this answer

The output shows "Runtime Environment" and no compiler information, indicating a JRE. Version 11.0.12 is Java SE 11 LTS. Option C and D are wrong because the version is 11, not 8 or 17.

Option A is incorrect because JDK would include the compiler.

239
Drag & Dropmedium

Arrange the steps to overload a method 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 define one method, then define another with same name but different parameters, ensure unique signatures, and then call with matching arguments.

240
MCQhard

A developer is using try-with-resources with a custom resource class that implements AutoCloseable. The class's close() method throws a custom exception `ResourceException`. In the try block, an IOException occurs. Which of the following best describes the exception that is propagated to the caller?

A.The IOException is discarded and the ResourceException is thrown.
B.The IOException is propagated with the ResourceException added as a suppressed exception.
C.The IOException is lost and the caller receives no exception.
D.Both exceptions are thrown simultaneously as a multi-exception.
AnswerB

try-with-resources handles this by suppressing the close exception and propagating the primary exception.

Why this answer

When using try-with-resources, if both the try block and the close() method throw exceptions, the exception from the try block is the one propagated to the caller, and any exception from close() is added as a suppressed exception to that primary exception. This is specified in Java's try-with-resources semantics (JLS §14.20.3). Therefore, the IOException from the try block is propagated, and the ResourceException from close() is suppressed within it.

Exam trap

The trap here is that candidates often think the last exception thrown (from close()) overrides the earlier exception, but Java's try-with-resources specifically preserves the try block exception and suppresses the close() exception.

How to eliminate wrong answers

Option A is wrong because the IOException is not discarded; it is the primary exception propagated, and the ResourceException is added as a suppressed exception, not thrown instead. Option C is wrong because the IOException is not lost; it is propagated to the caller, and the caller receives the IOException with the ResourceException suppressed. Option D is wrong because Java does not throw multiple exceptions simultaneously; only one exception is propagated, and others are suppressed within it.

241
MCQhard

A team is developing a financial application that processes large arrays of market data. They have a method that calculates moving averages by copying a subarray for each window. The current implementation creates a new array for each window using System.arraycopy. The application is running slowly in production. The team identifies that the method is called millions of times per minute. The array is large and the window size is small. The garbage collector overhead is high due to many short-lived arrays. Which optimization should they apply to reduce object creation and improve performance?

A.Use a Stream to process the array without creating intermediate arrays.
B.Use a single temporary array and reuse it by copying data into it for each window.
C.Use Arrays.copyOfRange() which is faster than System.arraycopy.
D.Use ArrayList instead of array to avoid copy.
AnswerB

Reuses one array, eliminating repeated allocations and reducing GC pressure.

Why this answer

Reusing a single temporary array eliminates the repeated allocation of short-lived arrays for each window, directly reducing garbage collector overhead. The current implementation uses System.arraycopy to create a new array per window, which is the primary source of object churn. By allocating one array once and copying data into it for each window, the team minimizes object creation while still performing the necessary copy operation.

Exam trap

The 1Z0-811 exam often tests the misconception that using a more modern API (like Streams or copyOfRange) automatically improves performance, when in fact the key optimization is reducing object allocation frequency.

How to eliminate wrong answers

Option A is wrong because using a Stream does not inherently avoid intermediate array creation; streams may still allocate temporary objects or buffers, and the core issue of per-window array allocation is not addressed. Option C is wrong because Arrays.copyOfRange() internally creates a new array each time, so it does not reduce object creation; it may even be slower than System.arraycopy due to additional bounds checking. Option D is wrong because ArrayList internally uses an Object[] array and would still require copying or allocation for each window, and it introduces boxing overhead for primitive data types, worsening performance.

242
MCQmedium

A developer writes: Object obj = new String("Hello"); System.out.println(obj.length()); What will be the output?

A.null
B.Runtime exception
C.5
D.Compilation error
E.0
AnswerD

The code produces a compilation error because the `obj` variable is declared with the static type `Object`. Although the runtime object is a `String`, the Java compiler performs method resolution based solely on the variable's declared type. The `Object` class does not possess a `length()` method. Consequently, attempting to invoke `obj.length()` fails during compilation, as the method signature is not found within the `Object` class's accessible members.

Why this answer

The code fails to compile because the reference variable 'obj' is of type Object, which does not have a length() method. The length() method is defined in the String class, not in Object. Since the compiler checks the declared type (Object) for method availability, it does not find length() and produces a compilation error.

Exam trap

Oracle often tests the distinction between compile-time type and runtime type, trapping candidates who assume that because the object is a String, the length() method is automatically available on any reference to it.

How to eliminate wrong answers

Option A is wrong because null is not printed; the code never executes due to a compilation error. Option B is wrong because a runtime exception would only occur if the code compiled and then failed at runtime, but here the compiler rejects the code. Option C is wrong because 5 would be the output if obj were declared as String, but the declared type is Object, so length() is not accessible.

Option E is wrong because 0 would be the length of an empty string, but the code does not compile to produce any output.

243
MCQeasy

A class defines two methods with the same name but different parameter lists. This is known as:

A.Method overriding
B.Method hiding
C.Method shadowing
D.Method overloading
AnswerD

Overloading allows same name, different parameters.

Why this answer

Method overloading occurs when a class defines multiple methods with the same name but different parameter lists (different number, type, or order of parameters). This is a compile-time polymorphism mechanism in Java that allows a method to handle different inputs without changing its name.

Exam trap

The trap here is that candidates often confuse method overloading with method overriding because both involve methods with the same name, but overriding requires identical parameter lists and occurs in inheritance, while overloading requires different parameter lists and can occur in the same class.

How to eliminate wrong answers

Option A is wrong because method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass, requiring the same method signature (name and parameter list), not different parameter lists. Option B is wrong because method hiding applies to static methods in a subclass that have the same signature as a static method in the superclass, not to methods with different parameter lists. Option C is wrong because method shadowing refers to a variable in a narrower scope (e.g., a local variable) having the same name as a variable in an outer scope (e.g., a field), not to methods with the same name but different parameters.

244
MCQhard

A class has a static variable counter initialized to 0. Two threads increment counter 1000 times each using counter++. What is a possible final value of counter?

A.1000
B.0
C.2000
D.Any value between 1000 and 2000 inclusive
AnswerD

Actual range due to race condition.

Why this answer

`counter++` is not an atomic operation; it consists of three steps: read, increment, and write. When two threads execute this non-atomic operation concurrently without synchronization, interleaving can cause lost updates, resulting in a final value that is less than 2000 but at least 1000 (since each thread increments at least once). The possible final value is any integer between 1000 and 2000 inclusive.

Exam trap

Oracle often tests the misconception that `counter++` is atomic, leading candidates to incorrectly choose 2000, when in fact the non-atomic nature allows any value between 1000 and 2000 due to lost updates.

How to eliminate wrong answers

Option A is wrong because it assumes only one thread successfully increments 1000 times while the other thread's increments are completely lost, which is possible but not the only possible outcome; the question asks for 'a possible final value', and 1000 is within the range but not the only correct answer. Option B is wrong because it suggests the counter could remain 0, which is impossible since each thread executes 1000 increments, and even with worst-case interleaving, each thread's increments will partially succeed, resulting in at least 1000. Option C is wrong because it assumes perfect atomicity and no race condition, which would only be true if `counter++` were synchronized or atomic; in reality, race conditions prevent guaranteeing 2000.

245
MCQeasy

A method is designed to compute the average of an array of test scores. What should the method return if the array is empty (length 0)?

A.Return 0.0
B.Do not compile; requires a return of type double
C.Throw a RuntimeException
D.Return null
AnswerA

Default value for empty average.

Why this answer

The method should return 0.0 for an empty array to avoid division by zero and to provide a safe default value. In Java, an empty array has length 0, and computing the average would require dividing by zero, which throws an ArithmeticException. Returning 0.0 is a common convention for empty collections, as it allows the caller to handle the result gracefully without crashing.

Exam trap

Oracle often tests the distinction between primitive and wrapper types; the trap here is that candidates may think returning null is acceptable for a double return type, but double is a primitive and cannot hold null.

How to eliminate wrong answers

Option B is wrong because the code compiles fine; the method can return 0.0, which is a double literal, satisfying the return type. Option C is wrong because throwing a RuntimeException (like IllegalArgumentException) is not required by the language and would be poor design; the method should handle the edge case gracefully rather than forcing exception handling on the caller. Option D is wrong because null cannot be returned for a primitive double return type; the method signature specifies double, not Double, so null is not assignable.

246
MCQhard

A team deploys a Java application and observes frequent Full GC pauses. Which garbage collector is designed to minimize pause times?

A.Garbage-First (G1GC) (-XX:+UseG1GC)
B.Concurrent Mark Sweep (CMS) (-XX:+UseConcMarkSweepGC)
C.Serial GC (-XX:+UseSerialGC)
D.Parallel GC (-XX:+UseParallelGC)
AnswerA

G1GC aims to limit pause times and reduce Full GC frequency.

Why this answer

G1GC (Garbage-First) is designed to provide predictable pause times and minimize Full GC pauses by dividing the heap into regions and collecting the regions with the most garbage first. Option B (CMS) was also designed for low pauses but is deprecated and can cause fragmentation. Option C (Serial) is for single-threaded environments and has long pauses.

Option D (Parallel) focuses on throughput, not pause times.

247
MCQmedium

What is the result of the following code snippet? int a = 5; int b = 2; double c = (double) (a / b); System.out.println(c);

A.2
B.2.0
C.Compilation error
D.2.5
AnswerB

a/b is integer division (2), then cast to double.

Why this answer

The expression `(a / b)` performs integer division, resulting in 2 (since both a and b are ints). The cast `(double)` is applied to the result of that integer division, converting the integer 2 to 2.0. The output is therefore 2.0.

Exam trap

The trap here is that candidates often believe the cast to double will cause the division to be performed in floating-point, but the cast is applied after the integer division, so the fractional part is already lost.

How to eliminate wrong answers

Option A is wrong because it omits the decimal point; the cast to double ensures the output is a floating-point number, not an integer. Option C is wrong because the code compiles without error; the cast is syntactically valid and applied to an int expression. Option D is wrong because it assumes the division is performed in floating-point context, but integer division truncates the fractional part before the cast, so the result is 2.0, not 2.5.

248
MCQhard

A team is designing a library that handles network timeouts. They create a custom exception `NetworkTimeoutException` that extends `Exception`. They want to ensure that callers are forced to handle this exception. Which declaration is appropriate for a method that throws this exception?

A.public void connect() throws RuntimeException
B.public void connect() throws NetworkTimeoutException
C.public void connect() throws e where e is NetworkTimeoutException
D.public void connect() throw NetworkTimeoutException
AnswerB

Correct syntax: checked exception declared with `throws` forces callers to handle or declare it.

Why this answer

The method must declare the custom checked exception `NetworkTimeoutException` in its throws clause to force callers to handle it. Since `NetworkTimeoutException` extends `Exception` (not `RuntimeException`), it is a checked exception, and the Java compiler enforces that any method throwing it must declare it with the `throws` keyword followed by the exception type name.

Exam trap

The trap here is confusing the `throw` keyword (used to throw an exception in code) with the `throws` keyword (used in method declarations), and assuming that declaring a superclass like `RuntimeException` satisfies the requirement to declare a specific checked exception.

How to eliminate wrong answers

Option A is wrong because `RuntimeException` is an unchecked exception, so declaring it does not force callers to handle the custom checked exception; the method should declare `NetworkTimeoutException` specifically. Option C is wrong because the `throws` clause requires the exception class name directly, not a variable or placeholder like `e where e is NetworkTimeoutException`; Java syntax does not support such a construct. Option D is wrong because the keyword is `throws` (with an 's'), not `throw`; `throw` is used to actually throw an exception inside the method body, not in the method declaration.

249
MCQhard

What is the result of the following code? int a = 8; int b = 3; System.out.println(a >> 1);

A.2
B.3
C.4
D.16
AnswerC

8 shifted right by 1 is 4.

Why this answer

The right shift operator `>>` shifts the bits of the integer `a` (which is 8, binary `1000`) to the right by 1 position. This discards the least significant bit and fills the most significant bit with the sign bit (0 for positive numbers), resulting in binary `0100`, which is decimal 4. Therefore, `System.out.println(a >> 1)` prints 4.

Exam trap

Oracle often tests the confusion between the right shift (`>>`) and left shift (`<<`) operators, as well as the misconception that `>> 1` always divides by 2 (which is true for positive integers but not for negative ones due to sign extension).

How to eliminate wrong answers

Option A is wrong because 2 would be the result of `a >> 2` (shifting right by 2 positions), not `a >> 1`. Option B is wrong because 3 would be the result of `a % b` (modulus) or `a / b` with integer division (8/3 = 2, not 3), not a right shift. Option D is wrong because 16 would be the result of `a << 1` (left shift, which multiplies by 2), not a right shift.

250
Multi-Selecteasy

Which TWO statements are correct about array declaration and initialization in Java?

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

Valid declaration and allocation.

Why this answer

`int[] a = new int[5];` declares an array of integers with a size of 5 and initializes all elements to their default value (0 for int). This is the standard syntax for array declaration and initialization in Java, where the size is specified after `new`.

Exam trap

Oracle often tests the distinction between C-style array syntax and Java's strict rules, specifically that you cannot combine a size specifier with an initializer list, and that size is never placed in the declaration brackets in Java.

251
MCQeasy

A junior developer writes a simple 'Hello World' program and saves it as HelloWorld.java. He compiles it successfully with 'javac HelloWorld.java', confirming that HelloWorld.class is created in the current directory. When he tries to run it with the command 'java HelloWorld', the system returns 'Error: Could not find or load main class HelloWorld'. The current directory is indeed the one containing HelloWorld.class. He has JAVA_HOME set to the JDK installation directory and has verified that java is in the PATH. What is the most likely cause?

A.The class file is corrupt
B.The classpath does not include the current directory
C.The main method is missing or incorrectly declared
D.The java command is not in the PATH
AnswerB

Java does not automatically search the current directory; use '-cp .' to include it.

Why this answer

By default, the java command does not include the current directory in the classpath, so even though HelloWorld.class exists in the current directory, the JVM cannot find it. The developer must explicitly add the current directory using -cp . or set the CLASSPATH environment variable. Option A is incorrect because a corrupt class file would typically cause a ClassFormatError, not 'Could not find or load main class'.

Option C is incorrect because a missing or incorrect main method would yield 'Main method not found in class HelloWorld' error. Option D is incorrect because the error message indicates that the java command executed (it found the java executable), so it is in the PATH.

252
Multi-Selecteasy

Which TWO access modifiers allow access from a subclass in a different package?

Select 2 answers
A.private
B.static
C.default (no modifier)
D.protected
E.public
AnswersD, E

Protected members are accessible in subclasses even if they are in different packages.

Why this answer

(protected) is correct because the protected access modifier allows access to members of a superclass by subclasses in different packages, provided the subclass inherits from the superclass. Option E (public) is also correct because public members are accessible from any class, regardless of package or inheritance.

Exam trap

Oracle often tests the distinction between access modifiers and non-access modifiers, so candidates may mistakenly select 'static' as an access modifier because it is commonly used with methods and fields.

253
MCQhard

A mobile app backend uses Java streams to process user data. The code snippet filters users who are active and older than 18, then collects them into a list: List<User> result = users.stream() .filter(u -> u.isActive()) .filter(u -> u.getAge() > 18) .collect(Collectors.toList()); Performance metrics show that this stream operation is slow when the user list has millions of entries. The team wants to improve performance without changing the business logic. Which change would most likely improve performance?

A.Replace .stream() with .parallelStream().
B.Use a HashSet instead of List for users collection.
C.Replace the stream with a traditional for loop.
D.Combine both filters into one using logical AND operator.
AnswerA

Parallel processing can utilize multiple cores for large datasets.

Why this answer

Replacing `.stream()` with `.parallelStream()` enables parallel processing of the stream, which can leverage multiple CPU cores to process the filter operations concurrently. For large datasets (millions of entries), this can significantly reduce execution time by splitting the workload across threads, while preserving the same business logic and order of operations.

Exam trap

The trap here is that candidates may think combining filters (Option D) is the most effective optimization, but the Oracle exam tests the understanding that parallelization is the key performance lever for large data sets, not minor syntactic changes.

How to eliminate wrong answers

Option B is wrong because using a `HashSet` instead of a `List` for the `users` collection does not improve stream processing performance; `HashSet` offers O(1) lookup but does not affect the sequential iteration or filtering of a stream. Option C is wrong because replacing the stream with a traditional for loop would not inherently improve performance; in fact, streams can be optimized by the JVM, and a for loop would lose the ability to parallelize easily. Option D is wrong because combining both filters into one using logical AND (`&&`) reduces the number of lambda expressions but does not change the underlying sequential processing; the performance gain is negligible and does not address the core issue of single-threaded execution.

254
MCQmedium

A web application uses a HashMap to cache user session data. The keys are String objects representing session IDs, and values are Session objects. After some time, the cache memory usage grows excessively, causing OutOfMemoryError. The cache is never cleared. The team decides to implement a cache eviction policy. Which approach is best suited for this scenario in terms of Java standard library?

A.Use WeakHashMap instead of HashMap.
B.Wrap the HashMap with Collections.synchronizedMap.
C.Use LinkedHashMap with removeEldestEntry method.
D.Use TreeMap with a custom comparator.
AnswerC

LinkedHashMap can implement LRU cache easily.

Why this answer

LinkedHashMap provides a straightforward way to implement a cache eviction policy by overriding the `removeEldestEntry` method. This method is automatically called by `put` and `putAll` to decide whether to remove the eldest entry, allowing you to limit the cache size and prevent OutOfMemoryError without manual eviction logic.

Exam trap

Oracle often tests the distinction between data structures that provide automatic eviction (LinkedHashMap) versus those that only manage references (WeakHashMap) or ordering (TreeMap), leading candidates to mistakenly choose WeakHashMap because they confuse weak references with cache eviction.

How to eliminate wrong answers

Option A is wrong because WeakHashMap uses weak references for keys, meaning entries are removed when the key is no longer strongly referenced elsewhere, which is not suitable for session IDs that are typically stored as string literals or constants with strong references; this would cause premature eviction or no eviction at all. Option B is wrong because Collections.synchronizedMap only provides thread safety by synchronizing all method calls, but does not implement any eviction policy, so memory usage would still grow unbounded. Option D is wrong because TreeMap maintains keys in sorted order using a comparator, which adds overhead and does not provide any built-in eviction mechanism; it is designed for ordered traversal, not cache size management.

255
MCQmedium

In a login system, the authentication method receives an array of user roles as a String[] and checks if a specific role is present. The array may be large (thousands of roles), and the method is called frequently for each user request. Performance is critical. The array is static and does not change after initialization. Which approach is most efficient for repeated checks?

A.Use a for loop to iterate and compare each string.
B.Sort the array and use Arrays.binarySearch().
C.Convert the array to a HashSet once and reuse it for lookups.
D.Use a List and the contains() method.
AnswerC

HashSet provides O(1) average lookup time.

Why this answer

Converting the array to a HashSet once provides O(1) average-time complexity for subsequent contains() checks, which is far more efficient than O(n) linear search or O(log n) binary search when the method is called frequently on a static array. The HashSet leverages hash codes for direct bucket lookup, making it ideal for repeated membership tests on large, unchanging data sets.

Exam trap

Oracle often tests the misconception that sorting and binary search is the most efficient approach for repeated lookups, but they overlook the upfront sorting cost and the fact that HashSet provides O(1) average-time complexity, which is superior for static, frequently queried data.

How to eliminate wrong answers

Option A is wrong because a for loop performs O(n) linear search on each call, which is inefficient for thousands of roles and frequent requests. Option B is wrong because sorting the array takes O(n log n) upfront, and binary search is O(log n) per check, but the overhead of sorting and the requirement for the array to remain sorted (which is unnecessary here) makes it less efficient than a HashSet for repeated lookups. Option D is wrong because List.contains() also performs O(n) linear search internally, offering no performance advantage over a simple for loop.

256
MCQeasy

Which of the following exceptions is a checked exception?

A.ArrayIndexOutOfBoundsException
B.ArithmeticException
C.IOException
D.NullPointerException
AnswerC

IOException is a checked exception.

Why this answer

IOException is a checked exception in Java, meaning it must be either caught or declared in the method signature using a try-catch block or throws clause. Checked exceptions are subclasses of Exception (excluding RuntimeException and its subclasses), and IOException directly extends Exception, making it subject to compile-time checking.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions by listing common RuntimeException subclasses (like NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException) as distractors, hoping candidates confuse them with checked exceptions due to their frequent occurrence in code.

How to eliminate wrong answers

Option A is wrong because ArrayIndexOutOfBoundsException is a subclass of RuntimeException, making it an unchecked exception that does not require explicit handling. Option B is wrong because ArithmeticException is also a subclass of RuntimeException, so it is unchecked and can occur at runtime without mandatory handling. Option D is wrong because NullPointerException is a subclass of RuntimeException, thus it is an unchecked exception that the compiler does not enforce handling for.

257
Multi-Selecthard

Which THREE are checked exceptions in Java? (Choose three.)

Select 3 answers
A.ArrayIndexOutOfBoundsException
B.SQLException
C.NullPointerException
D.IOException
E.FileNotFoundException
AnswersB, D, E

It is a checked exception.

Why this answer

SQLException is a checked exception in Java because it extends Exception directly (not RuntimeException). Checked exceptions must be either caught with a try-catch block or declared in the method signature using the throws clause. SQLException is thrown when there is a database access error or other SQL-related issues, forcing the developer to handle potential failures at compile time.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions by including common RuntimeException subclasses (like NullPointerException and ArrayIndexOutOfBoundsException) as distractors, exploiting the misconception that any exception must be handled.

258
Multi-Selecteasy

Which TWO statements are true about the switch statement in Java? (Choose two.)

Select 2 answers
A.It can be used with char variables.
B.The break statement is mandatory at the end of each case.
C.The default case is optional.
D.Case labels can be runtime expressions.
E.It can be used with long variables.
AnswersA, C

char is supported in switch.

Why this answer

Options A and C are correct. A: Switch supports char, int, short, byte, String, and enum types, so char is valid. B is false because the break statement is optional; without it, execution falls through to the next case.

C is true: the default case is optional. D is false because case labels must be compile-time constant expressions, not runtime expressions. E is false because long variables are not allowed in switch statements.

259
MCQhard

A developer needs to search an unsorted array of 100,000 customer IDs (int) for a specific ID. Which approach is most efficient for a single search?

A.Use Arrays.binarySearch() directly on the unsorted array
B.Iterate through the array and compare each element
C.First sort the array using Arrays.sort(), then use binary search
D.Convert the array to a HashSet and then search
AnswerB

Linear search has O(n) time, optimal for a single search on unsorted data.

Why this answer

A linear search (iterating through the array and comparing each element) is the most efficient approach for a single search on an unsorted array. It has O(n) time complexity and requires no preprocessing, which is optimal when you only need to find one element once.

Exam trap

Oracle often tests the misconception that binary search is always faster, but candidates forget that binary search requires a sorted array and that sorting itself adds cost, making linear search more efficient for a single unsorted search.

How to eliminate wrong answers

Option A is wrong because Arrays.binarySearch() requires a sorted array; on an unsorted array, it produces undefined results (typically incorrect index or negative value). Option C is wrong because sorting the array first with Arrays.sort() (O(n log n)) and then performing binary search (O(log n)) is less efficient than a single linear scan (O(n)) for a one-time search. Option D is wrong because converting the array to a HashSet requires iterating through all elements (O(n)) and then searching (O(1) average), but the conversion overhead makes it less efficient than a simple linear search for a single query.

260
MCQhard

A developer is troubleshooting a performance issue in a reporting application. A nested loop iterates over a large dataset: the outer loop processes each row, and the inner loop performs a complex computation on each column. The application is taking longer than expected. Upon reviewing the code, the developer notices that the inner loop's termination condition is recalculated each iteration, which involves a costly method call. Which optimization should the developer implement to improve performance?

A.Use the break statement to exit early based on a precomputed value
B.Move the inner loop's condition calculation outside the outer loop
C.Convert the loops to recursive calls
D.Change the inner loop to use a while loop
AnswerB

By storing the result of the costly method in a variable before the inner loop, the method is called only once per outer iteration.

Why this answer

Moving the condition calculation outside the outer loop (e.g., storing the result of the costly method call in a variable before the inner loop) eliminates redundant calls, improving performance. Option A is incorrect because using a break statement based on a precomputed value would not address the condition recalculation; the break would exit early but the condition is still recalculated each iteration unless moved outside. Option C is incorrect because converting to recursive calls would typically add overhead (stack frames) and is not a performance optimization for this specific issue.

Option D is incorrect because simply changing to a while loop does not change the fact that the condition is recalculated each iteration; the costly method call would still be made each time unless the limit is precomputed.

261
MCQhard

What is the value of z after executing: int x = 3; int y = 2; int z = x++ * --y;

A.3
B.6
C.4
D.2
AnswerA

x++ uses 3, --y yields 1, product = 3.

Why this answer

The expression `x++ * --y` uses post-increment on `x` and pre-decrement on `y`. Post-increment returns the original value of `x` (3) before incrementing it to 4. Pre-decrement decrements `y` from 2 to 1, then returns the new value (1).

The multiplication is 3 * 1 = 3, which is assigned to `z`. So the correct answer is 3.

Exam trap

Oracle often tests the difference between pre- and post-increment/decrement operators, and the trap here is that candidates mistakenly apply both operators to the original values or forget that post-increment returns the value before the increment.

How to eliminate wrong answers

Option B (6) is wrong because it assumes both operators use the original values (3 * 2) without considering that `--y` decrements before use. Option C (4) is wrong because it might result from misapplying post-increment on `x` (using 4) and pre-decrement on `y` (using 1), or from thinking `x++` returns the incremented value. Option D (2) is wrong because it could come from incorrectly applying pre-decrement to `y` (1) and then multiplying by 2, or from confusing the order of operations.

262
MCQeasy

A developer wants to ensure that a class cannot be subclassed. Which keyword should be used?

A.final
B.protected
C.private
D.abstract
E.static
AnswerA

A class declared as final cannot be subclassed.

Why this answer

The `final` keyword prevents a class from being subclassed. When a class is declared `final`, the compiler enforces that no other class can extend it, ensuring its implementation cannot be overridden or inherited. This is the correct mechanism in Java to prevent subclassing.

Exam trap

Oracle often tests the `final` keyword in the context of inheritance, and the trap here is that candidates confuse `final` with `abstract` (which forces subclassing) or `private` (which is about access, not inheritance prevention), leading them to pick the wrong option.

How to eliminate wrong answers

Option B is wrong because `protected` controls access to members (fields, methods) from subclasses and the same package, but does not prevent a class from being subclassed. Option C is wrong because `private` restricts access to within the class itself, but a class cannot be declared `private` at the top level (only inner classes can be private), and even then it does not prevent subclassing of the outer class. Option D is wrong because `abstract` explicitly requires a class to be subclassed to be instantiated, which is the opposite of preventing subclassing.

Option E is wrong because `static` is used for class-level members (methods, fields, inner classes) and cannot be applied to a top-level class; it has no effect on subclassing prevention.

263
MCQhard

Given the compilation error above, which fix would resolve the error?

A.Add a throws FileNotFoundException clause to the main method.
B.Change FileReader to BufferedReader.
C.Wrap the code in a try-catch block for FileNotFoundException.
D.Use FileInputStream instead.
AnswerC

Wrapping the code in a try-catch block for FileNotFoundException correctly handles the checked exception locally, satisfying the compiler's requirement.

Why this answer

The compilation error indicates that the code uses a constructor or method that throws a checked `FileNotFoundException` (a subclass of `IOException`). In Java, checked exceptions must be either caught with a try-catch block or declared in the method signature. Wrapping the code in a try-catch block for `FileNotFoundException` handles the exception locally, resolving the compilation error without altering the method signature.

Exam trap

The trap here is that candidates often think adding a `throws` clause (Option A) is always the correct fix, but the question's context (a compilation error within a method that may not be allowed to throw checked exceptions, such as the main method in a simple program) makes try-catch the appropriate solution, and they overlook that `FileInputStream` (Option D) also throws the same checked exception.

How to eliminate wrong answers

Option A is wrong because adding a `throws FileNotFoundException` clause to the main method would only propagate the exception, not resolve the compilation error if the error is due to an unhandled checked exception within the code; however, the question states the error is a compilation error, and while adding throws could fix it, the more standard and recommended fix for a single statement is to handle it locally with try-catch, and the question implies the error is from code that is not in a method that can throw it (e.g., inside a block without throws). Option B is wrong because changing `FileReader` to `BufferedReader` does not eliminate the `FileNotFoundException`; `BufferedReader` itself does not throw that exception, but it typically wraps a `FileReader` which does, so the underlying issue remains. Option D is wrong because using `FileInputStream` instead of `FileReader` still throws a `FileNotFoundException` (as both are checked exceptions), so it does not resolve the compilation error.

264
MCQmedium

Given methods: void print(Integer i) { System.out.println("Integer"); } void print(int i) { System.out.println("int"); } What is output of print(10);?

A.Compilation error
B."int"
C."Integer"
D.Runtime error
AnswerB

Correct. Exact match with int parameter.

Why this answer

When calling print(10) with an integer literal, Java's method overloading resolution prefers the primitive int version over the Integer wrapper type because the literal 10 is a primitive int. The compiler selects the most specific matching method without requiring autoboxing, so the void print(int i) method is invoked, printing "int".

Exam trap

Oracle often tests the misconception that autoboxing will always convert a primitive to its wrapper type, leading candidates to incorrectly choose the Integer overload, but the compiler prioritizes exact primitive matches to avoid unnecessary boxing.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; method overloading with both int and Integer is valid and the compiler can resolve the call. Option C is wrong because the compiler does not choose the Integer version when a primitive int literal is passed, as autoboxing is only used if no exact primitive match exists. Option D is wrong because no runtime error occurs; the method call is resolved at compile time and executes without exception.

265
MCQmedium

Refer to the exhibit. What is the output?

A.null
B.Vehicle
C.Compilation error
D.Car
E.Runtime error
AnswerB

In Java, fields are not polymorphic; the reference type determines which field is accessed. v is of type Vehicle, so v.type refers to Vehicle's type field.

Why this answer

In Java, fields are not polymorphic; the reference type determines which field is accessed. v is of type Vehicle, so v.type refers to Vehicle's type field.

266
MCQhard

Based on the command, which garbage collector is configured for this application?

A.Parallel GC
B.Garbage-First (G1GC)
C.Serial GC
D.Concurrent Mark Sweep (CMS)
AnswerB

The flag -XX:+UseG1GC enables G1GC.

Why this answer

XX:+UseG1GC explicitly sets the Garbage-First (G1GC) garbage collector. Option A is incorrect; Parallel GC would be enabled with -XX:+UseParallelGC. Option C is incorrect; Serial GC would be enabled with -XX:+UseSerialGC.

Option D is incorrect; CMS would be enabled with -XX:+UseConcMarkSweepGC.

267
MCQmedium

A method 'public static double average(int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; i++) sum += numbers[i]; return sum / numbers.length; }' is called with array {10, 20, 30}. What change is needed to return the correct average?

A.Change the loop to for (int i = 1; i <= numbers.length; i++)
B.Change 'sum / numbers.length' to '(double) sum / numbers.length'
C.Change return type to int
D.Add a second parameter for the length
AnswerB

The original code performs integer division because both `sum` and `numbers.length` are integer types. This truncates any fractional part, leading to an incorrect average for inputs that do not divide evenly. Casting `sum` to `double` before the division forces floating-point arithmetic. This ensures `numbers.length` is also promoted to `double`, allowing the calculation to produce a precise decimal result, satisfying the requirement to return the correct average.

Why this answer

The method performs integer division because both `sum` (int) and `numbers.length` (int) are integers, truncating the fractional part. Casting `sum` to `double` before division forces floating-point arithmetic, preserving the decimal value. For the array {10, 20, 30}, the correct average is 20.0, but integer division yields 20 (truncated from 20.0, though here it matches by coincidence; for non-integer averages like {10, 20, 31}, the error would be obvious).

Exam trap

Oracle often tests the distinction between integer and floating-point division in Java, trapping candidates who overlook that dividing two ints always truncates the decimal, even when assigned to a double variable or returned from a double method.

How to eliminate wrong answers

Option A is wrong because changing the loop to start at index 1 would skip the first element (10), and using `<=` would cause an ArrayIndexOutOfBoundsException when `i` equals `numbers.length`. Option C is wrong because changing the return type to int does not fix the integer division issue; the result would still be truncated, and the method signature would no longer match the intended return of a double average. Option D is wrong because the array already provides its length via `numbers.length`, and adding a second parameter is unnecessary and would not resolve the integer division problem.

268
Multi-Selecteasy

Which THREE of the following are valid loop constructs in Java?

Select 3 answers
A.while loop
B.for loop
C.switch statement
D.if statement
E.do-while loop
AnswersA, B, E

Correct: The while loop is a standard loop construct in Java.

Why this answer

The correct answers are A (while loop), B (for loop), and E (do-while loop) because all three are valid loop constructs in Java. The while loop repeats as long as a condition is true, the for loop provides a compact iteration mechanism, and the do-while loop guarantees at least one execution.

Exam trap

A common trap is forgetting that do-while is a valid loop construct. Candidates often select only while and for, but do-while is also a legitimate loop in Java.

269
Multi-Selecthard

Which TWO are characteristics of the Java Runtime Environment (JRE)?

Select 2 answers
A.It includes the Java compiler (javac) for compiling source code.
B.It is smaller in size compared to the JDK.
C.It provides a debugger for troubleshooting code.
D.It is necessary to run any Java application.
E.It contains the JVM and core class libraries.
AnswersD, E

JRE provides the runtime required to execute Java programs.

Why this answer

Options D and E are correct. The JRE (Java Runtime Environment) is necessary to run any Java application (D) and it contains the JVM and core class libraries (E). Option A is incorrect because the Java compiler (javac) is part of the JDK, not the JRE.

Option B is incorrect because although the JRE is smaller than the JDK, this is a relative comparison and not a defining characteristic of the JRE itself. Option C is incorrect because the debugger is included in the JDK, not the JRE.

270
Multi-Selecteasy

Which two of the following operators are logical operators in Java? (Choose two.)

Select 2 answers
A.||
B.&
C.&&
D.|
E.~
AnswersA, C

Correct: || is the logical OR operator.

Why this answer

|| is the logical OR operator in Java, which returns true if at least one of the two boolean operands is true. Option C is correct because && is the logical AND operator, which returns true only if both boolean operands are true. Both operators perform short-circuit evaluation, meaning the right operand is not evaluated if the result is already determined by the left operand.

Exam trap

The trap here is that candidates often confuse bitwise operators (&, |) with logical operators (&&, ||) because they look similar, but Java treats them distinctly based on operand types and evaluation behavior.

271
Multi-Selecthard

Which TWO statements correctly describe the Java language? (Choose two.)

Select 2 answers
A.Java supports multiple inheritance of implementation.
B.Java supports operator overloading.
C.Java supports object-oriented programming.
D.Java supports multiple inheritance of classes.
E.Java is a statically typed language.
AnswersC, E

Java is primarily object-oriented.

Why this answer

Java is fundamentally an object-oriented programming language that supports encapsulation, inheritance, and polymorphism. Java's design revolves around classes and objects, and all code must be written inside a class, making OOP a core principle of the language.

Exam trap

Oracle often tests the distinction between multiple inheritance of implementation (not supported) and multiple inheritance of type (supported via interfaces), and candidates mistakenly think Java supports operator overloading because of the + operator for strings.

272
MCQhard

A company is developing a Java-based inventory management system. The system runs on a single server and processes up to 1000 concurrent requests. The development team has implemented the code using multiple threads to handle requests. Recently, the system has been experiencing intermittent data corruption in the inventory counts. After reviewing the code, the team suspects that the issue is related to thread safety. The team is considering the following solutions: (A) Use the 'synchronized' keyword on all methods that update inventory counts. (B) Use 'volatile' keyword on the inventory count variables. (C) Use 'AtomicInteger' for inventory counts. (D) Increase the number of threads to handle requests faster. Which solution should the team implement to fix the data corruption issue with minimal performance impact?

A.Use 'AtomicInteger' for inventory counts.
B.Increase the number of threads to handle requests faster.
C.Use 'volatile' keyword on the inventory count variables.
D.Use the 'synchronized' keyword on all methods that update inventory counts.
AnswerA

AtomicInteger provides lock-free, thread-safe operations with good performance.

Why this answer

AtomicInteger provides thread-safe atomic operations (like incrementAndGet) without requiring synchronization, ensuring consistent inventory counts under concurrent access with minimal performance overhead compared to full method synchronization.

Exam trap

Oracle often tests the distinction between visibility (volatile) and atomicity (AtomicInteger), trapping candidates who think volatile alone solves read-modify-write race conditions.

How to eliminate wrong answers

Option B is wrong because increasing the number of threads does not fix thread safety issues; it can worsen data corruption by increasing race conditions. Option C is wrong because volatile only ensures visibility of changes across threads but does not provide atomicity for compound operations like read-modify-write (e.g., count++), which is the root cause of corruption. Option D is wrong because using synchronized on all methods that update inventory counts would fix the issue but introduces significant performance impact due to thread contention, making it less optimal than AtomicInteger.

273
MCQhard

A developer is writing a bitmask validation method. The method should return true if both input integers (x and y) have exactly the same least significant bit set. The developer writes: if (x & y == 1) { return true; } However, the condition never evaluates to true even when both numbers are odd (least significant bit = 1). Debugging shows that x and y are positive integers. What is the root cause and the correct fix?

A.Use modulo: if (x % 2 == 1 && y % 2 == 1) { ... }
B.Add parentheses: if ((x & y) == 1) { ... }
C.Use bitwise OR: if (x | y == 1) { ... }
D.Use logical AND: if (x && y == 1) { ... }
AnswerB

Parentheses ensure the bitwise AND is performed before the comparison, correctly checking if the least significant bit of x & y is 1.

Why this answer

In Java, the bitwise AND operator & has lower precedence than the equality operator ==. So x & y == 1 is parsed as x & (y == 1), which first evaluates y == 1 to a boolean, then performs bitwise AND with x, treating true as 1 and false as 0. That's not the intended check.

The correct fix is to add parentheses to ensure & is evaluated first: (x & y) == 1. This checks if both numbers have the same least significant bit set (both odd). Option B correctly adds parentheses.

Options A, C, and D do not correctly address the bitwise check: A uses modulo which works for odd/even but not general bitmasking; C uses bitwise OR which checks if either bit is set; D uses logical AND which is for booleans, not integers.

274
Multi-Selectmedium

Which TWO command-line tools are included in the Oracle JDK for monitoring and troubleshooting Java applications? (Select exactly 2)

Select 2 answers
A.jstack
B.jmod
C.jstat
D.javap
E.jdb
AnswersA, C

jstack prints Java thread dumps for troubleshooting deadlocks and thread issues.

Why this answer

jstack is a command-line tool included in the Oracle JDK that prints Java stack traces of threads for a given Java process or core dump. It is used to diagnose deadlocks, thread contention, and other concurrency issues by showing the state and call stack of each thread.

Exam trap

Oracle often tests the distinction between development tools (javap, jdb) and runtime monitoring tools (jstack, jstat), leading candidates to mistakenly select javap or jdb because they are familiar from debugging sessions.

275
Multi-Selecteasy

Which THREE are valid Java identifiers?

Select 3 answers
A.2ndValue
B.my_value
C.$dollar
D.my-var
E._myVar
AnswersB, C, E

Valid underscore in name.

Why this answer

(my_value) is a valid Java identifier because it starts with a letter (m) and contains only letters, digits, and underscores. Java identifiers must begin with a letter, underscore, or dollar sign, and subsequent characters can include letters, digits, underscores, or dollar signs.

Exam trap

The 1Z0-811 exam often tests the rule that identifiers cannot start with a digit and cannot contain hyphens, tricking candidates who might think underscores or dollar signs are invalid or that hyphens are acceptable.

276
MCQmedium

A team is designing a system where a 'Report' class can be generated in different formats (PDF, Excel, HTML). They want to avoid modifying the Report class when adding new formats. Which OOP principle or pattern should they use?

A.Method Overloading
B.Composition
C.Inheritance
D.Singleton
AnswerB

Composing Report with a formatter interface allows adding formats without modifying Report.

Why this answer

Omposition (often implemented via the Strategy pattern), which allows the Report class to delegate format generation to separate strategy objects. This adheres to the Open/Closed Principle: the Report class is closed for modification but open for extension. Adding a new format only requires creating a new strategy class without altering the Report class.

Option B (Composition) is correct. Option A (Method Overloading) is incorrect because it would require adding a new overloaded method for each format in the Report class, violating the goal of not modifying it. Option C (Inheritance) is incorrect because it would create a rigid hierarchy where each format is a subclass of Report, leading to tight coupling and difficulty in adding new formats without modifying existing code.

Option D (Singleton) is incorrect because it ensures a single instance, which does not address the need for flexible format generation.

277
Multi-Selecthard

Which THREE statements are correct about the 'main' method signature in Java?

Select 3 answers
A.It must be declared public.
B.It can be declared to return an int.
C.It must be declared void.
D.It must be declared static.
E.It can be named any valid identifier.
AnswersA, C, D

JVM needs access to call it.

Why this answer

The Java Language Specification (JLS) requires the main method to be declared public so that the JVM can access it from outside the class. Without public visibility, the JVM would not be able to invoke the method as the entry point of the application.

Exam trap

Oracle often tests the misconception that the main method can have a non-void return type or a different name, tricking candidates who confuse it with other methods or C/C++ entry points.

278
MCQmedium

Refer to the exhibit. What is the result of attempting to compile and run the code?

A.Compilation error because x is private in A
B.Prints 0
C.Runtime error
D.Prints 5
AnswerA

Private members are not inherited.

Why this answer

The code fails to compile because class B attempts to access the private field `x` of class A from a different class. In Java, private members are only accessible within the same class, not from subclasses or other classes, even if they are in the same file. The `super.x` reference in class B is illegal, causing a compilation error.

Exam trap

Oracle often tests the misconception that private members are accessible in subclasses, especially when the subclass is in the same file or package, but Java's access control is strictly class-based, not file-based.

How to eliminate wrong answers

Option B is wrong because the code never compiles, so no value is printed. Option C is wrong because the error is caught at compile time, not at runtime. Option D is wrong because even if `x` were accessible, the value 5 would not be printed due to the compilation failure.

279
MCQhard

Consider: for(int i=0;i<10;i++) { int x = i; } System.out.println(x); What is the result?

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

Correct. x is out of scope.

Why this answer

The variable `x` is declared inside the `for` loop block, so its scope is limited to that block. Attempting to use `x` outside the loop (in the `System.out.println(x);` statement) causes a compilation error because `x` is not in scope at that point. The Java compiler enforces block-level scoping rules, and any reference to a variable outside its declared block results in a 'cannot find symbol' error.

Exam trap

The trap here is that candidates often overlook Java's strict block scoping rules and assume a variable declared inside a loop is accessible after the loop, confusing it with languages that have function-level scoping or with the loop variable `i` itself, which is also scoped to the loop block.

How to eliminate wrong answers

Option A is wrong because it assumes the variable `x` is accessible after the loop and holds the last assigned value (9), but `x` is out of scope. Option B is wrong because it incorrectly suggests the loop variable `i` or some other value (10) is printed, but `x` is not accessible. Option D is wrong because it assumes `x` defaults to 0, but local variables in Java are not automatically initialized and must be explicitly assigned before use; moreover, `x` is out of scope.

280
MCQeasy

A junior developer wrote the following code to compare two strings entered by a user: if (username == "admin") { grantAccess(); } else { denyAccess(); }. The code always denies access even when the user enters 'admin'. What is the most likely cause, and how should the code be fixed?

A.The input string has leading or trailing spaces. Use username.trim().equals("admin") instead.
B.The variable username is null, causing a NullPointerException that is caught and denied access. Add a null check.
C.The strings are compared using == which is case-sensitive. Use username.equalsIgnoreCase("admin") instead.
D.The strings are compared using == which checks reference equality. Use username.equals("admin") instead.
AnswerD

equals compares content.

Why this answer

In Java, the == operator compares object references, not the actual content of strings. When comparing two String objects for logical equality, the .equals() method must be used. The code if (username == "admin") checks whether username and the string literal "admin" refer to the same memory location, which is false when username is obtained from user input (e.g., via Scanner or console), even if the characters are identical.

Exam trap

Oracle Java Foundations exam often tests the distinction between reference equality (==) and value equality (.equals()) for String objects, and the trap here is that candidates may think the issue is case sensitivity or whitespace, when the fundamental problem is the use of the wrong comparison operator.

How to eliminate wrong answers

Option A is wrong because while leading/trailing spaces could cause a mismatch, the most likely cause is the use of ==, not spaces; trimming alone does not fix the reference comparison issue. Option B is wrong because a null username would throw a NullPointerException at runtime, not silently deny access, and the code does not show any exception handling. Option C is wrong because case sensitivity is not the core issue; the problem is reference equality, and using equalsIgnoreCase would still fail if == is used (the method would not be called correctly).

281
MCQhard

A custom exception class must extend which class to be a checked exception?

A.Throwable
B.Error
C.RuntimeException
D.Exception
AnswerD

Any class that extends Exception (and not RuntimeException) is a checked exception.

Why this answer

In Java, a checked exception is any exception that is a subclass of `Exception` but not a subclass of `RuntimeException`. To create a custom checked exception, your class must extend `Exception` (or a subclass of `Exception` that is itself a checked exception). This forces callers to handle or declare the exception, enforcing compile-time checking.

Exam trap

The trap here is that candidates often confuse `Throwable` with `Exception` or think that extending `RuntimeException` still produces a checked exception, but the key distinction is that only subclasses of `Exception` (excluding `RuntimeException` and its subclasses) are checked.

How to eliminate wrong answers

Option A is wrong because `Throwable` is the superclass of all errors and exceptions; extending `Throwable` directly creates a class that is neither a checked exception nor an unchecked exception in the standard sense, and it is not the intended way to create a custom checked exception. Option B is wrong because `Error` is reserved for serious system-level problems (e.g., `OutOfMemoryError`) that are not meant to be caught or handled by application code; extending `Error` creates an unchecked, non-recoverable error, not a checked exception. Option C is wrong because `RuntimeException` is the base class for unchecked exceptions; extending `RuntimeException` creates an exception that does not require handling or declaration, which is the opposite of a checked exception.

282
MCQhard

Given: String str = "Java"; str = str.concat(" SE"); str.replace('a', 'A'); System.out.println(str); What is the output?

A.Java
B.JAVA SE
C.Java SE
D.JAvA SE
AnswerC

The output is "Java SE" because Java String objects are immutable. The `str.concat(" SE")` operation creates a new String "Java SE" and successfully reassigns `str` to refer to this new object. However, `str.replace('a', 'A')` also creates a new String ("JAvA SE"), but its return value is not assigned back to `str`. Consequently, `str` continues to refer to the "Java SE" object established by the `concat` method, which is then printed to the console.

Why this answer

The `concat` method returns a new String "Java SE" which is assigned back to `str`. The `replace` method also returns a new String but its result is not assigned to any variable, so the original `str` remains unchanged. The final `println` outputs the current value of `str`, which is "Java SE".

Exam trap

The trap here is that candidates assume `replace` modifies the original string in place, forgetting that String methods return a new object and the result must be assigned to affect the variable.

How to eliminate wrong answers

Option A is wrong because `str.concat(" SE")` creates a new String "Java SE" and assigns it to `str`, so the output is not just "Java". Option B is wrong because `replace('a', 'A')` is not applied to `str` (its return value is discarded), so the string is not converted to "JAVA SE". Option D is wrong because the `replace` method would replace all occurrences of 'a' with 'A', but since its result is not stored, `str` remains "Java SE", not "JAvA SE".

283
MCQhard

Which statement about abstract classes and interfaces is true in Java?

A.Both B and D
B.An interface can have instance variables
C.An abstract class can be instantiated
D.An interface can have constructor
E.An abstract class can have concrete methods
AnswerE

Correct. Abstract classes can have both abstract and concrete methods.

Why this answer

An abstract class in Java can contain concrete (non-abstract) methods with full implementations, which subclasses can inherit or override. This is a key distinction from interfaces (prior to Java 8), which could only declare abstract methods. Abstract classes cannot be instantiated directly, but they provide a partial implementation that concrete subclasses complete.

Exam trap

The trap here is that candidates often confuse the capabilities of abstract classes and interfaces, mistakenly thinking abstract classes cannot have concrete methods or that interfaces can have constructors, leading them to select options like A, B, or D.

How to eliminate wrong answers

Option A is wrong because it claims both B and D are true, but B and D are false. Option B is wrong because interfaces cannot have instance variables; they can only have constants (public static final fields). Option C is wrong because abstract classes cannot be instantiated directly; they must be subclassed and the subclass instantiated.

Option D is wrong because interfaces cannot have constructors; they are not instantiable and constructors are only for classes.

284
MCQhard

Given boolean a = true, b = false, c = true; What is the result of (a || b) && (b || c)?

A.Short-circuit evaluation prevents evaluation
B.true
C.Compilation error
D.false
AnswerB

Both sides evaluate to true.

Why this answer

a||b = true, b||c = true, true && true = true.

285
MCQhard

A method is declared as: public static int[] generateSequence(int n) { ... }. Which return statement is valid inside this method?

A.return result; where result is an int variable
B.return new int[n];
C.return 0;
D.return new int[0];
AnswerB, D

Creates an integer array of length `n` and returns it. This is both syntactically and semantically valid for the method `generateSequence`.

Why this answer

The method's return type is `int[]`, meaning it must return a reference to an integer array. Option B, `return new int[n];`, creates an array of length `n` and returns it, which is valid. Option D, `return new int[0];`, also creates an integer array (of length 0) and returns it, which is syntactically valid as well.

Options A and C are invalid because they return primitive `int` values, not `int[]` references. Therefore, both B and D are correct return statements.

Exam trap

Oracle often tests the distinction between primitive types and array types, trapping candidates who think returning a single `int` or a literal `0` is acceptable because they overlook the `[]` in the return type.

How to eliminate wrong answers

Option A is wrong because `result` is declared as an `int` variable, but the method return type is `int[]`, so returning a single `int` causes a type mismatch compilation error. Option C is wrong because `0` is a primitive `int`, not an array, and cannot be implicitly converted to `int[]`. Option D is wrong because `new int[0]` returns an `int[]` of length 0, which is syntactically valid but not the only correct answer; however, the question asks for a valid return statement, and `new int[0]` is indeed valid—but the trap is that candidates might think it's invalid because it's empty, while in Java an empty array is a valid `int[]` object.

286
MCQeasy

A package named com.example.util is declared in a file. Where should the file be placed in the directory structure?

A.com.example.util/
B.util/
C.com/example/util/
D.com/example/util.java
AnswerC

Directory path matching package hierarchy.

Why this answer

Java requires that the directory structure of a package matches the package declaration. A package named `com.example.util` must be stored in a directory hierarchy `com/example/util/` so that the Java compiler and runtime can locate the class files based on the fully qualified name. This ensures that the file is accessible via the classpath or module path.

Exam trap

The trap here is that candidates often confuse the package name with a file name or think the directory structure can be flattened, leading them to pick options that treat the package as a single folder or as a file extension.

How to eliminate wrong answers

Option A is wrong because `com.example.util/` is not a valid directory path; it treats the entire package name as a single directory, which violates Java's requirement that each dot in the package name corresponds to a subdirectory. Option B is wrong because `util/` would only match the last component of the package name, ignoring the `com.example` prefix, causing the compiler to fail to resolve the package. Option D is wrong because `com/example/util.java` is a file path, not a directory; the file must be placed inside the `util` directory, not named as a file itself.

287
MCQmedium

A junior developer wrote a while loop that never terminates. What is the most likely cause?

A.The loop condition is always true
B.The loop variable is incremented correctly
C.The loop uses a for structure
D.The loop body contains a break statement
AnswerA

If the condition never evaluates to false, the loop continues indefinitely.

Why this answer

A while loop terminates only when its boolean condition evaluates to false. If the condition is always true, the loop will run indefinitely, causing an infinite loop. In Java, this typically happens when the loop variable is not updated or the condition logic is flawed.

Exam trap

The trap here is that candidates may think a break statement always causes termination, but in this context, a break would actually prevent an infinite loop, not cause it.

How to eliminate wrong answers

Option B is wrong because correctly incrementing the loop variable would help the loop terminate, not cause it to never terminate. Option C is wrong because the loop structure (while vs for) does not inherently cause infinite loops; a for loop can also be infinite if its condition is always true. Option D is wrong because a break statement inside the loop body would provide an exit mechanism, preventing an infinite loop.

288
Multi-Selectmedium

Which THREE are valid components of the Java Virtual Machine (JVM)?

Select 3 answers
A.Java source code (.java files)
B.Java compiler (javac)
C.Heap memory area
D.Execution engine
E.Class loader subsystem
AnswersC, D, E

Heap is where all objects are allocated.

Why this answer

The correct components of the JVM listed here are: Heap memory area (C), Execution engine (D), and Class loader subsystem (E). The Java compiler (B) is part of the JDK, not the JVM. Java source code (A) is input to the compiler, not a JVM component.

The class loader loads bytecode into the JVM, the heap stores objects, and the execution engine executes bytecode.

289
Multi-Selectmedium

Which three of the following code snippets produce the output '5'?

Select 3 answers
A.System.out.println(2 + "3");
B.System.out.println(2 + 3);
C.System.out.println("5");
D.System.out.println("2" + 3);
E.System.out.println(5);
AnswersB, C, E

Prints 5 as int.

Why this answer

The expression `2 + 3` performs integer addition, resulting in `5`, which is then passed to `System.out.println` and printed as the string representation of the integer `5`. Option C is correct because the string literal `"5"` is printed directly. Option E is correct because the integer literal `5` is printed as its string representation.

Exam trap

The trap here is that candidates often forget that `+` with a `String` operand triggers concatenation, not arithmetic, leading them to incorrectly select options A or D as producing `5`.

290
MCQmedium

A company is developing a security-sensitive banking application. Which Java feature most directly enhances security?

A.Automatic garbage collection
B.Platform independence via bytecode
C.Built-in multithreading support
D.Bytecode verification
AnswerD

Bytecode verification checks code for security violations before execution.

Why this answer

(Bytecode verification) is correct because it performs a series of checks on the bytecode, such as ensuring type safety, no stack overflows, and no illegal jumps, which prevents malicious code from compromising the JVM. Option A (garbage collection) manages memory automatically but does not directly enforce security. Option B (platform independence via bytecode) allows Java to run on any platform but does not inherently provide security.

Option C (built-in multithreading support) facilitates concurrent execution but is not a security feature.

291
MCQhard

A developer needs to iterate over a 2D array row by row and exit early if a specific value is found in any cell. Which nested loop structure with control statements is most efficient?

A.Outer for with inner for, use return
B.Outer while with inner for, use continue
C.Outer do-while with inner while, use break without label
D.Outer for with inner for, use labeled break
AnswerD

Labeled break can exit the outer loop directly, making it efficient.

Why this answer

A labeled break allows the developer to exit both the inner and outer loops immediately when the target value is found. This is the most efficient approach for a row-by-row search in a 2D array, as it avoids unnecessary iterations after the value is located. Using a labeled break provides precise control over nested loop termination without requiring additional flags or method extraction.

Exam trap

Oracle often tests the distinction between break (unlabeled) and labeled break in nested loops, trapping candidates who assume break exits all loops when it only exits the innermost one.

How to eliminate wrong answers

Option A is wrong because using return inside a nested loop will exit the entire method, which is not appropriate if the method needs to continue executing after the loop (e.g., to process other logic). Option B is wrong because continue only skips the current iteration of the innermost loop, not the entire nested structure, so it cannot exit early when the value is found. Option C is wrong because break without a label only exits the innermost loop (the inner while), leaving the outer do-while to continue iterating, which fails to achieve early exit from both loops.

292
MCQeasy

Which primitive type can store a single character?

A.String
B.char
C.int
D.Character
AnswerB

Primitive type for characters.

Why this answer

char is the primitive for a single 16-bit Unicode character.

293
MCQhard

A parent class has a static method display() and an instance method show(). A child class attempts to override both. What is the outcome?

A.Both will be overridden
B.Only show() can be overridden
C.Only display() can be overridden
D.Neither can be overridden
AnswerB

Instance methods are overridden; static methods are hidden.

Why this answer

In Java, static methods belong to the class, not instances, so they cannot be overridden—they can only be hidden. Instance methods, however, can be overridden to provide polymorphic behavior. Therefore, only the instance method show() can be overridden; display() is hidden, not overridden.

Exam trap

The trap here is that candidates confuse method hiding with overriding, assuming static methods follow the same polymorphic rules as instance methods, leading them to incorrectly select option A or C.

How to eliminate wrong answers

Option A is wrong because static methods cannot be overridden; they are hidden, and both cannot be overridden. Option C is wrong because display() is static and cannot be overridden; only instance methods can be overridden. Option D is wrong because show() is an instance method and can be overridden, so it is not true that neither can be overridden.

294
Multi-Selectmedium

Which THREE are true about Java constructors?

Select 3 answers
A.A constructor cannot have a return type
B.A constructor can be marked final
C.A constructor can be abstract
D.A constructor can be overloaded
E.A constructor can be private
AnswersA, D, E

A constructor in Java is a special method that initialises an object, and the language specification explicitly prohibits any return type declaration, including `void`, because the constructor’s sole purpose is to allocate and initialise the instance, not to return a value. This satisfies the stem’s constraint that a constructor cannot have a return type, distinguishing it from regular methods which must declare one.

Why this answer

Constructors in Java do not have a return type, not even void. If you attempt to add a return type to a constructor, the compiler treats it as a regular method, not a constructor, which can lead to unexpected behavior. This is a fundamental rule of Java syntax.

Exam trap

The trap here is that candidates may confuse constructors with regular methods and think that final or abstract modifiers apply, but Java explicitly forbids these on constructors because they are not inherited or overridden.

295
MCQhard

Given the code: String s1 = "Java"; String s2 = new String("Java"); if (s1 == s2) { System.out.print("Equal"); } else { System.out.print("Not Equal"); } What is the output?

A.Runtime error
B.Compilation error
C.Equal
D.Not Equal
AnswerD

s1 is interned, s2 is a new object.

Why this answer

The == operator compares object references, not the actual string content. s1 is a string literal stored in the string pool, while s2 is a new String object created on the heap, so they refer to different memory locations, making the comparison false and printing 'Not Equal'.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because the code compiles and runs without any runtime error; the comparison simply evaluates to false. Option B is wrong because the code is syntactically valid and compiles successfully; there is no compilation error. Option C is wrong because s1 and s2 are not the same object reference; s1 points to the string pool literal, and s2 points to a distinct heap object, so they are not equal with ==.

296
MCQeasy

Which loop construct guarantees that the loop body executes at least once?

A.Enhanced for loop
B.while loop
C.for loop
D.do-while loop
AnswerD

The do-while executes the body before checking the condition.

Why this answer

The do-while loop is the only Java loop construct that guarantees the loop body executes at least once because the condition is evaluated after the body executes. In contrast, the while and for loops evaluate the condition before the first iteration, so the body may never execute if the condition is initially false. The enhanced for loop also checks for elements before entering the body.

Exam trap

Oracle often tests the subtle distinction between pre-test and post-test loops, and the trap here is that candidates confuse the do-while loop with the while loop, assuming both can skip execution, when in fact only the do-while guarantees at least one iteration.

How to eliminate wrong answers

Option A is wrong because the enhanced for loop (for-each) iterates over an array or Iterable and only executes the body if there is at least one element to process; if the collection is empty, the body never runs. Option B is wrong because the while loop evaluates its boolean condition before each iteration, including the first, so if the condition is false initially, the body is skipped entirely. Option C is wrong because the for loop (traditional) evaluates the condition before each iteration; if the condition is false at the start, the body never executes.

297
MCQmedium

A developer is working on a Java application that processes sensor data. The code uses a class 'SensorDataProcessor' which directly instantiates specific sensor classes like 'TemperatureSensor' and 'PressureSensor' inside its methods. The team wants to make the system extensible to support new sensor types without modifying the processor class. Which design change best achieves this?

A.Make SensorDataProcessor abstract and subclass it for each sensor
B.Use a static factory method in SensorDataProcessor to create sensors
C.Create a separate configuration file listing sensors and use reflection to instantiate them
D.Define a Sensor interface and use dependency injection to pass sensor objects to the processor
AnswerD

Dependency injection allows the processor to work with any Sensor implementation.

Why this answer

Defining a Sensor interface and using dependency injection (e.g., passing sensor objects via constructor or setter) decouples the processor from concrete sensor classes, allowing new sensor types to be added without modifying the processor. Option A is wrong because creating subclasses for each sensor would still require modifying the processor if new sensor types are added. Option B is wrong because a static factory method still couples the processor to the factory and requires changes when new sensors are added.

Option C is wrong because reflection is complex, error-prone, and not the best practice for this scenario.

298
Matchingmedium

Match each Java operator to its description.

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

Concepts
Matches

Increment by 1

Modulo (remainder) operator

Logical AND (short-circuit)

Checks if an object is of a certain type

Ternary conditional operator

Why these pairings

The correct matches are: == for equality, && for logical AND. Common confusions include mixing assignment (=) with comparison (==) and misunderstanding the ternary operator vs. logical operators.

299
MCQhard

Given: int[] arr = {10,20,30}; System.out.println(arr[3]); What is the result?

A.ArrayIndexOutOfBoundsException
B.30
C.0
D.NullPointerException
AnswerA

Correct: runtime exception due to invalid index.

Why this answer

Arrays in Java are zero-indexed, so a valid index for an array of length 3 is 0, 1, or 2. Accessing index 3 is out of bounds, causing an ArrayIndexOutOfBoundsException at runtime.

Exam trap

The trap here is that candidates may forget arrays are zero-indexed and mistakenly think the last element is at index 3, or assume Java returns a default value like 0 for invalid indices.

How to eliminate wrong answers

Option B is wrong because arr[3] does not return 30; 30 is at index 2, and accessing index 3 is invalid. Option C is wrong because Java does not automatically return a default value for out-of-bounds array access; it throws an exception instead. Option D is wrong because the array reference arr is not null; the exception is due to an invalid index, not a null reference.

300
Multi-Selectmedium

Which TWO of the following are best practices for exception handling in Java?

Select 2 answers
A.Catch specific exceptions rather than generic Exception or Throwable.
B.Always catch Exception in every method to prevent crashes.
C.Use try-with-resources for classes that implement AutoCloseable.
D.Throw an exception from a finally block to ensure cleanup failures are reported.
E.Ignore exceptions by leaving the catch block empty.
AnswersA, C

Specific exceptions allow precise handling and avoid catching unexpected errors.

Why this answer

Catching specific exceptions (e.g., IOException, SQLException) allows you to handle each error condition appropriately, rather than using a broad catch-all like Exception or Throwable which can mask unexpected bugs and make code harder to maintain. This follows the principle of precise exception handling, ensuring that only recoverable or expected exceptions are caught, while letting runtime exceptions propagate.

Exam trap

Oracle often tests the distinction between catching specific exceptions versus generic ones, and the trap here is that candidates may think catching Exception is a safe default, not realizing it hides important error details and violates best practices.

Page 3

Page 4 of 7

Page 5

All pages