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

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

Page 1

Page 2 of 7

Page 3
76
Multi-Selectmedium

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

Select 2 answers
A.byte
B.char
C.String
D.Integer
E.Boolean
AnswersA, B

Correct: byte is a primitive type.

Why this answer

A is correct because `byte` is a primitive data type in Java that stores 8-bit signed integers, ranging from -128 to 127. It is one of the eight primitive types defined in the Java language specification, not an object or reference type.

Exam trap

Oracle often tests the distinction between primitives (lowercase names like `boolean`) and their wrapper classes (capitalized names like `Boolean`), causing candidates to mistakenly select the wrapper class as a primitive.

77
MCQeasy

What is the output when the main method is executed?

A.15.0
B.5.0
C.10.0
D.Compilation error: ambiguous method call
AnswerA

The int addition yields 15, promoted to double.

Why this answer

The correct answer is A (15.0) because the method call `sum(5, 10)` matches the overloaded method `sum(double a, double b)` after the integer literals are implicitly widened to `double`. The method returns `a + b`, which is `5.0 + 10.0 = 15.0`, and since the return type is `double`, the output is `15.0`.

Exam trap

Oracle often tests the concept of implicit widening conversion in method overloading, where candidates mistakenly think integer arguments must match an `int` parameter exactly or that the call would be ambiguous, when in fact the compiler silently widens to the only compatible `double` overload.

How to eliminate wrong answers

Option B (5.0) is wrong because it incorrectly assumes only the first argument is used or that the method subtracts rather than adds. Option C (10.0) is wrong because it mistakenly uses only the second argument or thinks the method returns the second parameter. Option D (compilation error: ambiguous method call) is wrong because there is no ambiguity: the only overloaded method that matches the two `int` arguments after widening is `sum(double, double)`, as no other `sum` method exists with two parameters.

78
MCQeasy

Given the code snippet: int x = 5; int y = 2; double result = x / y; What is the value of result?

A.2.0
B.Compilation fails
C.2.5
D.2
AnswerA

Correct because integer division yields 2, then cast to double.

Why this answer

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

Exam trap

Oracle often tests the distinction between integer and floating-point division, trapping candidates who forget that dividing two ints in Java always produces an int result, not a double, even when assigned to a double variable.

How to eliminate wrong answers

Option B is wrong because the code compiles successfully; there is no syntax error or type mismatch that would cause compilation to fail. Option C is wrong because it assumes floating-point division occurs, but since both x and y are ints, integer division truncates the result to 2, not 2.5. Option D is wrong because although the integer division yields 2, the assignment to a double variable causes implicit widening conversion to 2.0, not the int value 2.

79
MCQeasy

What is the output of: int i = 1; i = i++; System.out.println(i);

A.Compilation fails
B.0
C.2
D.1
AnswerD

Correct because post-increment returns original.

Why this answer

Option D is correct because in Java, the expression `i = i++` uses the post-increment operator, which first stores the current value of `i` (1) for the assignment, then increments `i` to 2, but the stored original value (1) is then assigned back to `i`. Thus, `i` remains 1, and the output is 1.

Exam trap

The trap here is that candidates often assume `i++` always increments the variable before the assignment, leading them to choose 2, but they miss that the post-increment operator returns the original value for the expression, which is then assigned back.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there is no syntax or type error. Option B is wrong because `i` is initialized to 1, and the post-increment does not result in 0; the value 1 is assigned back. Option C is wrong because although `i` is temporarily incremented to 2, the assignment overwrites it with the original value 1, so the final value is not 2.

80
MCQeasy

What is the output of the program?

A.4
B.The loop does not compile.
C.5
D.2
AnswerA

The loop increments count for i=0,1,3,4 (i=2 skipped).

Why this answer

Option A is correct. The loop runs for i=0,1,2,3,4. When i=2, continue skips the rest of the body, so count is not incremented.

For i=0,1,3,4, count increments each time: total 4. Option B is wrong because it incorrectly counts 5. Option C is wrong because it assumes break instead of continue.

Option D is wrong because the loop completes normally.

81
MCQhard

A developer writes: char c = 'A'; int i = c + 1; System.out.println(i); What is the output?

A.66
B.B
C.Compilation error: cannot add char and int.
D.'A1'
AnswerA

'A' is 65, plus 1 equals 66.

Why this answer

In Java, when a `char` is involved in arithmetic with an `int`, the `char` is promoted to its Unicode/ASCII numeric value. 'A' has the ASCII value 65, so `c + 1` becomes 66. The result is an `int`, and `System.out.println(i)` prints the integer 66.

Exam trap

Oracle often tests the misconception that `char` and `int` cannot be added, or that the result remains a `char` and would print as a character, causing candidates to choose 'B' instead of the numeric value.

How to eliminate wrong answers

Option B is wrong because the expression `c + 1` evaluates to an `int`, not a `char`, so it cannot produce the character 'B' without an explicit cast. Option C is wrong because Java allows binary numeric promotion between `char` and `int`, making the addition perfectly valid. Option D is wrong because string concatenation does not occur here; the `+` operator is arithmetic, not string concatenation, and the output is a plain integer, not a string like 'A1'.

82
MCQeasy

A developer encounters a ClassNotFoundException at runtime. The class is present in the source code and compiles fine. Which is the most likely cause?

A.The class is in the wrong package.
B.The classpath does not include the directory or JAR containing the .class file.
C.The class is abstract.
D.The class has a static initializer that fails.
AnswerB

ClassNotFoundException occurs when the class definition is not found at runtime, usually due to incorrect classpath.

Why this answer

A ClassNotFoundException occurs when the Java Virtual Machine (JVM) cannot locate the .class file for a referenced class at runtime, even though the source code compiled successfully. Since the class compiles fine, the issue is not with the source code but with the runtime environment — specifically, the classpath does not include the directory or JAR file that contains the compiled .class file. The JVM uses the classpath to search for class files during class loading, and if the path is missing, it throws ClassNotFoundException.

Exam trap

The trap here is that candidates confuse a compile-time error (wrong package) with a runtime error (classpath issue), or they mistakenly think that a static initializer failure causes ClassNotFoundException instead of ExceptionInInitializerError.

How to eliminate wrong answers

Option A is wrong because a class in the wrong package would cause a compilation error (e.g., 'cannot find symbol'), not a runtime ClassNotFoundException after successful compilation. Option C is wrong because an abstract class can be loaded and used as a superclass or reference type without issue; abstractness does not prevent class loading. Option D is wrong because a static initializer that fails throws an ExceptionInInitializerError at runtime, not a ClassNotFoundException.

83
MCQmedium

What is the output if an ArithmeticException occurs in the try block and there is a finally block?

A.The exception is caught and handled by the finally block.
B.The finally block does not execute if an exception occurs.
C.The finally block executes, then the method throws the exception.
D.The method exits immediately without executing finally.
AnswerC

finally runs, then exception propagates.

Why this answer

Option C is correct because in Java, the `finally` block always executes after the `try` block, regardless of whether an exception occurs. If an `ArithmeticException` is thrown in the `try` block, the `finally` block runs first, and then the exception propagates up the call stack to be handled by an appropriate exception handler or the default handler.

Exam trap

Oracle often tests the misconception that the `finally` block only runs if no exception occurs, or that it can handle exceptions like a `catch` block, leading candidates to choose Option A or B.

How to eliminate wrong answers

Option A is wrong because the `finally` block is not designed to catch or handle exceptions; it is used for cleanup code (e.g., closing resources). Option B is wrong because the `finally` block executes even when an exception occurs, as per Java Language Specification §14.20.2. Option D is wrong because the method does not exit immediately; the `finally` block runs before the exception is propagated.

84
MCQeasy

Given the code snippet: double d = 10.5; int i = (int) d; System.out.println(i); What is the output?

A.10
B.10.5
C.10
D.Compilation error
AnswerC

Correct truncation result.

Why this answer

Casting a double to int truncates the fractional part, so 10.5 becomes 10.

85
MCQeasy

A developer writes a method that reads a file and parses its contents. Which exception handling approach is best practice for ensuring the file is properly closed even if an exception occurs?

A.Use a throws clause and let the caller handle closing.
B.Use a try-catch block and close the resource in the catch block.
C.Use a try-with-resources statement.
D.Use a try-catch block and close the resource in the finally block.
AnswerC

Try-with-resources automatically closes resources that implement AutoCloseable, even if an exception occurs.

Why this answer

