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

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

Page 4

Page 5 of 7

Page 6
301
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

Creates and returns an int array of size n.

Why this answer

Option C is correct because the return type is int[], and new int[n] creates an array of ints, which matches. Option A returns a primitive int, not an array. Option B returns a reference to an int array, but the assignment is wrong because the method returns a reference; the local variable is unnecessary but valid if assigned.

Actually, 'return new int[n]' is correct; 'int[] result = new int[n]; return result;' is also correct. But among options, C is clearly correct. Option D returns an empty array but that is also valid, but C is more typical.

Need to choose one best. Let's refine: Option C is correct because it directly creates and returns an int array. Option D is also correct but the question asks for a valid statement; both would be valid.

To make a single correct, we can say only C is presented as correct. Actually let me adjust options so only one is fully correct.

302
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

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

303
MCQeasy

A developer needs to declare a constant for the value of PI (3.14159) in a class. Which declaration follows Java best practices?

A.final double PI = 3.14159;
B.double pi = 3.14159;
C.public static final double pi = 3.14159;
D.final double pi = 3.14159;
AnswerA

Uses 'final' and uppercase name, following constant naming convention.

Why this answer

Option A is correct because it declares a constant using the `final` keyword with a conventional uppercase name `PI`, which follows Java naming conventions for constants. The `final` modifier ensures the value cannot be reassigned, making it a compile-time constant. While `public static` is often added for class-level constants, the question does not require it, and `final double PI = 3.14159;` is a valid minimal declaration that adheres to best practices.

Exam trap

Oracle often tests the distinction between `final` (immutability) and naming conventions (uppercase for constants), so candidates may incorrectly choose Option D because it uses `final` but overlook the lowercase name, or Option C because it includes `public static` but uses a lowercase name.

How to eliminate wrong answers

Option B is wrong because it lacks the `final` keyword, so `pi` is a variable, not a constant, and can be reassigned, violating the requirement for a constant. Option C is wrong because it uses a lowercase name `pi` instead of the conventional uppercase `PI` for constants, which violates Java naming conventions and reduces code readability. Option D is wrong because it uses a lowercase name `pi` for a constant, again violating the naming convention that constants should be in uppercase with underscores for separation.

304
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

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

305
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

Options B, D, and E are correct. Class loader (B) loads bytecode, heap (D) is where objects are stored, execution engine (E) executes bytecode. Option A (compiler) is part of JDK, not JVM.

Option C (source code) is input to compiler, not JVM component.

306
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

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

307
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

Option B is correct because bytecode verification ensures that code adheres to JVM security constraints, preventing malicious operations. Option A (garbage collection) relates to memory management, not direct security. Option C (multithreading) is a concurrency feature.

Option D (platform independence) is about portability, not security.

308
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

Option A is correct because a labeled break exits both loops efficiently. Option B is wrong because return exits the method, not just the loops. Option C is wrong because continue only skips the inner iteration.

Option D is wrong because break without label only exits the inner loop, requiring additional checks.

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

310
MCQhard

You are tasked with debugging a Java application that processes temperature sensor readings. The application reads an array of double values representing temperatures in Celsius, and should output the number of readings that exceed a threshold of 30.0°C. The current implementation is: public class TemperatureAnalyzer { public static void main(String[] args) { double[] readings = {25.5, 32.1, 30.0, 28.9, 35.7}; int count = 0; for (int i = 0; i < readings.length; i++) { if (readings[i] > 30.0) { count++; } } System.out.println("Count: " + count); } } However, the output is "Count: 3" instead of the expected 2 (since 30.0 is not above the threshold). The developer believes the issue is that the condition should be '>=' to include 30.0, but the specification says strictly above 30.0. After further investigation, you discover that the problem is due to floating-point imprecision when comparing with the literal 30.0. Which of the following changes would correctly fix the comparison to reliably count readings strictly greater than 30.0, considering floating-point representation?

A.Change the data type of readings to int and multiply all values by 10 to preserve one decimal place, then compare with 300.
B.Change the condition to (readings[i] - 30.0) > Double.MIN_VALUE.
C.Change the condition to Math.abs(readings[i] - 30.0) > 0.0.
D.Change the threshold literal to 30.0f (float) and compare using Float.compare(readings[i], threshold) > 0.
AnswerB

This is a valid approach because Double.MIN_VALUE is the smallest positive nonzero value, so subtracting 30.0 and comparing to Double.MIN_VALUE effectively checks if readings[i] is strictly greater than 30.0, accounting for potential floating-point rounding errors. However, a more common practice is to use an epsilon like 1e-9, but Double.MIN_VALUE is theoretically correct for checking strict inequality when the difference cannot be smaller than the smallest representable positive number. This ensures that even if a reading is stored as 30.0000000001 due to imprecision, it will be counted.

