Courseiva

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

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

Page 2

Page 3 of 7

Page 4
151
MCQeasy

A programmer wants to iterate over a list of strings and print each that starts with 'A'. Which loop construct is best suited?

A.Do-while loop
B.Enhanced for loop
C.Traditional for loop with index
D.While loop with iterator
AnswerB

Simplest for iterating over all elements.

Why this answer

The enhanced for loop (for-each) is best suited because it provides a clean, concise syntax for iterating over a collection like a List<String> without needing an explicit index or iterator. It directly yields each element, allowing a simple if-statement to check if the string starts with 'A' and print it, making the code more readable and less error-prone.

Exam trap

The 1Z0-811 exam often tests the misconception that a traditional for loop with an index is always the most flexible or efficient choice, but for simple element access without index manipulation, the enhanced for loop is the idiomatic and recommended construct in Java.

How to eliminate wrong answers

Option A is wrong because a do-while loop is a post-test loop that always executes the body at least once, which is unnecessary and less readable for iterating over a list where the number of elements is known. Option C is wrong because a traditional for loop with an index requires manual index management and bounds checking, adding complexity and potential off-by-one errors without any benefit for simple element access. Option D is wrong because a while loop with an iterator, while functional, requires explicit calls to hasNext() and next(), introducing more boilerplate and the risk of NoSuchElementException if not handled correctly, making it less elegant than the enhanced for loop.

152
MCQeasy

A class that does not define any constructor has:

A.A private constructor
B.A public constructor with arguments
C.It cannot be instantiated
D.A default no-argument constructor
E.No constructor
AnswerD

Java automatically provides a default no-arg constructor with the same access as the class.

Why this answer

Java automatically provides a default no-arg constructor with the same access as the class.

153
MCQeasy

What is the output of: System.out.println(new Manager("Alice", 5).getName());

A.Runtime exception
B.Compilation fails
C.Alice
D.null
AnswerC

Correct; name is set via super constructor.

Why this answer

The code creates a new Manager object with the name "Alice" and a level of 5, then calls getName() on it. Assuming Manager extends a class (likely Employee) that has a constructor setting the name field via super(name), getName() returns the stored name "Alice". The code compiles and runs without exception, printing "Alice".

Exam trap

Oracle often tests whether candidates understand that a subclass constructor can pass arguments to a superclass constructor, and that inherited methods like getName() work correctly without additional overrides, causing some to mistakenly think the code fails or returns null.

How to eliminate wrong answers

Option A is wrong because no runtime exception occurs; the object is properly constructed and getName() simply returns the name field. Option B is wrong because the code compiles successfully; there is no syntax error or missing method, as getName() is presumably inherited or defined in Manager or its superclass. Option D is wrong because the name field is explicitly set to "Alice" in the constructor call, so getName() does not return null.

154
MCQmedium

Refer to the exhibit. What is the output when the following code is executed? Vehicle v = new Car(); v.accelerate(); System.out.println(v.speed);

A.10
B.0
C.Compilation error
D.20
AnswerD

Correct because the Car's overridden accelerate method adds 20 to speed, resulting in 20.

Why this answer

The code uses polymorphism: the reference variable v of type Vehicle points to a Car object. Since accelerate() is overridden in Car, the overridden method is invoked, adding 20 to the speed instance variable inherited from Vehicle. The protected field speed is accessible in the subclass.

Therefore, after calling v.accelerate(), speed becomes 20. Option D is correct.

155
MCQeasy

Which command compiles a Java file and generates a .class file?

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

javac compiles .java files to .class files.

Why this answer

The `javac` command is the Java compiler, which translates Java source code (`.java` files) into bytecode stored in `.class` files. This is the standard compilation step in the Java development process, as defined by the Java SE specification.

Exam trap

Oracle often tests the distinction between the compiler (`javac`) and the launcher (`java`), as candidates may confuse compiling with running a program, especially when both commands are used in sequence.

How to eliminate wrong answers

Option A is wrong because `jar` is the Java Archive tool used to package multiple `.class` files and resources into a single compressed archive (`.jar` file), not for compiling source code. Option B is wrong because `javadoc` generates API documentation from Java source code comments, producing HTML files, not `.class` files. Option C is wrong because `java` is the Java runtime launcher that executes compiled `.class` files (or `.jar` files) in the JVM, not a compiler.

156
MCQeasy

What does the java command with -jar option do?

A.Compiles Java files inside the JAR
B.Executes a JAR file by reading its manifest
C.Lists contents of the JAR file
D.Creates a new JAR file
AnswerB

java -jar runs the JAR with the class from manifest.

Why this answer

The `java -jar` command executes a JAR file by reading the `Main-Class` entry from the JAR's manifest file (`META-INF/MANIFEST.MF`). This tells the Java launcher which class contains the `public static void main(String[] args)` method to start the application. It does not compile, list, or create JAR files.

Exam trap

Oracle often tests the misconception that `java -jar` compiles or manipulates the JAR file, when in fact it strictly executes the application defined in the manifest.

How to eliminate wrong answers

Option A is wrong because the `java` command does not compile source files; compilation is done by the `javac` command, and the JAR file already contains compiled `.class` files. Option C is wrong because listing the contents of a JAR file is performed by the `jar tf` command, not by `java -jar`. Option D is wrong because creating a JAR file is done by the `jar cf` command, while `java -jar` only executes an existing JAR.

157
MCQmedium

A developer is writing a method to find the first occurrence of a negative number in an array and return its index, or -1 if none found. The current implementation uses a for loop with an if condition and a return when found. However, the method throws a NullPointerException when the array is null. The developer wants to handle this edge case gracefully and still return -1. Which approach is most appropriate?

A.Add a null check at the beginning of the method and return -1 if null
B.Use an enhanced for loop with a null check
C.Use a try-catch block inside the loop
D.Use a while loop with a null check inside
AnswerA

This handles the null case elegantly and prevents the exception.

Why this answer

It directly checks if the array reference is null before any iteration, returning -1 immediately. This is the simplest and most efficient way to handle a null input, avoiding any attempt to access the array's length or elements, which would throw a NullPointerException. The method's contract is preserved by returning -1 when no negative number is found, including the case of a null array.

Exam trap

Oracle often tests the misconception that a null check inside a loop (or using a try-catch) can handle a null array, but the NullPointerException occurs before the loop body executes, making any inside-loop handling ineffective.

How to eliminate wrong answers

Option B is wrong because an enhanced for loop still requires the array reference to be non-null to iterate; if the array is null, the loop will throw a NullPointerException before any null check inside the loop can execute. Option C is wrong because using a try-catch block inside the loop is inefficient and poor practice; it would catch the NullPointerException only after the loop attempts to access the null array, and the exception would occur before the loop even starts, not inside it. Option D is wrong because a while loop with a null check inside still requires the array reference to be non-null to evaluate the loop condition (e.g., index < array.length), which throws a NullPointerException before the null check inside the loop body can execute.

158
MCQhard

Which of the following best demonstrates polymorphism in Java?

A.Overloading a method with different parameter lists
B.Using an interface reference to call a method on an implementing object
C.Using static methods
D.Overriding a method in a subclass
E.Using final methods
AnswerB

Polymorphism allows one interface to be used for different implementations, as when an interface reference invokes the appropriate method at runtime.

Why this answer

Polymorphism in Java allows an object to take multiple forms, typically achieved through inheritance and interfaces. Option B demonstrates this by using an interface reference to invoke a method on an implementing object, where the actual method executed is determined at runtime based on the object's class, not the reference type.

Exam trap

Oracle often tests the distinction between compile-time polymorphism (overloading) and runtime polymorphism (overriding with interface/superclass references), so candidates mistakenly choose overloading or overriding alone without the reference context.

How to eliminate wrong answers

Option A is wrong because method overloading is compile-time polymorphism (static binding), not runtime polymorphism; it resolves method calls based on parameter lists at compile time. Option C is wrong because static methods belong to the class, not instances, and cannot be overridden, thus they do not exhibit polymorphic behavior. Option D is wrong because method overriding alone is not the best demonstration; it is a mechanism that enables polymorphism, but the question asks for the best demonstration, which requires using a superclass or interface reference to call overridden methods.

Option E is wrong because final methods cannot be overridden, which prevents polymorphic behavior entirely.

159
Multi-Selectmedium

Which THREE are valid loop constructs in Java? (Choose three.)