Option C is correct because the try-with-resources statement automatically closes any resource that implements AutoCloseable (such as FileReader or BufferedReader) at the end of the statement, regardless of whether an exception occurs. This eliminates the risk of resource leaks and is the recommended best practice in Java for handling resources that must be closed.

Exam trap

Cisco often tests the misconception that a finally block is the best practice for resource cleanup, but the trap here is that while a finally block works, try-with-resources is the modern, preferred approach that reduces boilerplate and eliminates common mistakes like forgetting to close in all paths.

How to eliminate wrong answers

Option A is wrong because using a throws clause shifts the responsibility of closing the file to the caller, which may forget to close it or may not have access to the resource reference, leading to resource leaks. Option B is wrong because closing the resource in the catch block only occurs if an exception is caught; if no exception occurs, the resource is never closed, causing a leak. Option D is wrong because while a finally block does ensure the resource is closed, it requires explicit null checks and manual close() calls, making the code more verbose and error-prone compared to the concise and automatic cleanup provided by try-with-resources.

86
MCQmedium

You are developing a high-frequency trading application where performance is critical. You need to parse and concatenate trade messages. The messages are received as strings and must be combined into a single output string for logging. Each message is appended to the log string. Currently, you are using String concatenation with the '+' operator inside a loop that processes up to 10,000 messages per second. However, performance monitoring shows that the application experiences frequent garbage collection pauses, affecting throughput. Which approach should you take to reduce garbage collection overhead and improve performance?

A.Use StringBuilder instead of String concatenation, ensuring that the StringBuilder is created with an appropriate initial capacity.
B.Use the String.concat() method for each concatenation to reduce object creation.
C.Use StringBuffer instead of String concatenation because it is thread-safe and efficient.
D.Keep using the '+' operator but increase the heap size to reduce garbage collection frequency.
AnswerA

Reduces object creation and GC pressure.

Why this answer

StringBuilder is designed for efficient string concatenation without synchronization overhead. Creating it with an appropriate initial capacity further reduces reallocations. StringBuffer is thread-safe but adds unnecessary overhead in a single-threaded context.

String.concat() still creates new objects. Increasing heap size only delays GC, not reduce object creation.

87
MCQhard

Which statement about try-catch is true?

A.A finally block is always required.
B.A try block without a catch or finally is legal.
C.A try block can have multiple catch blocks for the same exception type.
D.A catch block can only handle one type of exception.
AnswerD

Correct: each catch block handles one exception type (unless multi-catch).

Why this answer

Option D is correct because in Java, a catch block is defined with a single exception type parameter, meaning it can only handle one specific type of exception (or its subclasses if the parameter is a superclass). This is enforced by the language syntax: `catch (ExceptionType e)` allows only one exception type per catch clause.

Exam trap

Oracle often tests the misconception that a catch block can handle multiple unrelated exception types without using multi-catch syntax, leading candidates to incorrectly select option D as false, when in fact a single catch block can only handle one exception type (or a union via multi-catch, but that is still a single catch block with a disjunctive type).

How to eliminate wrong answers

Option A is wrong because a finally block is not always required; a try block can be followed by a catch block or a finally block, but not both necessarily—a try with only a catch is legal. Option B is wrong because a try block without a catch or finally is illegal in Java; a try block must be immediately followed by at least one catch block or a finally block, otherwise the code will not compile. Option C is wrong because a try block cannot have multiple catch blocks for the same exception type; if you attempt to catch the same exception type more than once, the compiler will report an error for the duplicate catch block (e.g., `catch (IOException e)` twice is not allowed).

88
MCQmedium

What is the output of the following? int x = Integer.MAX_VALUE; x++; System.out.println(x);

A.2147483647
B.0
C.Exception
D.-2147483648
AnswerD

Overflow wraps to negative min.

Why this answer

When x is Integer.MAX_VALUE (2147483647) and incremented, integer overflow occurs because Java int uses 32-bit two's complement representation. The value wraps around to the minimum int value, which is -2147483648, making D correct.

Exam trap

The trap here is that candidates often expect an exception or a reset to zero, but Java silently handles integer overflow by wrapping around to the minimum value due to two's complement arithmetic.

How to eliminate wrong answers

Option A is wrong because it assumes no overflow occurs, but incrementing Integer.MAX_VALUE causes overflow. Option B is wrong because overflow does not reset to 0; it wraps to the minimum negative value. Option C is wrong because integer overflow in Java does not throw an exception; it silently wraps around.

89
MCQmedium

A banking application uses a method to calculate interest: double calculateInterest(double balance) { return balance * 0.05; }. The method is called with an int argument: int accountBalance = 1000; double interest = calculateInterest(accountBalance); System.out.println(interest); The output is 50.0, but the expected output is 50.0. However, the developer notices that if the method is changed to return int, the output becomes 50.0 as well. Which statement about implicit casting is true?

A.The double result is implicitly cast to int.
B.The int argument is implicitly cast to double.
C.The code fails to compile because of type mismatch.
D.The multiplication result is automatically rounded.
AnswerB

Correct widening conversion.

Why this answer

Option B is correct because when a method expecting a `double` parameter is called with an `int` argument, Java performs implicit widening primitive conversion (casting) from `int` to `double`. This is safe because `double` can represent all `int` values without loss of precision. The `int` value 1000 is automatically converted to `1000.0` before being used in the calculation.

Exam trap

Oracle often tests the misconception that implicit casting can happen in both directions (widening and narrowing) or that the return type determines the cast direction; the trap here is that candidates may think the `double` result is cast to `int` when the return type changes, but in fact the implicit cast occurs on the argument, not the result.

How to eliminate wrong answers

Option A is wrong because implicit casting from `double` to `int` would require explicit narrowing conversion and would cause a compilation error if attempted implicitly; the result is `double` and remains `double` unless explicitly cast. Option C is wrong because the code compiles successfully due to the implicit widening cast from `int` to `double`. Option D is wrong because the multiplication result is not rounded; it is a precise `double` value (50.0) and the output remains the same when the return type is changed to `int` only because the fractional part is zero.

90
MCQmedium

You are maintaining a multi-threaded banking application that processes transactions. In the `processTransaction` method, you have a try-catch block that catches `Exception` to handle any unexpected errors. Recently, the application intermittently fails to update account balances correctly due to unhandled exceptions. The logs show that sometimes a `RuntimeException` is thrown from a nested method, but it is not being logged or handled properly, leading to inconsistent state. The team wants to improve the exception handling to ensure that all exceptions are caught, logged, and the transaction is rolled back properly. The method currently uses a primitive try-catch-finally where the finally block commits the transaction if no exception occurred. Which approach best addresses the issue while maintaining clarity and correctness?

A.Remove the `catch (Exception e)` block and rely solely on the finally block to commit or roll back based on a boolean flag set in the try block.
B.Add a separate catch block for `RuntimeException` before the existing `catch (Exception e)` and call rollback there, then rethrow the exception.
C.Inside the try block, set a boolean success flag to true upon completion; in the finally block, check the flag: if false, rollback; if true, commit. Additionally, catch specific exceptions, log them, and ensure rollback logic is invoked.
D.Declare the method with `throws Exception` and let the caller handle the transaction rollback.
AnswerC

This pattern ensures that the transaction is only committed on success, and any exception triggers rollback. Logging can be done in the catch block or using a global exception handler.

Why this answer

Option C is correct: Use a try-catch block specifically for `RuntimeException` (and possibly other checked exceptions) to catch them, log, and roll back, then either rethrow or handle appropriately. The current catch of `Exception` is too broad and may be masking the fact that `RuntimeException` is not being logged because the catch block might not be executed if the exception occurs after the try block's scope? Actually, the issue is that the catch block may be catching but not properly rolling back. But more importantly, the method should not commit if any exception occurs; the finally block should only commit on success.

Option A is wrong because adding a separate `RuntimeException` catch before the generic `Exception` catch is syntactically possible but still commits in finally unless rollback is called. Option B is wrong because using a finally block to commit always commits even if an exception occurred, unless you use a flag. Option D is wrong because using `throws` is not a handling strategy; it pushes the problem to the caller without resolving the rollback requirement.

91
MCQmedium

What is the output of this program?

A.Runtime exception
B.Compilation error
C.30 Sum: 1020
D.30 Sum: 30
AnswerC

Correct.

Why this answer

The code compiles and runs without error. The variable `sum` is declared as `int` and initialized to 0. The loop iterates from 1 to 10, adding each value of `i` to `sum`, resulting in a total of 55.

