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

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

Page 6

Page 7 of 7

451
MCQhard

Refer to the exhibit. What is the output when running the main method?

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

Static init block, then instance init block, then constructor.

Why this answer

The correct answer is B because the code demonstrates a standard Java class hierarchy with method overriding and the use of the `super` keyword. When `new C()` is instantiated, the constructor of `C` calls `super()` (implicitly or explicitly), which invokes the constructor of `B`. In `B`, the constructor calls `super()` again, invoking the constructor of `A`.

Since `A`'s constructor prints 'A', then `B`'s constructor prints 'B', and finally `C`'s constructor prints 'C', the output is 'A B C'.

Exam trap

Oracle often tests the order of constructor execution in inheritance, and the trap here is that candidates mistakenly think constructors execute from child to parent (like destructors in C++) or confuse the output order with method overriding behavior, leading them to choose 'C B A' or 'B A C'.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 'B A C', which would occur if constructors were called in reverse order or if `super()` was not used correctly, but Java always calls parent constructors first. Option C is wrong because it suggests 'A C B', which would happen if `C`'s constructor printed before `B`'s, but `super()` in `C` invokes `B`'s constructor before `C`'s own print statement. Option D is wrong because it suggests 'C B A', which would be the order of a destructor chain or if constructors were called from child to parent, but Java constructors execute from the top of the hierarchy down.

452
MCQmedium

Refer to the exhibit. A Java program throws a NullPointerException. Which is the most likely cause?

A.An object not initialized before use
B.A syntax error in the try block
C.Incorrect classpath preventing class loading
D.A missing import statement in the source code
AnswerA

NullPointerException occurs when invoking a method or field on a null reference.

Why this answer

A NullPointerException is thrown when the JVM attempts to access a method or field on an object reference that is null. The most common cause is that the object was declared but never instantiated (e.g., `String s; s.length();`). This is a runtime exception, not a compile-time error, so it occurs during execution when the reference variable points to null.

Exam trap

Oracle often tests the distinction between compile-time errors (syntax, imports, classpath) and runtime exceptions (NullPointerException), trapping candidates who confuse a missing import or classpath issue with a null reference problem.

How to eliminate wrong answers

Option B is wrong because a syntax error in the try block would be caught at compile time, not at runtime as a NullPointerException. Option C is wrong because an incorrect classpath prevents class loading, resulting in a ClassNotFoundException or NoClassDefFoundError, not a NullPointerException. Option D is wrong because a missing import statement causes a compile-time error (e.g., 'cannot find symbol'), not a runtime NullPointerException.

453
MCQhard

Given: short s = 10; s = s + 5; What is the result?

A.s = 10
B.Runtime exception
C.s = 15
D.Compilation fails: possible lossy conversion from int to short
AnswerD

s + 5 is int, cannot assign to short.

Why this answer

The expression `s + 5` performs arithmetic on a `short` and an `int` literal, so the result is promoted to `int`. Assigning that `int` back to a `short` variable without an explicit cast causes a compilation error because an `int` may be larger than a `short` (16-bit range), leading to possible lossy conversion. Therefore, option D is correct.

Exam trap

Oracle often tests the misconception that arithmetic on smaller numeric types (like `short` or `byte`) stays within that type, when in fact Java promotes them to `int` before the operation, causing a compilation error on assignment back without a cast.

How to eliminate wrong answers

Option A is wrong because it suggests the value remains 10, but the arithmetic operation `s + 5` would compute 15, not 10, and the code fails to compile before any assignment occurs. Option B is wrong because the error is a compile-time error, not a runtime exception; Java catches type mismatch issues during compilation. Option C is wrong because although the mathematical result is 15, the code does not compile due to the lossy conversion from `int` to `short`, so no assignment occurs.

454
Multi-Selecthard

Which THREE are valid Java identifiers? (Choose three.)

Select 3 answers
A.$dollar
B.my var
C.2ndValue
D._value
E.myVar123
AnswersA, D, E

Starts with dollar sign, valid.

Why this answer

Option A is correct because Java identifiers can start with a dollar sign ($), which is a valid identifier character according to the Java Language Specification (JLS). The $dollar follows the rule that identifiers must begin with a letter, underscore, or dollar sign, and subsequent characters can include letters, digits, underscores, or dollar signs.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit, leading candidates to mistakenly think '2ndValue' is valid because it contains letters, while overlooking the initial digit violation.

455
MCQhard

Given 'int[] source = {1,2,3,4,5};' and 'int[] dest = new int[3];' which code correctly copies the first three elements from source to dest using System.arraycopy?

A.System.arraycopy(source, 0, dest, 0, 3);
B.System.arraycopy(source, 0, dest, 0, 5);
C.System.arraycopy(source, 1, dest, 0, 3);
D.System.arraycopy(source, 0, dest, 1, 3);
AnswerA

Correct parameters.

Why this answer

Option A is correct because `System.arraycopy(source, 0, dest, 0, 3)` copies exactly three elements starting from index 0 of the source array to index 0 of the destination array, matching the requirement. The `length` argument (3) specifies the number of array elements to copy, and the destination array has a capacity of 3, so no `ArrayIndexOutOfBoundsException` occurs.

Exam trap

Oracle often tests the misconception that the `length` parameter refers to the total size of the destination array rather than the number of elements to copy, leading candidates to choose option B.

How to eliminate wrong answers

Option B is wrong because `length` is 5, which would attempt to copy 5 elements into `dest` that only has 3 elements, causing an `ArrayIndexOutOfBoundsException`. Option C is wrong because `srcPos` is 1, so it copies elements starting from index 1 (values 2,3,4) instead of the first three elements (1,2,3). Option D is wrong because `destPos` is 1, so it would place the copied elements starting at index 1 of `dest`, leaving index 0 unchanged and potentially causing an `ArrayIndexOutOfBoundsException` when writing beyond the array bounds.

456
MCQhard

What is the result of: Integer a = null; int b = (a != null) ? a : 0; System.out.println(b);

A.0
B.NullPointerException
C.Compilation error
D.null
AnswerA

Correct. Ternary returns 0.

Why this answer

The ternary operator evaluates the condition (a != null). Since a is null, the condition is false, so the expression returns the second operand, which is the int literal 0. This value is assigned to int b, and System.out.println(b) prints 0.

No NullPointerException occurs because the ternary operator never attempts to unbox a null reference.

Exam trap

Oracle often tests the misconception that accessing a null reference in any part of a ternary expression will throw a NullPointerException, but the key is that the unboxing only occurs if the selected branch actually references the null object.

How to eliminate wrong answers

Option B is wrong because a NullPointerException would only occur if the ternary operator attempted to auto-unbox a null Integer to int, but the condition (a != null) is false, so the expression evaluates to the int literal 0, not to a. Option C is wrong because the code compiles successfully; the ternary operator is syntactically valid and both operands are compatible with int assignment. Option D is wrong because b is a primitive int, which cannot hold a null value; the output is the integer 0, not the string 'null'.

457
MCQhard

A developer writes: int x = 5; int y = x++ + ++x; What is the value of y after execution?

A.12
B.11
C.10
D.Compilation error
AnswerA

x++ uses 5 then increments to 6; ++x increments to 7 then uses 7; sum is 12.

Why this answer

