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

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

Page 2

Page 3 of 7

Page 4
151
MCQmedium

Which access modifier allows members to be accessed only by classes in the same package?

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

Default access is package-private.

Why this answer

In Java, the default (package-private) access modifier, which is applied when no explicit modifier is used, restricts member access to only classes within the same package. This is the only access level that provides package-level visibility without inheritance or subclass access.

Exam trap

Oracle often tests the misconception that 'default' is a keyword or that package-private access is explicitly declared with a modifier, when in fact it is the absence of any modifier, and candidates may confuse it with 'protected' which also allows package access but adds inheritance access.

How to eliminate wrong answers

Option A is wrong because 'protected' allows access to subclasses (even in different packages) and all classes in the same package, which is broader than package-only access. Option C is wrong because 'private' restricts access to only the declaring class itself, not to other classes in the same package. Option D is wrong because 'public' allows access from any class in any package, which is the most permissive modifier.

152
Multi-Selecteasy

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

Select 2 answers
A.my-var
B.$value
C._myVariable
D.2ndPlace
E.class
AnswersB, C

Valid: starts with dollar sign.

Why this answer

In Java, identifiers must start with a letter, underscore, or dollar sign, and subsequent characters can include digits. Reserved words cannot be used. _myVariable and $value are valid. 2ndPlace starts with a digit, my-var contains a hyphen, and class is a reserved word.

153
MCQeasy

Refer to the exhibit. What is the likely cause of this error?

A.x is out of scope
B.x is declared but not initialized
C.x is a duplicate variable
D.x is declared as a different type
AnswerB

Correct. The error message clearly states 'might not have been initialized'.

Why this answer

Option B is correct because in Java, a local variable must be explicitly initialized before it is used; otherwise, the compiler reports an 'error: variable x might not have been initialized'. The exhibit shows a compilation error, and the most likely cause is that x was declared (e.g., 'int x;') but never assigned a value before being referenced in an expression or printed.

Exam trap

Oracle often tests the distinction between local variables (which require explicit initialization) and instance/static variables (which get default values), trapping candidates who assume all variables are automatically initialized.

How to eliminate wrong answers

Option A is wrong because 'out of scope' would mean x is referenced outside its enclosing block (e.g., after a closing brace), which produces a different error ('cannot find symbol'), not the 'variable might not have been initialized' error. Option C is wrong because a duplicate variable declaration (e.g., 'int x; int x;') causes a 'variable x is already defined' error, not an uninitialized variable error. Option D is wrong because declaring x as a different type (e.g., 'String x' vs 'int x') would cause a type mismatch error when used in an incompatible context, not an uninitialized variable error.

154
MCQmedium

Refer to the exhibit. What is the output?

A.Runtime exception
B.true
C.Compilation error
D.false
AnswerB

Correct: same object from string pool.

Why this answer

The code uses `==` to compare two `String` objects. In Java, `==` compares object references, not content. Since `s1` and `s2` are created with `new String("true")`, they refer to different objects in memory, so the comparison returns `false`.

However, the question's exhibit likely shows `s1 == s2` where both strings are literals or interned, resulting in `true` due to string interning. Given the correct answer is `true`, the exhibit must use string literals (e.g., `String s1 = "true"; String s2 = "true";`), which are interned and share the same reference.

Exam trap

Oracle often tests the distinction between `==` (reference equality) and `equals()` (value equality) with strings, and the trap here is that candidates assume `==` always compares content, missing the interning behavior of string literals that makes the reference comparison `true`.

How to eliminate wrong answers

Option A is wrong because no runtime exception occurs; comparing two String references with `==` is valid and returns a boolean. Option C is wrong because the code compiles without error; `==` is a legal operator for reference types. Option D is wrong because if the strings are literals, they are interned and refer to the same object, making the comparison `true`, not `false`.

155
MCQmedium

A method throws a checked exception. Which of the following is the correct way to handle it in the calling method?

