Courseiva

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

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

Page 5

Page 6 of 7

Page 7
376
MCQhard

What is the value of y after executing the following code? ```java int y = 10 + 12; ```

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

The value of y is 22 because Java's operator precedence rules dictate that multiplication operations are evaluated before addition. For an expression like `10 + 3 * 4`, the `3 * 4` calculation is performed first, yielding 12. Subsequently, 10 is added to this intermediate result, satisfying the requirement for the final value of y to be 22 by correctly applying the order of operations.

Why this answer

The code snippet `int y = 10 + 12;` performs integer addition, resulting in y = 22. Java's primitive arithmetic follows standard rules, so adding 10 and 12 yields 22 without any overflow or conversion issues.

Exam trap

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

How to eliminate wrong answers

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

377
Multi-Selecthard

Which TWO statements about interfaces in Java are true?

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

Interfaces can extend other interfaces.

Why this answer

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

378
MCQeasy

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

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

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

Why this answer

The JDK (Java Development Kit) is a software development environment used for developing Java applications. It includes the JRE (Java Runtime Environment) plus development tools such as the Java compiler (javac), debugger, and other utilities. In contrast, the JRE provides only the runtime environment needed to run Java applications.

Therefore, option D is correct because the JDK includes compilers and tools for development. Option A is incorrect because the JDK provides far more than just a debugger and profiler; it includes the compiler and other essential tools. Option B is incorrect because the JDK includes the JRE, not the other way around.

Option C is incorrect because the JRE is required to run Java applications, while the JDK is needed for development; the JDK is not required to run applications.

379
MCQhard

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

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

FileNotFoundException is a subclass of IOException, allowed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

380
Multi-Selecthard

Which TWO statements are true about interfaces in Java?

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

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

Why this answer

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

Exam trap

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

381
MCQeasy

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

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

This is the correct value 11.

Why this answer

Multiplication has higher precedence than addition: 4 * 2 = 8, then 3 + 8 = 11. Therefore, x is 11, making option A the correct answer.

382
MCQhard

Given the following code, String s1 = new String("example"); String s2 = "example"; System.out.println(s1 == s2); Why does the code output false?

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

Correct: this explains the difference in references.

Why this answer

The code likely creates s1 using the 'new' operator, which forces the creation of a new String object in the heap, not in the string pool. s2 is a string literal, which is interned and placed in the string pool. The '==' operator compares object references, so s1 and s2 refer to different objects, hence the comparison returns false.

383
MCQeasy

What is the value of 10 % 3?

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

Correct: 10 ÷ 3 = 3 remainder 1.

Why this answer

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

384
MCQhard

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

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

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

Why this answer

Platform independence via JVM. The Java Virtual Machine (JVM) abstracts the underlying operating system and hardware, so bytecode compiled on any platform can run on any other platform that has a compatible JVM. This allows the same bytecode to run on Windows, Linux, and macOS without modification.

Option A (Bytecode verification) is a security check that validates bytecode before execution, but it does not provide cross-platform portability. Option C (Just-in-Time compilation) optimizes performance by compiling bytecode to native code at runtime, but it is not essential for platform independence. Option D (Thread synchronization) is a concurrency control mechanism that prevents race conditions, but it does not affect cross-platform execution.

385
MCQhard

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

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

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

Why this answer

The performance and memory issues are caused by using String concatenation (+=) inside a loop, which creates many intermediate String objects because Strings are immutable in Java. StringBuilder is mutable and designed for efficient string concatenation without creating intermediate objects, making it the optimal solution. Option A (StringBuilder) is correct.

Option B (calling intern()) would not improve performance and could degrade it. Option C (increasing heap size) only postpones the OutOfMemoryError and does not fix the inefficiency. Option D (StringBuffer) is thread-safe but slower due to synchronization; it is unnecessary in this single-threaded context.

Therefore, replacing concatenation with StringBuilder is the most effective resolution.

386
Multi-Selecteasy

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

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

Correct usage.

Why this answer

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

Exam trap

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

387
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

388
MCQhard

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

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

== compares references, and they are different.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

389
Multi-Selectmedium

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

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