The expression `int y = x++ + ++x;` involves post-increment and pre-increment operators. Initially, `x = 5`. In `x++`, the current value (5) is used, then `x` becomes 6.

In `++x`, `x` is incremented to 7, then the new value (7) is used. So, `y = 5 + 7 = 12`. Option A is correct.

Exam trap

Cisco often tests the confusion between post-increment and pre-increment operators, where candidates mistakenly assume both increments use the same value or overlook the order of evaluation.

How to eliminate wrong answers

Option B (11) is wrong because it incorrectly assumes both increments use the same intermediate value (e.g., 5 + 6). Option C (10) is wrong because it might assume both increments use the original value (5 + 5) or misapply operator precedence. Option D (compilation error) is wrong because the expression is syntactically valid in Java; post-increment and pre-increment can be used together in an expression without error.

458
MCQeasy

What is the output of System.out.println(1 + 2 + "3" + 4 + 5);?

A.3345
B.12345
C.3"3"45
D.15
AnswerA

String concatenation after first addition.

Why this answer

Java evaluates the expression left-to-right. The first operation is `1 + 2`, which is integer addition, yielding `3`. Then `3 + "3"` triggers string concatenation, producing `"33"`.

The remaining `+ 4` and `+ 5` are also string concatenations, appending `"4"` and `"5"` to give `"3345"`. The `println` method outputs this string.

Exam trap

The trap here is that candidates assume all `+` operators behave the same way, failing to recognize that the presence of a string literal changes the operator's meaning from arithmetic addition to string concatenation, and that left-to-right evaluation means the first two numbers are added as integers before the string is encountered.

How to eliminate wrong answers

Option B is wrong because it assumes all numbers are concatenated as strings from the start, ignoring that `1 + 2` is evaluated as integer addition before any string context. Option C is wrong because it incorrectly includes literal quotes in the output, which Java never prints; the `+` operator does not produce quote characters. Option D is wrong because it sums all numbers as integers (1+2+3+4+5=15), ignoring that the string `"3"` forces subsequent operations to be string concatenation, not arithmetic.

459
MCQeasy

A developer compiles a Java application using the command `javac -d bin src/com/example/App.java`. Which of the following is true?

A.The compiler searches for source files in the `bin` directory.
B.The compiled .class files are placed in the `bin` directory maintaining the package structure.
C.The compiler creates a JAR file named `App.jar` in the `bin` directory.
D.The compiler compiles the code into a named module.
AnswerB

`-d bin` sets the root for output; the class file will be at `bin/com/example/App.class`.

Why this answer

The `-d` option in the `javac` command specifies the destination directory for compiled `.class` files. When `-d bin` is used, the compiler places the `.class` files into the `bin` directory, preserving the package directory structure (e.g., `bin/com/example/App.class`). This is the standard behavior for organizing compiled output separately from source code.

Exam trap

Oracle often tests the misconception that `-d` specifies the source directory or that `javac` can produce JAR files, leading candidates to confuse the roles of `javac` and `jar` tools.

How to eliminate wrong answers

Option A is wrong because the `-d` flag specifies the output directory, not the source directory; the compiler searches for source files in the path provided after the `-d` option (here, `src/com/example/App.java`), not in `bin`. Option C is wrong because `javac` does not create JAR files; JAR creation is done with the `jar` tool, not the `javac` compiler. Option D is wrong because the command does not include any module-related options (like `--module-source-path` or `-p`) and compiles a single class file, not a named module; named modules require a `module-info.java` file and specific module path settings.

460
MCQmedium

Refer to the exhibit. What is the problem with this class?

A.The constructor is missing a return type
B.The constructor parameter shadows the field, causing name to remain null
C.The getName method should be void
D.The field name is private and cannot be accessed within the class
AnswerB

The assignment should be 'this.name = name;' to assign to the field.

Why this answer

Option A is correct because the constructor parameter name shadows the field name, and the assignment 'name = name' assigns the parameter to itself, leaving the field null. Option B is wrong because the field is private and accessible within the class. Option C is wrong because constructors don't have return types.

Option D is wrong because the method returns a String correctly.

461
MCQmedium

What is the output of the program?

A.Two
B.Two Three Default
C.Compilation fails because case 2 is missing a break.
D.Two Three
AnswerD

Fall-through from case 2 to case 3, then break.

Why this answer

The switch statement matches the value 2, executing the case 2 block which prints 'Two'. Since there is no break statement, execution falls through to case 3, printing 'Three'. The default case is not executed because fall-through stops at the end of the switch block.

Thus, the output is 'Two Three'.

Exam trap

Oracle often tests the concept of fall-through in switch statements, where candidates mistakenly assume that each case is isolated and requires a break to avoid compilation errors, or that the default case always executes regardless of a match.

How to eliminate wrong answers

Option A is wrong because it ignores the fall-through from case 2 to case 3, which prints 'Three' as well. Option B is wrong because the default case is only executed if no matching case is found; here case 2 matches, so default is skipped. Option C is wrong because a missing break does not cause compilation failure; it is syntactically valid and results in fall-through behavior.

462
MCQeasy

Which is the correct way to call a superclass constructor from a subclass constructor?

A.super(); anywhere
B.super(); as first statement
C.super(); at the end
D.this.super();
AnswerB

Correct syntax and position.

Why this answer

In Java, a call to the superclass constructor using `super()` must be the first statement in a subclass constructor. This ensures that the superclass initialization completes before any subclass-specific code executes, maintaining the inheritance chain. Option B correctly identifies this requirement.

Exam trap

Oracle often tests the misconception that `super()` can be placed anywhere in the constructor body, leading candidates to choose option A, when in fact Java strictly requires it as the first statement.

How to eliminate wrong answers

Option A is wrong because `super()` cannot be placed anywhere; it must be the first statement, or the compiler will report an error. Option C is wrong because placing `super()` at the end would attempt to initialize the superclass after subclass code, violating Java's constructor chaining rules and causing a compilation failure. Option D is wrong because `this.super()` is invalid syntax; `super()` is a standalone keyword call, not a method on `this`.

463
MCQmedium

A developer writes: if (x = 5) { System.out.println("x is 5"); } What is the result?

A.Compilation error
B.Prints "x is 5" if x equals 5
C.No output
D.Prints "x is 5" always
AnswerA

Assignment is not boolean and cannot be used in if condition.

Why this answer

In Java, the assignment operator `=` is used for assignment, not comparison. The expression `x = 5` assigns the value 5 to variable `x` and returns the assigned value (5). Since the condition in an `if` statement must be a boolean expression, and `int` cannot be implicitly converted to `boolean`, the compiler throws a compilation error.

This is a fundamental syntax rule in Java, unlike in C/C++ where such an assignment would be allowed as a truthy check.

Exam trap

Oracle often tests the distinction between assignment (`=`) and comparison (`==`) in conditional statements, exploiting the common misconception that Java behaves like C/C++ where an assignment expression can be used as a boolean condition.

How to eliminate wrong answers

Option B is wrong because the code does not compile, so it never executes to check if x equals 5. Option C is wrong because a compilation error occurs before any runtime output, so there is no 'no output' scenario. Option D is wrong because even if the code compiled (which it does not), the assignment would always set x to 5, but the condition would still be a non-boolean type, causing a compilation error; thus it never prints anything.

464
MCQeasy

A developer writes a loop that iterates over an array of integers. The loop should stop when it encounters a negative number. Which control flow construct best achieves this?