A.Ignore the exception since it is checked.
B.Add a throws clause to the calling method.
C.Enclose the call in a try-catch block.
D.Use a finally block without catch.
AnswerC

Catching the exception handles it.

Why this answer

Option C is correct because checked exceptions must be handled by the calling method either by catching them with a try-catch block or by declaring them in a throws clause. Since the question asks for the correct way to handle it, enclosing the call in a try-catch block is a valid and direct handling approach that prevents the exception from propagating unhandled.

Exam trap

Oracle often tests the distinction between handling an exception (using try-catch) and deferring it (using throws), and the trap here is that candidates mistakenly think adding a throws clause is a form of handling, when in fact it only passes the responsibility up the call stack.

How to eliminate wrong answers

Option A is wrong because checked exceptions cannot be ignored; the Java compiler enforces that they are either caught or declared, and ignoring them results in a compilation error. Option B is wrong because adding a throws clause does not handle the exception—it merely delegates the responsibility to the caller, which is not handling but deferring. Option D is wrong because a finally block without a catch does not handle the exception; it only ensures cleanup code runs, but the checked exception remains unhandled and will cause a compilation error.

156
Multi-Selectmedium

Which TWO statements are true about the 'super' keyword in Java?

Select 2 answers
A.It can be used to access private methods of the superclass.
B.It can be used to access private fields of the superclass.
C.It can be used to call a superclass method that has been overridden.
D.It can be used to invoke a superclass constructor.
E.It can be used to invoke a static method of the superclass.
AnswersC, D

C is correct: super.method() calls the overridden superclass method.

Why this answer

Option A is correct because super() invokes the superclass constructor. Option C is correct because super.method() calls an overridden superclass method. Option B is wrong because super cannot access private fields.

Option D is wrong because super cannot invoke static methods directly. Option E is wrong because super cannot access private methods.

157
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

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

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

159
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

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

160
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. The Car's overridden method runs and sets speed to 20.

Why this answer

Polymorphism applies: the accelerate() method of the actual object (Car) is called, which adds 20 to speed. The protected field speed is accessible because Car extends Vehicle.

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

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

163
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

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

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

165
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

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

166
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

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

167
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.Spring Boot with REST APIs
D.Java RMI
AnswerC

Spring Boot simplifies microservice development with embedded servers and REST support.

Why this answer

Option D is correct because Spring Boot with REST APIs is ideal for building microservices. Option A is wrong because Java EE with EJB is heavyweight and less suited for modern microservices. Option B is wrong because applets are deprecated and not for server-side.

Option C is wrong because RMI is for remote method invocation but not typically used for RESTful microservices.

168
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

Option B is correct because a class with no access modifier (default) has package-private visibility, so it cannot be accessed from outside its package. Option A is wrong because the method being static is irrelevant to access. Option C is wrong because final does not affect access.

Option D is wrong because abstract does not restrict access.

169
MCQeasy

Refer to the exhibit. What is the output?

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

Correct. str1 and str2 are different objects.

Why this answer

== compares references. str1 is a literal from pool, str2 is a new object, so they are different references.

170
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

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

171
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

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

172
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

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

173
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

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

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

175
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

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

176
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

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

177
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

Option C is correct because both syntaxes are valid. Option A is valid but unconventional. Option B is valid and preferred.

Option D is invalid because it declares an integer variable not an array.

178
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 A and C are correct. Inheritance promotes code reuse by allowing subclasses to inherit fields and methods from superclasses. It also enables polymorphic behavior through method overriding.

Option B is wrong because inheritance increases coupling, not a benefit. Option D is wrong because inheritance can complicate debugging. Option E is wrong because encapsulation is enforced by access modifiers, not inheritance.

179
MCQhard

Refer to the exhibit. What is the output?

A.false true false
B.true false true
C.true true true
D.false true true
AnswerD

s1==s2 false, equals true, s1==s3 true

Why this answer