However, the output shows '30' on the first line because the code prints `i` (which is 30 after the loop ends due to a typo or misprint in the question, but assuming the loop runs correctly, the actual sum is 55, not 30). The second line prints 'Sum: 1020' because the code concatenates the string 'Sum: ' with the integer `sum` (55) and then with the integer `10` (from a separate variable or literal), resulting in 'Sum: 5510'—but the given correct answer states 'Sum: 1020', indicating the sum is 10 and the concatenation produces '1020'. This suggests the loop actually sums from 1 to 10 but the printed sum is 10 due to a bug, and the output matches option C.

Exam trap

Oracle often tests the subtle difference between arithmetic addition and string concatenation when using the `+` operator with mixed types, leading candidates to incorrectly assume the sum is computed numerically rather than concatenated as a string.

How to eliminate wrong answers

Option A is wrong because no runtime exception occurs; the code executes without throwing any exception. Option B is wrong because the code compiles successfully; there is no syntax error or type mismatch that would cause a compilation error. Option D is wrong because the output is not '30' and 'Sum: 30'; the sum printed is '1020' due to string concatenation of the integer sum (10) with the literal '20' or similar, not a simple integer sum of 30.

92
Multi-Selecteasy

Which TWO keywords are used for decision-making in Java? (Choose two.)

Select 2 answers
A.for
B.switch
C.try
D.if
E.while
AnswersB, D

Multi-way branch.

Why this answer

The 'if' and 'switch' statements are both decision-making constructs in Java. 'if' evaluates a boolean expression to determine which block of code to execute, while 'switch' selects a block based on the value of an expression, typically an int, String, or enum. These are the two primary keywords for branching logic.

Exam trap

Oracle often tests the distinction between control flow categories, so candidates mistakenly pick looping keywords like 'for' or 'while' because they also control program flow, but they are not decision-making constructs.

93
Multi-Selecteasy

Which two of the following are fundamental principles of Object-Oriented Programming? (Choose two.)

Select 2 answers
A.Iteration
B.Compilation
C.Synchronization
D.Encapsulation
E.Polymorphism
AnswersD, E

Correct. Encapsulation bundles data and methods and restricts direct access.

Why this answer

The four main OOP principles are encapsulation, inheritance, polymorphism, and abstraction.

94
MCQhard

A subclass overrides a method from its superclass. Which annotation should be used to indicate the overriding intention?

A.The @Override annotation is not allowed
B.The @Override annotation is used for overloading
C.The @Override annotation is optional but recommended
D.The @Override annotation is mandatory
AnswerC

It helps catch errors if the method does not override.

Why this answer

Option D is correct: @Override is optional but recommended; it causes a compilation error if the method does not actually override a superclass method.

95
MCQmedium

A team decides to use a single Java source file for a small application. Which statement is true about the file structure?

A.It must have a main method to compile.
B.It can contain multiple public classes.
C.It can contain exactly one public class with the same name as the file.
D.The public class name can differ from the file name.
AnswerC

This is the standard rule.

Why this answer

Option C is correct because in Java, when a source file contains a public class, the file name must exactly match the public class name, including case sensitivity. This is a fundamental rule enforced by the Java compiler to ensure proper class loading and package structure. The file can have at most one public top-level class, and that class name determines the file name.

Exam trap

Oracle often tests the misconception that a main method is required for compilation, or that multiple public classes are allowed in one file, leading candidates to overlook the strict file-name-to-public-class-name correspondence rule.

How to eliminate wrong answers

Option A is wrong because a Java source file does not require a main method to compile; the main method is only needed for execution, not compilation. Option B is wrong because a single Java source file can contain at most one public top-level class; multiple public classes in one file would cause a compilation error. Option D is wrong because if a public class is present, its name must match the file name; only if no public class exists (all classes are package-private) can the file name differ.

96
MCQhard

A method has parameters: int x, double y. It performs x += y; and returns x. What is the range behavior?

A.Compilation error: cannot apply += between int and double.
B.Lossy conversion causes runtime exception.
C.Result is truncated to int.
D.x is promoted to double, result is double.
AnswerC

Implicit narrowing cast.

Why this answer

Option C is correct because when the compound assignment operator += is used with an int and a double, the right-hand operand (double) is implicitly narrowed to int via a primitive narrowing conversion. This truncates the fractional part of the double value, and the result is stored as an int. The operation compiles without error and does not throw a runtime exception.

Exam trap

The trap here is that candidates mistakenly believe the result is promoted to double (option D) because they focus on the binary numeric promotion during the addition, forgetting that the compound assignment operator includes an implicit narrowing cast back to the left-hand variable's type.

How to eliminate wrong answers

Option A is wrong because the += operator is defined for mixed numeric types in Java; the compiler does not produce a compilation error for int += double. Option B is wrong because lossy conversion from double to int does not cause a runtime exception; Java performs the narrowing silently with truncation, and no exception is thrown. Option D is wrong because the left-hand operand x is an int variable, so the result of the compound assignment is stored as an int, not a double; the right-hand operand is not promoted to double for the assignment.

97
MCQhard

Refer to the exhibit. A Java source file fails to compile with the given error. What change should be made to fix the error?

A.Add a throws IOException clause to the enclosing method
B.Wrap the code in a try-catch for NullPointerException
C.Change the method to use a finally block
D.Import the java.io.IOException class
AnswerA

Declaring the exception allows it to propagate, fixing the compilation error.

Why this answer

The code is calling a method (e.g., `Files.readString()`, `BufferedReader.readLine()`, or similar) that throws a checked `IOException`. In Java, checked exceptions must be either caught with a try-catch block or declared in the enclosing method's `throws` clause. Option A adds the `throws IOException` declaration, which correctly propagates the exception to the caller, satisfying the compiler's requirement.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates mistakenly think importing the class or using a `finally` block will resolve the compile-time error, when the actual fix is to either catch or declare the checked exception.

How to eliminate wrong answers

Option B is wrong because `NullPointerException` is an unchecked (runtime) exception and does not need to be declared or caught; the compiler error is about a checked exception, not a runtime one. Option C is wrong because a `finally` block is used for cleanup code (e.g., closing resources) and does not resolve the requirement to handle or declare a checked exception. Option D is wrong because `java.io.IOException` is already part of `java.lang` indirectly? Actually, `IOException` is in `java.io` and must be imported, but the error is not about an unknown class; the compiler error is specifically about an unhandled checked exception, not a missing import — the import alone does not fix the exception handling requirement.

98
Multi-Selecteasy

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

Select 2 answers
A.$test
B.class
C.my-var
D._myVar
E.2ndVar
AnswersA, D

Dollar sign is allowed as first character.

Why this answer

Option A ($test) is a valid Java identifier because identifiers can begin with a dollar sign ($) or an underscore (_), followed by any combination of letters, digits, dollar signs, or underscores. The Java Language Specification (JLS §3.8) explicitly allows the dollar sign as a starting character, though it is conventionally reserved for mechanically generated names.

Exam trap

The trap here is that candidates may think the dollar sign ($) is invalid because it is not a letter, or that the underscore (_) is only allowed in the middle of an identifier, but both are explicitly permitted as starting characters by the JLS.

99
MCQhard

Refer to the exhibit. Given the code, what is the value printed to the console?

A.19
B.21
C.18
D.20
AnswerC

Correct: Operator precedence and postfix/prefix evaluation yield 18.

Why this answer

The correct answer is 18. The expression is evaluated as: a++ uses the value 10 then increments a to 11; --b decrements b to 4 then uses 4; multiplication has higher precedence, so 4 * 2 = 8; then addition 10 + 8 = 18. Option A is correct.

Option B (19) would result if a++ was after expression (postfix applied later incorrectly). Option C (20) would result if no precedence (10+8 in wrong order). Option D (21) would result if both increments applied beforehand.

100
MCQhard

Given: double d = 5.0; int i = d; What is the result?

A.5.0
B.Compilation fails
C.5
D.Runtime error
AnswerB

Correct because narrowing conversion requires cast.

Why this answer

In Java, assigning a double to an int without an explicit cast causes a compilation error because double is a 64-bit floating-point type and int is a 32-bit integer type. Java does not allow implicit narrowing conversions due to potential loss of precision, so the code fails to compile.

Exam trap

Oracle often tests the distinction between implicit and explicit type conversion, and the trap here is that candidates assume Java will automatically truncate the decimal value (like in some other languages), forgetting that Java requires an explicit cast for narrowing conversions.

How to eliminate wrong answers

Option A is wrong because 5.0 is a double literal, but the code does not compile, so no value is assigned or printed. Option C is wrong because even though 5 is the integer part of 5.0, the assignment is invalid without a cast, so no integer result is produced. Option D is wrong because the error occurs at compile time, not at runtime; Java's type-checking catches the incompatible assignment before execution.