A.do-while loop
B.for loop with break inside if condition
C.enhanced for loop with return
D.while loop with continue
AnswerB

Correctly exits the loop when negative number is encountered.

Why this answer

Option A is correct because break exits the loop when condition met. Option B is wrong because continue skips to next iteration, doesn't stop loop. Option C is wrong because do-while executes at least once but doesn't provide early exit without additional logic.

Option D is wrong because return exits the method, which may not be desired.

465
Multi-Selectmedium

Which TWO keywords are used to control access to class members? (Choose two.)

Select 2 answers
A.private
B.static
C.public
D.abstract
E.final
AnswersA, C

Correct: private restricts access to within the class.

Why this answer

Option A is correct because the `private` keyword restricts access to the class member so that it can only be accessed within the same class. Option C is correct because the `public` keyword allows access to the class member from any other class in any package. These are two of the four access modifiers in Java (private, default, protected, public) that directly control visibility and access to class members.

Exam trap

Oracle often tests the distinction between access modifiers (private, public) and non-access modifiers (static, abstract, final), so the trap here is that candidates confuse keywords that affect behavior or structure with those that control visibility and access to class members.

466
Multi-Selecthard

Which TWO of the following operations on String objects result in a new String object?

Select 2 answers
A."Hello".toString()
B."Hello".length()
C."Hello".charAt(0)
D."Hello".replace('l', 'p')
E."Hello".concat(" World")
AnswersD, E

Returns new string with replacements.

Why this answer

Option D is correct because `String.replace()` returns a new `String` object with the replacement applied, as `String` is immutable in Java. The original `"Hello"` remains unchanged, and a new string `"Heppo"` is created.

Exam trap

Oracle often tests the distinction between methods that return a new `String` versus those that return a primitive or the same reference, exploiting the common misconception that all `String` methods modify the original object.

467
MCQeasy

A developer writes a class 'Animal' with a method 'sound()'. The 'Cat' subclass overrides 'sound()'. If an Animal reference points to a Cat object, which method is called when sound() is invoked?

A.Runtime error
B.Cat's sound()
C.Animal's sound()
D.Compilation error
AnswerB

Correct. Java uses dynamic method dispatch for instance methods.

Why this answer

Polymorphism ensures that the overridden method in the actual object's class is called at runtime, even if the reference is of the superclass type.

468
Multi-Selectmedium

Which two of the following are valid ways to create a String object?

Select 2 answers
A.String s = "Hello";
B.String s = 12345;
C.String s = (String) new Integer(10);
D.String s = new String("Hello");
E.String s = 'Hello';
AnswersA, D

Valid string literal.

Why this answer

Option A creates a new String object via constructor. Option B creates a string literal. Option C is a char literal and not assignable to String.

Option D is an int literal. Option E is a cast that results in a compile-time error because Integer cannot be cast to String.

469
MCQeasy

Which of the following correctly declares and initializes an array of strings with the elements "A", "B", and "C"?

A.String[] arr = new String[] {"A", "B", "C"};
B.String[] arr = ("A", "B", "C");
C.String[] arr = ["A", "B", "C"];
D.String[] arr = {"A", "B", "C"};
AnswerD

Correct shorthand initialization.

Why this answer

Option D is correct because in Java, an array can be declared and initialized using the array initializer syntax with curly braces `{}` directly after the declaration, as in `String[] arr = {"A", "B", "C"};`. This is a shorthand that implicitly creates a new array object with the specified elements, and it is only valid in a declaration statement (not in an assignment to an already-declared variable).

Exam trap

Oracle often tests the distinction between the shorthand array initializer (using curly braces) and the anonymous array creation expression (using `new`), and the trap here is that candidates may incorrectly choose the `new` syntax (Option A) because it is also valid, but the exam expects the most direct and standard declaration form without the `new` keyword.

How to eliminate wrong answers

Option A is wrong because `String[] arr = new String[] {"A", "B", "C"};` is syntactically valid but it uses an anonymous array creation expression with an explicit `new` keyword, which is not the simplest or most direct way to declare and initialize in one line; however, the question asks for the correct declaration and initialization, and while this syntax works, it is not the standard shorthand that the exam expects (the exam considers the array initializer without `new` as the correct form for this context). Option B is wrong because `String[] arr = ("A", "B", "C");` uses parentheses, which is invalid syntax in Java for array initialization; parentheses are used for grouping expressions or method calls, not for array literals. Option C is wrong because `String[] arr = ["A", "B", "C"];` uses square brackets, which is invalid syntax in Java for array initialization; square brackets are used for array indexing or type declaration, not for defining array contents.

470
MCQeasy

What is the result of: int[] arr = new int[5]; System.out.println(arr[5]);

A.ArrayIndexOutOfBoundsException
B.null
C.-1
D.0
AnswerA

Correct. Runtime exception thrown.

Why this answer

Option A is correct because Java arrays are zero-indexed, meaning a valid index for an array of length 5 is 0 through 4. Accessing index 5 throws an ArrayIndexOutOfBoundsException at runtime, as it is outside the array's bounds.

Exam trap

Oracle often tests the misconception that accessing an out-of-bounds index returns a default value like 0 or null, or that Java silently wraps around, when in fact it always throws an exception.

How to eliminate wrong answers

Option B is wrong because an array of primitive int cannot store null; only object arrays can have null elements, and accessing an out-of-bounds index throws an exception, not returns null. Option C is wrong because Java does not return -1 for out-of-bounds array access; that behavior is specific to methods like String.indexOf(), not array indexing. Option D is wrong because while uninitialized int array elements default to 0, accessing an invalid index does not return the default value—it throws an exception.

471
Drag & Dropmedium

Arrange the steps to create an object from a class 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 define the class, then declare a variable, instantiate with new, assign to variable, and then use the object.

472
MCQeasy

What is the default value of a boolean variable in Java?

A.null
B.true
C.false
D.0
AnswerC

Correct.

Why this answer

In Java, the default value of a boolean variable (when declared as a class field or instance variable) is 'false'. This is specified by the Java Language Specification (JLS §4.12.5), which defines default values for all primitive types. Unlike local variables, which must be explicitly initialized, instance and static variables receive default values automatically.

Exam trap

Oracle often tests the distinction between default values for primitives vs. objects, and the trap here is that candidates confuse boolean's default with the default for Boolean (which is null) or mistakenly think boolean defaults to true or a numeric value.

How to eliminate wrong answers

Option A is wrong because 'null' is the default value for object references, not for primitive types like boolean. Option B is wrong because 'true' is not the default; the JLS explicitly states that the default for boolean is false. Option D is wrong because 0 is the default for numeric primitives (int, long, etc.), not for boolean, which is not a numeric type and cannot be assigned 0.

473
MCQhard

A developer creates an interface 'Drawable' with a single abstract method 'draw()'. They then create a class 'Circle' that implements Drawable but forgets to provide the draw() method. Circle is not declared abstract. What will happen when compiling Circle?

A.Compilation fails because interfaces cannot be implemented without overriding all methods
B.Compilation succeeds, a default empty method is generated
C.Compilation fails because Circle must either implement draw() or be declared abstract
D.Compilation succeeds but a warning is issued
AnswerC

Correct. The class must either implement the abstract method or be declared abstract itself.

Why this answer