$ is allowed.

Why this answer

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

Exam trap

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

390
Matchingmedium

Match each access modifier to its visibility level.

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

Concepts
Matches

Accessible from anywhere

Accessible within same package and subclasses

Accessible only within same package

Accessible only within same class

Why these pairings

In Java, access modifiers control visibility: private (class-only), default (package), protected (package + subclasses), public (everywhere). Common mistakes include confusing private with default and protected with private.

391
Multi-Selectmedium

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

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

5 < 10 true.

Why this answer

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

Exam trap

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

392
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

393
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

394
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

395
MCQmedium

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

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

Correct because concat does not modify s.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

396
MCQeasy

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

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

Try-with-resources automatically closes AutoCloseable resources.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

397
MCQmedium

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

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

This line uses the well-defined constant Long.MAX_VALUE, which is clear and maintainable.

Why this answer

The correct answer is E. Long.MAX_VALUE is the standard and readable way to obtain the maximum long value. While option D (9223372036854775807L) is syntactically valid, it is not recommended because it is error-prone and does not clearly convey intent.

Options A and C are incorrect: A has an unnecessary cast, and C omits the L suffix, causing a compile error. Option B exceeds the long range.

Exam trap

Candidates may be tempted to use a numeric literal with L suffix, but the best practice is to use the Long.MAX_VALUE constant to avoid typos and improve readability.

How to eliminate wrong answers

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

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

398
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

399
MCQmedium

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

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

Correct: the original array is unchanged.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

400
MCQmedium

What is printed when the main method runs?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

401
MCQmedium

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

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

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

Why this answer

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

402
MCQeasy

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

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

java runs the JVM.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

403
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

404
MCQhard

Refer to the exhibit. What is the output?

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

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

Why this answer

The exhibit shows code that initializes an integer array with values 1 through 5. The enhanced for loop iterates over each element, adding each value to the variable 'sum' (starting at 0). After summing all five elements (1+2+3+4+5), sum equals 15.

The code then prints the value of sum minus 3, which is 12. Therefore, option C is correct.

Exam trap

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

How to eliminate wrong answers

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

405
MCQmedium

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

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

Final methods cannot be overridden.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

406
MCQeasy

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

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

char is a 16-bit Unicode character.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

407
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

408
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

409
MCQhard

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

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

This option logs all orders, including cancelled ones, but it does not skip processing correctly; it still calls process(order) for cancelled orders if the condition is not properly set. The explanation in the stem misstates this option's effect.

Why this answer

Option A correctly logs all orders, including cancelled ones, by placing log(order) outside the if block. It processes only non-cancelled orders, avoiding the exception. Option C (continue) would skip both process and logging, failing to log cancelled orders.

Option B unnecessarily complicates the loop and may still encounter index issues, while Option D modifies the array, which is prohibited. Therefore, A is the best choice.

410
MCQhard

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

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

Sorts ascending, then reversing yields descending order.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

411
MCQeasy

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

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

Private members are accessible only within the same class.

Why this answer

Private members are accessible only within the same class.

412
MCQeasy

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

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

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

Why this answer

The correct approach is Option D. The current code catches Exception generically, which prevents the specific handling of PaymentException. Option D catches Exception, checks if it is an instance of PaymentException, updates the order status and sends notification, and then does not rethrow the exception.

This satisfies the business requirements without changing the method signature or propagating any exception to the caller. Option A is incorrect because rethrowing a RuntimeException still propagates an exception. Option B is incorrect because declaring throws Exception propagates the checked exception.

Option C is incorrect because a finally block would execute even on success, leading to incorrect notifications and status updates.

413
MCQeasy

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

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

Simplest and clearest for iterating over all elements.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

414
MCQmedium

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

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

Condition false, assigns 20.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

415
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

416
MCQeasy

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

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

ArrayIndexOutOfBoundsException is thrown at runtime.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

417
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

418
MCQmedium

Which of the following is a valid Java identifier?

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

Underscore allowed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

419
MCQhard

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

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

Elements must implement Comparable.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

420
MCQhard

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

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

Exits the outer loop immediately.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