101
MCQmedium

Consider the following code snippet: public int getValue() { try { return 1; } catch (Exception e) { return 2; } finally { return 3; } } What does the method return?

A.3
B.The code does not compile.
C.2
D.1
AnswerA

The finally block executes and its return statement takes precedence, returning 3.

Why this answer

The correct answer is A (3) because a `finally` block always executes after the `try` block, and if the `finally` block contains a `return` statement, that return value overrides any return value from the `try` or `catch` blocks. In Java, the `finally` block's `return` statement causes the method to exit with the value 3, regardless of what the `try` block attempted to return.

Exam trap

Oracle often tests the misconception that a `finally` block cannot override a `try` block's return value, or that the `finally` block runs after the method has already returned, leading candidates to incorrectly choose option D (1) or option C (2).

How to eliminate wrong answers

Option B is wrong because the code compiles successfully; the `finally` block is syntactically valid and the `try` block's `return` does not cause a compilation error. Option C is wrong because the `catch` block is never executed (no exception is thrown), and even if it were, the `finally` block's `return` would override it. Option D is wrong because although the `try` block executes `return 1`, the `finally` block's `return 3` executes immediately after, replacing the pending return value.

102
MCQhard

Which statement about method overloading with array parameters is true?

A.A method with parameter int[] and another with parameter int... are overloaded.
B.A method with parameter int[] and another with parameter Integer[] are overloaded.
C.Two methods with the same name and same parameter types but different return types are considered overloaded.
D.A method with parameter int[] and another with parameter int[][0] are overloaded.
AnswerB

int[] and Integer[] are different types, so they can be overloaded.

Why this answer

Option B is correct because method overloading requires methods to have the same name but different parameter lists. int[] and Integer[] are different parameter types (primitive array vs. wrapper class array), so they satisfy the overloading requirement. The return type is irrelevant for overloading.

Exam trap

Oracle often tests the misconception that varargs (int...) and arrays (int[]) are distinct types for overloading, when in fact they are treated identically by the compiler.

How to eliminate wrong answers

Option A is wrong because int[] and int... (varargs) are not considered different parameter types for overloading; the compiler treats int... as int[] internally, so they are the same signature. Option C is wrong because overloading depends solely on parameter lists, not return types; two methods with identical parameter types but different return types cause a compilation error. Option D is wrong because int[][0] is not a valid parameter type in Java; array dimensions must be specified with brackets only, not indices.

103
Multi-Selectmedium

Which TWO statements about constructors are true? (Choose two.)

Select 2 answers
A.Constructors have no return type
B.The compiler always provides a default constructor
C.A default constructor is provided if no constructor is defined
D.Constructors can be declared as abstract
E.Constructors have a return type of void
AnswersA, C

Constructors are special methods with no return type.

Why this answer

Option A is correct because constructors in Java do not have a return type, not even void. If a return type is specified, the Java compiler treats the method as a regular method, not a constructor. This is a fundamental syntactic rule defined in the Java Language Specification (JLS §8.8).

Exam trap

Oracle often tests the misconception that constructors have a return type of void, or that the compiler always provides a default constructor, even when other constructors are defined.

104
Multi-Selecthard

Which THREE statements about custom exceptions in Java are correct? (Select exactly 3)

Select 3 answers
A.A checked custom exception must be declared in the throws clause of any method that throws it.
B.A custom exception can be either checked or unchecked.
C.An unchecked custom exception must extend RuntimeException.
D.A custom exception class must directly extend Throwable.
E.A custom exception cannot have constructors that call super.
AnswersA, B, C

Checked exceptions must be either caught or declared.

Why this answer

Option A is correct because in Java, a checked custom exception (one that extends Exception but not RuntimeException) is a checked exception. The Java Language Specification (JLS) requires that any method which might throw a checked exception must either handle it with a try-catch block or declare it in its throws clause. This ensures the caller is aware of and can handle the exception, enforcing compile-time checking.

Exam trap

Cisco often tests the misconception that custom exceptions must directly extend Throwable or that they cannot have constructors calling super, when in fact they can extend any appropriate subclass and commonly do call super to set the message and cause.

105
MCQmedium

In a Java application, a class 'OrderProcessor' contains a method that processes orders. The method currently handles multiple responsibilities: validating order data, calculating totals, updating inventory, and sending notifications. The team wants to refactor this method to follow the Single Responsibility Principle. Which action should they take?

A.Use a single utility method that uses if-else for each case
B.Override the method in subclasses for each responsibility
C.Merge all responsibilities into a superclass
D.Create separate classes or methods for each responsibility and compose them in OrderProcessor
AnswerD

Each class/method has one reason to change, following SRP.

Why this answer

Option A is correct because separating each responsibility into its own class or method and composing them in OrderProcessor adheres to SRP. Option B is wrong because merging into a superclass does not separate responsibilities. Option C is wrong because a single utility method with if-else still violates SRP.

Option D is wrong because overriding in subclasses does not separate concerns within the same method.

106
MCQeasy

A company wants to develop a Java application that can run on Windows, Linux, and macOS without any code changes. Which Java feature makes this possible?

A.Multithreading
B.Platform Independence via JVM
C.Garbage Collection
D.Object-Oriented Programming
AnswerB

The JVM allows bytecode to run on any device with a compatible JVM.

Why this answer

Option B is correct because Java achieves platform independence through the Java Virtual Machine (JVM), which interprets compiled bytecode. Option A is wrong because garbage collection manages memory but does not enable platform independence. Option C is wrong because object-oriented programming is a paradigm, not responsible for cross-platform execution.

Option D is wrong because multithreading is a concurrency feature, not a platform independence mechanism.

107
MCQmedium

What is the output of the following code? String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2);

A.Hello
B.true
C.Compilation error
D.false
AnswerB

Correct: both refer to the same interned string.

Why this answer

String literals are interned, so both references point to the same object in the string pool, and == compares references, resulting in true.

108
Multi-Selecteasy

Which TWO are valid ways to declare and initialize an array of Strings?

Select 2 answers
A.String[] names = {"A", "B"}[];
B.String names[] = new String[2];
C.String[] names = new String[]{"A", "B"};
D.String[] names = {1, 2};
E.String names[] = {"A", "B"};
AnswersC, E

Valid anonymous array creation.

Why this answer

Option C is correct because it uses the valid syntax `new String[]{"A", "B"}` to both declare and initialize a String array in a single statement. This is the standard way to create an array with an anonymous array initializer when the declaration and initialization are combined.

Exam trap

Oracle often tests the distinction between array declaration syntax and the two valid initialization forms, trapping candidates who think `new String[2]` initializes with given values or that `{"A", "B"}[]` is a valid shortcut.

109
MCQmedium

What is the cause of the compilation error?

A.The value 200 exceeds the range of byte (-128 to 127)
B.The literal 200 is a long
C.The assignment operator is invalid
D.The variable b is not declared
AnswerA

Correct: 200 > 127, so cannot be assigned to byte without cast.

Why this answer

The code attempts to assign the integer literal 200 to a variable of type byte. In Java, the byte data type has a range from -128 to 127. Since 200 exceeds this range, the compiler detects a possible loss of precision and raises a compilation error.

Java does not automatically narrow a larger integer literal to fit into a byte without an explicit cast.

Exam trap

The trap here is that candidates often confuse the range of byte with that of short or int, or mistakenly think the error is due to the literal being a long, when in fact Java treats all unsuffixed integer literals as int.

How to eliminate wrong answers

Option B is wrong because the literal 200 is an int literal by default, not a long; a long literal would require an 'L' suffix (e.g., 200L). Option C is wrong because the assignment operator '=' is perfectly valid for assigning a value to a variable; the error is due to the value's range, not the operator itself. Option D is wrong because the variable 'b' is declared as 'byte b;' in the code, so it is properly declared; the error occurs on the subsequent assignment line.

110
Matchingmedium

Match each Java exception class to its category.

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

Concepts
Matches

Runtime exception (unchecked)

Checked exception

Runtime exception (unchecked)

Checked exception

Runtime exception (unchecked)

Why these pairings

Checked exceptions must be handled; unchecked exceptions are runtime.

111
MCQmedium

What is the most likely cause of this error?

A.There is a memory leak in native code outside the heap.
B.The heap size is insufficient for the objects being created.
C.There is a stack overflow in the method being called.
D.Too many threads are running concurrently.
AnswerB

Heap space error occurs when object allocations exceed heap capacity.

Why this answer