Select 3 answers
A.while (condition) { }
B.repeat { } until (condition);
C.do { } while (condition);
D.loop (condition) { }
E.for (initialization; condition; update) { }
AnswersA, C, E

Standard while loop.

Why this answer

The `while` loop is a standard Java construct that repeatedly executes a block of code as long as the specified boolean condition evaluates to `true`. The syntax `while (condition) { }` is valid even with an empty body, as the condition is checked before each iteration.

Exam trap

Oracle often tests the recognition of valid Java syntax versus constructs from other languages, so candidates may mistakenly select `repeat-until` or `loop` if they are familiar with other programming languages or do not recall Java's exact loop keywords.

160
MCQhard

Given: abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() {} } Which is true?

A.Shape cannot have a constructor
B.Circle must override draw()
C.Shape s = new Shape(); is valid
D.draw() must be public in Circle
AnswerB

Circle provides implementation; it compiles fine.

Why this answer

Circle is a concrete class that extends the abstract class Shape, which declares the abstract method draw(). A concrete subclass of an abstract class must provide an implementation for all inherited abstract methods, unless the subclass is also declared abstract. Circle provides an implementation of draw() with an empty body, which satisfies the override requirement.

Exam trap

The trap here is that candidates often think abstract classes cannot have constructors (option A) or that overriding methods must always be public (option D), but the Java specification allows constructors in abstract classes and only requires the overriding method to have at least the same access level as the abstract method.

How to eliminate wrong answers

Option A is wrong because abstract classes can have constructors, even though they cannot be instantiated directly; constructors are invoked via super() in subclasses. Option C is wrong because Shape is abstract and cannot be instantiated; the line 'new Shape()' would cause a compilation error. Option D is wrong because the overriding method draw() in Circle can have default (package-private) access, as the original abstract method in Shape has default access; the access level of the overriding method must be at least as accessible as the original, but it does not have to be public.

161
MCQhard

A team is designing a new system that requires deploying independent services communicating over a network. Which Java technology is most suitable for this architecture?

A.Java Applets
B.Java EE with EJB
C.Java EE with JAX-RS RESTful Web Services
D.Java RMI
AnswerC

Correct. Java EE with JAX-RS is the standard Java technology for RESTful web services, enabling independent services to communicate over a network via HTTP. JAX-RS annotations like @Path and @GET simplify service creation.

Why this answer

Java EE with JAX-RS (Java API for RESTful Web Services) enables building RESTful services that communicate over HTTP, which is ideal for independent services in a microservices architecture. Option A is incorrect: Java Applets are client-side components that run in a browser and are not suitable for server-side network communication. Option B is incorrect: Java EE with EJB is a heavyweight, monolithic approach that is less suited for modern microservices architectures.

Option D is incorrect: Java RMI is a remote method invocation protocol for tightly coupled distributed systems, not designed for lightweight RESTful services.

Exam trap

Candidates may mistakenly choose Spring Boot because it is popular, but the question specifically asks for a 'Java technology' from the core Java ecosystem. JAX-RS is the correct standard choice.

162
MCQhard

A Java class named 'Helper' is defined in package 'utils'. Another class in a different package tries to access a public method of Helper but receives a compilation error. The Helper class is declared as 'class Helper' (without public modifier). What is the likely issue?

A.The method is declared as final
B.The method is not static
C.The class is abstract
D.The class has package-private access
AnswerD

Default access (no modifier) makes the class accessible only within its package.

Why this answer

The Helper class is declared with default (package-private) access because no access modifier is specified. Therefore, it is only accessible within the utils package. A class in a different package cannot access it, even if it tries to call a public method of that class, because the class itself is not accessible.

The method's access modifier is irrelevant if the class is not accessible. Option A is incorrect because final does not affect access. Option B is incorrect because static is unrelated to access across packages.

Option C is incorrect because abstract does not restrict access.

163
MCQeasy

What is the output of the following code? String str1 = "Java"; String str2 = new String("Java"); System.out.println(str1 == str2);

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

Correct. str1 and str2 are different objects.

Why this answer

The == operator compares object references. One string is a literal (stored in the string pool) and the other is created using the 'new' keyword (heap object). They are different references, so the comparison returns false.

164
Multi-Selectmedium

Which two expressions evaluate to true? (Choose two)

Select 2 answers
A.true && false
B.10 > 5
C.'a' == 'b'
D.false || !false
E.3 < 3
AnswersB, D

True because 10 is greater than 5.

Why this answer

The expression `10 > 5` uses the greater-than operator, which evaluates to `true` since 10 is indeed greater than 5. Option D is correct because `!false` evaluates to `true`, and the logical OR operator (`||`) returns `true` if at least one operand is `true`, so `false || true` yields `true`.

Exam trap

Oracle often tests the distinction between relational operators (`<`, `>`) and equality operators (`==`), where candidates mistakenly think `3 < 3` is true or that `'a' == 'b'` might be true due to character comparison confusion.

165
Multi-Selecthard

Which THREE statements are true about passing arrays to methods in Java?

Select 3 answers
A.If the method modifies elements of the array, the caller does not see the changes.
B.Varargs parameters allow passing zero or more arguments of the specified type.
C.If the method assigns a new array to the parameter, the caller's variable is updated.
D.The method receives a reference to the array.
E.Passing null as an array argument is allowed at compile time.
AnswersB, D, E

Varargs (T...) accept multiple arguments or an array.

Why this answer

Varargs (variable-length arguments) in Java allow a method to accept zero or more arguments of a specified type, using the syntax `Type... param`. This is syntactic sugar for an array parameter, and the method body treats it as an array. This enables flexible method invocation without requiring the caller to explicitly create an array.

Exam trap

The trap here is that candidates often confuse pass-by-value for object references with pass-by-reference, leading them to incorrectly believe that reassigning the parameter (Option C) or modifying elements (Option A) behaves the same way, when in fact only element modifications are visible to the caller.

166
Multi-Selecthard

Which THREE are valid ways to declare and initialize an integer variable in Java? (Choose three.)

Select 3 answers
A.int x = 2.0;
B.int x = 1_000;
C.int x = 0xG;
D.int x = 03;
E.int x = 0;
AnswersB, D, E

Underscore allowed.

Why this answer

Java allows underscores in numeric literals (introduced in Java 7) to improve readability, and `1_000` is a valid integer literal representing 1000. The compiler simply ignores the underscores during parsing.

Exam trap

Oracle often tests the distinction between valid integer literal formats and common invalid ones, such as using underscores incorrectly or assuming any letter is valid in hexadecimal, to catch candidates who overlook Java's strict literal syntax rules.

167
MCQmedium

A developer writes a method that accepts a variable number of int arguments and returns their product. Which method signature correctly implements this?

A.public static int product(int[] nums)
B.public static int product(int nums...)
C.public static int product(int... nums)
D.public static int product(int... nums, int extra)
AnswerC

Varargs correctly declared.

Why this answer

The syntax `int... nums` is the proper Java varargs syntax, allowing a method to accept zero or more `int` arguments, which are then treated as an array inside the method. This enables the developer to call `product(2, 3, 4)` or `product()` and compute the product by iterating over the array.

Exam trap

Oracle often tests the requirement that varargs must be the last parameter, and the trap here is that candidates might think `int nums...` is valid or that a regular array parameter qualifies as variable arguments.

How to eliminate wrong answers

Option A is wrong because it requires the caller to explicitly create and pass an `int[]` array, not a variable number of arguments. Option B is wrong because the ellipsis must come before the parameter name, not after; `int nums...` is invalid syntax. Option D is wrong because varargs must be the last parameter in the method signature; placing `int extra` after `int... nums` causes a compilation error.

168
MCQmedium

A company is developing a configuration manager that must be shared across all components to ensure consistent settings. The manager should prevent direct instantiation and provide a single access point. Which design pattern and implementation should be used?

A.Prototype pattern with cloning
B.Builder pattern with a static inner class
C.Factory pattern with a public constructor
D.Singleton pattern with a private constructor and a static getInstance() method
AnswerD

Correct. Singleton ensures a single instance and provides global access.

Why this answer

The Singleton pattern ensures a class has only one instance and provides a global point of access. A private constructor prevents direct instantiation, and a static getInstance() method provides controlled access.

169
MCQmedium

Given two String objects s1 = "Hello" and s2 = "Hello", what does the expression (s1 == s2) return?