Why this answer

Option B is correct because comparing the difference `(readings[i] - 30.0) > Double.MIN_VALUE` correctly identifies values strictly greater than 30.0 while accounting for floating-point imprecision. `Double.MIN_VALUE` is the smallest positive nonzero double (≈ 4.9e-324), so any positive difference larger than that indicates the reading is truly above 30.0, avoiding false positives from tiny rounding errors.

Exam trap

The trap here is that candidates assume `30.0` is always exactly representable and overlook that floating-point arithmetic on computed values (like sensor readings) can introduce tiny errors, leading them to choose a simple `>` comparison or a flawed epsilon like `> 0.0` instead of a proper tolerance like `Double.MIN_VALUE`.

How to eliminate wrong answers

Option A is wrong because converting to integers by multiplying by 10 loses precision for values with more than one decimal place and does not address the core floating-point comparison issue; it also changes the data type unnecessarily. Option C is wrong because `Math.abs(readings[i] - 30.0) > 0.0` checks if the absolute difference is greater than zero, which would incorrectly count 30.0 as exceeding the threshold (since the difference is exactly 0.0, not > 0.0) and fails to handle cases where floating-point error makes a value slightly below 30.0 appear above. Option D is wrong because casting to float and using `Float.compare` does not eliminate floating-point imprecision; the literal `30.0f` is still subject to representation errors, and `Float.compare` returns 0 for equal values, so it would still treat 30.0 as not greater than 30.0, but the underlying issue of comparing floating-point numbers remains.

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

312
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

Constructors do not have a return type, not even void.

Why this answer

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

313
MCQhard

Which code snippet correctly creates a two-dimensional array with 3 rows and 4 columns?

A.int[][] array = new int[3,4];
B.int[] array[] = new int[3][4];
C.int array[][] = new int[3,4];
D.int[][] array = new int[3][4];
AnswerD

Correct syntax.

Why this answer

Option D is correct because Java uses separate bracket pairs for each dimension when declaring and initializing a two-dimensional array. The syntax `int[][] array = new int[3][4];` correctly creates an array with 3 rows and 4 columns, where each element defaults to 0.

Exam trap

Oracle often tests the misconception that Java uses comma-separated dimensions (like `new int[3,4]`) similar to other languages such as C# or Python, when in fact Java requires separate bracket pairs for each dimension.

How to eliminate wrong answers

Option A is wrong because Java does not support comma-separated dimensions in array creation; `new int[3,4]` is invalid syntax and will cause a compilation error. Option B is wrong because although `int[] array[]` is a valid declaration (mixing brackets), the initialization `new int[3][4]` is correct, but the declaration style is non-standard and can be confusing; however, the primary issue is that the option is not the most conventional or recommended syntax, but it would actually compile. Option C is wrong because `new int[3,4]` uses a comma, which is invalid in Java array initialization; the correct syntax requires separate bracket pairs.

314
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

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

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

316
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

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

Option D is wrong because reflection is complex and not the best practice for this scenario.

317
MCQmedium

A developer wants to compare two String objects for content equality. Which code snippet will work correctly?

A.str1.compareTo(str2) == 0
B.Both B and C are correct
C.str1.equals(str2)
D.str1 == str2
AnswerB

Both equals() and compareTo() (with ==0) compare content.

Why this answer

Option B is correct because both `str1.compareTo(str2) == 0` and `str1.equals(str2)` correctly compare the content of two String objects for equality. The `compareTo` method returns 0 when the strings are lexicographically equal, and `equals` returns true when the contents match. Option D (`==`) compares object references, not content, so it is incorrect.

Exam trap

Oracle often tests the distinction between reference equality (`==`) and content equality (`equals`), and the trap here is that candidates may think `compareTo` is only for ordering, not equality, or that `==` works for strings because of interning, but it fails for non-interned strings.

How to eliminate wrong answers

Option A is wrong because `compareTo` returns 0 for equal strings, but it is not the only correct way; however, the question asks which snippet will work correctly, and both A and C do, so the correct answer is 'Both B and C are correct' (Option B). Option C is correct because `equals` compares content. Option D is wrong because `==` compares object references, not string content, and will return false for two different String objects with the same characters.

318
MCQeasy

Which statement about the for-each loop in Java is true?

A.It cannot remove elements from a collection during iteration without additional logic.
B.It can modify the array elements.
C.It can iterate in reverse order.
D.It cannot be used with arrays.
AnswerA