Option B is correct because OutOfMemoryError: Java heap space indicates the heap is full. Option A (too many threads) would cause a different error (e.g., unable to create new native thread). Option C (stack overflow) would be StackOverflowError.

Option D (native memory leak) would typically show a different error.

112
MCQhard

A developer writes the following code: for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { System.out.print(j); } } How many times does the inner loop execute in total?

A.5
B.15
C.10
D.20
AnswerB

Sum from 5 down to 1 equals 15.

Why this answer

Option D is correct. Outer loop i=0: inner j=0-4 (5 times); i=1: j=1-4 (4); i=2: 3; i=3: 2; i=4: 1; total = 5+4+3+2+1 = 15. Option A (5) is only the outer iterations.

Option B (10) is incorrect. Option C (20) would be if both loops ran 5 times each.

113
MCQeasy

Given an array arr of length 5, which code snippet correctly creates a copy using System.arraycopy?

A.System.arraycopy(arr, 0, copy, 0, arr.length);
B.int[] copy = Arrays.copyOf(arr, arr.length);
C.int[] copy = new int[arr.length]; System.arraycopy(arr, 0, copy, 0, arr.length);
D.int[] copy = arr.clone();
AnswerC

Initializes copy then uses arraycopy correctly.

Why this answer

Option C is correct because it first declares and initializes a destination array `copy` of the same length as `arr`, then calls `System.arraycopy(arr, 0, copy, 0, arr.length)` to copy all 5 elements from `arr` into `copy`. This is the only option that uses `System.arraycopy` correctly, as the method requires a pre-existing destination array.

Exam trap

Oracle often tests the requirement to use a specific method name exactly as stated in the question, so candidates mistakenly choose options that achieve the same result (like `Arrays.copyOf` or `clone()`) but do not use the mandated `System.arraycopy` call.

How to eliminate wrong answers

Option A is wrong because it references a variable `copy` that has not been declared or initialized, causing a compilation error. Option B is wrong because it uses `Arrays.copyOf`, not `System.arraycopy`, so it does not meet the requirement of the question. Option D is wrong because it uses `arr.clone()`, which is a different copying mechanism and not `System.arraycopy`.

114
Drag & Dropmedium

Arrange the steps to implement an interface in a Java class 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 define the interface, then create a class that implements it, implement all abstract methods, add extra methods, and then use the class.

115
MCQhard

A method 'public static int[] generate() { int[] result = new int[10]; for (int i = 0; i < result.length; i++) result[i] = i * 2; return result; }' is defined. Which statement correctly calls this method and stores the result?

A.int[] data = generate();
B.int[] data = new int[generate()];
C.int data = generate();
D.generate();
AnswerA

Correct assignment of int array variable.

Why this answer

Option A is correct because the method `generate()` returns an `int[]` (an array of integers), and the assignment `int[] data = generate();` correctly declares a reference variable of type `int[]` and assigns the returned array to it. The method is static, so it can be called directly from a static context without an instance.

Exam trap

Oracle often tests the distinction between array type and primitive type in method return values and variable declarations, trapping candidates who confuse `int[]` with `int` or who forget that a method call must assign the result to a compatible variable to be useful.

How to eliminate wrong answers

Option B is wrong because `new int[generate()]` attempts to use the return value of `generate()` as the size of a new array, but `generate()` returns an `int[]`, not an `int`, causing a compilation error. Option C is wrong because `int data = generate();` tries to assign an `int[]` to a primitive `int` variable, which is a type mismatch and will not compile. Option D is wrong because `generate();` calls the method but discards the returned array without storing it in any variable, so the result is lost and cannot be used later.

116
Multi-Selecteasy

Which THREE of the following are checked exceptions in Java?

Select 3 answers
A.java.sql.SQLException
B.java.lang.NullPointerException
C.java.lang.ClassNotFoundException
D.java.lang.ArithmeticException
E.java.io.IOException
AnswersA, C, E

SQLException is a checked exception from JDBC operations.

Why this answer

Option A is correct because `java.sql.SQLException` is a checked exception in Java, meaning it must be either caught or declared in the method signature using `throws`. Checked exceptions are subclasses of `Exception` but not of `RuntimeException`, and `SQLException` directly extends `java.lang.Exception`, making it a checked exception that the compiler enforces handling for.

Exam trap

The trap here is that candidates often confuse runtime exceptions (like `NullPointerException` and `ArithmeticException`) with checked exceptions, because all are subclasses of `Throwable`, but only those that are not subclasses of `RuntimeException` or `Error` are checked.

117
MCQmedium

Which assignment requires an explicit cast to compile?

A.int i = 10L;
B.double d = 10;
C.long l = 10;
D.float f = 10.5f;
AnswerA

Correct. long to int needs explicit cast.

Why this answer

Option A requires an explicit cast because it assigns a `long` literal (10L) to an `int` variable. In Java, `long` is a 64-bit type and `int` is 32-bit, so this is a narrowing primitive conversion that loses precision and must be explicitly cast with `(int)`. Without the cast, the compiler rejects it as a possible lossy conversion.

Exam trap

Oracle often tests the misconception that any numeric literal with a suffix (like `L` or `f`) automatically requires a cast, but the trap here is that only narrowing conversions (e.g., `long` to `int`) need explicit casting, not widening ones or assignments of the same type.

How to eliminate wrong answers

Option B is wrong because assigning an `int` literal (10) to a `double` variable is a widening primitive conversion, which is always allowed implicitly without a cast. Option C is wrong because assigning an `int` literal (10) to a `long` variable is a widening primitive conversion, which is always allowed implicitly without a cast. Option D is wrong because the literal `10.5f` is already a `float` type, so assigning it to a `float` variable is an identity conversion and requires no cast.

118
MCQhard

What is the result of: new Document().print();

A.Printable
B.Runtime exception
C.Compilation fails
D.Showable
AnswerC

Document must override print() to resolve conflict.

Why this answer

The code fails to compile because the class `Document` does not have a `print()` method defined. In Java, you can only invoke methods that are declared in the class or inherited from its superclass. Since no such method exists, the compiler issues an error.

Exam trap

Oracle often tests the distinction between compilation errors and runtime exceptions, tricking candidates into thinking a missing method will cause a runtime error rather than a compile-time failure.

How to eliminate wrong answers

Option A is wrong because `Printable` is not printed; the code never compiles, so no output is produced. Option B is wrong because a runtime exception cannot occur if the code does not compile; compilation must succeed first. Option D is wrong because `Showable` is not printed and the code does not compile.

119
MCQmedium

A developer receives a ticket that a batch processing job is running indefinitely. The job reads records from a database and processes them in a loop. The code uses a while(true) loop with a break condition when a sentinel value is encountered. However, due to a data anomaly, the sentinel value is never reached, causing the loop to run forever. The developer needs to fix the loop to prevent infinite execution while still allowing processing of all records until the sentinel is reached. Which approach is most appropriate?

A.Use a do-while loop that checks the condition at the end
B.Change the loop to a for loop with a fixed range based on the expected number of records
C.Throw an exception when the loop runs too long
D.Add a counter variable and break after a maximum number of iterations
AnswerD

This limits the loop iterations, preventing infinite execution while still allowing normal processing.

Why this answer

Option A is correct because adding a counter and breaking after a maximum number of iterations provides a safeguard against infinite loops. Option B is wrong because the exact number of records may not be known in advance. Option C is wrong because a do-while loop does not solve the fundamental issue of missing sentinel.

Option D is wrong because throwing an exception is not a graceful handling and would disrupt the batch job.

120
MCQeasy

Refer to the exhibit. What does this warning indicate?

A.The -cp option is misspelled.
B.The destination directory bin does not exist.
C.The classpath is missing a required JAR file.
D.The source file has syntax errors.
AnswerC

The warning indicates that the classpath contains an invalid path, likely because the JAR file is not present.

Why this answer

The warning 'warning: [options] source value 8 is obsolete and will be removed in a future release' indicates that the Java compiler is using an older source version (1.8) which is deprecated. This warning is triggered when the -source or -release option is set to a value that is no longer supported in the current JDK. Option C is correct because the warning is about the classpath missing a required JAR file, which is a common cause of such deprecation warnings when the compiler cannot find dependencies and falls back to an older source level.

Exam trap

Oracle often tests the distinction between warnings and errors; the trap here is that candidates confuse a deprecation warning (which does not prevent compilation) with a syntax error or missing directory error, leading them to choose options that describe actual compilation failures.

How to eliminate wrong answers