A class that implements an interface must provide implementations for all abstract methods, or it must be declared abstract. Without the implementation and without being abstract, the class does not compile.

474
MCQhard

A developer encounters an ArrayIndexOutOfBoundsException while running a unit test. The stack trace shows the error occurs in a method that is called from many places. Which tool or technique would most efficiently identify the specific call path?

A.Review the code manually to trace all possible callers.
B.Set a breakpoint in the method and debug the test.
C.Run a static analysis tool to detect the issue.
D.Add log statements at the beginning of the method.
AnswerB

Debugging allows inspection of the call stack and variables.

Why this answer

Setting a breakpoint in the method and debugging the test allows the developer to inspect the call stack at runtime, immediately revealing the exact sequence of method invocations that led to the ArrayIndexOutOfBoundsException. This is the most efficient approach because it directly captures the specific call path without requiring manual tracing or post-hoc analysis.

Exam trap

Oracle often tests the misconception that static analysis tools can identify runtime call paths, but they only detect potential code issues, not the specific execution flow that leads to an exception.

How to eliminate wrong answers

Option A is wrong because manually reviewing all possible callers is time-consuming and error-prone, especially in a large codebase where the method is called from many places, and it does not guarantee identifying the exact runtime path that triggers the exception. Option C is wrong because static analysis tools can detect potential array index issues but cannot determine the specific runtime call path that leads to the exception, as they analyze code without execution context. Option D is wrong because adding log statements requires modifying code, recompiling, and re-running the test, which is less efficient than debugging and may not capture the exact state at the point of failure without extensive logging.

475
MCQeasy

Which data type should be used to store a single character like 'A'?

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

Correct: char stores a single 16-bit Unicode character.

Why this answer

In Java, the `char` data type is a single 16-bit Unicode character, capable of storing any character from the Unicode standard, including 'A'. It is the primitive type specifically designed for a single character, whereas `String` is a reference type for sequences of characters.

Exam trap

Oracle often tests the distinction between `char` and `String` by presenting a single character literal like 'A' and expecting candidates to recognize that `char` uses single quotes while `String` uses double quotes, leading some to incorrectly choose `String` due to familiarity with text handling.

How to eliminate wrong answers

Option A is wrong because `String` is a reference type used for sequences of characters, not a single character; using it for a single character introduces unnecessary object overhead. Option C is wrong because `byte` is an 8-bit integer type with a range of -128 to 127, which cannot directly represent most Unicode characters like 'A' without casting and loss of character semantics. Option D is wrong because `int` is a 32-bit integer type, which can technically hold a character's numeric value but is not intended for character storage and lacks the semantic clarity and type safety of `char`.

476
MCQhard

A developer is working on a Java application that processes user input. The application reads an integer from the command line using args[0], converts it to an int, and uses it in a loop. When testing, the application throws a NumberFormatException when the user provides an alphabetic string. The developer needs to handle this exception gracefully by prompting the user to enter a valid number and retrying. However, the developer must avoid infinite loops. The current code uses a while loop with a flag. Which approach ensures the code handles the exception, provides feedback, and terminates if the user enters 'quit'? The environment is a standard Java SE 11 application. The developer wants a robust solution without using external libraries.

A.Use a try-catch inside a loop that continues if exception caught, and breaks if input equals 'quit' or conversion succeeds.
B.Catch the exception and ignore it; the loop will naturally terminate.
C.Use a do-while loop that never checks for 'quit'; the exception is caught outside the loop.
D.Catch the exception in the loop and call System.exit(0) immediately.
AnswerA

Correct: handles exception, allows retry, and exits on 'quit'.

Why this answer

Option B is correct because it catches NumberFormatException, prints a message, and allows retry, but sets the flag to false if user enters 'quit' to exit.

477
MCQhard

Given the code: int[] arr = {1,2,3}; for(int x : arr) { if(x==2) continue; System.out.print(x); } What is the output?

A.2
B.Compilation error
C.13
D.123
AnswerC

1 and 3 are printed.

Why this answer

The enhanced for loop iterates over the array {1,2,3}. When x equals 2, the continue statement skips the remainder of the loop body for that iteration, so System.out.print(x) is not executed for 2. Thus, only 1 and 3 are printed, producing output '13'.

Exam trap

The trap here is that candidates often confuse continue with break, thinking continue terminates the loop entirely, or they forget that continue skips only the current iteration's remaining code, leading them to include the skipped value in the output.

How to eliminate wrong answers

Option A is wrong because it suggests the output is '2', but the continue statement skips printing 2, so 2 is not output. Option B is wrong because the code compiles successfully; the enhanced for loop and continue are valid Java syntax. Option D is wrong because it includes '2' in the output, but the continue statement prevents 2 from being printed, so the output is '13', not '123'.

478
MCQeasy

A developer writes a catch block that handles multiple exception types that have a subclass relationship. Which of the following is a valid use of the multi-catch feature?

A.catch (IOException | FileNotFoundException e) { ... }
B.catch (IOException e) { ... } catch (SomeOtherUnrelatedException e) { ... }
C.catch (FileNotFoundException | IOException e) { ... }
D.catch (IOException e) { ... } catch (FileNotFoundException e) { ... }
AnswerB

Separate catches are allowed; the more specific exception (if needed) should come first, but if they are unrelated, order doesn't matter. This approach is valid.

Why this answer

Option B is correct because it demonstrates the proper use of separate catch blocks for unrelated exception types, which is valid. The multi-catch feature (introduced in Java 7) allows catching multiple exception types in a single catch block only if they are not in a parent-child relationship; otherwise, the compiler reports an error due to unreachable code. Since IOException and SomeOtherUnrelatedException are unrelated, separate catch blocks are perfectly valid.

Exam trap

Cisco often tests the rule that multi-catch cannot contain exception types with a subclass relationship, and that separate catch blocks must order exceptions from most specific to most general to avoid unreachable code.

How to eliminate wrong answers

Option A is wrong because it attempts to catch IOException and FileNotFoundException in a multi-catch block, but FileNotFoundException is a subclass of IOException, making the catch for FileNotFoundException unreachable and causing a compilation error. Option C is wrong for the same reason as A — the order does not matter; the compiler still detects the subclass relationship and rejects the multi-catch. Option D is wrong because it places the more specific exception (FileNotFoundException) after the more general one (IOException), which means the FileNotFoundException catch block will never be executed (unreachable code), leading to a compilation error.

479
MCQhard

A team is developing a Java application that uses many third-party libraries. One library throws a checked exception that is not declared in its method signature. Which approach best handles this situation?

A.Ignore the exception because it is not declared.
B.Declare the library's exception in the method signature.
C.Wrap the exception in a RuntimeException and throw it.
D.Catch the exception and log it, then continue execution.
AnswerC

This satisfies the compiler and preserves the exception chain.

Why this answer

Option C is correct because a checked exception that is not declared in a method signature cannot be propagated without handling it. Wrapping it in a RuntimeException (an unchecked exception) bypasses the compiler's checked-exception enforcement, allowing the exception to be thrown without modifying the method signature. This is a common pattern when integrating third-party libraries that throw checked exceptions from methods that do not declare them.

Exam trap

The trap here is that candidates may think they can simply declare the library's exception in their own method signature (Option B), but the compiler requires the exception to be actually declared in the library's method signature, which it is not, making this approach invalid.