A.Compilation error
B.false
C.It depends on the JVM
D.true
AnswerD

Both strings are string literals, so they are interned and share the same reference.

Why this answer

The `==` operator compares object references, not string content. Since both `s1` and `s2` are string literals, Java's string interning ensures they refer to the same `String` object in the string constant pool, so `s1 == s2` returns `true`.

Exam trap

The trap here is that candidates often confuse reference equality (`==`) with value equality (`.equals()`), and incorrectly assume `==` always returns `false` for strings, forgetting that string literals are interned.

How to eliminate wrong answers

Option A is wrong because the expression `(s1 == s2)` is syntactically valid and compiles without error. Option B is wrong because `==` does not compare string content; it compares references, and due to string interning both references point to the same object, so the result is `true`, not `false`. Option C is wrong because the behavior of string literals being interned is guaranteed by the Java Language Specification (JLS §3.10.5), not dependent on the JVM implementation.

170
MCQmedium

A developer writes two methods: public void process(int a) { ... } and public void process(double a) { ... }. Which method is called by process(10)?

A.The method with double parameter
B.Compilation error: ambiguous call
C.The method with int parameter
D.Runtime error: NoSuchMethod
AnswerC

The int version is the best match for an int argument.

Why this answer

Java selects the most specific overloaded method at compile time. When calling process(10), the integer literal 10 is an int, so the compiler prefers the method with the int parameter over the double parameter, as no implicit widening conversion is required.

Exam trap

Oracle often tests the misconception that Java will always widen an int to a double when both overloads exist, leading candidates to incorrectly choose the double parameter method.

How to eliminate wrong answers

Option A is wrong because Java does not automatically widen an int to a double when a more specific int overload exists; the compiler chooses the exact match. Option B is wrong because the call is not ambiguous; the int parameter method is a perfect match, so no ambiguity arises. Option D is wrong because the method with the int parameter exists and is accessible, so no runtime error occurs.

171
MCQeasy

Which is the correct way to declare an array of integers in Java?

A.Both A and B are valid.
B.int[] array = new int[5];
C.int array = new int[5];
D.int array[] = new int[5];
AnswerA

Both declarations compile and declare arrays.

Why this answer

In Java, arrays can be declared with the brackets either after the type (e.g., int[] array = new int[5];) or after the variable name (e.g., int array[] = new int[5];). Both syntaxes are valid, so the correct answer is the option that states both are valid. Option C (int array = new int[5];) is invalid because it declares an integer variable, not an array, and omits the brackets.

172
Multi-Selectmedium

Which TWO of the following are valid benefits of using inheritance in Java? (Choose two.)

Select 2 answers
A.Increases coupling between classes
B.Allows polymorphic behavior
C.Promotes code reuse
D.Enforces encapsulation
E.Simplifies debugging
AnswersB, C

Inheritance supports method overriding and runtime polymorphism.

Why this answer

Options B and C are correct. Inheritance promotes code reuse by allowing subclasses to reuse fields and methods from superclasses, reducing redundancy. It also enables polymorphic behavior through method overriding, allowing objects to be treated as instances of their parent class.

Option A is incorrect because inheritance actually increases coupling between classes, which is generally considered a disadvantage, not a benefit. Option D is incorrect because encapsulation is enforced through access modifiers (private, protected, public), not inheritance. Option E is incorrect because inheritance can actually complicate debugging by introducing dependencies across classes.

173
MCQeasy

Given: int a = 9; int b = 2; double c = a / b; System.out.println(c); What is the output?

A.4.5
B.4.0
C.0.0
D.4
AnswerB

In integer division, 9/2 = 4, and since c is double, it becomes 4.0. This is correct.

Why this answer

The expression `a / b` performs integer division because both operands are `int`. The result of `9 / 2` is `4` (the fractional part is truncated). This integer result is then implicitly widened to `double` when assigned to `c`, producing `4.0`.

Therefore, the output is `4.0`.

Exam trap

Oracle often tests the distinction between integer and floating-point division, trapping candidates who assume that assigning the result to a `double` variable automatically performs floating-point division.

How to eliminate wrong answers

Option A is wrong because it assumes floating-point division occurs, yielding `4.5`, but integer division truncates the fractional part. Option C is wrong because it is a duplicate of the correct answer but listed as a separate option; the output is `4.0`, not `4.0` as a distinct choice. Option D is wrong because it outputs `4` as an integer, but the variable `c` is of type `double`, so the printed value includes the decimal point and zero.

174
Multi-Selecthard

Which THREE of the following are primitive data types in Java?

Select 3 answers
A.void
B.boolean
C.int
D.String
E.char
AnswersB, C, E

Primitive boolean type.

Why this answer

(boolean) is correct because boolean is one of the eight primitive data types in Java, representing a single bit of information with only two possible values: true or false. It is not an object and does not have methods, unlike reference types such as Boolean (the wrapper class).

Exam trap

Oracle often tests the distinction between primitive types and their corresponding wrapper classes or commonly used reference types like String, leading candidates to mistakenly include String or void as primitives.

175
MCQhard

Consider the following interface: public interface Drawable { void draw(); } A developer implements Drawable in class Circle. Which statement about the implementation is correct?

A.The draw method must be declared public
B.Both A and D
C.The class must be abstract if it does not provide body for draw
D.The draw method can have a body in the interface
E.The draw method must be declared final
AnswerA

Correct: Interface methods are implicitly public, so the implementing class must declare the method as public.

Why this answer

Interface methods are implicitly public and abstract unless declared as default or static. In this interface, draw() is abstract, so it cannot have a body. Therefore, the implementing class must declare draw() as public (making A correct).

Option D is false because the interface method has no body. Option C is false because Circle provides an implementation, so the condition for being abstract is not met. Thus, only A is correct, making B incorrect.

176
Multi-Selecthard

Which three statements about String immutability are true? (Choose three)

Select 3 answers
A.String objects can be modified after creation
B.String objects can be changed by calling methods
C.The intern() method returns a String from the pool
D.String concatenation creates a new String
E.StringBuilder can be used to create mutable strings
AnswersC, D, E

True; intern() returns canonical representation.

Why this answer

The `intern()` method returns a canonical representation of the string from the string pool, ensuring that strings with the same content share the same memory reference, which is a key aspect of immutability and memory optimization in Java.

Exam trap

Oracle often tests the misconception that calling a method on a String changes the original object, when in fact all such methods return a new String, leaving the original unchanged.

177
MCQhard

Consider the following code: ```java import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (FileInputStream fis = new FileInputStream("test.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis))) { System.out.println(br.readLine()); } catch (IOException e) { System.out.println("Error"); } } } ``` Which statement about this code is true?

A.The resource 'br' is not closed properly.
B.The code will not compile because of the throws clause.
C.The resource 'fis' is closed before 'br'.
D.The catch block is unnecessary.
AnswerD

The try-with-resources already ensures proper handling; the catch block just rethrows, making it redundant.

Why this answer

The code likely uses a try-with-resources statement, which automatically closes resources. The catch block is unnecessary since the resources are closed automatically, and the exception can be declared to be thrown. The code compiles without the catch block, and resource management is handled by the try-with-resources construct.

Exam trap

The 1Z0-811 exam often tests the misconception that a catch block is required in try-with-resources, but the catch block is optional and only needed if you want to handle exceptions locally rather than propagating them with `throws`.

How to eliminate wrong answers

Option A is wrong because the try-with-resources statement ensures that `br` is closed automatically at the end of the try block, even if an exception is thrown. Option B is wrong because the `throws` clause is valid and does not prevent compilation; it simply declares that the method may throw `IOException`. Option C is wrong because in a try-with-resources statement, resources are closed in the reverse order of their declaration, so `br` is closed before `fis`.

178
MCQeasy

Given the code snippet: 'int[] nums = {10, 20, 30, 40}; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; }'. What is the value of sum after execution?

A.100
B.30
C.60
D.140
AnswerA

Sums all four elements correctly.

Why this answer

(100) because the for loop iterates over each element of the array {10, 20, 30, 40} and adds it to the sum variable. The sum starts at 0, and after adding 10, 20, 30, and 40, the total becomes 100.

Exam trap

Oracle often tests whether candidates correctly compute the sum of all array elements versus partial sums, exploiting the common mistake of misinterpreting loop bounds or array indices.

How to eliminate wrong answers