421
MCQhard

Refer to the exhibit. What is the output?

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

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

Why this answer

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

422
MCQmedium

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

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

Maintains insertion order, fast iteration.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

423
Multi-Selecthard

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

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

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

Why this answer

In Java, arrays are objects, and when you pass an array to a method, you pass a copy of the reference to the array. This means the method can modify the contents of the array (e.g., change element values), and those changes are reflected in the original array because both the caller and the method refer to the same array object in heap memory.

Exam trap

The trap here is that candidates confuse 'passing by reference' with 'passing the reference by value' — they think reassigning the parameter inside the method will update the caller's variable, but Java always passes references by value, so the original reference is unchanged.

424
MCQhard

Given the following code: class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } } class C extends B { C() { System.out.print("C"); } public static void main(String[] args) { new C(); } } 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

In Java, when an object of a subclass is created, constructors are executed from the topmost superclass down to the subclass. Assuming the exhibit shows class C extends B extends A, with each constructor printing its class name, the output will be 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.

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

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

427
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

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

428
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'.

429
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

The 1Z0-811 exam 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.

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

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

432
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

The constructor parameter 'name' shadows the field 'name'. The assignment 'name = name' assigns the parameter to itself, leaving the field 'name' uninitialized (null). Option A is incorrect because constructors do not have a return type.

Option C is incorrect because getName() returns a String, and it is fine to not be void. Option D is incorrect because the private field is accessible within the class.

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

434
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`.

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

436
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

A for loop with a break statement allows the developer to iterate over an array of integers and immediately exit the loop when a negative number is encountered. The break statement terminates the loop's execution unconditionally, making it the most direct and readable control flow construct for this requirement.

Exam trap

Candidates often confuse 'continue' (which skips to the next iteration) with 'break' (which exits the loop entirely), leading them to incorrectly select Option D when they need to stop the loop upon encountering a negative number.

How to eliminate wrong answers

Option A is wrong because a do-while loop guarantees at least one iteration before checking the condition, which is unnecessary and could cause the loop to process a negative number before stopping. Option C is wrong because an enhanced for loop with return would exit the entire method, not just the loop, which is an overly broad and incorrect control flow for this scenario. Option D is wrong because a while loop with continue would skip the current iteration and proceed to the next, not stop the loop entirely when a negative number is found.

437
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

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.

438
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

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

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

440
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

String literal, directly assigned to String variable. This is valid because string literals are instances of String.

Why this answer

A string literal, which is a valid way to create a String object. Option D uses the String constructor with a string argument, also valid. Option B assigns an integer literal to a String variable, which is not allowed.

Option C attempts to cast an Integer object to String, which causes a compile-time error because Integer is not a subclass of String. Option E uses a char literal ('Hello' is invalid because char literals are single characters) and is not assignable to String.

441
MCQeasy

Which of the following correctly uses the shorthand array initializer to declare and initialize 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. This uses the shorthand array initializer syntax with curly braces.

Why this answer

Option D correctly uses the shorthand array initializer with curly braces directly in the declaration. Option A uses the full syntax with the 'new' keyword, which is also valid but not the shorthand. Option B is wrong because it uses parentheses.

Option C is wrong because it uses square brackets.

Exam trap

The trap is that some candidates might think that the 'new' keyword is required, but Java allows the shorthand array initializer directly in a declaration, as shown in Option D.

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.

442
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

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.

443
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

First define the class, then declare a variable, instantiate with new, assign to variable, and then use the object.

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

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

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

447
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`.

448
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

It uses a try-catch inside a while loop that continues if an exception is caught, allowing the user to re-enter input. The loop also checks if the input equals 'quit' to break out, ensuring the program can terminate gracefully. This approach provides feedback (prompting the user) and avoids infinite loops.

Option B is incorrect because ignoring the exception would not provide feedback or allow retry. Option C is incorrect because it never checks for 'quit', risking an infinite loop. Option D is incorrect because calling System.exit(0) terminates the program abruptly, which is not graceful.

449
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'.

450
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

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

The 1Z0-811 exam 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.

Page 5

Page 6 of 7

Page 7

All pages