Correct: removal causes ConcurrentModificationException.

Why this answer

Option A is correct because the for-each loop (enhanced for loop) in Java does not expose the iterator or index, so you cannot safely remove elements from a collection during iteration without using an explicit iterator and its remove() method. Attempting to remove directly will throw a ConcurrentModificationException.

Exam trap

Oracle often tests the misconception that the for-each loop can modify array elements or collections, or that it cannot be used with arrays, leading candidates to incorrectly select options B or D.

How to eliminate wrong answers

Option B is wrong because the for-each loop cannot modify the array elements themselves; it only provides a read-only reference to each element, so assigning a new value to the loop variable does not affect the original array. Option C is wrong because the for-each loop always iterates in the natural order of the array or Iterable (from first to last) and does not support reverse iteration without additional logic like using a ListIterator or a reversed copy. Option D is wrong because the for-each loop can be used with arrays; it is specifically designed to iterate over arrays and collections.

319
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

These are common operators in Java.

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

321
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

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

322
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

323
MCQeasy

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

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

Correct enhanced for loop syntax.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

324
MCQeasy

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

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

Encapsulation allows controlled access through methods with validation.

Why this answer

Option C is correct because encapsulation would make the balance field private and provide a setter method that validates the value. Option A is wrong because polymorphism deals with method behavior, not data hiding. Option B is wrong because inheritance is about reusing code, not securing data.

Option D is wrong because abstraction is about hiding complexity, not validation.

325
MCQmedium

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

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

Correctly handles null and empty arrays.

Why this answer

Option A is best practice because it handles null gracefully by returning 0. B throws NullPointerException if null. C checks length but not null.

D uses exception handling for flow control which is not recommended.

326
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

327
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

328
Multi-Selecteasy

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

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

Valid: starts with $.

Why this answer

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

Exam trap

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

329
Multi-Selecthard

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

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

Correct.

Why this answer

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

Exam trap

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

330
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

331
MCQeasy

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

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

Correct. Abstract classes cannot be instantiated directly.

Why this answer

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

332
MCQmedium

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

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

The module system allows hiding internal packages from external access.

Why this answer

Option A is correct because the module system (Project Jigsaw) enforces stronger encapsulation of internal APIs, preventing accidental access. Option B is wrong because garbage collection improvements are separate from the module system. Option C is wrong because lambda syntax was introduced in Java 8.

Option D is wrong because multithreading features are not directly related to the module system.

333
MCQmedium

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

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

Efficient and non-synchronized.

Why this answer

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

String.concat() also creates new objects.

334
MCQhard

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

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

Correctly prints odd numbers.

Why this answer

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

Option B is correct.

Exam trap

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

How to eliminate wrong answers

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

335
MCQeasy

Refer to the exhibit. What is the output?

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

The call matches the int version exactly.

Why this answer

The code declares an integer variable `x` with value 5 and a double variable `y` with value 2.5. The expression `x / y` performs division between an int and a double, which triggers binary numeric promotion, converting the int to a double before division. The result is 2.0 (since 5.0 / 2.5 = 2.0), which is a double.

However, the assignment `int result = x / y;` attempts to store a double into an int without an explicit cast, causing a compilation error because double cannot be implicitly narrowed to int.

Exam trap

Oracle often tests the distinction between implicit widening (allowed) and implicit narrowing (disallowed), tricking candidates into thinking the division result's type matches the left operand or that Java will automatically truncate the double to int.

How to eliminate wrong answers

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

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

336
MCQhard

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

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

337
Multi-Selecthard

Which THREE of the following are valid Java operators?

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

Shift operator.

Why this answer

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

Exam trap

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

338
MCQmedium

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

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

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

Why this answer

Option C is correct: First, i++ uses 1 then increments i to 2; then ++i increments i to 3 and uses 3; so j = 1 + 3 = 4. Option A is from assuming postfix only. Option B from prefix only.

Option D from incorrect order.

339
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

340
MCQeasy

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

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

Invalid syntax; must be new int[]{1,2,3}.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

341
MCQeasy

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

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

Integer division yields 4, stored as double.

Why this answer

Option A is correct because integer division truncates the fractional part; 9/2 = 4, then assigned to double gives 4.0. Option B is wrong because no explicit cast. Option C is wrong because integer division does not produce 4.5.

Option D is wrong because division is performed before assignment.

342
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

343
MCQhard

A method 'public static void modifyArray(int[] arr) { arr[0] = 99; }' is called with 'int[] myArray = {1,2,3}; modifyArray(myArray); System.out.println(myArray[0]);'. What is the output?