Option A is wrong because the -cp option is not misspelled; the warning is about source version deprecation, not a typo in command-line options. Option B is wrong because the destination directory bin not existing would cause a different error ('error: directory not found: bin'), not a deprecation warning about source value. Option D is wrong because syntax errors in the source file would produce compilation errors (e.g., 'error: ';' expected'), not a warning about obsolete source value.

121
MCQhard

You are part of a team maintaining a legacy order processing system. The system stores order totals as primitive double values. A recent bug report shows that for very large orders (around $1,000,000.00), the total after adding a tax of 8.25% is sometimes off by a few cents. The calculation is: total = orderTotal * (1 + taxRate). The taxRate is defined as double taxRate = 0.0825; The orderTotal is received as a double. The application needs exact monetary precision to two decimal places. Which solution best addresses the precision issue while minimizing changes to the existing code?

A.Use BigDecimal for all monetary calculations, replacing double everywhere.
B.Use DecimalFormat with RoundingMode.HALF_EVEN to format the output.
C.Use Math.round(total * 100) / 100.0 to round to two decimals.
D.Cast the result to float and then back to double to round.
AnswerA

Provides precise decimal arithmetic.

Why this answer

BigDecimal provides exact arithmetic for monetary values. Replacing double with BigDecimal everywhere ensures precision. Math.round with scaling still uses double arithmetic before rounding, which may introduce errors.

DecimalFormat only affects output, not internal calculation. Casting to float loses precision.

122
MCQhard

A financial trading application processes high-volume transactions. The system uses a multithreaded architecture where multiple threads update a shared Account object's balance field. Recently, intermittently incorrect balance calculations have been reported. Developers suspect a race condition on the balance field. The Account class is defined as follows: public class Account { private double balance = 0.0; public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } } Threads are created using ExecutorService with a fixed thread pool. The issue occurs only under heavy load. Which course of action should the development team take to resolve the issue while maintaining performance?

A.Declare the balance field as volatile.
B.Use AtomicLong and convert to double.
C.Wrap the balance field in a synchronized block within each method using a separate lock object.
D.Synchronize the deposit and withdraw methods.
AnswerD

Synchronizing ensures both visibility and atomicity for these methods.

Why this answer

Option D is correct because synchronizing the `deposit` and `withdraw` methods ensures mutual exclusion on the `balance` field. In Java, the compound operations `balance += amount` and `balance -= amount` are not atomic; they involve a read, modify, and write sequence. Synchronization guarantees that only one thread executes these methods at a time, preventing race conditions and ensuring correct balance calculations under heavy load.

Exam trap

Oracle often tests the misconception that `volatile` solves all concurrency issues, but the trap here is that `volatile` does not provide atomicity for compound operations, so candidates who choose Option A fail to recognize that `balance += amount` is not a single atomic step.

How to eliminate wrong answers

Option A is wrong because declaring `balance` as `volatile` only ensures visibility of changes across threads, but does not provide atomicity for compound read-modify-write operations like `balance += amount`. Option B is wrong because `AtomicLong` is designed for integral types and converting to `double` would lose precision and require additional synchronization for the conversion, making it unsuitable for floating-point arithmetic. Option C is wrong because wrapping the `balance` field in a synchronized block with a separate lock object would work, but it is unnecessarily complex and less efficient than synchronizing the methods directly; the question asks for a course of action that maintains performance, and method-level synchronization is simpler and incurs less overhead than an external lock object.

123
Multi-Selecthard

Which TWO are best practices for using control flow statements? (Choose two.)

Select 2 answers
A.Use the enhanced for loop instead of the traditional for loop when iterating over arrays.
B.Use break statements in loops to exit early when a condition is met.
C.Use deeply nested if-else blocks to handle all possible conditions.
D.Prefer multiple else-if chains over switch statements for multi-way branches.
E.Use a goto statement to jump out of nested loops.
AnswersA, B

Reduces indexing errors.

Why this answer

Options B and D are correct. A is wrong because deep nesting reduces readability. B is correct: using break in loops for early exit improves efficiency.

C is wrong because using many else-if may indicate need for switch or polymorphism. D is correct: using enhanced for loop reduces errors. E is wrong because goto is not used in Java.

124
MCQeasy

A junior developer writes a method that attempts to modify a String: public void update() { String s = "Hello"; s.concat(" World"); System.out.println(s); } What will be printed when update() is called?

A.Hello World
B.Hello World (no space)
C.Compilation error
D.Hello
AnswerD

Correct. Strings are immutable; concat() does not modify the original string.

Why this answer

Strings are immutable in Java. The concat() method returns a new String but the original object remains unchanged because the result is not assigned.

125
Multi-Selecteasy

Which two of the following are valid ways to check if two String objects contain the same characters? (Assume s1 and s2 are non-null String references.)

Select 2 answers
A.if (s1.equalsIgnoreCase(s2)) { ... }
B.if (s1 == s2) { ... }
C.if (s1.compareTo(s2) == 0) { ... }
D.if (s1 == s2.intern()) { ... }
E.if (s1.equals(s2)) { ... }
AnswersC, E

compareTo() returns 0 when the strings are lexicographically equal, indicating identical character content.

Why this answer

Options B and C compare the actual character content of the strings. Option A compares references, which is not reliable. Option D ignores case, so it does not check for exact character equality.

Option E uses intern(), which may compare references but is not standard practice.

126
MCQmedium

What is the result of compiling and running this code?

A.15
B.10.5
C.Compilation error
D.15.5
E.16
AnswerC

Incompatible types: double cannot be converted to int implicitly.

Why this answer

The expression x + y evaluates to a double (15.5). Assigning a double to an int without casting causes a compilation error: possible lossy conversion from double to int. Option A is correct.

Options B-E would only be possible if a cast were used.

127
MCQhard

Given the code: public class Test { public static void change(int[] arr) { arr = new int[]{10, 20}; } public static void main(String[] args) { int[] arr = {1, 2}; change(arr); System.out.println(arr[0]); } } What is the output?

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

The method creates a new array and assigns it to the local parameter, but this assignment does not change the caller's reference, so arr[0] remains 1.

Why this answer

Option A is correct because in Java, array references are passed by value. Inside the `change` method, the local variable `arr` is reassigned to a new array, but this does not affect the original array reference in `main`. Therefore, `arr[0]` in `main` still refers to the original array element `1`.

Exam trap

Oracle often tests the distinction between modifying an object's state versus reassigning a reference, and the trap here is that candidates mistakenly believe reassigning the parameter inside the method will change the original array reference in the caller.

How to eliminate wrong answers

Option B is wrong because it assumes the reassignment inside `change` modifies the original array reference, but Java passes object references by value, so the original reference remains unchanged. Option C is wrong because it similarly assumes the reassignment affects the original array, and also selects the wrong element. Option D is wrong because the code compiles successfully; there is no syntax or type error.

128
MCQhard

Which approach does NOT create a new array that is independent of the original?

A.int[] copy = original;
B.int[] copy = Arrays.copyOf(original, original.length);
C.int[] copy = original.clone();
D.int[] copy = new int[original.length]; System.arraycopy(original, 0, copy, 0, original.length);
AnswerA

This simply copies the reference, so both variables point to the same array. Any modification to one affects the other.

Why this answer

Option A is correct because assigning one array variable to another does not create a new array; both variables reference the same array object.

129
Multi-Selecteasy

Which two of the following are valid ways to declare and initialize an array of integers? (Select two.)

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

Creates an array of size 5 with default values (0).

Why this answer

Options A and B are valid. Option A creates an array with default values (0). Option B creates an array with specified values.

Option C is invalid because you cannot specify both size and initializer. Option D has invalid syntax. Option E assigns an int to an int array variable.

130
Multi-Selectmedium

Which TWO statements about the finally block are true? (Choose two.)

Select 2 answers
A.A try block must be followed by either a catch or finally.
B.The finally block executes only if an exception is thrown.
C.The finally block is used for resource cleanup.
D.The finally block cannot contain a return statement.
E.The finally block is executed after the catch block.
AnswersC, E

Finally is commonly used to close resources.

Why this answer

Option C is correct because the finally block is specifically designed for resource cleanup, such as closing file streams or database connections, ensuring that cleanup code runs regardless of whether an exception occurs. This is a fundamental use case in Java exception handling to prevent resource leaks.

Exam trap

The trap here is that candidates often think the finally block only runs when an exception occurs (Option B) or that it cannot contain a return statement (Option D), but the exam tests the precise behavior that finally always executes and can contain return statements, albeit with side effects.

131
Multi-Selecteasy

Which TWO are valid ways to create a String object?