Option B (30) is wrong because it represents only the sum of the first two elements (10 + 20) or a misunderstanding of the loop bounds. Option C (60) is wrong because it represents the sum of the first three elements (10 + 20 + 30) or a confusion with the array length. Option D (140) is wrong because it might result from incorrectly including an extra element or misreading the array values (e.g., adding 50 or double-counting).

179
MCQhard

A method 'public static void modify(int[][] matrix) { matrix[0][0] = 99; }' is called with 'int[][] values = {{1,2},{3,4}}; modify(values);'. What is the value of values[0][0] after the call?

A.99
B.Exception
C.1
D.0
AnswerA

The method modifies the original array element.

Why this answer

Java passes object references by value. When 'modify(values)' is called, the reference to the 2D array is copied into the method parameter 'matrix'. Since 'matrix' points to the same array object, modifying 'matrix[0][0]' directly changes the original array's element, so 'values[0][0]' becomes 99.

Exam trap

The trap here is that candidates often confuse pass-by-value with pass-by-reference for objects, mistakenly thinking the method cannot modify the original array, or they assume an exception occurs due to incorrect array indexing.

How to eliminate wrong answers

Option B is wrong because no exception occurs; the method accesses a valid index (0,0) within the array bounds. Option C is wrong because the value 1 is overwritten by the assignment 'matrix[0][0] = 99', so it is not retained. Option D is wrong because 0 is the default value for uninitialized int array elements, but here the element was explicitly initialized to 1 and then changed to 99.

180
Multi-Selecteasy

Which THREE of the following are key features of the Java programming language?

Select 3 answers
A.Use of pointers for direct memory access
B.Support for multiple inheritance of classes
C.Platform independence through bytecode and JVM
D.Automatic memory management (garbage collection)
E.Strong type checking at compile time
AnswersC, D, E

Java source code is compiled to bytecode, which runs on any JVM.

Why this answer

Java is platform independent via bytecode, has automatic garbage collection, and is strongly typed. It does not support multiple inheritance for classes (only interfaces) and does not have pointers.

181
MCQmedium

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

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

Body executes first, then condition checked.

Why this answer

The do-while loop is a post-test loop, meaning the condition is evaluated after the loop body executes. This guarantees that the body runs at least once, regardless of whether the condition is initially true or false. In contrast, for, while, and enhanced for loops are pre-test loops that check the condition before entering the body, so they may execute zero times.

Exam trap

Oracle often tests the distinction between pre-test and post-test loops, and the trap here is that candidates confuse the do-while loop with the while loop, assuming both can execute zero times, or they forget that the enhanced for loop requires at least one element to execute.

How to eliminate wrong answers

Option A is wrong because the enhanced for loop (for-each) iterates over an array or collection and only executes if there is at least one element; if the array or collection is empty, the body never runs. Option C is wrong because the standard for loop evaluates its condition before each iteration, so if the condition is false initially, the body executes zero times. Option D is wrong because the while loop checks its condition before entering the body, so if the condition is false at the start, the body never executes.

182
MCQmedium

A developer writes a method that reads a file and must ensure the file is closed even if an exception occurs. Which construct should be used?

A.A throws declaration in the method signature
B.A finally block without any resource declaration
C.A try-with-resources statement
D.A try-catch-finally block with explicit close in finally
AnswerC

try-with-resources automatically closes resources implementing AutoCloseable.

Why this answer

The try-with-resources statement automatically closes any resource that implements `AutoCloseable` (such as `FileReader` or `BufferedReader`) at the end of the statement, even if an exception occurs. This eliminates the need for explicit cleanup code and ensures deterministic resource management without relying on a `finally` block.

Exam trap

Oracle often tests whether candidates recognize that a `finally` block with explicit `close()` is not the best practice compared to try-with-resources, even though it technically works, because the exam emphasizes modern, concise, and safe resource management.

How to eliminate wrong answers

Option A is wrong because a `throws` declaration only propagates exceptions to the caller; it does not provide any mechanism to close the file. Option B is wrong because a `finally` block without any resource declaration cannot close the file unless the resource reference is accessible, and it does not guarantee the resource was successfully opened before attempting to close it. Option D is wrong because while a try-catch-finally block with explicit `close()` in `finally` can work, it is verbose, error-prone (e.g., forgetting to close, or a `close()` throwing its own exception), and is superseded by the cleaner try-with-resources construct.

183
Drag & Dropmedium

Arrange the steps to define a class with a main method in Java in the correct order.

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

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

First declare the class, then define the main method, add other members, write code in main, and finally compile and run.

184
MCQmedium

A method is declared as: public static void main(String[] args) { }. Which statement is true?

A.The method can be overridden in a subclass.
B.The method can return an int.
C.The method can be called without creating an instance of the class.
D.The method can be private.
AnswerC

It is static, so it belongs to the class.

Why this answer

The `static` modifier in the method signature means the method belongs to the class itself, not to any instance. Therefore, it can be invoked using the class name (e.g., `ClassName.main(args)`) without creating an object of the class. This is a fundamental characteristic of static methods in Java.

Exam trap

Oracle often tests the distinction between static and instance members, and the trap here is that candidates mistakenly think static methods can be overridden like instance methods, or that the `main` method's access modifier can be changed without breaking JVM entry-point requirements.

How to eliminate wrong answers

Option A is wrong because static methods cannot be overridden; they can only be hidden in a subclass, and method overriding requires instance methods with the same signature. Option B is wrong because the method signature explicitly declares `void` as the return type, meaning it cannot return any value, including an `int`. Option D is wrong because the `main` method must be `public` for the JVM to access it when starting the application; making it `private` would prevent the JVM from calling it, resulting in a runtime error.

185
Multi-Selecteasy

Which TWO of the following are primitive data types in Java?

Select 2 answers
A.String
B.Integer
C.double
D.int
E.Boolean
AnswersC, D

Primitive.

Why this answer

(double) is correct because double is a 64-bit IEEE 754 floating-point primitive data type in Java, used for decimal values with double precision. Option D (int) is correct because int is a 32-bit signed two's complement integer primitive, the default integer type in Java. Both are part of the eight primitive types defined in the Java Language Specification.

Exam trap

Oracle often tests the distinction between primitive types and their corresponding wrapper classes (e.g., int vs. Integer, boolean vs. Boolean), and the trap here is that candidates confuse the capitalized wrapper class name with the lowercase primitive keyword.

186
MCQmedium

A logging utility class keeps track of the number of log entries using a static integer variable. The class is instantiated multiple times in the application. How does the count variable behave?

A.Each instance has its own copy of count
B.All instances share the same count variable
C.count is reset each time a new instance is created
D.count cannot be accessed from static methods
AnswerB

Correct. A static variable is shared across all instances.

Why this answer

Static variables are shared among all instances of a class. There is only one copy of the variable, regardless of the number of instances.

187
Multi-Selecteasy

Which TWO statements are true about the Java programming language?

Select 2 answers
A.It is a purely procedural language.
B.It supports direct pointer manipulation for memory access.
C.It is a strongly-typed language.
D.It allows multiple inheritance of classes.
E.It provides automatic memory management through garbage collection.
AnswersC, E

All variables must have a declared type.

Why this answer

Options C and E are correct. Java is a strongly-typed language (C) that provides automatic memory management through garbage collection (E). Option A is wrong because Java is object-oriented, not purely procedural.

Option B is wrong because Java does not support direct pointer manipulation; it uses references. Option D is wrong because Java does not allow multiple inheritance of classes; it uses interfaces to achieve a form of multiple inheritance.

188
MCQmedium

Which of the following correctly uses the ternary operator to set int max to the larger of two ints x and y?

A.int max = x > y ? x : y;
B.int max = x > y ? y : x;
C.int max = if (x > y) x else y;
D.int max = (x > y) ? x, y;
AnswerA

Correct syntax.

Why this answer

The ternary operator `? :` evaluates the boolean expression `x > y`; if true, it returns `x`, otherwise `y`, assigning the larger value to `int max`. This is the standard syntax for a conditional assignment in Java, as defined in the Java Language Specification (JLS §15.25).

Exam trap

Oracle often tests the exact syntax of the ternary operator, specifically that the colon `:` is required to separate the true and false expressions, and that the operator returns a value, not a statement like `if`.

How to eliminate wrong answers