How to eliminate wrong answers

Option A is wrong because ignoring a checked exception that is not declared in the method signature will cause a compilation error; the compiler enforces that checked exceptions must be either caught or declared. Option B is wrong because you cannot declare an exception in your method signature that the library method does not declare; the compiler will not allow you to declare an exception that is not actually thrown by the called method. Option D is wrong because catching and logging the exception then continuing execution may mask critical failures, and it does not address the fact that the exception is not declared in the method signature, which still prevents compilation.

480
Multi-Selectmedium

Which TWO are benefits of using try-with-resources?

Select 2 answers
A.It ensures resources are closed even if an exception occurs
B.It eliminates the need for finally block entirely
C.Resources are closed automatically only if no exception occurs
D.Resources are closed in reverse order of declaration
E.It requires that resources implement the Closeable interface
AnswersA, D

Yes, closure happens automatically on any exit.

Why this answer

Option A is correct because the try-with-resources statement ensures that each resource declared in the try clause is automatically closed at the end of the statement, regardless of whether an exception occurs. This is achieved by the Java compiler generating implicit finally blocks that call the close() method on each resource, even if an exception is thrown during the try block or during the closing of another resource.

Exam trap

Oracle often tests the distinction between AutoCloseable and Closeable, and the misconception that resources are only closed if no exception occurs, leading candidates to incorrectly select Option C or E.

481
Multi-Selecthard

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

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

int is a primitive integer type.

Why this answer

Option A is correct because `int` is a primitive data type in Java that stores 32-bit signed integer values. Primitive types are predefined by the language and are not objects, meaning they are stored directly on the stack for efficiency.

Exam trap

Oracle often tests the distinction between primitive types and commonly used reference types like `String` and `Object`, exploiting the misconception that `String` behaves like a primitive because of its special language support (e.g., string literals and the `+` operator).

482
MCQhard

A company wants to run existing Java SE application code on an embedded device with limited resources. Which Java edition is designed for such environments?

A.Java Card
B.Java FX
C.Java EE (Enterprise Edition)
D.Java ME (Micro Edition)
AnswerD

Java ME is tailored for embedded and mobile devices.

Why this answer

Option C is correct because Java ME (Micro Edition) is for embedded and mobile devices with constrained resources. Option A (Java Card) is for smart cards. Option B (Java EE) is for enterprise servers.

Option D (Java FX) is a UI framework, not an edition.

483
MCQeasy

A developer writes the following code: int x = 5; System.out.println(x++); What is the output?

A.Compilation error
B.5
C.6
D.Runtime exception
AnswerB

x++ returns 5, then x becomes 6.

Why this answer

The expression `x++` is a post-increment operator, which returns the current value of `x` (5) before incrementing it. Therefore, `System.out.println(x++)` prints 5, and then `x` becomes 6. Option B is correct because the output is the original value of `x`.

Exam trap

Oracle often tests the difference between post-increment and pre-increment operators, where candidates mistakenly think `x++` prints the incremented value (6) instead of the original value (5).

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; post-increment is a valid Java operator. Option C is wrong because it reflects a misunderstanding of post-increment vs. pre-increment; `x++` prints the value before increment, not after. Option D is wrong because no runtime exception occurs; the operation is well-defined and safe.

484
MCQmedium

A developer wants to create a class that can be used to represent different types of vehicles (e.g., Car, Truck, Motorcycle) and each vehicle type should be able to start its own engine in a specific way. Which OOP concept should be used to allow the vehicle class to define a common interface while letting subclasses provide specific implementations?

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

Polymorphism allows a common interface to have different implementations, achieved via method overriding.

Why this answer

Polymorphism allows the Vehicle class to define a common method (e.g., startEngine()) that each subclass (Car, Truck, Motorcycle) overrides with its own specific implementation. When the method is called on a Vehicle reference, the JVM uses dynamic method dispatch at runtime to invoke the correct subclass version, enabling different engine-starting behaviors through a single interface.

Exam trap

Oracle often tests the distinction between abstraction (defining the interface) and polymorphism (using that interface to invoke different implementations at runtime), so candidates mistakenly choose abstraction when the question emphasizes 'specific implementations' and runtime behavior.

How to eliminate wrong answers

Option B (Inheritance) is wrong because inheritance alone only provides code reuse and a parent-child relationship; it does not inherently allow different subclass implementations to be invoked through a common interface at runtime. Option C (Encapsulation) is wrong because encapsulation focuses on hiding internal state via private fields and public accessors, not on defining a common interface with multiple implementations. Option D (Abstraction) is wrong because abstraction (e.g., abstract classes or interfaces) defines the contract but does not by itself enable runtime selection of specific implementations; that runtime behavior is polymorphism.

485
MCQmedium

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

A.HelloWorld
B.Hello World
C.Compilation error
D.Hello World
AnswerD

Correct: concatenation yields 'Hello World'.

Why this answer

Option D is correct because the + operator performs string concatenation in Java. s1 + s2 combines "Hello" and " World" to produce "Hello World", which is then printed. The space is part of s2, so the output includes it.

Exam trap

Oracle often tests whether candidates notice the leading space in s2 (" World") versus assuming no space, leading them to choose Option A ("HelloWorld") instead of the correct output with the space.

How to eliminate wrong answers

Option A is wrong because it omits the space between "Hello" and "World", but s2 starts with a space, so the concatenation includes it. Option B is wrong because it shows "Hello World" without the leading space, but the actual output is "Hello World" with the space from s2. Option C is wrong because the code compiles and runs without error; string concatenation with + is valid Java syntax.

486
MCQmedium

During execution, the JVM uses Just-In-Time (JIT) compilation. What is its primary benefit?

A.Translates bytecode into an intermediate language for interpretation.
B.Improves execution speed by compiling frequently used bytecode to native code.
C.Converts Java source code directly into bytecode.
D.Enhances security by verifying bytecode integrity.
AnswerB

JIT identifies hot spots and compiles them for faster execution.

Why this answer

Option A is correct because JIT compiles bytecode to native machine code at runtime for performance improvement. Option B is incorrect because JIT does not generate bytecode. Option C is incorrect because JIT does not translate to intermediate languages.

Option D is incorrect because JIT is not for security.

487
Multi-Selecthard

Which THREE statements are true about method overloading in Java?

Select 3 answers
A.Two methods with the same name, same parameter types, but different return types are overloaded.
B.The return type can be different, but it is not sufficient to differentiate overloaded methods.
C.Method overloading is resolved at runtime.
D.Overloaded methods can be defined in the same class.
E.Overloaded methods must have different parameter lists.
AnswersB, D, E

Return type alone does not distinguish overloads.

Why this answer

Option B is correct because in Java, method overloading requires methods to have different parameter lists. While the return type can be different, it alone is not sufficient to differentiate overloaded methods; the compiler uses the method signature (name + parameter types) to resolve overloads, and return type is not part of the signature.

Exam trap

The trap here is that candidates often confuse overloading with overriding, mistakenly thinking that return type or runtime resolution plays a role in overloading, when in fact overloading is purely compile-time and based on parameter lists.

488
MCQmedium

A developer is writing a Java application that processes a large number of transactions. The application must ensure that each transaction is committed only if all steps complete successfully, otherwise the entire transaction should be rolled back. Which Java concept should the developer use to implement this requirement?