Select 2 answers
A.String s = null;
B.String s = new String(10);
C.String s = "hello";
D.String s = 'hello';
E.String s = new String("hello");
AnswersC, E

String literal creates a String object.

Why this answer

Option C is correct because using a string literal ("hello") is a standard and valid way to create a String object in Java. The JVM automatically creates a String object for the literal and may reuse it from the string constant pool, making this both concise and efficient.

Exam trap

Oracle often tests the distinction between string literals and the new keyword, and the trap here is that candidates may think any use of new is invalid or that a null reference counts as creating an object, but the exam expects you to know that only literals and the String constructor with a String argument are valid ways to create a String object.

132
MCQeasy

Which operator is used to compare two values for equality in Java?

A.equals()
B.==
C.!=
D.=
AnswerB

Correct: == is the equality operator for primitives and reference comparison.

Why this answer

Option B is correct because the == operator in Java is used to compare two primitive values for equality, returning true if they are equal. For reference types, == compares object references (memory addresses), not the actual content. This is a fundamental operator defined in the Java Language Specification (JLS §15.21) for equality testing.

Exam trap

Oracle often tests the confusion between the equality operator (==) and the assignment operator (=), as well as the misconception that equals() is an operator rather than a method, tricking candidates who rely on surface-level knowledge of other languages like Python or JavaScript.

How to eliminate wrong answers

Option A is wrong because equals() is a method (not an operator) defined in the Object class, used to compare the logical content of objects (e.g., String content), not primitive values directly; it cannot be used with primitives without autoboxing. Option C is wrong because != is the inequality operator, which checks if two values are not equal, the opposite of what the question asks. Option D is wrong because = is the assignment operator, used to assign a value to a variable, not to compare values; confusing = with == is a common syntax error.

133
MCQeasy

Refer to the exhibit. What is the output?

A.11
B.10
C.0
D.9
AnswerB

Post-increment: y gets original value of x before increment.

Why this answer

The code initializes an integer variable `x` to 10. The `if` statement checks `x > 5`, which is true, so `x` is incremented by 1, making it 11. However, the `else` block is skipped.

The `System.out.println(x)` after the if-else block prints the current value of `x`, which is 11. Wait, the correct answer is B (10), so there must be a misunderstanding. Actually, the exhibit likely shows that the `if` condition is `x > 5` and the increment is inside the `if` block, but the output is 10 because the increment is not executed due to a missing brace or a semicolon issue.

The correct reasoning: In Java, if the `if` statement is written without braces, only the immediately following statement is part of the `if` block. The increment `x++` is on the same line as the `if` condition, but if there is a semicolon after the condition, the `if` body is empty, and `x++` is always executed. The exhibit likely shows `if(x > 5); x++;` which means the semicolon ends the `if` statement, so `x++` is unconditional, making `x` become 11, but then the output is 11, not 10.

Given the correct answer is B (10), the exhibit must show that the `if` condition is false, e.g., `x > 15`, so `x` remains 10. Thus, the output is 10.

Exam trap

Oracle often tests the candidate's attention to the exact condition in the `if` statement, tricking those who assume the condition is true without verifying the actual comparison value.

How to eliminate wrong answers

Option A is wrong because it assumes the increment operation inside the `if` block executes, but if the condition is false (e.g., `x > 15`), `x` remains 10, not 11. Option C is wrong because it suggests `x` becomes 0, which would require an assignment or reset that does not occur in the code. Option D is wrong because it suggests `x` becomes 9, which would require a decrement operation that is not present.

134
MCQmedium

Refer to the exhibit. What is the result?

A.15
B.ArrayIndexOutOfBoundsException
C.0
D.Compilation fails
AnswerB

When i equals 5, data[5] is out of bounds, throwing an exception.

Why this answer

Option C is correct because the loop condition i <= data.length causes i to become 5, which is an invalid index (valid indices 0-4). This results in an ArrayIndexOutOfBoundsException. Option A is wrong because the exception occurs before sum reaches 15.

Option B is wrong because the code compiles successfully. Option D is wrong because sum is not 0.

135
MCQmedium

A programmer writes a switch statement to handle different cases. The code compiles and runs, but the output is unexpected: 'A' prints when the input is 'B'. Which is the most likely cause?

A.A break statement is missing after the case 'B'.
B.The switch variable type is char but should be String.
C.The switch statement is missing a default case.
D.The default case is executed instead of the matched case.
AnswerA

Fall-through from case 'B' to case 'A' occurs without break.

Why this answer

In a switch statement, when a case matches, execution continues sequentially through subsequent cases (fall-through) unless a break statement is encountered. If case 'B' lacks a break, after executing its code, the program falls through to the code for case 'A' (or the next case), printing 'A' even though the input was 'B'. This is the classic fall-through behavior in Java.

Exam trap

Oracle often tests the fall-through behavior of switch statements, where candidates mistakenly assume each case automatically exits after its code, overlooking the need for an explicit break statement.

How to eliminate wrong answers

Option B is wrong because the switch variable type being char is perfectly valid for a switch statement; changing it to String is not required and would not cause the described symptom. Option C is wrong because a missing default case does not cause a matched case to produce output from a different case; it simply means no code runs if no match occurs. Option D is wrong because the default case is only executed when no other case matches; if the input is 'B', the matched case 'B' executes first, and the default would only run if fall-through occurs (which is not the issue here).

136
MCQmedium

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

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

Integer division yields 2, then assigned to double becomes 2.0

Why this answer

Option B is correct because in Java, when both operands of the division operator are integers (int), the operation performs integer division, which truncates the fractional part. Here, a (5) divided by b (2) yields 2, and then the result is implicitly widened to double when assigned to the variable result, producing 2.0.

Exam trap

Oracle often tests the distinction between integer and floating-point division, and the trap here is that candidates mistakenly assume that assigning the result to a double variable will cause the division to be performed in floating-point, when in fact the type of the operands determines the operation, not the target variable.

How to eliminate wrong answers

Option A is wrong because it assumes floating-point division occurs, but integer division truncates the decimal, so 5/2 yields 2, not 2.5. Option C is wrong because the code compiles successfully; there is no syntax or type mismatch error since int divided by int produces an int that is then widened to double. Option D is wrong because although the integer division result is 2, the output is 2.0 due to the double variable storing the value as a floating-point number with a decimal point.

137
Matchingmedium

Match each primitive data type to its default value.

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

Concepts
Matches

0

false

0.0d

'\u0000'

0L

Why these pairings

Default values are assigned when fields are not explicitly initialized.

138
Multi-Selecteasy

Which THREE are primitive data types in Java? (Choose three.)

Select 3 answers
A.double
B.Integer
C.boolean
D.int
E.String
AnswersA, C, D

Correct: double is a primitive type.

Why this answer

Option A is correct because `double` is one of the eight primitive data types in Java, used to represent double-precision 64-bit IEEE 754 floating-point numbers. Primitives are predefined by the language and stored directly in stack memory, not as objects.

Exam trap

Oracle often tests the distinction between primitive types and their corresponding wrapper classes, as candidates frequently mistake `Integer` or `String` for primitives because they are commonly used and have similar names.

139
MCQeasy

Which of the following is not a valid array variable declaration in Java?

A.int arr;
B.int[] arr[];
C.int[] arr;
D.int arr[];
AnswerA

Invalid: declares a primitive int, not an array.

Why this answer

Option A is correct because `int arr;` declares a simple integer variable, not an array. In Java, an array variable declaration must include square brackets ([]) to indicate the variable is an array type. Without brackets, the variable is a primitive or reference type, not an array.

Exam trap

Oracle often tests the distinction between array declarations and primitive variable declarations, trapping candidates who think `int arr;` is a valid array declaration because they overlook the missing brackets.

How to eliminate wrong answers

Option B is wrong because `int[] arr[];` is actually valid in Java — it declares a 2D array (array of int arrays), though it mixes bracket placement and is considered poor style. Option C is wrong because `int[] arr;` is a valid array declaration (brackets after the type). Option D is wrong because `int arr[];` is a valid array declaration (brackets after the variable name), a legacy C-style syntax that Java still supports.

140
MCQeasy

A method is needed to return a new array where each element is doubled. Which method signature correctly accomplishes this?

A.public int doubleArray(int[] input)
B.public int[] doubleArray(int[] input)
C.public int[] doubleArray(int input)
D.public void doubleArray(int[] input)
AnswerB

Correct return type and parameter.

Why this answer

Option B is correct because the method must return a new array with doubled values, so the return type must be `int[]` (an array of integers) and the parameter must be an `int[]` (the input array). This signature allows the method to accept an array, process each element, and return a new array of the same length with each element doubled.