Option B is wrong because it assigns the smaller value (`y` when `x > y` is true, and `x` when false), effectively setting `max` to the minimum of the two ints, not the maximum. Option C is wrong because it uses `if` statement syntax inside an expression, which is not valid in Java; the ternary operator requires the `? :` syntax, not an `if-else` block. Option D is wrong because it uses a comma `,` instead of a colon `:` to separate the two possible values, which is syntactically incorrect and will cause a compilation error.

189
Multi-Selecteasy

Which TWO are true about the Java Runtime Environment (JRE)? (Choose two.)

Select 2 answers
A.It is larger than the JDK
B.It includes the Java compiler
C.It includes the JVM
D.It includes development tools
E.It is required to run Java applications
AnswersC, E

The JVM is a core component of the JRE.

Why this answer

The JRE (Java Runtime Environment) includes the JVM (Java Virtual Machine) and core libraries necessary to run Java applications. Therefore, option C is correct. Option E is correct because the JRE is required to run any Java application; without it, Java bytecode cannot be executed.

Option A is incorrect: the JRE is smaller than the JDK (Java Development Kit) because the JDK contains additional tools like the compiler and debugger. Option B is incorrect: the Java compiler is part of the JDK, not the JRE. Option D is incorrect: development tools are included in the JDK, not the JRE.

190
MCQeasy

In a banking application, a class 'Account' has a private field 'balance'. Which is the best way to allow subclasses to read but not directly modify 'balance'?

A.Make balance public
B.Provide a public getBalance() method
C.Use a static variable
D.Make balance protected
AnswerB

Getter provides read-only access; keep field private.

Why this answer

It follows encapsulation: a public getBalance() method provides read-only access to the private balance field. Subclasses cannot directly modify balance because it is private. Option D (protected) is incorrect because protected access allows subclasses to directly read and write the field, which violates the requirement that subclasses should not be able to directly modify balance.

Exam trap

Oracle often tests the misconception that protected access is sufficient for read-only access, but protected actually allows both reading and writing by subclasses, failing the 'not directly modify' requirement.

How to eliminate wrong answers

Option A is wrong because making balance public violates encapsulation, allowing any class (including subclasses) to directly modify the field without restriction. Option C is wrong because a static variable is shared across all instances of the class, which is inappropriate for an instance-specific balance and does not solve the read-only requirement. Option D is wrong because making balance protected allows subclasses to directly read and modify the field, which does not prevent modification as required.

191
Multi-Selectmedium

A developer has written a Java program that uses third-party libraries. Which TWO actions are necessary to run the program on a different machine? (Choose two.)

Select 2 answers
A.Copy only the .class files of the program
B.Install the JDK
C.Set the PATH environment variable to include the java executable
D.Install the JRE
E.Copy the .java source files
AnswersC, D

The system must find the java command.

Why this answer

Options C and D are correct. To run a Java program, the JRE must be installed (D) because it provides the Java Runtime Environment including the JVM. The PATH must include the java executable's directory (C) so that the 'java' command can be invoked.

Option A is incorrect because .class files alone are insufficient; third-party libraries (JARs) are also needed and must be accessible. Option B is incorrect because the JDK (Java Development Kit) is only needed for compilation and development, not for running. Option E is incorrect because source files are not required to run the compiled program.

192
MCQhard

Given: String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); Which of the following is true?

A.s1 == s2 is false, s1 == s3 is true
B.s1 == s2 is true, s1 == s3 is true
C.s1 == s2 is false, s1 == s3 is false
D.s1 == s2 is true, s1 == s3 is false
AnswerD

Correct due to string literal pooling and new String().

Why this answer

String literals in Java are interned, meaning s1 and s2 both reference the same object from the string pool, so s1 == s2 is true. However, s3 is created using the new keyword, which forces the creation of a new String object on the heap, so s1 == s3 is false because == compares object references, not content.

Exam trap

The trap here is that candidates often confuse == (reference equality) with .equals() (value equality) and assume that all String objects with the same content are the same reference, forgetting that new String() always creates a separate object.

How to eliminate wrong answers

Option A is wrong because it claims s1 == s2 is false, but both are string literals and Java interns them, so they reference the same object. Option B is wrong because it claims s1 == s3 is true, but the new keyword creates a distinct object on the heap, so the references differ. Option C is wrong because it claims s1 == s2 is false, which contradicts string interning behavior.

193
MCQhard

A programmer writes code to transpose a 2D array (matrix). Given: int[][] matrix = {{1,2},{3,4}}; int[][] result = new int[2][2]; for (int i=0; i<2; i++) for (int j=0; j<2; j++) result[j][i] = matrix[i][j]; What is the value of result[1][0]?

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

After transpose, result[1][0] equals original matrix[0][1].

Why this answer

The code transposes the matrix by assigning matrix[i][j] to result[j][i]. For result[1][0], we need the value where j=1 and i=0, which comes from matrix[0][1] = 2. Thus, result[1][0] = 2, making option C correct.

Exam trap

The trap here is confusing the indices: candidates often mistakenly think result[1][0] corresponds to matrix[1][0] (value 3) instead of correctly swapping to matrix[0][1] (value 2).

How to eliminate wrong answers

Option A is wrong because 4 would be the value of result[1][1] (from matrix[1][1]), not result[1][0]. Option B is wrong because 3 would be the value of result[0][1] (from matrix[1][0]), not result[1][0]. Option D is wrong because 1 would be the value of result[0][0] (from matrix[0][0]), not result[1][0].

194
Multi-Selectmedium

Which TWO of the following are legal ways to declare and initialize an array?

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

Valid. Array initializer syntax.

Why this answer

It uses the valid syntax `int[] arr = new int[]{1,2,3};` which declares an array variable of type `int[]`, creates a new array object with an initializer list, and assigns it to the variable. This is a legal way to both declare and initialize an array in a single statement, as the array size is inferred from the number of elements in the initializer.

Exam trap

Oracle often tests the distinction between declaration and initialization, and the trap here is that candidates may think `int arr[];` (Option B) is sufficient because it declares an array, but the question explicitly requires both declaration and initialization, making it incomplete.

195
Multi-Selectmedium

Which THREE statements are true about the switch statement in Java? (Choose three.)

Select 3 answers
A.It can be used with boolean expressions.
B.The default case must be placed at the end of the switch block.
C.Without a break statement, execution falls through to the next case.
D.The default case is optional.
E.It can be used with String objects.
AnswersC, D, E

True. Without a break, execution falls through to the next case (fall-through behavior).

Why this answer

Options C, D, and E are true. Option C correctly describes fall-through behavior: without a break statement, execution continues to the next case. Option D correctly states that the default case is optional.

Option E is true because, since Java 7, the switch statement can be used with String objects. Options A and B are false: A is incorrect because switch does not support boolean expressions; B is incorrect because the default case can appear anywhere in the switch block.

Exam trap

Candidates often mistakenly believe that switch can be used with boolean expressions or that the default case must be at the end. Also, many think that switch supports String objects in older Java versions.

196
Multi-Selecthard

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

Select 3 answers
A.An interface can be instantiated directly
B.An interface can extend multiple interfaces
C.An interface can contain static methods
D.An interface can contain default methods
E.An interface can have private fields
AnswersB, C, D

Interfaces support multiple inheritance of type.

Why this answer

Options B, C, and D are true about interfaces in Java. An interface can extend multiple interfaces using the extends keyword. Since Java 8, interfaces can contain static methods (with body) and default methods.

Option A is false because interfaces cannot be instantiated directly; they must be implemented by a class. Option E is false because interface fields are implicitly public static final; private fields are not permitted in interfaces (private methods are allowed since Java 9, but not fields).

197
MCQmedium

Consider a method that takes an int array and modifies it: public static void doubleArray(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] *= 2; } }. What is the output of: int[] nums = {1, 2, 3}; doubleArray(nums); System.out.println(nums[1]);

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

The method doubles each element, so 2 becomes 4.

Why this answer

The method `doubleArray` multiplies each element of the array by 2. The array `nums` is passed by reference, so modifications inside the method affect the original array. After execution, `nums[1]` (originally 2) becomes 4, which is printed.

Exam trap

The trap here is that candidates often confuse pass-by-value for object references with pass-by-value for primitives, incorrectly assuming the array is copied and the original remains unchanged, leading them to pick the original value (option C).

How to eliminate wrong answers