A.Exception handling
B.Inheritance
C.Multithreading
D.Encapsulation
AnswerA

Exception handling can catch failures and trigger rollback.

Why this answer

Option A is correct because exception handling in Java allows the developer to catch runtime failures (e.g., SQLException, IOException) within a try block and, in the catch block, invoke a rollback on the transaction (e.g., Connection.rollback()). If all steps succeed, the transaction is committed via Connection.commit(). This ensures atomicity — the 'all-or-nothing' property required for transaction processing.

Exam trap

Oracle often tests whether candidates confuse 'transaction management' with 'multithreading' — the trap here is assuming that concurrent execution (Option C) is needed for atomicity, when in fact atomicity is enforced by exception handling and explicit commit/rollback calls, not by running steps in parallel.

How to eliminate wrong answers

Option B is wrong because inheritance is a mechanism for code reuse and establishing type hierarchies (e.g., extends), not for controlling transactional commit/rollback behavior. Option C is wrong because multithreading deals with concurrent execution of tasks (e.g., using Thread or Runnable), not with ensuring atomicity of a single transaction's steps. Option D is wrong because encapsulation hides internal state and exposes methods via access modifiers (e.g., private fields with public getters/setters), which does not provide any mechanism for conditional commit or rollback.

489
MCQmedium

A developer runs the command shown in the exhibit. The developer wants to ensure the application uses the latest available language features. Which action should the developer take?

A.Download and install a newer version of the JDK.
B.Enable lambda expressions by setting the -enable-lambdas flag.
C.Use the -source and -target flags to compile for a newer version.
D.Upgrade the JVM to the latest version.
AnswerA

A newer JDK includes both compiler and runtime with latest features.

Why this answer

Option A is correct because the latest available language features (e.g., pattern matching, sealed classes, records) are tied to the JDK version. Downloading and installing a newer JDK provides both the compiler (javac) and runtime (JVM) that support those features. Simply upgrading the JVM (Option D) or using -source/-target flags (Option C) does not enable new language syntax in the compiler if the JDK itself is outdated.

Exam trap

The trap here is that candidates confuse upgrading the JVM (runtime) with upgrading the JDK (development kit), or think that compiler flags like -source and -target can retroactively add new language features to an older JDK.

How to eliminate wrong answers

Option B is wrong because there is no -enable-lambdas flag in Java; lambda expressions were introduced in Java 8 and are enabled by default when using a JDK 8 or later. Option C is wrong because the -source and -target flags only control the version of source code accepted and the class file format produced, but they do not add new language features to an older JDK; you need a newer JDK to compile with newer syntax. Option D is wrong because upgrading only the JVM (runtime) does not give the compiler access to new language features; the JDK (which includes javac) must also be updated.

490
MCQmedium

An application requires storing a fixed set of 12 monthly temperatures. Which initialization is most appropriate?