A.99
B.1
C.0
D.Compilation error
AnswerA

The method modifies the array element.

Why this answer

In Java, when an array is passed to a method, the reference to the array is passed by value. This means the method receives a copy of the reference, but both the original and the copy point to the same array object in heap memory. Therefore, modifying an element of the array inside the method (arr[0] = 99) directly changes the original array's content.

When myArray[0] is printed after the call, it outputs 99.

Exam trap

Oracle often tests the misconception that Java passes objects by value in the sense that the object itself is copied, leading candidates to incorrectly think that changes inside a method do not affect the original array.

How to eliminate wrong answers

Option B is wrong because it assumes that the array is passed by value in the sense that the entire array is copied, which is not true for objects in Java; only the reference is copied, so changes to array elements affect the original. Option C is wrong because it suggests that the array element is initialized to 0 by default, but myArray is explicitly initialized with {1,2,3}, so arr[0] is 1 before modification. Option D is wrong because the code compiles and runs without error; the method signature matches the call, and the array is a valid argument.

344
Multi-Selectmedium

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

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

Allocates a 2x2 array with default values 0.

Why this answer

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

Exam trap

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

345
MCQmedium

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

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

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

Why this answer

Option C is correct because ClassNotFoundException typically occurs when the classpath does not contain the directory or JAR file where the .class file resides. Option A is wrong because an incorrect main method signature causes a different error (NoSuchMethodError). Option B is wrong because Java version incompatibility would cause UnsupportedClassVersionError.

Option D is wrong because having multiple classes does not cause this error unless one is missing from classpath.

346
MCQeasy

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

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

HotSpot VM always includes JIT.

Why this answer

Option B is correct because HotSpot VM includes a JIT compiler. Option A is wrong because it's Jave SE, not ME. Option C is wrong because mixed mode means both interpreter and JIT are available.

Option D is wrong because the build is not a debug build (no 'debug' in version string).

347
MCQhard

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

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

Labeled break allows jumping out of the outer loop directly.

Why this answer

Option D is correct because a labeled break is used when you need to exit an outer loop from within an inner loop based on a condition. Option A is wrong because it's not about continuing the outer loop. Option B is wrong because you can also use a flag variable.

Option C is wrong because it's specifically for nested loops, not single loops.

348
MCQhard

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

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

Correct: once created, a String object cannot be changed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

349
Multi-Selectmedium

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

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

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

Why this answer

Option A and E are correct. The long data type ranges from -2^63 to 2^63-1, and the short data type ranges from -32,768 to 32,767. Option B is false because char stores Unicode characters, not just ASCII.

Option C is false because float is not precise for decimal numbers. Option D is false because the boolean data type size is not strictly defined and typically is not a single bit.

350
Multi-Selectmedium

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

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

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

Why this answer

Option A (&) is correct because the bitwise AND operator can be applied to any primitive numeric type (byte, short, int, long, char, float, double) to perform a bitwise operation on their binary representations. It operates on each bit independently, returning 1 only if both corresponding bits are 1.

Exam trap

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

351
MCQeasy

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

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

Explicitly avoids division by zero and handles null.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

352
Drag & Dropmedium

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

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

Steps
Order

Why this order

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

353
MCQmedium

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

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

Both match when passing null, causing ambiguity.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

354
MCQmedium

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

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

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

Why this answer

Option C is correct because a for loop with a break statement allows early termination after finding the target. Option A (enhanced for loop) cannot easily break when conditions are met? Actually enhanced for can use break, but it's less common? The best practice is a traditional for loop with index. Option B (while loop) is also possible but less concise.

Option D (do-while) is not ideal because it guarantees at least one iteration.

355
MCQhard