Option B is wrong because it assumes the entire array is doubled multiple times or that `nums[1]` becomes 8, which would require an extra doubling step. Option C is wrong because it represents the original value of `nums[1]` before the method call, ignoring that the array is modified in place. Option D is wrong because it suggests `nums[1]` remains 3, which is the value of `nums[2]` after doubling, not `nums[1]`.

198
MCQmedium

A developer writes a method that reads a file and processes its contents. If the file does not exist, the method should notify the caller. Which exception should the method declare in its throws clause?

A.RuntimeException
B.FileNotFoundException
C.Exception
D.IOException
AnswerB

FileNotFoundException is a checked exception specifically for missing files.

Why this answer

`FileNotFoundException` is a checked exception that specifically indicates a file cannot be found at the specified path. The method must declare it in its `throws` clause to notify the caller that this condition can occur and must be handled or re-declared, as required by Java's checked exception rules.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates choose `IOException` (Option D) because it is a parent class, failing to recognize that the most specific exception (`FileNotFoundException`) is the correct and precise choice for the given scenario.

How to eliminate wrong answers

Option A is wrong because `RuntimeException` is an unchecked exception; it does not need to be declared in a `throws` clause, and using it would not properly notify the caller of a checked file-not-found condition. Option C is wrong because `Exception` is too broad; declaring it would force the caller to handle or declare all checked exceptions, which is overly general and not specific to the file-not-found scenario. Option D is wrong because while `IOException` is a checked exception that could cover file-not-found, it is the parent class of `FileNotFoundException`; using the more specific `FileNotFoundException` is the correct practice to precisely communicate the exact failure condition.

199
Multi-Selectmedium

Which TWO statements are true about the main method?

Select 2 answers
A.It must be declared final.
B.It must be declared public.
C.It must return an int.
D.It must be declared static.
E.It cannot be overloaded.
AnswersB, D

The `main` method must be declared `public` to allow the Java Virtual Machine (JVM) to invoke it from outside the class when starting programme execution. This access modifier ensures the method is universally accessible, enabling the JVM to locate and execute the application's entry point. Without it, the JVM would be unable to access and initiate the programme, leading to runtime errors.

Why this answer

The Java Language Specification (JLS) requires the main method to be declared public so that the JVM can access it from outside the class. Option D is correct because the main method must be static, allowing the JVM to invoke it without creating an instance of the class.

Exam trap

Oracle often tests the misconception that the main method must be final or cannot be overloaded, but the JLS only mandates public, static, and void, and overloading is permitted as long as the standard signature is present.

200
MCQhard

A calculator class has two overloaded methods: add(int a, int b) and add(double a, double b). A call to add(3, 4) will invoke which method?

A.add(double, double)
B.add(int, int)
C.Runtime decision based on actual parameters
D.Compilation error: ambiguous
AnswerB

Correct. The arguments are int literals, so the int version is invoked.

Why this answer

Overloaded method resolution is based on compile-time types. The literal 3 and 4 are ints, so the int version is the most specific match and is called.

201
MCQhard

A developer implements a method to check if a number exists in an array using binary search. The array is not sorted. What will happen?

A.The method returns correct results always.
B.Runtime exception.
C.Compilation error.
D.The method returns incorrect results sometimes.
AnswerD

Binary search may return incorrect results, such as not finding an existing element or returning a wrong index, because the array is not sorted.

Why this answer

Binary search requires the array to be sorted to work correctly. If the array is not sorted, the algorithm may skip over the target element or incorrectly conclude it is absent, leading to incorrect results. Therefore, the method returns incorrect results sometimes.

Exam trap

The trap here is that candidates assume binary search will still work or throw an error, but the exam tests the prerequisite that the array must be sorted for binary search to produce correct results.

How to eliminate wrong answers

Option A is wrong because binary search on an unsorted array does not guarantee correct results; it relies on the sorted order to eliminate halves. Option B is wrong because no runtime exception is thrown by the binary search logic itself; the code compiles and runs, but produces incorrect output. Option C is wrong because there is no compilation error; the method is syntactically valid and will compile successfully.

202
Multi-Selecteasy

Which two of the following are primitive data types in Java? (Choose two)

Select 2 answers
A.boolean
B.double
C.Character
D.String
E.Integer
AnswersA, B

boolean is a primitive type.

Why this answer

`boolean` is a primitive data type in Java that can hold only two values: `true` or `false`. It is not an object and does not have methods, making it a fundamental building block for conditional logic.

Exam trap

The trap here is that candidates often confuse wrapper classes (like `Integer`, `Character`) with their corresponding primitive types, especially when the wrapper name closely resembles the primitive name (e.g., `Integer` vs `int`).

203
MCQeasy

A developer declares an integer variable inside a method but does not assign a value. What is the result of attempting to print the variable?

A.Prints null
B.Compilation error
C.Prints 0
D.Runtime exception
AnswerB

Local variables must be initialized before use.

Why this answer

In Java, local variables (declared inside a method) must be initialized before use. The compiler performs definite assignment analysis and will reject code that attempts to read an uninitialized local variable, producing a compilation error. This rule ensures memory safety and prevents undefined behavior.

Exam trap

Oracle often tests the distinction between local variables (which must be initialized) and instance/class fields (which get default values), trapping candidates who assume all variables default to 0 or null.

How to eliminate wrong answers

Option A is wrong because null is a value that can only be assigned to reference types, not primitive int variables; printing an uninitialized int would not produce null. Option C is wrong because while instance variables of type int default to 0, local variables do not receive default values and must be explicitly assigned. Option D is wrong because the error is caught at compile time, not at runtime; no bytecode is generated for the uninitialized access, so no runtime exception can occur.

204
MCQmedium

What is the output of the code? ```java for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.print(i + " "); } ```

A.0 1 2 3 4
B.1 3 4
C.0 1 2 3
D.0 1 3 4
AnswerD

Correct output.

Why this answer

The code uses a for loop that iterates from i = 0 to i < 5 (i.e., 0 through 4). Inside the loop, there is an if condition that checks if i equals 2. When i == 2, the continue statement is executed, which skips the rest of that iteration, so the System.out.print statement is not executed for i = 2.

Therefore, the loop prints 0, 1, 3, and 4, each followed by a space. Option D correctly lists this output.

Exam trap

The trap here is that candidates may forget that continue skips only the current iteration, not the entire loop, leading them to think the loop stops entirely or to misplace the starting value.

How to eliminate wrong answers

Option A is wrong because it includes 2, which is skipped by the continue statement when i == 2. Option B is wrong because it omits 0, which is printed before the continue condition is met, and also omits 2 but incorrectly includes 1, 3, 4 without 0. Option C is wrong because it stops at 3, missing 4, as the loop condition i < 5 would continue to i = 4.

205
Multi-Selecthard

Which THREE statements are true about the Java logging API (java.util.logging)?

Select 3 answers
A.Handlers can be attached to loggers to output messages
B.The default configuration logs all messages at FINEST level
C.Loggers are organized in a hierarchical namespace
D.All loggers automatically forward messages to the root logger
E.You can set severity levels per logger
AnswersA, C, E

Handlers define output destinations.

Why this answer

The Java Logging API allows Handlers (such as ConsoleHandler, FileHandler, or custom handlers) to be attached to Logger objects to output log messages to destinations like the console, files, or network sockets. This is a core design pattern of the API: loggers produce log records, and handlers are responsible for publishing them.

Exam trap

Oracle often tests the misconception that the default logging level is FINEST or that all loggers automatically forward every message to the root logger, but in reality the default level is INFO and forwarding depends on level checks and the useParentHandlers flag.

206
MCQeasy

A developer writes code to calculate the average of two integers: int a = 5; int b = 10; int avg = a / b;. Which change ensures the average is correctly calculated as a double?

A.No change needed; integer division is correct
B.Change the variable types to double
C.Cast one operand to double: (double) a / b
D.Use Math.round(a / b)
AnswerC

Casting one operand to double ensures floating-point division.

Why this answer

In Java, when both operands of the division operator are integers, integer division is performed, truncating the fractional part. By casting one operand to double, the operation becomes floating-point division, yielding a double result (0.5). This ensures the average is calculated correctly as a double.

Exam trap

Oracle often tests the misconception that changing variable types alone fixes integer division, but the trap is that integer literals (5 and 10) remain int unless explicitly cast or assigned to double variables before the division.

How to eliminate wrong answers