A.ArrayList<Double> temps = new ArrayList<>();
B.double[] temps = new double[12];
C.double[] temps = {15.5, 16.2, 18.0, 20.1, 23.4, 27.8, 30.0, 29.5, 26.2, 22.0, 18.5, 16.0};
D.double temps[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
AnswerC

Directly initializes with the needed values.

Why this answer

Option C is correct because it initializes a fixed-size array of 12 doubles with the actual monthly temperature values in a single statement, which is the most appropriate for storing a fixed set of 12 values. The array size is implicitly determined by the number of elements in the initializer list, and the syntax is concise and readable for this use case.

Exam trap

Oracle often tests the distinction between array declaration with an initializer list versus just allocating an array with default values, and the trap here is that candidates may choose Option B because it specifies the correct size, but overlook that it does not actually store the required temperature data.

How to eliminate wrong answers

Option A is wrong because ArrayList<Double> is a resizable collection, which is unnecessary and less efficient for a fixed set of 12 values; it also requires autoboxing for primitive doubles, adding overhead. Option B is wrong because it only declares an array of size 12 with default values (0.0), but does not initialize it with the actual temperature data, so it is incomplete for the requirement of storing the fixed set of monthly temperatures. Option D is wrong because it initializes all 12 elements to 0.0, which does not represent the actual monthly temperatures and is not the most appropriate initialization for the given data.

491
MCQhard

A company's legacy code has a method that takes an array of integers and returns a new array containing only the positive numbers. The current implementation uses a fixed-size array equal to the input size and counts positive numbers, then copies them, but if many negatives exist, the result array has trailing zeros (which are removed by copying again). This wastes memory and time. The array can be large (up to 1 million elements). The developer wants to improve memory efficiency and runtime without using external libraries. Which approach should they implement?

A.Use an ArrayList to collect positive numbers, then convert to int[].
B.Use a stream to filter and collect to array.
C.First count positives, then create an array of that exact size, fill it.
D.Use a linked list and then convert.
AnswerC

Efficient: exactly allocated array, O(n) time.

Why this answer

Option C is correct because it avoids the overhead of dynamic resizing (as in ArrayList) or boxing (as in streams) by first counting the positives in a single pass, then creating an exact-sized int[] array, and filling it in a second pass. This yields O(n) time complexity and minimal memory overhead, directly addressing the legacy code's inefficiency without external libraries.

Exam trap

Oracle often tests the misconception that ArrayList or streams are always more efficient, but here the constraint 'without using external libraries' and the need for primitive efficiency make the two-pass counting approach the correct choice.

How to eliminate wrong answers

Option A is wrong because ArrayList<Integer> requires autoboxing each int to Integer, consuming more memory and CPU, and its internal array may need resizing, adding overhead. Option B is wrong because streams involve boxing overhead and are not allowed per the constraint 'without using external libraries' (streams are part of java.util.stream, which is an external library in the context of the legacy code). Option D is wrong because a linked list has O(n) memory overhead per node and requires conversion to int[], adding extra passes and memory churn.

492
MCQhard

Given int[] arr = {1,2,3}; which correctly creates a new array with length 5 and copies the contents of arr?

A.int[] newArr = new int[5]; newArr = arr;
B.int[] newArr = arr.clone(); newArr.length = 5;
C.int[] newArr = Arrays.copy(arr, 5);
D.int[] newArr = Arrays.copyOf(arr, 5);
AnswerD

Arrays.copyOf creates a new array with specified length and copies elements.

Why this answer

Option D is correct because `Arrays.copyOf(int[] original, int newLength)` creates a new array of the specified length (5) and copies the elements from the original array into it, padding with default values (0 for int) for any extra positions. This method is specifically designed for this task, ensuring the original array remains unchanged.

Exam trap

The trap here is that candidates often confuse reference assignment (`=`) with array copying, or they misremember the exact method name (`Arrays.copy` vs `Arrays.copyOf`), leading them to pick options that either fail to copy or do not compile.

How to eliminate wrong answers

Option A is wrong because `newArr = arr;` merely assigns the reference of `arr` to `newArr`, discarding the previously allocated `new int[5]` array; both variables then point to the same 3-element array, so no copy occurs and the length is not 5. Option B is wrong because `arr.clone()` creates a new array of the same length (3), and `newArr.length = 5;` is a compile-time error — array length is final and cannot be reassigned. Option C is wrong because `Arrays.copy(arr, 5)` is not a valid method; the correct method name is `Arrays.copyOf`, and `Arrays.copy` does not exist in the standard Java library.

493
Multi-Selectmedium

Which TWO of the following are valid ways to create a String?

Select 2 answers
A.String s = 'Hello';
B.String s = new String("Hello");
C.String s = 123;
D.String s = String.valueOf("Hello");
E.String s = "Hello";
AnswersB, E

Correct.

Why this answer

Option B is correct because it uses the `new` keyword to explicitly create a new String object in the heap, which is a valid way to instantiate a String. Option E is correct because it uses a string literal, which is the most common and efficient way to create a String in Java, leveraging the string constant pool.

Exam trap

Oracle often tests the distinction between string literals and `new String()`, and the trap here is that candidates may think `String.valueOf("Hello")` creates a new String, when it actually returns the same reference from the pool, making it not a valid 'creation' in the exam's intended sense.

494
MCQhard

A developer is working on a Java application that processes user input. The application reads a string from the console and needs to compare it with a predefined constant string "ADMIN". The developer writes the following code: if (input == "ADMIN") { grantAccess(); }. During testing, the condition sometimes fails even when the user enters ADMIN. The input string is obtained via Scanner.nextLine(). Which is the most likely cause and best fix?

A.Use input.equals("ADMIN") instead of ==.
B.Use input.compareTo("ADMIN") == 0.
C.Use input == "ADMIN" with intern() on input.
D.Convert input to char array and compare.
AnswerA

Correct because equals compares values.

Why this answer

Option A is correct because `==` compares object references, not string content. `Scanner.nextLine()` returns a new `String` object, so `input == "ADMIN"` compares references, which are different even if the content matches. Using `input.equals("ADMIN")` compares the actual character sequence, which is the correct way to test string equality in Java.

Exam trap

Oracle often tests the distinction between reference equality (`==`) and value equality (`equals()`) for strings, exploiting the common misconception that `==` compares string content because it works for primitive types.

How to eliminate wrong answers

Option B is wrong because `compareTo()` returns an integer (0 if equal) and is intended for ordering, not simple equality; it works but is less readable and more error-prone than `equals()`. Option C is wrong because calling `intern()` on `input` would force it into the string pool, making `==` work, but this is an unnecessary performance hit and not the idiomatic fix; the standard practice is to use `equals()`. Option D is wrong because converting to a char array and comparing element-by-element is overly complex, inefficient, and not the standard Java approach for string comparison.

495
Multi-Selectmedium

Which three statements about constructors in Java are true? (Choose three.)

Select 3 answers
A.The default constructor has no parameters
B.Constructors can be abstract
C.Constructors cannot return a value
D.Constructors can be overloaded
E.Constructors can be final
AnswersA, C, D

Correct. If no constructor is defined, the compiler adds a no-argument constructor.

Why this answer

Constructors can be overloaded to provide different initialization options, they cannot return a value (not even void), and if no constructor is defined, the compiler provides a default no-arg constructor.

496
MCQeasy

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

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

a and b refer to same array.

Why this answer

Option C is correct because in Java, arrays are reference types. When `int[] b = a;` is executed, `b` does not create a new array; it simply references the same array object as `a`. Therefore, modifying `b[0]` directly changes the element in the original array `a`, so `a[0]` prints 99.

Exam trap

The trap here is that candidates often confuse reference assignment with copying the array contents, leading them to incorrectly believe that `b[0] = 99;` only affects `b` and not `a`.

How to eliminate wrong answers

Option A is wrong because it assumes the default value for an array element is 0, but the array was initialized with values and then modified via the reference. Option B is wrong because it assumes that `b` is a copy of `a` and that changes to `b` do not affect `a`, which is a misunderstanding of reference assignment in Java. Option D is wrong because the code compiles without error; the assignment `int[] b = a;` is valid, and `b[0] = 99;` is a legal assignment to an array element.

497
MCQmedium

What is the scope of a variable declared inside a for loop?

A.Inside the package
B.Only inside the loop block
C.Inside the class
D.Inside the entire method
AnswerB

Correct: variables declared in for loop are local to that block.

Why this answer

In Java, a variable declared inside a for loop (including the initialization block or the loop body) has block scope, meaning it is only accessible within the loop block itself. This is defined by the Java Language Specification (JLS §6.10), which states that the scope of a local variable declaration is the rest of the block in which the declaration appears. Once the loop completes, the variable goes out of scope and cannot be referenced.

Exam trap

Oracle often tests the misconception that a variable declared in the for loop's initialization block has method-level scope, leading candidates to incorrectly choose 'Inside the entire method' when the variable is actually scoped only to the loop block.

How to eliminate wrong answers

Option A is wrong because a variable declared inside a for loop is not accessible at the package level; package scope applies to members declared with default (package-private) access within a class, not to local variables. Option C is wrong because class scope applies to instance or static fields declared directly in the class body, not to variables declared inside a loop. Option D is wrong because method scope would allow the variable to be used anywhere within the method, but a variable declared inside a for loop is confined to the loop block and cannot be accessed after the loop ends.

498
MCQhard

A developer is working on a Java program that processes sensor data. The data is stored in a 2D array 'double[][] readings', where each row represents a sensor and each column a time interval. The method 'public static double[] averagePerSensor(double[][] data)' should compute the average reading for each sensor (row) and return a 1D array of averages. The developer writes the following implementation: 'double[] result = new double[data.length]; for (int i = 0; i < data.length; i++) { double sum = 0; for (int j = 0; j < data[i].length; j++) { sum += data[i][j]; } result[i] = sum / data[i].length; } return result;'. However, the program sometimes throws a NullPointerException. What is the most likely cause?

A.The method returns a double[] but should return double[][].
B.The rows have different numbers of columns.
C.One or more rows in the 2D array are null.
D.The outer loop uses data[i].length instead of data.length.
AnswerC

Accessing length on null row causes NPE.

Why this answer

The NullPointerException occurs because the code attempts to access `data[i].length` when `data[i]` is null. In Java, a 2D array is an array of arrays, and any row can be null. The code does not check for null rows before iterating over the columns, so if a row is null, accessing `data[i][j]` or `data[i].length` throws a NullPointerException.

Option C correctly identifies this as the most likely cause.

Exam trap

Oracle often tests the distinction between a null row and a row with zero columns, where candidates mistakenly think a zero-length row causes the exception, but only a null reference triggers a NullPointerException when accessing array length or elements.

How to eliminate wrong answers

Option A is wrong because the method signature correctly returns `double[]` (a 1D array of averages), not `double[][]`. Option B is wrong because rows having different numbers of columns is allowed in Java (jagged arrays) and does not cause a NullPointerException; the inner loop correctly uses `data[i].length` to handle varying lengths. Option D is wrong because the outer loop correctly uses `data.length` to iterate over rows; using `data[i].length` would be incorrect but would cause an ArrayIndexOutOfBoundsException, not a NullPointerException.

499
Multi-Selecteasy

Which three statements about arrays are correct? (Choose three.)

Select 3 answers
A.The size of an array can change after creation.
B.Arrays are objects in Java.
C.The length of an array must be specified at compile time with a constant expression.
D.Arrays can store both primitive and object types.
E.Array indices start at 0.
AnswersB, D, E

Arrays inherit from Object and have methods like clone().

Why this answer

Option B is correct because in Java, arrays are objects that are dynamically created and can be assigned to variables of type Object, cloned via the clone() method, and have a length field (not a method). They inherit from java.lang.Object and are treated as reference types, even when they store primitive values.

Exam trap

The trap here is that candidates often confuse the compile-time constant requirement for array lengths with the fact that the length can be a runtime expression, leading them to incorrectly select option C as correct.

500
MCQeasy

A security-sensitive class should not be extended by any other class. Which modifier should be applied to the class declaration?

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

Correct. A final class cannot be extended.

Why this answer

The final modifier prevents a class from being subclassed, which is appropriate for security or design reasons.

501
Multi-Selecthard

Which three of the following are valid ways to declare and initialize a variable of type int? (Choose three.)

Select 3 answers
A.int b = 0xA;
B.int e = 10.0;
C.int d = 010;
D.int c = 0b2;
E.int a = 10;
AnswersA, C, E

Correct: hexadecimal literal 0xA equals 10 decimal.

Why this answer

Option A is correct because `0xA` is a hexadecimal integer literal in Java, representing the decimal value 10. Java allows hexadecimal literals using the prefix `0x` or `0X`, and they are valid for initializing an `int` variable.

Exam trap

Oracle often tests the distinction between valid integer literal formats and invalid ones, such as using a digit 2 in a binary literal or assigning a floating-point literal without a cast, which candidates might overlook due to familiarity with other languages.

502
MCQeasy

What is the value of the expression (10 > 5) && (3 < 2)?

A.1
B.true
C.false
D.0
AnswerC

The second condition is false.

Why this answer

The expression (10 > 5) evaluates to true, and (3 < 2) evaluates to false. The logical AND operator (&&) returns true only if both operands are true. Since one operand is false, the entire expression evaluates to false.

In Java, the result of a boolean expression is a boolean literal, not an integer.

Exam trap

Oracle often tests the distinction between boolean and integer types in Java, trapping candidates who expect true/false to be represented as 1/0 as in C or JavaScript.

How to eliminate wrong answers

Option A is wrong because 1 is an integer literal, but the && operator in Java returns a boolean (true or false), not an int. Option B is wrong because the expression does not evaluate to true; the second operand (3 < 2) is false, making the entire AND expression false. Option D is wrong because 0 is an integer literal, and Java does not implicitly convert integers to booleans in logical expressions; the result is a boolean false, not the integer 0.

503
MCQhard

Refer to the exhibit. The code at line 6 of ArrayExample.java is: int[] arr = {10, 20, 30, 40, 50}; int sum = 0; for (int i = 0; i <= arr.length; i++) sum += arr[i]; Which change fixes the exception?

A.Change array declaration to int[] arr = new int[6];
B.Change loop initialization to i = 1
C.Change loop condition to i < arr.length
D.Change arr.length to arr.length - 1
AnswerC

Stops before index 5, which is out of bounds.

Why this answer

Option A corrects the loop condition to avoid accessing index arr.length. Option B changes the start index, still causes out of bounds. Option C fixes the length but not the loop condition.

Option D changes the array size but not the loop.

504
MCQeasy

A developer writes: int x; System.out.println(x); What is the result?

A.null
B.Compilation fails
C.Runtime error
D.0
AnswerB

Correct. The variable x is not initialized.

Why this answer

Local variables must be initialized before use. x is not initialized, so compilation fails.

505
MCQeasy

Refer to the exhibit. Which statement is true about the InvalidInputException class?

A.It cannot be thrown by a method.
B.It is a checked exception.
C.It is an unchecked exception.
D.It can only be caught in a finally block.
AnswerB

Extending Exception (not RuntimeException) creates a checked exception.

Why this answer

The InvalidInputException class extends Exception, which makes it a checked exception. Checked exceptions must be either caught or declared in the method signature using 'throws', otherwise the code will not compile. This is the core reason why option B is correct.

Exam trap

Oracle often tests whether candidates confuse checked and unchecked exceptions by presenting a custom exception class that extends Exception (checked) but looks like it might be unchecked because of its name or usage context.

How to eliminate wrong answers

Option A is wrong because a checked exception like InvalidInputException can be thrown by a method using the 'throw' statement, as long as the method declares it with 'throws'. Option C is wrong because InvalidInputException extends Exception, not RuntimeException, so it is a checked exception, not an unchecked exception. Option D is wrong because a checked exception can be caught in a try block or propagated, not only in a finally block; the finally block is for cleanup code and does not catch exceptions by itself.

506
MCQmedium

Which design principle is violated by making all fields public in a class?

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

Encapsulation hides internal data; public fields expose it.

Why this answer

Making all fields public violates the principle of encapsulation, which requires that an object's internal state be hidden from external access and only modifiable through controlled methods (getters/setters). In Java, public fields allow any class to directly read or modify the field, breaking data integrity and the ability to enforce invariants. Encapsulation is a core OOP concept that protects the internal representation of an object.

Exam trap

Oracle often tests the distinction between OOP principles by presenting a scenario that seems to involve inheritance or abstraction, but the core violation is always about data hiding and controlled access—candidates mistakenly choose 'abstraction' because they confuse hiding implementation details with hiding data fields.

How to eliminate wrong answers

Option A is wrong because inheritance is a mechanism for creating class hierarchies (using extends), not a design principle about field visibility; public fields do not prevent inheritance. Option B is wrong because abstraction focuses on hiding implementation details behind interfaces or abstract classes, not on field access control; public fields can still exist within an abstract design. Option D is wrong because polymorphism relies on method overriding and interface implementation, not on field access modifiers; public fields do not affect polymorphic behavior.

507
MCQhard

A developer uses a switch statement with a String variable. Which is true about this usage?

A.It works only with primitive types
B.It causes a compilation error because strings are not supported
C.It works with strings starting from Java 7
D.It requires a default case
AnswerC

Switch on strings is valid since Java 7.

Why this answer

Option C is correct because, starting from Java 7 (JSR 334), the switch statement supports String objects in addition to primitive types and enums. The compiler uses the `hashCode()` and `equals()` methods of the String class to evaluate the switch expression against case labels, making it a valid and efficient way to branch on string values.

Exam trap

Oracle often tests the Java version where String support was introduced (Java 7), and the trap here is that candidates who learned Java before 7 or who confuse switch with older limitations may incorrectly think Strings are not allowed or that only primitives work.

How to eliminate wrong answers

Option A is wrong because switch statements in Java support not only primitive types (int, char, byte, short) but also enumerated types and, since Java 7, String objects. Option B is wrong because String support was explicitly added in Java 7; it does not cause a compilation error in Java 7 or later. Option D is wrong because a default case is optional in a switch statement; it is only required if you need to handle values that do not match any case label, but the compiler does not enforce its presence.

508
MCQmedium

A developer is implementing a login verification method that compares a user-entered password against a stored hash. The passwords are stored as String objects. Which approach ensures correct comparison?

A.if (enteredPassword.compareTo(storedHash) == 0)
B.if (enteredPassword.equals(storedHash))
C.if (enteredPassword == storedHash)
D.if (enteredPassword.hashCode() == storedHash.hashCode())
AnswerB

Compares string content correctly.

Why this answer

Option B is correct because String.equals() compares the actual content. Option A uses reference equality, which is incorrect. Option C uses hash codes which may have collisions.

Option D uses compareTo which is for lexicographic order, not equality.

Page 6

Page 7 of 7

All pages