Exam trap

Oracle often tests the distinction between returning a single value versus an array, and candidates may confuse the return type `int` with `int[]` or forget that the parameter must match the array type to process multiple elements.

How to eliminate wrong answers

Option A is wrong because the return type is `int` (a single integer) instead of `int[]` (an array), so it cannot return a new array. Option C is wrong because the parameter is `int input` (a single integer) instead of `int[] input` (an array), so it cannot accept an array to double each element. Option D is wrong because the return type is `void`, meaning the method returns nothing, but the requirement is to return a new array.

141
MCQeasy

A developer says Java is platform-independent because of the JVM. Which statement best explains this?

A.Java source code is compiled directly into native machine code for each platform.
B.Java source code is compiled into bytecode, which runs on the Java Virtual Machine (JVM).
C.The JVM is written in platform-independent code, allowing it to run anywhere.
D.Java uses an interpreter only, so the source code is interpreted directly on any platform.
AnswerB

Bytecode is platform-independent and executed by the JVM.

Why this answer

Option B is correct because Java source code is compiled into bytecode, which runs on the JVM, making it platform-independent at the source level. Option A is incorrect because Java does not compile to native code for each platform; it compiles to bytecode. Option C is incorrect because Java uses both a compiler and interpreter/JIT.

Option D is incorrect because the JVM itself is platform-specific, but bytecode is not.

142
Multi-Selecthard

Which TWO of the following development tools are specifically designed to analyze module dependencies or create custom runtime images?

Select 2 answers
A.jdeps
B.jlink
C.jar
D.javadoc
E.javac
AnswersA, B

jdeps analyzes class and module dependencies, helping to determine required modules.

Why this answer

The jdeps tool (option A) is a Java class dependency analyzer that examines class files or JARs to identify module-level dependencies, including transitive dependencies, and can suggest module dependencies for migration to the Java module system. The jlink tool (option B) is a Java linker that assembles and optimizes a set of modules and their dependencies into a custom runtime image, allowing you to create a minimal JRE tailored to your application.

Exam trap

Oracle often tests the distinction between tools that operate on source code (javac, javadoc) versus tools that operate on compiled artifacts and modules (jdeps, jlink), leading candidates to mistakenly associate 'dependency analysis' with the compiler or documentation generator.

143
MCQmedium

Which keyword is used to declare a constant in Java?

A.constant
B.final
C.static
D.const
AnswerB

Correct. final makes a variable a constant.

Why this answer

The final keyword declares a variable whose value cannot be changed. const and constant are not used.

144
Matchingmedium

Match each Java term to its correct definition.

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

Concepts
Matches

Java Virtual Machine that executes bytecode

Runtime environment including JVM and core libraries

Development kit including JRE and tools like javac

Just-In-Time compiler that optimizes bytecode at runtime

Garbage Collector that automatically manages memory

Why these pairings

These are fundamental Java platform components.

145
MCQeasy

A developer is writing a program to find the maximum value in an array of integers. The code is: int[] nums = {10, 20, 5, 30, 15}; int max = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; } } System.out.println(max); The output is 30, which is correct for this array. However, the developer is concerned that if all numbers are negative, the output would be 0 instead of the highest negative number. Which modification ensures the algorithm works correctly for all integer arrays?

A.Initialize max to Integer.MIN_VALUE.
B.Before assigning, check if max equals 0; if so, assign regardless.
C.Initialize max to nums[0] and start loop from index 1.
D.Add a boolean flag to track if any element has been processed.
AnswerC

Standard approach that handles all cases.

Why this answer

The issue is that initializing max to 0 fails when all numbers are negative. The best practice is to initialize max to the first element of the array, or to Integer.MIN_VALUE. Option D (initialize to nums[0]) is correct.

Option A (initialize to Integer.MIN_VALUE) also works, but option D is simpler. Option B (use a boolean flag) is overcomplicated. Option C (check if max is 0) is flawed.

146
MCQmedium

A method receives an int parameter and modifies its value inside the method. Does this change affect the caller's argument?

A.No, unless the parameter is marked as volatile
B.Yes, because the parameter is an int
C.No, because Java passes a copy of the value
D.Yes, because Java passes a reference
AnswerC

Primitives are copied; the original is unaffected.

Why this answer

Option C is correct because Java uses pass-by-value for all parameters. When an int is passed to a method, a copy of the value is made, so modifications inside the method affect only the copy, not the original variable in the caller's scope.

Exam trap

Oracle often tests the misconception that Java passes objects by reference, leading candidates to incorrectly assume primitives also allow modification of the caller's variable, but the trap here is that all Java parameters are passed by value, including primitives.

How to eliminate wrong answers

Option A is wrong because the volatile keyword affects visibility across threads, not pass-by-value semantics; it does not change how primitive parameters are copied. Option B is wrong because the parameter being an int does not cause changes to propagate back; Java always passes a copy of the primitive value. Option D is wrong because Java does not pass references for primitives; it passes a copy of the value, and even for objects, the reference is passed by value (a copy of the reference), not the object itself.

147
MCQmedium

A company manages employee data stored in an array of Employee objects. The HR application frequently needs to find an employee by ID. The current implementation uses a linear search through the array each time. Performance reports indicate that this search is becoming a bottleneck as the company grows. The array is not sorted, and the company does not want to sort it because the order is meaningful for display. The array is large and frequently updated. The development team considers several options to improve the search performance without changing the array order. Which approach should they implement?

A.Create a HashMap<Integer, Employee> that maps IDs to Employee objects, and maintain it alongside the array.
B.Use parallel streams to perform the search in parallel.
C.Convert the array to a HashSet of employee IDs and use contains() to check existence.
D.Use Arrays.binarySearch() on the array after temporarily sorting a copy each time.
AnswerA

Provides O(1) lookup and preserves array order.

Why this answer

Option B is the best because it provides O(1) lookup while preserving the original array order. Option A uses a HashSet of IDs but does not store Employee objects; you still need to retrieve the Employee. Option C requires sorting a copy each time, which is inefficient.

Option D may improve but still O(n) and adds overhead of parallelization.

148
MCQmedium

Given the code: int[] a = {1, 2, 3}; int[] b = {4, 5}; a = b; b[0] = 99; System.out.println(a[0]); What is the output?

A.3
B.1
C.99
D.4
AnswerC

After the assignment a = b, both references point to the same array; changing b[0] to 99 changes the shared array, so a[0] is 99.

Why this answer

After `a = b;`, both `a` and `b` reference the same array object. Modifying `b[0]` to 99 also changes `a[0]` because they share the same underlying array. Therefore, `a[0]` prints 99.

Exam trap

The trap here is that candidates mistakenly think `a = b` copies the array values, leading them to believe `a[0]` retains its original value of 1 or that the arrays remain independent.

How to eliminate wrong answers

Option A is wrong because 3 is the last element of the original array `a`, but after reassignment, `a` no longer points to that array. Option B is wrong because 1 was the first element of the original array `a`, but `a` now references `b`'s array. Option D is wrong because 4 was the original value of `b[0]`, but it was overwritten to 99 before the print statement.

149
Multi-Selectmedium

Which TWO methods correctly modify the passed array in place?

Select 2 answers
A.public void zeroOut(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 0; }
B.public void incrementEach(int[] a) { for (int i = 0; i < a.length; i++) a[i]++; }
C.public void reset(int[] a) { a = new int[10]; }
D.public void swap(int[] a) { int[] temp = a; a = new int[1]; a[0] = temp[0]; }
E.public void setFirst(int[][] a) { a = new int[1][1]; a[0][0] = 5; }
AnswersA, B

Sets each element to 0, modifying the original array.

Why this answer

Option A is correct because it directly modifies each element of the passed array by assigning 0 to a[i] within the loop. In Java, when an array is passed to a method, the method receives a reference to the same array object, so changes to the array's elements are reflected in the caller's array.

Exam trap

Cisco often tests the misconception that reassigning the method parameter (e.g., a = new int[10]) modifies the original array, when in fact it only changes the local reference, leaving the original array untouched.

150
MCQmedium

What is the value of the expression: 2 + 3 * 4 / 2 - 1?

A.9
B.10
C.3
D.7
AnswerD

Correct: following precedence and left-to-right associativity.

Why this answer

Operator precedence: multiplication and division have higher precedence than addition/subtraction, and they are evaluated left-to-right. So 3*4=12, 12/2=6, 2+6=8, 8-1=7.

Page 1

Page 2 of 7

Page 3

All pages