Option A is wrong because integer division of 5 by 10 yields 0, not 0.5, so the average is incorrect. Option B is wrong because simply changing variable types to double would work only if both variables are declared as double; however, the code as written uses int literals, and changing only the variable types without adjusting the literals or division would still result in integer division if the operands remain int. Option D is wrong because Math.round(a / b) first performs integer division (resulting in 0) and then rounds it, still producing 0, not a double average.

207
MCQeasy

Refer to the exhibit. What is the output?

A.3
B.2
C.1
D.0
AnswerB

Correct: The loop increments count for elements 1 and 2 (indices 0 and 1). When arr[1] (value 2) is encountered, the break statement exits the loop, so count is 2.

Why this answer

The code initializes an array `arr` with values {1, 2, 3}. The for loop iterates over the array, and the `if` condition checks if the current element equals 2. When `arr[1]` (value 2) is encountered, the `break` statement exits the loop immediately.

The loop executes only twice (for indices 0 and 1), so the counter `count` is incremented twice, resulting in output 2.

Exam trap

Oracle often tests the interaction between `break` and loop counters, where candidates mistakenly count all array elements or forget that `break` exits immediately without completing the remaining iterations.

How to eliminate wrong answers

Option A is wrong because it assumes the loop completes all three iterations and counts all elements, but the `break` exits early when value 2 is found. Option C is wrong because it suggests only one iteration occurs, but the loop runs for index 0 (value 1) and index 1 (value 2) before breaking, so count becomes 2. Option D is wrong because it implies the loop never executes or count is never incremented, but the loop does execute and increments count for each iteration before the break.

208
Multi-Selecthard

Which THREE are benefits of Java's platform independence? (Choose three.)

Select 3 answers
A.Ability to run on any device with a JVM
B.Write once, run anywhere
C.Faster execution compared to native code
D.Automatic memory management
E.Enhanced security through sandboxing
AnswersA, B, E

Platform independence allows the same bytecode to run on any device that has a JVM implementation.

Why this answer

Options A, B, and E are correct. Java's platform independence allows code to run on any device with a JVM (A), enables the 'write once, run anywhere' principle (B), and enhances security through sandboxing, which isolates untrusted code (E). Option C is incorrect because faster execution compared to native code is not a benefit; Java often runs slower due to interpretation or JIT compilation.

Option D is incorrect because automatic memory management (garbage collection) is a feature of the JVM but not directly a benefit of platform independence; it is a separate advantage of Java.

209
MCQmedium

Which access modifier makes a member visible only within its own class?

A.public
B.private
C.default (no modifier)
D.protected
AnswerB

Only within the class.

Why this answer

The private access modifier restricts visibility to only the class in which the member is declared. No other class, including subclasses or classes in the same package, can access a private member directly. This is the most restrictive access level in Java.

Exam trap

Oracle often tests the misconception that default access is the same as private, or that protected allows access from any class in the same package but not from subclasses in different packages.

How to eliminate wrong answers

Option A is wrong because public makes a member visible to all classes, not just its own class. Option C is wrong because default (no modifier) makes a member visible to all classes within the same package, not just its own class. Option D is wrong because protected makes a member visible to subclasses and classes in the same package, not just its own class.

210
Multi-Selectmedium

A developer is debugging a Java application that throws a NullPointerException. Which two actions help identify the source of the exception? (Choose two.)

Select 2 answers
A.Use System.out.println statements
B.Use a debugger to step through code
C.Examine the stack trace
D.Recompile with -g flag
E.Catch the exception and print its message
AnswersB, C

A debugger allows setting breakpoints and stepping through code to inspect variable values and find where the null reference occurs.

Why this answer

To identify the source of a NullPointerException, the most effective actions are examining the stack trace (option C) and using a debugger (option B). The stack trace shows the exact line number and method call sequence where the exception occurred, pinpointing the location. A debugger allows you to step through code, inspect variable states, and observe the flow leading to the null reference.

While System.out.println (A), catching the exception and printing its message (E), and recompiling with -g (D) can provide debugging information, they are not as direct or efficient for locating the root cause; notably, catching the exception does not prevent it and only prints the message without full stack details.

211
Drag & Dropmedium

Arrange the steps to handle an exception using try-catch-finally 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

The try block contains risky code, catch handles the exception, and finally executes cleanup. The order is try, catch, then finally.

212
Multi-Selecthard

Which THREE statements are true about the break and continue statements in Java? (Choose three.)

Select 3 answers
A.A labeled break can be used to exit an outer loop.
B.The continue statement skips the current iteration and proceeds to the next iteration.
C.The break statement terminates the innermost enclosing loop or switch.
D.The continue statement can be used to exit a loop entirely.
E.The break statement cannot be used outside a loop.
AnswersA, B, C

Correct: labeled break exits outer loop.

Why this answer

A labeled break in Java allows you to specify a label on an outer loop and then use 'break label;' to exit that outer loop directly, not just the innermost loop. This is useful for breaking out of nested loops when a condition is met in an inner loop.

Exam trap

The trap here is that candidates often confuse the behavior of 'continue' (which only skips the current iteration) with 'break' (which terminates the loop), and they may forget that 'break' is also valid in switch statements, not just loops.

213
MCQeasy

Given: String s = "Java"; s.concat(" Rocks"); System.out.println(s); What prints?

A."Java"
B."Rocks"
C.""
D."Java Rocks"
AnswerA

Correct. s still refers to "Java".

Why this answer

Strings in Java are immutable. The `concat()` method returns a new string object 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 "Java".

Exam trap

The trap here is that candidates mistakenly believe `concat()` modifies the original string, confusing it with mutable classes like StringBuilder or StringBuffer, or they forget that the return value must be assigned to capture the result.

How to eliminate wrong answers

Option B is wrong because "Rocks" would only print if the variable `s` had been reassigned to the result of `concat()`, which was not done. Option C is wrong because the string `s` is never set to an empty string; it retains its original value "Java". Option D is wrong because although `concat()` creates a new string "Java Rocks", that new string is not stored or printed; the original `s` is printed instead.

214
MCQmedium

A class defines a static variable initialized at declaration: static int count = 10;. A static method attempts to modify it: count = 20;. Which statement is true?

A.The variable cannot be accessed from a static method
B.The code causes a compilation error
C.The variable can be changed to 20
D.The variable is read-only
AnswerC

Static variables are modifiable unless declared final.

Why this answer

Static variables belong to the class, not instances, and can be accessed and modified by static methods. The assignment `count = 20;` is valid and changes the value from 10 to 20 at runtime.

Exam trap

Oracle often tests the misconception that static methods cannot access static variables, or that static variables are implicitly final, leading candidates to choose compilation error or read-only options.

How to eliminate wrong answers

Option A is wrong because static variables are accessible from static methods; they are class-level members. Option B is wrong because the code compiles successfully; there is no syntax or semantic error in modifying a static variable from a static method. Option D is wrong because static variables are mutable unless declared with the `final` modifier; here `count` is not final, so it is read-write.

215
MCQmedium

The code does not compile. What is the error?

A.Missing semicolon after if condition
B.Variable x is not initialized
C.System.out.println syntax error
D.Assignment instead of comparison in if condition
AnswerD

Correct: x = 5 is assignment, not boolean.

Why this answer

The code uses a single equals sign `=` (assignment) inside the `if` condition instead of `==` (comparison). In Java, `if (x = 5)` assigns the value 5 to `x` and then evaluates the assignment expression to the assigned value (5), which is an `int`, not a `boolean`. The `if` statement requires a `boolean` expression, so this causes a compilation error.

Exam trap

Oracle often tests the distinction between assignment (`=`) and comparison (`==`) in conditional statements, exploiting the fact that beginners mistakenly think assignment is valid in an `if` condition because it works in other languages like C or JavaScript.

How to eliminate wrong answers

Option A is wrong because the `if` statement does not require a semicolon after its condition; a semicolon would actually create an empty statement body. Option B is wrong because variable `x` is initialized (e.g., `int x = 0;` or similar) before the `if` statement in typical code; the error is not about initialization. Option C is wrong because `System.out.println` syntax is correct; the error lies in the `if` condition, not the print statement.

216
Drag & Dropmedium

Arrange the steps to create and use a simple Java inheritance hierarchy 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 create the superclass, then create subclass with extends, override methods if needed, add new members, and then use the subclass.

217
MCQmedium

A novice developer wrote a condition: if (x = 10) { ... } What is the result?