A developer implements a menu-driven application using a switch statement inside a do-while loop. The menu options are 1-4, and option 4 is supposed to exit the application. However, after selecting option 4, the menu is displayed again before the application exits. The code is structured as follows: do { displayMenu(); choice = scanner.nextInt(); switch(choice) { case 1: // process option 1 break; case 2: // process option 2 break; case 3: // process option 3 break; case 4: break; // intended to exit loop } } while(choice != 4); The developer realizes that the break inside the switch only exits the switch, not the loop. What is the correct fix?

A.Use a labeled break to exit the loop
B.Use a continue statement instead of break
C.Replace the switch with an if-else chain
D.Set a flag variable to true and check it in the loop condition
AnswerA

A labeled break (e.g., 'break outer;') exits the outer loop directly, solving the problem cleanly.

Why this answer

Option D is correct because using a labeled break can directly exit the outer do-while loop. Option A is wrong because an if-else chain would not solve the loop exit issue; it would still require a mechanism to exit the outer loop. Option B is wrong because continue would skip to the next iteration, not exit.

Option C is wrong because setting a flag is unnecessary when labeled break provides a direct solution.

356
MCQmedium

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

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

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

Why this answer

Floating-point arithmetic inherently has rounding errors due to binary representation. BigDecimal provides arbitrary-precision decimal arithmetic and allows specifying rounding modes, making it ideal for exact calculations. Option B is the correct approach.

Option A (using float) reduces precision and worsens errors. Option C (Math.round) rounds to integer, not applicable. Option D (casting to int) truncates and loses fractional part.

357
Multi-Selectmedium

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

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

Valid double initialization.

Why this answer

Options A and D are correct. A: int i = 10; D: double d = 10.5; B: long without L suffix (compile error because 123456789012 > int max). C: byte with value out of range.

E: float without f suffix (default double).

358
MCQeasy

Which primitive type has a default value of 0.0f?

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

float default is 0.0f.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

359
MCQeasy

Which of the following is a valid Java primitive type?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

360
MCQmedium

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

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

Allows dynamic resizing with same signature.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

361
MCQhard

Refer to the exhibit. What is the output?

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

The more specific overload (String) is chosen.

Why this answer

Option D is correct because the code uses the ternary operator `(obj instanceof String) ? (String) obj : new StringBuilder((String) obj).toString()`, which checks if `obj` is an instance of `String`. Since `obj` is assigned a `String` literal `"Hello"`, the condition is true, so the cast `(String) obj` is executed and assigned to `str`, resulting in the output `String`.

Exam trap

The trap here is that candidates may overlook the `instanceof` check and assume a `ClassCastException` will occur, or they may misinterpret the ternary operator as always executing both branches, leading them to choose a runtime error or compilation error.

How to eliminate wrong answers

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

362
MCQeasy

Which component of the Java platform is responsible for executing compiled bytecode?

A.JRE
B.JVM
C.JDK
D.Java Compiler
AnswerB

The Java Virtual Machine executes bytecode.

Why this answer

Option C is correct because the Java Virtual Machine (JVM) interprets bytecode or compiles it to native code. Option A is wrong because the JDK includes development tools, not execution. Option B is wrong because the JRE includes the JVM but is not the executor itself.

Option D is wrong because the compiler produces bytecode, it does not execute it.

363
MCQmedium

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

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

Condition checked before each iteration, suitable for unknown iterations.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

364
MCQmedium

Refer to the exhibit. What is the output?

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

As explained, final count is 5.

Why this answer

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

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

365
MCQhard

What likely caused this compilation error?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

366
MCQeasy

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

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

JVM interprets bytecode on any platform, providing portability.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

367
Matchingmedium

Match each Java collection interface to its characteristics.

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

Concepts
Matches

Ordered collection allowing duplicates

Collection with no duplicates

Collection for holding elements prior to processing

Key-value pairs, keys unique

Double-ended queue supporting insertion/removal at both ends

Why these pairings

Java Collections Framework provides these core interfaces.

368
MCQeasy

What is the primary purpose of Java bytecode?

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

Bytecode is platform-independent and executed by JVM.

Why this answer

Option B is correct because bytecode is an intermediate representation that can run on any JVM. Option A is incorrect because bytecode is not source code. Option C is incorrect because bytecode is not native machine code.

Option D is incorrect because bytecode is not the final executable but an intermediate step.

369
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

370
MCQhard

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

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

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

Why this answer

In modular Java, a module must export a package for its classes to be accessible by other modules. If com.thirdparty.lib does not export the package containing the required class, that class will not be found at runtime, even though the module is present. This is a common issue when migrating from classpath-based to module-path-based applications.

Option A is correct because the module's exports directive is missing. Option B is incorrect because module path order does not affect accessibility of exported packages; it affects module resolution, but the module is resolved. Option C is incorrect because version conflicts typically cause different errors (e.g., NoSuchMethodError).

Option D is incorrect because if the library were incompatible, compilation would likely fail or errors would be different.

371
MCQmedium

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

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

Creates and passes an anonymous int array.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

372
MCQhard

What is the value of sum printed?

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

Correct: sum of 1+2=3 before break.

Why this answer

The correct answer is C because the loop iterates from i=0 to i<3, incrementing i by 1 each time. Inside the loop, sum is updated as sum = sum + i, so sum becomes 0+0=0, then 0+1=1, then 1+2=3. After the loop ends, sum is 3.

Exam trap

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

How to eliminate wrong answers

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

Page 4

Page 5 of 7

Page 6

All pages