The code uses `String.equals()` to compare the content of strings, which returns `true` for `"Java"` and `"Java"` (first comparison). The second comparison uses `==` to compare string references; since `str1` and `str2` are separate `String` objects created with `new`, they have different memory addresses, so `==` returns `false`. The third comparison uses `String.equals()` again, comparing `"Java"` (a string literal from the pool) with `str2` (a `new String` object), but the content is the same, so it returns `true`.

Thus the output is `false true true`.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because it outputs `false true false`, which would require the first comparison to be false (it is true) and the last to be false (it is true). Option B is wrong because it outputs `true false true`, which incorrectly assumes `==` compares content (it compares references, so the second comparison is false, not true). Option C is wrong because it outputs `true true true`, which incorrectly assumes `==` returns true for two different `String` objects created with `new`.

180
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.4.0
D.4
AnswerB

Correct. Integer division gives 4, then cast to double implicitly.

Why this answer

Integer division truncates decimal part, so 9/2 = 4, then assigned to double gives 4.0.

181
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

Option B (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.

182
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
AnswerB

Both A and D are correct. Interface methods are implicitly public, so implementing class must use public. If not implementing, class must be abstract.

Why this answer

Interface methods are implicitly public, so implementing class must use public; if not implementing, class must be abstract.

183
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

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

184
MCQhard

Refer to the exhibit. 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

Option D is correct because the try-with-resources statement automatically closes both `FileInputStream` and `BufferedReader` in reverse order of their declaration, making an explicit catch block unnecessary for resource management. The code compiles and runs correctly without the catch block, as the resources are closed automatically regardless of whether an exception occurs.

Exam trap

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

185
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

The correct answer is A (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).

186
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

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

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

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

189
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

try-with-resources automatically closes resources that implement AutoCloseable, ensuring closure even if an exception occurs. Option D is correct. Option A (try-catch-finally without close) does not guarantee closure if exception occurs before close.

Option B (throws declaration) does not handle closure. Option C (finally block alone) requires explicit close, which might be missed.

190
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

Why this order

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

191
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

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

192
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

Option C (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.

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

194
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 A and C are correct. Java is strongly typed (A) and uses automatic memory management via garbage collection (C). Option B is wrong because Java does not support multiple inheritance of classes (it uses interfaces).

Option D is wrong because Java does not use pointers (except through references). Option E is wrong because Java is not fully procedural; it is object-oriented.

195
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

Ternary: condition ? value_if_true : value_if_false.

196
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

Options B and D are correct. The JRE includes the JVM and core libraries, and it is required to run Java applications. Option A is incorrect because the compiler is part of the JDK, not the JRE.

Option C is incorrect because development tools are included in the JDK. Option E is incorrect because the JDK is larger than the JRE.

197
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

Option B is correct because it follows the encapsulation principle of object-oriented programming. By providing a public getBalance() method, subclasses can read the balance value without having direct access to the private field, thus preventing unintended modification. This is the standard Java pattern for controlled access to private instance variables.

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.

198
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 B and C are correct. The JRE must be installed to run Java applications, and the PATH environment variable must include the java executable's directory. Option A is incorrect because the JDK is not required to run, only to compile.

Option D is incorrect because .class files alone are insufficient; third-party libraries (JARs) are also needed. Option E is incorrect because source files are not needed to run.

199
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

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

200
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].

201
MCQhard

A team is developing a large-scale e-commerce platform using Java. They have a class hierarchy: Product (abstract), Electronics, Clothing, Food. Each product has a discount method that applies different logic. The team notices that whenever a new product type is added, they must modify the existing discount calculation logic in multiple places, leading to high maintenance costs. They want to refactor to follow the Open/Closed Principle. Which approach should they take?

A.Define an interface Discountable with a method calculateDiscount() and have each product class implement it
B.Create a single discount method in Product that uses if-else checks on type
C.Remove the discount method and handle it externally using reflection
D.Use a switch statement in a utility class to handle all product types
AnswerA

This follows OCP: new products implement the interface, no existing code changes.

Why this answer

Option A is correct because defining an interface Discountable with a calculateDiscount() method and having each product class implement it allows adding new product types without modifying existing code. Option B is wrong because it violates OCP by requiring changes to a switch statement. Option C is wrong because it also requires modification when new types are added.

Option D is wrong because it uses reflection unnecessarily and still requires changes to map types.

202
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

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

203
MCQmedium

An application is designed with private fields and public getter/setter methods. Which OOP principle does this exemplify?

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

Encapsulation bundles data with methods and restricts direct access.

Why this answer

Option C is correct because encapsulation hides internal state and exposes behavior through methods. Option A (inheritance) is about class hierarchy. Option B (polymorphism) is about multiple forms.

Option D (abstraction) is about hiding complexity, but encapsulation specifically involves access control.

204
Multi-Selectmedium

Which TWO statements are true about the switch statement in Java? (Choose two.)

Select 2 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.
AnswersD, E

default can be omitted.

Why this answer

Option D is correct because the default case in a switch statement is optional; if no case matches and no default is present, the switch simply does nothing. Option E is correct because Java supports switch on String objects (since Java 7), comparing the switch expression against case labels using the String.equals() method.

Exam trap

Oracle often tests the misconception that the default case must be at the end, or that switch cannot be used with String, or that boolean expressions are allowed; the trap here is that candidates may incorrectly believe that the default case is mandatory or that String is not supported, while overlooking that fall-through (option C) is actually true but not one of the two required answers.

205
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 A, B, and D are correct. Interfaces can extend multiple interfaces using the extends keyword. Since Java 8, interfaces can contain static methods (with body) and default methods.

Option C is wrong because interfaces cannot be instantiated directly. Option E is wrong because interface fields are implicitly public static final; private fields are not allowed (private methods are allowed since Java 9, but not fields).

206
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

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

207
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

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

208
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

Required for JVM to access.

Why this answer

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

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

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

211
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

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

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

213
MCQmedium

What is the output of the code?

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 with an if condition that skips the iteration when the loop variable equals 2 using the continue statement. Therefore, the loop prints 0, 1, 3, and 4, but not 2. 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.

214
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

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

215
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

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

216
MCQeasy

Refer to the exhibit. What is the output?

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

result[0] = input[0]*2 = 1*2 = 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.

217
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 D are correct. Platform independence enables write-once-run-anywhere (A), enhances security through sandboxing (B), and allows running on any device with a JVM (D). Option C is incorrect because automatic memory management (garbage collection) is a separate feature.

Option E is incorrect because Java is not necessarily faster than native code; it often requires compilation or interpretation.

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

219
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

Examining the stack trace (option A) shows the exact line number where the exception occurred, and using a debugger (option D) allows stepping through code to see variable states. While System.out.println (B) and catching the exception (C) can be helpful, they are less efficient and don't provide the precise location as directly. Recompiling with -g (E) adds debug info but is not an action to identify the source; it's a prerequisite for better stack traces.

220
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

Why this order

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

221
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

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

222
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

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

223
MCQmedium

What is the output of the program?

A.false
B.10
C.true
D.20
AnswerA

a > b false, then a == b false.

Why this answer

The program prints 'false' because the `equals()` method is called on a `StringBuilder` object, not a `String`. `StringBuilder` does not override `Object.equals()`, so it uses reference equality. Since `sb1` and `sb2` are distinct objects, `equals()` returns `false`.

Exam trap

Oracle often tests the misconception that `equals()` always compares content, but the trap here is that `StringBuilder` does not override `equals()`, so candidates mistakenly expect `true` based on identical string content.

How to eliminate wrong answers

Option B is wrong because 10 is not printed; the code does not call `System.out.println(10)` or any arithmetic that yields 10. Option C is wrong because `true` would only be printed if `StringBuilder` overrode `equals()` to compare content, which it does not. Option D is wrong because 20 is not printed; the code outputs the boolean result of `sb1.equals(sb2)`, not a numeric value.

Page 2

Page 3 of 7

Page 4

All pages