A.The condition always evaluates to true
B.It executes the block if x equals 10
C.Runtime exception thrown
D.Compilation error
AnswerD

x=10 is an assignment expression, returning int, which cannot be used as boolean.

Why this answer

In Java, the assignment operator `=` is used to assign a value, not to compare values. The condition `if (x = 10)` attempts to assign 10 to `x` within an `if` statement, which is not a boolean expression. Java requires the condition in an `if` statement to evaluate to a `boolean`, so this code will not compile.

Option D is correct because the compiler will report an error, typically stating 'incompatible types: int cannot be converted to boolean'.

Exam trap

The trap here is that candidates from other programming backgrounds (like C or JavaScript) may expect the assignment to be treated as a truthy value, but Java strictly requires a boolean condition, making this a compilation error.

How to eliminate wrong answers

Option A is wrong because the condition does not evaluate to true; it is not a valid boolean expression and causes a compilation error. Option B is wrong because the code does not execute the block when x equals 10; the assignment operator `=` changes the value of x to 10, but the expression `x = 10` is an int, not a boolean, so the if statement is invalid. Option C is wrong because no runtime exception occurs; the error is caught at compile time, not at runtime.

218
MCQmedium

A class has a method that is marked as protected. Which statement is true about its accessibility?

A.Only in subclasses
B.Only within the same package
C.Everywhere
D.Only within the same class
E.Within the same package and subclasses
AnswerE

Protected access allows access within the same package and by subclasses even in different packages.

Why this answer

In Java, the protected access modifier allows access within the same package and by subclasses (even if they are in different packages). Option E correctly states this combination, which is the precise definition of protected access as specified in the Java Language Specification (JLS §6.6.2).

Exam trap

The trap here is that candidates often confuse protected with package-private (default) access, forgetting that protected also grants access to subclasses in other packages, or they incorrectly think protected is as restrictive as private.

How to eliminate wrong answers

Option A is wrong because protected access is not limited only to subclasses; it also permits access from classes in the same package. Option B is wrong because protected access extends beyond the same package to subclasses in other packages. Option C is wrong because protected access is not universal; it excludes unrelated classes in different packages.

Option D is wrong because protected access is broader than only within the same class; that is the scope of private access.

219
MCQeasy

A method is expected to receive an integer and return its square. Which method signature is correct?

A.void square(int x) { return x*x; }
B.public square(int x) { return x*x; }
C.int square(int x) { x*x; }
D.int square(int x) { return x*x; }
AnswerD

Correct return type and syntax.

Why this answer

The method signature specifies a return type of 'int' and includes the 'return' keyword to return the squared value. In Java, a method that returns a value must declare the return type before the method name and must use the 'return' statement to send the result back to the caller.

Exam trap

Oracle often tests the distinction between method declaration and method signature, and the trap here is that candidates may forget that a non-void method must include a 'return' statement with a matching value, or they may confuse 'void' with a return type that allows returning a value.

How to eliminate wrong answers

Option A is wrong because the return type is 'void', which means the method cannot return a value, yet it attempts to use 'return x*x'. Option B is wrong because it omits the return type entirely; in Java, every method must declare a return type (or 'void'). Option C is wrong because it declares a return type of 'int' but does not include a 'return' statement; the method body must contain 'return x*x' to actually return the squared value.

220
MCQmedium

Given: int day = 3; switch(day) { case 1: System.out.print("A"); case 2: System.out.print("B"); case 3: System.out.print("C"); case 4: System.out.print("D"); } What prints?

A."BCD"
B."CD"
C."C"
D."ABCD"
AnswerB

Correct. Falls through from case 3 to case 4.

Why this answer

The switch statement does not have break statements, so after matching case 3, execution falls through to case 4, printing 'C' then 'D'. The output is 'CD'.

Exam trap

The 1Z0-811 exam often tests fall-through behavior by omitting break statements, trapping candidates who assume only the matched case executes.

How to eliminate wrong answers

Option A is wrong because it assumes fall-through stops at case 3, but case 4 also executes. Option C is wrong because it ignores fall-through to case 4. Option D is wrong because it assumes fall-through from case 1 through case 4, but the switch starts at case 3.

221
Multi-Selectmedium

Which two statements about the Arrays class are true? (Choose two.)

Select 2 answers
A.The Arrays class provides a method to sort only arrays of primitive types.
B.The Arrays class provides a method to fill an array with a specific value.
C.The Arrays class provides a method to perform binary search on any array.
D.The Arrays class provides a method to deep copy an array.
E.The Arrays class provides a method to convert an array to a List.
AnswersB, E

Arrays.fill() sets all elements to the specified value.

Why this answer

The `Arrays.fill()` method allows you to assign a specific value to every element of an array, or to a specified range within the array. This is a static utility method provided by the `java.util.Arrays` class, and it works for both primitive and object arrays.

Exam trap

The 1Z0-811 exam often tests the misconception that `Arrays.binarySearch()` works on any array, but it requires a sorted array; also, candidates may confuse `Arrays.copyOf()` with a deep copy, but it only performs a shallow copy.

222
Multi-Selecthard

Which three statements about the switch statement in Java are true?

Select 3 answers
A.a break statement is optional
B.switch can use char as the expression type
C.the switch statement can have multiple default cases
D.the default case is executed when no other case matches
E.switch can use boolean as the expression type
AnswersA, B, D

A `break` statement is indeed optional within a Java `switch` block, satisfying the 'true' constraint. Its omission results in "fall-through" behaviour, where execution continues into subsequent `case` blocks until a `break` is encountered or the `switch` block ends. This deliberate design allows for scenarios where multiple `case` labels should execute the same code, making `break` a control flow choice rather than a mandatory syntax element.

Why this answer

Options A, B, and D are true. A: The break statement is optional; without it, execution falls through to the next case. B: char can be used as the switch expression type because char is an integer-compatible type.

D: The default case executes when no other case matches. C is false because only one default case is allowed. E is false because boolean is not allowed as a switch expression.

223
MCQhard

You are developing a Java application for a library management system. The system must track the number of books in each genre. You need to store genre names (String) and their counts (int). The data will be accessed frequently and modified rarely. Which Java data structure should you use to store this mapping efficiently, while ensuring that genre names are unique?

A.ArrayList<Book>
B.LinkedList<String>
C.HashSet<String>
D.HashMap<String, Integer>
AnswerD

Maps unique genre to count.

Why this answer

HashMap<String, Integer> is the correct choice because it stores key-value pairs, where each genre name (String) is a unique key mapped to its count (Integer). This provides O(1) average-time complexity for lookups and updates, which is ideal for frequent access and rare modifications. The HashMap ensures key uniqueness via its hash-based implementation, directly meeting the requirement of unique genre names.

Exam trap

Oracle often tests the distinction between collections that store single elements (like HashSet) versus those that store key-value pairs (like HashMap), leading candidates to choose HashSet when a mapping is required.

How to eliminate wrong answers

Option A is wrong because ArrayList<Book> is a list of Book objects, not a mapping structure; it cannot store key-value pairs or enforce uniqueness of genre names. Option B is wrong because LinkedList<String> is a sequential list that only stores a single type (String) without any mapping capability, and it does not enforce uniqueness of elements. Option C is wrong because HashSet<String> stores unique strings but cannot associate a count (int) with each genre name; it lacks the key-value mapping required for this use case.

224
Multi-Selecthard

Which THREE of the following expressions compile without error? (Choose 3)

Select 3 answers
A.byte b = 1 + 2;
B.int i = 5L + 10;
C.double d = 10;
D.boolean b = (false || true);
E.float f = 5.5;
AnswersA, C, D

Compile-time constant, fits byte.

Why this answer

Options A, C, D are correct. A: byte addition promoted to int, then assigned to byte requires explicit cast? Actually byte + byte = int, but assignment to byte will require explicit cast. Wait: byte b = 1+2? 1 and 2 are literals, compile-time constant, so assignment is allowed because constant expression.

Actually 1 and 2 are int literals, but the result is compile-time constant 3, which fits in byte, so it's allowed. So A compiles. B: int + long = long, assigning to int requires explicit cast, so compile error.

C: double d = 10; 10 is int, widening assignment to double is fine. D: boolean b = (false || true); boolean expression, fine. E: float f = 5.5; 5.5 is double by default, requires explicit cast or f suffix, so compile error.

So correct: A, C, D.

Page 2

Page 3 of 7

Page 4

All pages