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

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

Page 1 of 7

Page 2
1
MCQhard

A developer needs to implement a menu-driven program that repeatedly displays options, reads input, and processes the choice until the user selects 'Exit'. Which loop structure and control flow is most appropriate?

A.for loop with break condition and nested if-else
B.for(;;) loop with if-else chain
C.do-while loop with switch statement
D.while(true) loop with if-else chain
AnswerC

Ensures menu displays once, switch is clear for multiple options.

Why this answer

Option C is correct because a do-while loop guarantees at least one iteration, which is ideal for menu-driven programs where the menu must be displayed before any input is processed. The switch statement provides a clean, readable way to handle multiple discrete choices (like menu options) compared to a chain of if-else statements, and it aligns with Java's control flow best practices for such scenarios.

Exam trap

Oracle often tests the misconception that while(true) or for(;;) loops are always appropriate for menu-driven programs, but they overlook the do-while's guarantee of at least one iteration, which is essential when the menu must be shown before any user input is read.

How to eliminate wrong answers

Option A is wrong because a for loop with a break condition and nested if-else is unnecessarily complex for a menu-driven program; the for loop is typically used for a known number of iterations, not indefinite user-driven loops, and the nested if-else makes the code less readable and harder to maintain than a switch. Option B is wrong because for(;;) is an infinite loop that works syntactically, but it lacks the guarantee of at least one iteration that a do-while provides, and using an if-else chain instead of a switch for multiple menu options is less efficient and less clear in Java. Option D is wrong because while(true) creates an infinite loop that, like for(;;), does not guarantee the menu is displayed before the first input check, and an if-else chain for multiple discrete options is inferior to a switch statement in terms of readability and performance when handling many cases.

2
MCQeasy

Refer to the exhibit. What is the likely cause?

A.The package is missing
B.The variable 'value' is not declared
C.The class name is misspelled
D.The variable 'value' is out of scope
E.The variable 'value' is declared but not initialized
AnswerB

The error indicates that the symbol 'value' cannot be found, meaning it is not declared in the class.

Why this answer

Option B is correct because the error message indicates that the variable 'value' has not been declared before use. In Java, every variable must be declared with a type and name before it can be referenced. The compiler cannot find a declaration for 'value' in the current scope, so it reports a 'cannot find symbol' error, which is the typical symptom of an undeclared variable.

Exam trap

Oracle often tests the difference between 'undeclared', 'out of scope', and 'uninitialized' by presenting an error message that could be interpreted in multiple ways, and the trap is that candidates confuse 'undeclared' with 'out of scope' because both produce a 'cannot find symbol' error, but only the former means the variable was never declared at all.

How to eliminate wrong answers

Option A is wrong because a missing package would cause a compilation error related to the package declaration or import, not a 'cannot find symbol' error for a local variable. Option C is wrong because a misspelled class name would produce a different error, such as 'cannot find symbol' for the class itself, not for a variable named 'value'. Option D is wrong because if 'value' were out of scope, the error would still be 'cannot find symbol', but the question's exhibit shows no declaration at all, making 'undeclared' the precise cause rather than scope.

Option E is wrong because a declared but uninitialized variable would compile (with a warning about potential use before initialization) but would not cause a 'cannot find symbol' error; the compiler would recognize the variable's declaration.

3
MCQhard

Given: boolean a = false; boolean b = true; boolean c = true; System.out.println(a || b && c); What is the output?

A.false
B.Compilation fails
C.None of the above
D.true
AnswerD

Correct due to operator precedence.

Why this answer

In Java, the logical AND operator (&&) has higher precedence than the logical OR operator (||). Therefore, the expression `a || b && c` is evaluated as `a || (b && c)`. Given `a = false`, `b = true`, and `c = true`, `b && c` evaluates to `true`, and then `false || true` evaluates to `true`.

Thus, the output is `true`, making option D correct.

Exam trap

The trap here is that candidates often evaluate the expression left-to-right without considering operator precedence, mistakenly thinking `a || b` is evaluated first (which would be `true`) and then `&& c` would produce `true && true` = `true`, but the actual precedence changes the grouping, though in this specific case both orders yield `true`; however, the trap is to test whether you know the precedence rule, not just the outcome.

How to eliminate wrong answers

Option A is wrong because it assumes the expression evaluates to `false`, which would only happen if both sides of the `||` were false, but `b && c` is true. Option B is wrong because the code compiles successfully; all variables are declared with valid boolean literals and the operators are correctly applied. Option C is wrong because 'None of the above' is not correct since option D provides the accurate output.

4
MCQmedium

A method 'public static void sort(int[] arr)' sorts the array in place. After calling 'sort(data)', the original array 'data' is changed. Which design issue does this demonstrate?

A.The method should use a wrapper class for the array.
B.The method should be declared as void to indicate modification.
C.The method should return a new array to avoid side effects.
D.The method should use pass-by-value to avoid modification.
AnswerC

Changing the original array can lead to unexpected behavior; returning a new array is a common practice.

Why this answer

Option C is correct because the method modifies the original array passed as an argument, which is a side effect. In Java, arrays are objects, and when passed to a method, the reference is passed by value, allowing the method to modify the array's contents. To avoid side effects and maintain immutability, the method should return a new sorted array instead of modifying the original.

Exam trap

The trap here is that candidates often confuse pass-by-value for objects with pass-by-reference, thinking that Java passes objects by reference, which would make modification expected, but the real issue is that the method's side effect violates the principle of least surprise and should be avoided by returning a new array.

How to eliminate wrong answers

Option A is wrong because using a wrapper class for the array does not prevent modification; the wrapper would still hold a reference to the same array, and the method could modify its contents. Option B is wrong because declaring the method as void does not indicate or prevent modification; it merely means the method does not return a value, but it can still modify the array in place. Option D is wrong because Java always uses pass-by-value for method arguments; for objects (including arrays), the reference is passed by value, so the method can modify the object's state, and this is not a design issue but a fundamental language behavior.

5
MCQeasy

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

A.Compilation fails
B.false
C.true
D.Hello
AnswerC

Both references point to the same interned string.

Why this answer

Option C is correct because string literals in Java are interned, meaning both s1 and s2 refer to the same String object in the string constant pool. The == operator compares object references, not content, so since both variables point to the same interned string, the comparison yields true.

Exam trap

The trap here is that candidates often confuse reference equality (==) with value equality (.equals()), assuming == always returns false for distinct string variables, without considering string interning of literals.

How to eliminate wrong answers

Option A is wrong because the code compiles without error; string literals are valid and the == operator is allowed on object references. Option B is wrong because it assumes == compares string content, which would be false only if the strings were created with new String("Hello") or were not interned; here both literals are interned, so references are equal. Option D is wrong because System.out.println does not print the string value when given a boolean expression; it prints the boolean result of the comparison.

6
Multi-Selecthard

Which TWO statements about the enhanced for loop (for-each) are correct?

Select 2 answers
A.It can iterate over any object that implements the Iterable interface.
B.It can be used to modify the elements of an array.
C.It can only be used with collections.
D.It provides an implicit counter variable.
E.It can iterate over arrays.
AnswersA, E

This includes Collection classes.

Why this answer

Option A is correct because the enhanced for loop (for-each) works with any object that implements the Iterable interface, which includes all Collection classes (like ArrayList, HashSet) and arrays. This allows the loop to iterate over elements without needing an explicit iterator or index, relying on the iterator() method provided by the Iterable contract.

Exam trap

The trap here is that candidates often think the enhanced for loop can modify elements (Option B) because they confuse the loop variable with a reference that can change the original object's state, but it only allows reading, not structural modification.

7
MCQeasy

A social media platform processes user login requests. Each request generates a welcome message by concatenating the username with a fixed greeting using the + operator inside a loop that runs hundreds of times per second for thousands of users. The development team notices that the application suffers from high memory consumption and slow response times under load. They profile the code and discover that the method building the welcome message is a bottleneck. The team considers several options to improve performance while maintaining thread safety. Which approach should the team implement?

A.Replace string concatenation with StringBuffer and use an initial capacity to minimize resizing.
B.Replace string concatenation with StringBuilder and allocate an initial capacity large enough to hold the final message.
C.Keep using the + operator but call intern() on the resulting string to reuse memory.
D.Replace string concatenation with the concat() method called on the greeting string.
AnswerB

Correct: StringBuilder is efficient and non-synchronized; initial capacity avoids resizing.

Why this answer

Option B is correct: StringBuilder with sufficient initial capacity reduces memory reallocations and is faster than StringBuffer for single-threaded contexts. Option A (StringBuffer) is thread-safe but slower due to synchronization, not needed here since the method is not shared across threads. Option C (concat()) still creates new strings internally, similar to + operator.

Option D (intern()) does not improve performance and may cause memory issues.

8
MCQmedium

A method is declared as: public void setAge(int age) { this.age = age; } Which statement is correct about this code assuming the class has an instance variable age?

A.The method is a constructor.
B.The method will cause a compilation error.
C.The method sets the instance variable age.
D.The method is static.
AnswerC

Uses 'this.age' to refer to instance variable.

Why this answer

Option C is correct because the method `setAge(int age)` uses the `this` keyword to assign the parameter value to the instance variable `age`, which is a standard setter pattern in Java. The method has a `void` return type and is not a constructor, and it compiles successfully because the instance variable `age` is assumed to exist in the class.

Exam trap

Oracle often tests the distinction between constructors and regular methods by including a `void` return type, which immediately disqualifies a method from being a constructor, even if it looks like one due to parameter assignment.

How to eliminate wrong answers

Option A is wrong because a constructor must have the same name as the class and no return type, not even `void`; this method has a return type of `void` and is named `setAge`, not matching the class name. Option B is wrong because the code compiles without error as long as the class has an instance variable named `age`; the `this` keyword correctly disambiguates the parameter from the instance variable. Option D is wrong because the method is not declared with the `static` keyword, so it is an instance method that operates on the current object's state.

9
MCQhard

Which of the following is a valid declaration of a float variable?

A.Both B and C are valid
B.float f = 10.5f;
C.float f = 10.5;
D.float f = 10.5F;
AnswerA

Both f and F suffixes denote float literal.

Why this answer

Float literals require suffix f or F. Without suffix, the literal is double and causes compilation error.

10
MCQmedium

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

A.compareTo()
B.=
C.==
D.equals()
AnswerD

Correct for value equality.

Why this answer

Option D is correct because the equals() method in Java's String class compares the actual character sequences of two strings for value equality. Unlike the == operator, which checks reference equality (whether two references point to the same object in memory), equals() performs a lexicographic comparison of the string contents, returning true if and only if both strings have the same length and the same characters in the same order.

Exam trap

The trap here is that candidates often confuse == with equals() because == works for primitive types (like int or char) to compare values, but for String objects it compares references, leading to incorrect results when comparing string contents.

How to eliminate wrong answers

Option A is wrong because compareTo() is a method that compares strings lexicographically and returns an integer (negative, zero, or positive) indicating the ordering, not a boolean value for equality. Option B is wrong because = is the assignment operator, used to assign a value to a variable, not a comparison operator. Option C is wrong because == checks reference equality for objects, including strings; it returns true only if both references point to the exact same String object in memory, not if the string contents are equal.

11
MCQeasy

In a Java method, a developer needs to skip the current iteration and move to the next when a certain condition is met inside a for loop. Which statement should be used?

A.return;
B.exit;
C.continue;
D.break;
AnswerC

Continue skips the current iteration and proceeds to the next.

Why this answer

Option D is correct because continue skips the rest of the loop body for the current iteration. Option A is wrong because return exits the method. Option B is wrong because break exits the loop.

Option C is wrong because exit is not a Java keyword.

12
MCQmedium

A program needs to read user input until 'quit' is entered. Which loop ensures that the condition is evaluated after executing the body at least once?

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

Do-while always executes body at least once before checking condition.

Why this answer

The do-while loop is the only loop construct in Java that guarantees the loop body executes at least once before the condition is evaluated. This is because the condition is checked after the body runs, making it ideal for scenarios like reading user input until a sentinel value like 'quit' is entered, where the first input must be processed before checking.

Exam trap

Oracle often tests the distinction between pre-test and post-test loops, and the trap here is that candidates confuse the while loop (which may execute zero times) with the do-while loop (which always executes at least once), especially when the problem explicitly requires the body to run before the condition check.

How to eliminate wrong answers

Option A is wrong because an enhanced for loop is designed to iterate over arrays or collections and cannot be used for conditional input reading; it always checks the iteration condition before entering the body. Option B is wrong because a for loop evaluates its condition before each iteration, so the body may never execute if the condition is initially false. Option C is wrong because a while loop checks the condition before executing the body, meaning it can execute zero times if the condition is false from the start.

13
MCQeasy

Which method overloading is valid?

A.void print(int a) and void print(int b) {}
B.void print(int a) and int print(int a) {}
C.void print(int a) and private void print(int a) {}
D.void print(int a) and void print(String s) {}
AnswerD

Different parameter types - valid overloading.

Why this answer

Option D is correct because method overloading in Java requires methods to have the same name but different parameter lists (different number, type, or order of parameters). Here, `void print(int a)` and `void print(String s)` have different parameter types (`int` vs `String`), which satisfies the overloading rule. The return type or access modifiers do not affect overloading.

Exam trap

Oracle often tests the misconception that changing the return type or access modifier alone is sufficient for method overloading, but the key requirement is a different parameter list.

How to eliminate wrong answers

Option A is wrong because it defines two methods with identical signatures (`void print(int a)` and `void print(int b)` — parameter names are irrelevant, only types and order matter), which causes a compilation error due to duplicate method definition. Option B is wrong because changing only the return type (`int` vs `void`) does not constitute overloading; the parameter list must differ, and this results in a compilation error. Option C is wrong because changing only the access modifier (`public` vs `private`) does not change the method signature; the parameter list is identical, so it is a duplicate method definition, not overloading.

14
MCQhard

Refer to the exhibit. What is the result?

A.Compilation error
B.0
C.Runtime exception
D.Infinity
AnswerC

Correct: ArithmeticException thrown.

Why this answer

The code attempts to divide an integer by zero, which in Java throws an ArithmeticException at runtime. Since the division is performed with integer operands (int / int), Java does not allow division by zero and raises an exception, not a floating-point infinity or zero. Therefore, the correct answer is C: Runtime exception.

Exam trap

Oracle often tests the difference between integer and floating-point division by zero, trapping candidates who assume all division by zero yields Infinity or a compile error, when in fact integer division throws a runtime exception.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; division by zero is a runtime issue, not a compile-time error. Option B is wrong because integer division by zero does not yield 0; it throws an exception instead. Option D is wrong because Infinity is only produced in floating-point arithmetic (e.g., double / 0.0), not in integer division, which throws an exception.

15
Multi-Selecthard

Which three of the following statements about primitive type conversion are true?

Select 3 answers
A.A float can be implicitly converted to long.
B.Implicit widening conversion is allowed from int to long.
C.A boolean can be converted to int using casting.
D.A char can be assigned to an int without cast because char is unsigned 16-bit and int is 32-bit.
E.Narrowing conversion from double to int requires an explicit cast.
AnswersB, D, E

int to long is a widening primitive conversion.

Why this answer

A is true: int to long is widening. B is true: narrowing double to int requires explicit cast. C is false: boolean cannot be cast to numeric types.

D is true: char to int is widening. E is false: float to long requires explicit cast.

16
Multi-Selecteasy

Which two statements about the break statement in Java are true?

Select 2 answers
A.break can be used inside a switch case
B.break can be used without any enclosing loop
C.break is used to skip to next iteration
D.break with label exits the labeled loop
E.break exits the current loop iteration
AnswersA, D

break is commonly used in switch to prevent fall-through.

Why this answer

Options B and D are true. B: break can be used in a switch case. D: break with a label exits the labeled loop.

A is false because break exits the entire loop, not just the iteration. C is false because continue skips iterations. E is false because break requires an enclosing loop or switch.

17
Multi-Selectmedium

Which TWO are valid ways to pass an array to a method in Java?

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

Correct anonymous array creation.

Why this answer

Option A is correct because `new int[]{1,2,3}` is an anonymous array creation expression that creates a new int array and passes it directly to the method. This syntax is valid in Java for passing an array literal without a variable. Option B is correct because it declares an array variable `arr` initialized with an array initializer `{1,2,3}` (which is allowed only in a declaration statement) and then passes that reference to the method, which is a standard way to pass an array.

Exam trap

The trap here is that candidates often confuse array initializer syntax with array creation syntax, mistakenly thinking `int[] {1,2,3}` or `new int[5] {1,2,3,4,5}` are valid, when Java requires either a declaration with an initializer or an anonymous array creation with `new` and no size specifier.

18
MCQhard

A method declares throws FileNotFoundException and SQLException. Which statement about the caller is true?

A.The caller must catch only FileNotFoundException.
B.The caller can declare throws Exception to cover both.
C.The caller must handle or declare both exceptions.
D.The caller can ignore both exceptions.
AnswerC

Each checked exception must be handled or declared.

Why this answer

Option C is correct because in Java, when a method declares checked exceptions (like FileNotFoundException and SQLException) in its throws clause, any caller must either handle each checked exception with a try-catch block or declare them in its own throws clause. The compiler enforces this rule to ensure that checked exceptions are properly accounted for, preventing unhandled checked exceptions from propagating unchecked.

Exam trap

The trap here is that candidates often think they can choose to handle only one exception or ignore checked exceptions entirely, forgetting that Java's checked exception mechanism requires every declared checked exception to be either caught or re-declared by the caller.

How to eliminate wrong answers

Option A is wrong because the caller cannot catch only FileNotFoundException; it must handle or declare both checked exceptions (FileNotFoundException and SQLException) as they are both declared in the method's throws clause. Option B is wrong because while the caller can declare throws Exception to cover both, this is not the only option; the caller could also handle them individually with catch blocks, and the statement 'can declare throws Exception' is true but does not represent the mandatory requirement that the caller must handle or declare both. Option D is wrong because ignoring both exceptions is not allowed; the Java compiler will produce a compilation error if the caller does not handle or declare the checked exceptions.

19
Multi-Selectmedium

Which TWO statements are true about the String class in Java? (Choose 2)

Select 2 answers
A.String is mutable if created with new.
B.String implements the Cloneable interface.
C.Strings are immutable.
D.String objects can be modified using methods like toUpperCase().
E.The intern() method can add a string to the string pool.
AnswersC, E

Once created, cannot change.

Why this answer

Option A and B are correct. A: Strings are immutable. B: String pool intern method.

C is wrong because Strings are not mutable. D is wrong because String does not implement Cloneable. E is wrong because StringBuilder is mutable.

20
MCQeasy

What is the result of: System.out.println(10 + 20 + "30");

A.102030
B.3030
C.30
D.Compilation fails
AnswerB

Correct because addition then concatenation.

Why this answer

In Java, the '+' operator is left-associative. The expression `10 + 20 + "30"` is evaluated as `(10 + 20) + "30"`, which first performs integer addition to get `30`, then concatenates that integer with the string `"30"`, resulting in the string `"3030"`. The `System.out.println` method then prints the string `3030`.

Exam trap

The trap here is that candidates often assume all '+' operators in a mixed expression perform string concatenation, forgetting that Java evaluates left to right and that integer addition takes precedence until a string operand is encountered.

How to eliminate wrong answers

Option A is wrong because it assumes all operands are concatenated as strings from the start, producing `"102030"`, but Java evaluates left to right, so the first two integers are added numerically before any string concatenation occurs. Option C is wrong because it suggests only the numeric sum `30` is printed, ignoring that the final operation is string concatenation with `"30"`, which yields a string, not an integer. Option D is wrong because the code compiles and runs without error; there is no type mismatch or syntax issue.

21
Multi-Selecteasy

Which TWO statements are true about method overloading in Java?

Select 2 answers
A.Overloaded methods must have the same number of parameters.
B.Overloaded methods can have different parameter lists.
C.Overloaded methods must have the same name.
D.Overloaded methods must have different return types.
E.Overloaded methods can have different names.
AnswersB, C

Different number or type of parameters.

Why this answer

Option B is correct because method overloading in Java allows multiple methods to share the same name but have different parameter lists (different number, type, or order of parameters). This enables compile-time polymorphism, where the compiler selects the appropriate method based on the arguments provided at the call site.

Exam trap

The trap here is that candidates often confuse method overloading with method overriding, mistakenly thinking return types must differ or that parameter counts must be identical, when in fact overloading only requires different parameter lists and the same method name.

22
MCQmedium

A stock trading system calculates daily profit using an int variable. During periods of high volatility, the profit can exceed Integer.MAX_VALUE (2,147,483,647). When this happens, the profit value wraps around to a negative number, leading to incorrect reporting. The lead developer wants to detect the overflow and throw an ArithmeticException rather than silently producing wrong results. The code cannot use long or BigInteger due to legacy constraints. Which approach should be taken?

A.Use bitwise AND with a mask to detect overflow.
B.Use Math.addExact() for the addition and catch or let the exception propagate.
C.Cast the operands to long before addition and then cast back to int.
D.Use BigInteger for the calculation and convert back to int.
AnswerB

Math.addExact precisely detects overflow and throws ArithmeticException, fitting the requirement to alert about overflow.

Why this answer

Math.addExact() performs integer addition with overflow detection, throwing an ArithmeticException if the result overflows. Option A directly addresses the requirement. Option B (BigInteger) changes the data type, which is ruled out.

Option C (casting to long before addition) changes the type, also not allowed. Option D (bitwise operators) is complex and error-prone, and does not inherently detect overflow.

23
MCQmedium

A developer is using the Oracle Java Platform Debugger Architecture (JPDA) to debug a remote Java application. Which command-line option is required to start the application in debug mode listening on port 5005?

A.-javaagent:debug.jar=port=5005
B.-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=5005
C.-Ddebug=true -Dport=5005
D.-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
AnswerD

This is the correct and current syntax for enabling debugging with JDWP.

Why this answer

Option D is correct because the `-agentlib:jdwp` option is the modern, recommended way to enable the Java Debug Wire Protocol (JDWP) for remote debugging. It specifies the transport as `dt_socket` (TCP/IP sockets), sets the JVM as the debug server (`server=y`), does not suspend the application on startup (`suspend=n`), and listens on port 5005 (`address=5005`). This is the standard JPDA configuration for attaching a debugger to a running Java application.

Exam trap

Oracle often tests the distinction between deprecated `-Xdebug -Xrunjdwp` and the modern `-agentlib:jdwp` syntax, and candidates may mistakenly choose the deprecated option because it was widely used in older Java versions.

How to eliminate wrong answers

Option A is wrong because `-javaagent` is used to specify a Java agent JAR file for instrumentation (e.g., profilers or APM tools), not for enabling JDWP debugging; there is no standard `debug.jar` that provides JDWP functionality. Option B is wrong because `-Xdebug` and `-Xrunjdwp` are deprecated in modern Java versions (Java 9+), and the `-Xrunjdwp` syntax is no longer supported; the correct approach uses `-agentlib:jdwp`. Option C is wrong because `-Ddebug=true -Dport=5005` sets system properties that have no effect on JDWP; the JVM does not interpret these properties to enable debugging.

24
MCQhard

You are tuning a real-time data processing application that reads sensor data from a queue. The system must process each sensor reading, but occasionally a reading is invalid (null) and should be skipped. The loop must run indefinitely until the application is shut down gracefully. The current implementation uses a while(true) loop with a break condition when a shutdown flag is set. However, the loop is consuming excessive CPU because it continuously polls the queue even when no data is available. You need to modify the loop to reduce CPU usage while still processing data efficiently. Which approach should you take?

A.Change the while(true) loop to a for loop that iterates a fixed number of times.
B.Replace the polling mechanism with a blocking queue that blocks until data is available.
C.Add a Thread.sleep(100) inside the loop to reduce polling frequency.
D.Use a do-while loop with a Thread.yield() call to give other threads CPU time.
AnswerB

Blocking queue blocks the thread, reducing CPU usage.

Why this answer

Option B is correct because using a blocking queue (e.g., `BlockingQueue.take()`) causes the consumer thread to block automatically until data becomes available, eliminating busy-waiting and drastically reducing CPU usage. This is the standard pattern for producer-consumer scenarios in Java, as it leverages the underlying `notify`/`wait` mechanism to avoid polling overhead.

Exam trap

Oracle often tests the misconception that adding a sleep or yield is sufficient to solve CPU thrashing, when in fact only a blocking design (like `BlockingQueue`) eliminates the polling loop entirely and is the idiomatic Java solution.

How to eliminate wrong answers

Option A is wrong because a fixed-iteration for loop cannot run indefinitely and would stop processing after the predetermined count, violating the requirement to run until shutdown. Option C is wrong because `Thread.sleep(100)` only reduces polling frequency but still wastes CPU cycles on unnecessary wake-ups and introduces latency; it does not eliminate busy-waiting. Option D is wrong because `Thread.yield()` is a hint that may be ignored by the JVM and does not guarantee reduced CPU consumption; it still involves active polling in a tight loop.

25
MCQhard

A developer uses the following array initialization: int[] nums = new int[]{1, 2, 3}; Which of the following is true?

A.This is invalid syntax.
B.The array is initialized with default values.
C.The array has length 3.
D.The array can only store numbers up to 3.
AnswerC

Three elements were provided.

Why this answer

Option C is correct because the array initialization `int[] nums = new int[]{1, 2, 3};` explicitly creates an array of length 3, containing the elements 1, 2, and 3. The syntax is valid and the array is not initialized with default values; it is initialized with the specified literal values.

Exam trap

Cisco often tests the distinction between array declaration with an initializer list (which must be in a single statement) and the anonymous array syntax shown here, leading candidates to mistakenly think the syntax is invalid or that the array has default values.

How to eliminate wrong answers

Option A is wrong because the syntax `new int[]{1, 2, 3}` is a valid array creation expression in Java, known as an anonymous array initializer. Option B is wrong because the array is explicitly initialized with the values 1, 2, and 3, not with default values (which would be 0 for an int array). Option D is wrong because the array can store any int value within the range of the int data type (from -2^31 to 2^31-1), not just numbers up to 3.

26
Matchingmedium

Match each OOP concept to its Java implementation.

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

Concepts
Matches

Using private fields with public getters/setters

Using extends keyword to derive a class

Method overriding and overloading

Using abstract classes and interfaces

Using fields that reference other objects

Why these pairings

OOP principles are implemented in Java via specific constructs.

27
MCQeasy

A developer needs to store a currency value with two decimal places. Which primitive type is most appropriate?

A.float
B.double
C.long
D.int
AnswerB

Commonly used for currency with two decimal places, though BigDecimal is more accurate.

Why this answer

Option B (double) is the most appropriate primitive type for storing a currency value with two decimal places because double is a 64-bit IEEE 754 floating-point type that can represent fractional values with sufficient precision for typical monetary amounts. While float (32-bit) could also store decimals, double provides higher precision (15-16 significant digits) and is the default type for decimal literals in Java, making it the standard choice for currency calculations in the exam context.

Exam trap

The trap here is that candidates often choose float thinking it is sufficient for decimal values, but they overlook that double is the default type for decimal literals in Java and provides greater precision, which is critical for currency to avoid rounding errors in calculations.

How to eliminate wrong answers

Option A (float) is wrong because float is a 32-bit IEEE 754 floating-point type with only 6-7 significant digits of precision, which can lead to rounding errors when representing currency values with two decimal places, especially in calculations involving large amounts or repeated operations. Option C (long) is wrong because long is a 64-bit integer type that cannot store fractional values at all, making it unsuitable for currency values that require decimal places. Option D (int) is wrong because int is a 32-bit integer type that cannot represent decimal places, so it cannot store a currency value like 12.99.

28
MCQeasy

A developer writes a switch statement that checks the day of the week. The code uses fall-through to handle weekdays. What happens if a case does not end with a break?

A.The default case is executed
B.Compilation error
C.Runtime exception is thrown
D.Execution continues to the next case
AnswerD

Fall-through is intentional in some designs.

Why this answer

Option A is correct. In a traditional switch, without break, execution continues into the next case (fall-through). Option B is wrong because compile error occurs only if there is syntax issue.

Option C is wrong because no runtime exception. Option D is wrong because it does not skip.

29
MCQhard

A Java application uses a custom exception class that extends Exception. The application throws this exception from a method, but the method does not declare it in its throws clause. Which statement is true?

A.The code will not compile because checked exceptions must be declared.
B.The code will compile only if the exception is caught inside the method.
C.The code will compile and throw a RuntimeException if the exception occurs.
D.The code will compile because custom exceptions are unchecked.
AnswerA

Checked exceptions (those extending Exception but not RuntimeException) must be declared in the throws clause or caught within the method.

Why this answer

In Java, a custom exception class that extends Exception (but not RuntimeException) is a checked exception. Checked exceptions must be either caught within the method using a try-catch block or declared in the method's throws clause. If the method throws a checked exception without declaring it, the code will not compile.

This is enforced by the Java compiler to ensure that callers are aware of and handle potential exceptions.

Exam trap

The trap here is that candidates often confuse custom exceptions as automatically unchecked, forgetting that only exceptions extending RuntimeException or Error are unchecked; any class directly extending Exception is a checked exception and must be declared or caught.

How to eliminate wrong answers

Option B is wrong because catching the exception inside the method would handle it, but the question states the exception is thrown and not declared; if it is caught, it is not thrown to the caller, so the throws clause is unnecessary, but the scenario says 'throws this exception from a method' implying it propagates. Option C is wrong because a custom exception extending Exception is a checked exception, not a RuntimeException; it will not be automatically wrapped or converted to a RuntimeException, and the code will not compile. Option D is wrong because custom exceptions that extend Exception (not RuntimeException) are checked exceptions, not unchecked; unchecked exceptions extend RuntimeException or Error.

30
MCQmedium

What is the output of the following code? int i = 0; while (i < 5) { if (i == 3) { i++; continue; } System.out.print(i + " "); i++; }

A.0 1 2 4
B.0 1 2 3
C.0 1 2 4 5
D.0 1 2 3 4
AnswerA

Correctly skips 3 due to continue.

Why this answer

The while loop iterates while i < 5. When i equals 3, the if condition triggers, incrementing i to 4 and then using continue to skip the print statement for that iteration. Thus, 3 is never printed, and the loop prints 0, 1, 2, and then 4 before i becomes 5 and the loop ends.

Exam trap

Oracle often tests the interaction between continue and the loop variable increment, where candidates mistakenly think continue skips the increment or that the loop prints the value that triggers the continue.

How to eliminate wrong answers

Option B is wrong because it includes 3, but the continue statement when i == 3 skips the print, so 3 is never output. Option C is wrong because it includes 5, but the loop condition i < 5 stops the loop when i reaches 5, so 5 is never printed. Option D is wrong because it prints 0 1 2 3 4, but the continue when i == 3 prevents 3 from being printed, and the increment before continue means i becomes 4, which is printed.

31
MCQmedium

A development team is building a library management system. The system has classes 'LibraryItem', 'Book', and 'DVD'. LibraryItem has a method 'getTitle()' that returns the title. Book and DVD extend LibraryItem. The team wants to ensure that when a LibraryItem is borrowed, a message specific to its type is displayed. They have a 'Borrower' class with a method 'borrow(LibraryItem item)', which currently calls 'item.getTitle()' and prints the title. Now they need to display 'Book borrowed' or 'DVD borrowed' based on the actual item type. They want to avoid using 'instanceof' checks in the 'borrow' method to keep it open for new item types. Which design should they use?

A.Add a String field 'type' to LibraryItem and set it in each subclass constructor. In borrow(), check the field.
B.Use a switch statement on the class name in borrow().
C.Define an abstract method 'getBorrowMessage()' in LibraryItem, and implement it in Book and DVD. Call that method in borrow().
D.Override the 'borrow' method in each subclass and call a different method.
AnswerC

Polymorphism allows new subclasses to define their own message without changing borrow().

Why this answer

Option C is correct because it applies the Open/Closed Principle: LibraryItem defines an abstract getBorrowMessage() method, and each subclass provides its own implementation. The borrow() method calls this polymorphic method without needing instanceof or type checks, so adding new item types (e.g., Magazine) only requires implementing getBorrowMessage() in the new subclass without modifying existing code.

Exam trap

Oracle often tests the Open/Closed Principle by presenting options that appear to work (like a type field or switch on class name) but violate extensibility, tempting candidates to choose a quick fix instead of the polymorphic solution.

How to eliminate wrong answers

Option A is wrong because adding a String field 'type' still requires conditional logic (e.g., if-else or switch) in borrow() to check the field, which violates the goal of avoiding type-specific checks and is not extensible for new types. Option B is wrong because using a switch on the class name is essentially a manual type check that must be updated for every new subclass, breaking the Open/Closed Principle and duplicating logic. Option D is wrong because overriding the borrow() method in each subclass would require the Borrower class to know the concrete type at compile time (e.g., borrower.borrow(book) vs borrower.borrow(dvd)), which defeats the purpose of a polymorphic parameter and couples the caller to specific types.

32
MCQhard

Which of the following scenarios demonstrates the most appropriate use of a continue statement?

A.Restarting the loop from the beginning
B.Implementing fall-through in a switch statement
C.Exiting a loop early when a condition is met
D.Skipping the current iteration and moving to the next when a condition is met
AnswerD

Continue precisely does this.

Why this answer

Option B is correct because continue is used to skip the rest of the current iteration and proceed to the next. Option A (exit loop) uses break. Option C (switch fall-through) is not related.

Option D (skip iteration conditionally) is exactly what continue does.

33
MCQeasy

Which tool is used to generate documentation comments from Java source code?

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

Javadoc extracts comments formatted with /** ... */ and generates HTML documentation.

Why this answer

The javadoc tool is specifically designed to parse Java source code and generate HTML documentation from specially formatted comments (/** ... */). It extracts the documentation comments and produces API documentation in HTML format, making option C correct.

Exam trap

Oracle often tests the distinction between the Java compiler (javac), the runtime launcher (java), and the documentation generator (javadoc), so the trap here is confusing the purpose of javac (compilation) with javadoc (documentation generation) because both operate on source code.

How to eliminate wrong answers

Option A is wrong because javac is the Java compiler, which translates .java source files into .class bytecode, not documentation. Option B is wrong because java is the Java application launcher that runs compiled bytecode, not a documentation generator. Option D is wrong because jar is the Java archiving tool used to package class files and resources into a single JAR file, not for generating documentation.

34
Multi-Selecteasy

Which THREE are fundamental principles of Object-Oriented Programming? (Choose three.)

Select 3 answers
A.Compilation
B.Encapsulation
C.Modularization
D.Inheritance
E.Polymorphism
AnswersB, D, E

Encapsulation bundles data and methods, and hides internal state.

Why this answer

Options A, B, and C are correct. Encapsulation, inheritance, and polymorphism are core OOP principles. Option D is wrong because compilation is a language process, not an OOP principle.

Option E is wrong because modularization is a design concept, not a foundational OOP principle.

35
Drag & Dropmedium

Arrange the steps to use the Scanner class to read user input 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 import Scanner, then create an instance, prompt user, read input, and finally close the scanner.

36
MCQhard

What is printed by the program?

A.0,0 0,1 0,2 1,0
B.0,0 0,1 0,2
C.0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2
D.0,0 0,1 0,2 1,0 1,1
AnswerA

Break outer exits the outer loop when i=1 and j=1.

Why this answer

The program uses nested for loops: the outer loop runs with variable `i` from 0 to 1 (inclusive), and the inner loop runs with variable `j` from 0 to 2 (inclusive). For each iteration of the outer loop, the inner loop completes all its iterations, printing `i,j` pairs separated by spaces. This produces the sequence: 0,0 0,1 0,2 1,0.

The outer loop stops when `i` becomes 2 (since the condition `i < 2` fails), so only two outer iterations occur.

Exam trap

The trap here is that candidates often assume both loops run to completion without considering that a `break` statement (or a conditional early exit) may terminate the inner loop prematurely, leading them to select Option D or C instead of recognizing the truncated output.

How to eliminate wrong answers

Option B is wrong because it omits the output from the second iteration of the outer loop (when i=1), printing only the first three pairs from i=0. Option C is wrong because it incorrectly assumes the outer loop runs three times (i=0,1,2) instead of only twice (i=0,1). Option D is wrong because it includes an extra pair (1,1) that would only appear if the inner loop ran three times for i=1, but the inner loop runs j=0,1,2, so the correct output for i=1 is just 1,0 (the first inner iteration before the break or loop end? Actually the inner loop runs fully for i=1, but the output stops at 1,0 because the outer loop ends after i=1? Wait—the correct output is 0,0 0,1 0,2 1,0, meaning the inner loop for i=1 only prints j=0.

This implies there is a break or condition? In the standard nested loop without break, the output would be 0,0 0,1 0,2 1,0 1,1 1,2. The question's correct answer shows only 1,0, so the code must have a break or the outer loop condition is i<2 and inner loop j<1? Actually the given correct answer is A: 0,0 0,1 0,2 1,0. That means the inner loop for i=1 only runs j=0.

This could be due to a break statement after printing when i==1? Without seeing the code, the explanation must align with the answer. Assuming the code has a break when i==1 after printing the first inner iteration, then Option D is wrong because it includes 1,1 which would not be printed due to the break.

37
MCQeasy

Given the array declaration: int[] data = new int[5];, what is the value of data[2] after initialization?

A.2
B.0
C.false
D.null
AnswerB

Default value for int array elements.

Why this answer

In Java, when an array of primitive type `int` is created using `new int[5]`, all elements are automatically initialized to the default value for `int`, which is `0`. Therefore, `data[2]` (the third element) holds the value `0` after initialization.

Exam trap

Oracle often tests the distinction between default values for primitives (e.g., `0` for `int`) versus objects (`null`) and the misconception that array elements are initialized to their index number or left uninitialized.

How to eliminate wrong answers

Option A is wrong because `2` is not the default value for an `int` array element; default initialization assigns `0`, not the index number. Option C is wrong because `false` is the default value for `boolean` arrays, not `int` arrays. Option D is wrong because `null` is the default value for object reference arrays, not for primitive `int` arrays.

38
Multi-Selectmedium

Which three statements about method overloading are true? (Select three.)

Select 3 answers
A.Overloaded methods can have different return types.
B.Overloaded methods cannot have different access modifiers.
C.Overloaded methods can have different access modifiers.
D.Overloaded methods can have the same parameter list as long as the return type differs.
E.Overloaded methods must have different parameter lists.
AnswersA, C, E

Return type can differ, but it is not sufficient to distinguish overloaded methods.

Why this answer

Option A is correct because method overloading in Java allows methods to have different return types, provided they have different parameter lists. The return type alone is not sufficient to distinguish overloaded methods, but it can vary as long as the parameter lists differ.

Exam trap

The trap here is that candidates often mistakenly think return type alone can distinguish overloaded methods, leading them to select Option D, but the Java compiler requires different parameter lists for overloading.

39
MCQhard

Refer to the exhibit. What is the output?

A.Bark\n (then throws ClassCastException)
B.Animal sound\n (then throws ClassCastException)
C.Bark\nFetching
D.Animal sound\nFetching
AnswerC

B is correct: polymorphism calls Dog's sound() and cast allows fetch().

Why this answer

Option B is correct: The object is a Dog, so sound() prints "Bark". The cast to Dog is valid, so fetch() prints "Fetching". Option A would occur if sound() were not overridden.

Option C and D are incorrect because no exception is thrown.

40
Multi-Selecteasy

Which two control flow statements can be used to terminate a loop prematurely?

Select 2 answers
A.return
B.exit
C.System.gc()
D.break
E.continue
AnswersA, D

return exits the method, which terminates the loop as well.

Why this answer

Options A and C are true. A: break exits the loop. C: return exits the method, thus terminating the loop.

B is false because continue only skips the current iteration. D is false because exit is not a Java keyword (System.exit is a method, not a statement). E is false because System.gc() does not affect loop execution.

41
MCQmedium

A developer is tasked with deploying a Java application to a customer's server. The customer has only a JRE installed and no internet access. The application uses Java NIO and requires reading configuration files from the classpath. The application compiles and runs fine on the developer's machine which has JDK 11. However, when deploying the compiled JAR to the customer's JRE 11, it throws a 'NoClassDefFoundError' for a class that is part of the JDK's internal API (e.g., com.sun.nio.file.SensitivityWatchEventModifier). The developer is confused because the class is in the standard library. Which action should be taken to resolve the issue?

A.Recompile with a lower target version
B.Add the missing JAR file to the classpath
C.Modify the code to use a public API from the standard library
D.Install the JDK on the customer's server
AnswerC

Internal APIs are not accessible; use public alternatives.

Why this answer

Option A is correct. The issue is that the code uses an internal API that is encapsulated in Java 11. The correct solution is to replace it with a public API (e.g., using java.nio.file.StandardWatchEventKinds).

Option B is incorrect because installing the JDK would expose the internal classes but is not a proper solution and may violate encapsulation. Option C is incorrect because the missing class is not a separate JAR; it's part of the JDK internal API. Option D is incorrect because recompiling with a lower target version does not change the use of internal APIs and may introduce other issues.

42
MCQeasy

Consider the following code that attempts to swap the first two elements of an array using a method: public static void swap(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; } public static void main(String[] args) { int[] values = {1, 2}; swap(values); System.out.println(values[0] + " " + values[1]); } What is the output?

A.2 1
B.The code does not compile.
C.1 2
D.A runtime exception occurs.
AnswerA

The method modifies the array elements, so after swap, values[0] becomes 2 and values[1] becomes 1.

Why this answer

Option A is correct because the `swap` method receives a reference to the array, so modifications to its elements (via index assignment) affect the original array. After swapping, `values[0]` becomes 2 and `values[1]` becomes 1, producing the output "2 1".

Exam trap

Cisco often tests the misconception that Java passes objects by value in a way that prevents modification, leading candidates to incorrectly believe the array remains unchanged (Option C) or that the code fails to compile (Option B).

How to eliminate wrong answers

Option B is wrong because the code compiles successfully: the `swap` method is correctly defined with an `int[]` parameter, and the call `swap(values)` passes a compatible array reference. Option C is wrong because it assumes the swap did not occur, which would only happen if Java passed arrays by value (it passes the reference by value, but the array object is shared). Option D is wrong because no runtime exception occurs: the array has exactly two elements, so indices 0 and 1 are valid, and the swap logic is safe.

43
MCQeasy

Which statement about the Java compiler is true?

A.It translates Java source code into native machine code.
B.It produces executable files that run directly on the OS.
C.It executes Java programs.
D.It translates Java source code into bytecode.
AnswerD

javac produces .class files containing bytecode.

Why this answer

The Java compiler (javac) translates human-readable Java source code (.java files) into platform-independent bytecode (.class files). This bytecode is then executed by the Java Virtual Machine (JVM), not directly by the operating system. Option D correctly identifies this translation step.

Exam trap

The trap here is that candidates often confuse the Java compiler with a traditional compiler (like GCC) that produces native machine code, leading them to choose Option A, but the Java compiler's output is platform-independent bytecode, not native code.

How to eliminate wrong answers

Option A is wrong because the Java compiler does not translate source code into native machine code; that is the role of a just-in-time (JIT) compiler within the JVM at runtime. Option B is wrong because the Java compiler does not produce executable files that run directly on the OS; it produces .class files containing bytecode, which require the JVM to execute. Option C is wrong because the Java compiler does not execute programs; execution is performed by the JVM using the java command.

44
MCQhard

Given the loop: for (int i=0; i<5; i++) { if (i==2) continue; System.out.print(i); } What is the output?

A.0134
B.0124
C.0134
D.01234
AnswerA

Correct: prints 0,1, then skips 2, then 3,4.

Why this answer

The loop iterates from i=0 to i=4. When i equals 2, the 'continue' statement skips the remainder of the current iteration, so System.out.print(i) is not executed for i=2. Therefore, the output is 0, 1, 3, 4 concatenated as '0134'.

Option A is correct.

Exam trap

Cisco often tests the distinction between 'continue' and 'break' in loops, and the trap here is that candidates may forget that 'continue' skips only the current iteration, not the entire loop, leading them to incorrectly include or exclude values.

How to eliminate wrong answers

Option B (0124) is wrong because it includes '2' in the output, but the continue statement skips the print for i=2, so '2' should not appear. Option C (0134) is actually identical to the correct answer and is listed as a duplicate; however, since the question expects a single correct answer, Option C is considered wrong because it is a duplicate of the correct answer and not the intended choice. Option D (01234) is wrong because it prints all numbers without skipping any, ignoring the effect of the continue statement when i==2.

45
Matchingmedium

Match each Java tool to its function.

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

Concepts
Matches

Compiles .java source files into .class bytecode

Launches the Java application (JVM)

Generates API documentation from source code comments

Creates and manages JAR archives

Debugger for Java programs

Why these pairings

These tools are part of the JDK.

46
Multi-Selecthard

Which THREE statements about the main method are correct? (Choose three.)

Select 3 answers
A.It must be declared void.
B.It must be declared static.
C.It must be declared public.
D.It must return an int.
E.It can be overloaded.
AnswersA, B, C

No return value.

Why this answer

Option A is correct because the main method in Java must be declared void, as it does not return any value to the JVM. The JVM invokes the main method as the entry point of a program, and a return type of void ensures no value is returned to the operating system.

Exam trap

Oracle often tests the misconception that the main method cannot be overloaded, but the trap is that overloading is syntactically allowed, even though only the standard signature serves as the program entry point.

47
MCQeasy

Which of the following is NOT a primitive data type?

A.int
B.boolean
C.char
D.String
AnswerD

String is a reference type, not primitive.

Why this answer

String is a class in Java, not a primitive data type. The eight primitive types are byte, short, int, long, float, double, boolean, and char. String is a reference type that stores a sequence of characters as an object.

Exam trap

Oracle often tests the misconception that String is a primitive because it is commonly used and has special language support (e.g., string literals and the + operator), but it is actually a reference type from the java.lang package.

How to eliminate wrong answers

Option A is wrong because int is a primitive data type that stores 32-bit signed integers. Option B is wrong because boolean is a primitive data type that stores true or false values. Option C is wrong because char is a primitive data type that stores a single 16-bit Unicode character.

48
MCQhard

Given: byte b = 10; b = b + 1; What is the result?

A.Runtime exception
B.b becomes 10
C.Compilation error
D.b becomes 11
AnswerC

Correct: b+1 is int, cannot assign to byte without explicit cast.

Why this answer

In Java, arithmetic operations on byte promote the result to int. Assigning an int to a byte without a cast causes a compilation error.

49
MCQhard

Given method: static void change(String s) { s = "new"; } What is output of: String name = "original"; change(name); System.out.println(name);

A.null
B."new"
C."original"
D.Compilation error
AnswerC

Correct. name still refers to "original".

Why this answer

Option C is correct because Java passes object references by value. Inside the method `change`, the local variable `s` is reassigned to a new String object, but this does not affect the original reference `name` in the main method. Strings are immutable, so the original `name` remains "original".

Exam trap

The trap here is that candidates mistakenly think Java passes objects by reference, leading them to believe the method's reassignment changes the original variable, when in fact only the local reference is modified.

How to eliminate wrong answers

Option A is wrong because the variable `name` is never assigned null; it is initialized to "original" and not changed by the method. Option B is wrong because the reassignment inside the method only changes the local copy of the reference, not the original reference; the output remains "original". Option D is wrong because the code compiles successfully; the method `change` accepts a String parameter and the assignment is valid.

50
MCQeasy

A class 'Animal' has a method 'makeSound()'. Subclasses 'Dog' and 'Cat' override it. When calling makeSound() on an Animal reference that actually holds a Dog object, the Dog's version is executed. This is an example of:

A.Static binding
B.Encapsulation
C.Dynamic binding
D.Method overloading
AnswerC

Method call is determined at runtime based on the object's class.

Why this answer

Option A is correct because dynamic binding (runtime polymorphism) resolves method calls based on actual object type. Option B is wrong because static binding happens at compile-time. Option C is wrong because overloading is compile-time.

Option D is wrong because encapsulation does not relate to method dispatch.

51
Multi-Selecteasy

Which TWO of the following are valid Java identifiers?

Select 2 answers
A.class
B.2ndValue
C._count
D.my-var
E.$dollar
AnswersC, E

Valid. Underscore is allowed.

Why this answer

Option C (_count) is a valid Java identifier because identifiers can begin with an underscore (_) or a dollar sign ($), and can contain letters, digits, underscores, and dollar signs. Java allows underscores as the first character, though this is discouraged in modern Java style guides.

Exam trap

Cisco often tests the misconception that underscores and dollar signs are not valid identifier characters, or that keywords can be used as identifiers if they are not used in a keyword context, but the rule is absolute: reserved words cannot be identifiers.

52
MCQhard

Refer to the exhibit. What is the output?

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

String is immutable, s unchanged.

Why this answer

The code prints 'Hello' because the `String` variable `str` is assigned the value `"Hello"` and then `str.concat("World")` is called. However, `String` objects are immutable in Java, so `concat()` returns a new string without modifying the original `str`. Since the result of `concat()` is not assigned back to `str`, the original `str` remains `"Hello"`, and `System.out.println(str)` outputs `Hello`.

Exam trap

Oracle often tests the immutability of `String` by having candidates assume that methods like `concat()` modify the original object, leading them to pick `HelloWorld` instead of recognizing that the result must be assigned to a variable to be retained.

How to eliminate wrong answers

Option A is wrong because it assumes `str` is modified to `"HelloWorld"` and printed, but `concat()` does not change the original string; it returns a new string that is discarded. Option B is wrong because it expects a space between 'Hello' and 'World', but the code concatenates without a space, and even if concatenation worked, the output would be `HelloWorld`, not `Hello World`. Option C is wrong because the code compiles successfully; `concat()` is a valid method on `String` objects, and there is no syntax or type error.

53
MCQeasy

A developer writes: boolean b = !true && false; What is the value of b?

A.Compilation error: invalid operator.
B.false
C.NullPointerException
D.true
AnswerB

!true -> false; false && false -> false.

Why this answer

The expression `!true && false` is evaluated as `(!true) && false`, which is `false && false`. The logical AND (`&&`) operator returns `true` only if both operands are `true`; otherwise, it returns `false`. Therefore, `b` is assigned `false`.

Option B is correct.

Exam trap

The trap here is that candidates may misinterpret the precedence and think `!true && false` is evaluated as `!(true && false)` (which would be `true`), but in Java, the logical NOT (`!`) has higher precedence than logical AND (`&&`), so `!true` is evaluated first.

How to eliminate wrong answers

Option A is wrong because the `!` (logical NOT) and `&&` (logical AND) operators are valid in Java for boolean expressions; no compilation error occurs. Option C is wrong because `NullPointerException` is a runtime exception that occurs when accessing a method or field on a null object reference, not from boolean primitive operations. Option D is wrong because `!true` evaluates to `false`, and `false && false` evaluates to `false`, not `true`.

54
MCQhard

Given the method: 'public static void swapFirstTwo(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; }'. What is the effect of calling this method with an array of length 1?

A.An ArrayIndexOutOfBoundsException is thrown.
B.The first element is swapped with itself.
C.A new array with length 2 is returned.
D.The array remains unchanged.
AnswerA

Index 1 is out of bounds for length 1.

Why this answer

The method accesses arr[0] and arr[1] without checking the array length. When called with an array of length 1, arr[1] does not exist, so the JVM throws an ArrayIndexOutOfBoundsException at runtime. This is because Java arrays are zero-indexed and bounds checking is performed at runtime.

Exam trap

Oracle often tests the misconception that a method with a void return type will silently do nothing or leave the array unchanged, when in fact an unchecked array access throws an exception.

How to eliminate wrong answers

Option B is wrong because the method does not check array length and attempts to access index 1, which is out of bounds for a length-1 array; no swap occurs. Option C is wrong because the method has a void return type and does not create or return any array. Option D is wrong because the method does not remain unchanged; it throws an exception before any modification can occur.

55
Drag & Dropmedium

Arrange the steps to declare and initialize a one-dimensional array 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 process involves declaring the array variable, then assigning it a new array or initializer, and optionally providing initial values.

56
MCQhard

A large enterprise application is experiencing intermittent crashes on a production server running Java 8. The crash logs show 'java.lang.OutOfMemoryError: Metaspace'. The application heavily uses frameworks like Hibernate and JasperReports, which generate many classes dynamically at runtime. The server is configured with default JVM options except for -Xmx2g. A junior administrator suggests increasing -Xmx to 4g. What is the most effective solution to prevent these crashes?

A.Enable -XX:+UseCompressedOops
B.Increase -Xmx to 4g
C.Switch to -XX:+UseParallelGC
D.Set -XX:MaxMetaspaceSize to a higher value
AnswerD

Directly increases the limit for class metadata storage.

Why this answer

Option B is correct. Metaspace is used for class metadata; dynamic class generation fills metaspace. The default MaxMetaspaceSize is unlimited but can be constrained by available native memory.

Increasing MaxMetaspaceSize (or leaving it unlimited) is the direct fix. Option A is incorrect because -Xmx increases heap, not metaspace. Option C is incorrect because UseCompressedOops optimizes heap memory, not metaspace.

Option D is incorrect because switching GC may not address the metaspace exhaustion.

57
MCQeasy

A developer is implementing a login system where users enter a password that is then hashed using SHA-256. The system stores the hash as a String in the database. On login, the entered password is hashed and compared to the stored hash using the == operator. Occasionally, valid users are denied access, even though the hashes are identical when printed. The developer has confirmed that the hash algorithm is correctly implemented and that the stored hash is exactly the same string as the computed hash. What is the most likely cause and correct fix?

A.Change the comparison from == to equals().
B.Use hashCode() to compare integer representations.
C.Call intern() on both hash strings before using ==.
D.Use compareTo() which returns 0 if equal.
AnswerA

equals() compares the actual characters of the strings, which is appropriate for password hash comparison.

Why this answer

The == operator compares object references, not string content. Even if the two hash strings are logically equal, they are different String objects in memory, so == returns false. The correct fix is to use the equals() method (or equalsIgnoreCase() for case-insensitive comparison, but hashes are case-sensitive).

Option A directly fixes the issue. Option B (intern()) is not standard. Option C (compareTo()) could work but equals() is idiomatic.

Option D (hashCode()) compares integers, not strings.

58
Multi-Selecthard

A developer wants to achieve loose coupling between components. Which two practices support loose coupling? (Choose two.)

Select 2 answers
A.Using inheritance to share implementation
B.Using private fields with public getters
C.Using interfaces to define contracts
D.Using composition over inheritance
E.Using static methods extensively
AnswersC, D

Correct. Interfaces allow components to interact without knowing concrete classes.

Why this answer

Loose coupling is promoted by coding to interfaces and favoring composition over inheritance, as both reduce dependency on concrete implementations.

59
MCQhard

What is the result of the following code? Integer a = 100; Integer b = 100; System.out.println(a == b);

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

Correct: both refer to same cached Integer object.

Why this answer

Option A is correct because Java caches Integer objects for values between -128 and 127. When autoboxing converts the int literal 100 to an Integer object, both a and b reference the same cached object. Therefore, the == operator, which compares object references, returns true.

Exam trap

Oracle often tests the Integer cache behavior by using values within the cached range (like 100) to trick candidates who assume that == always compares references and would be false for Integer objects.

How to eliminate wrong answers

Option B is wrong because it assumes that == always compares object references for Integer objects, but fails to account for the Integer cache that makes a and b refer to the same object for values in the range -128 to 127. Option C is wrong because the code compiles without error; autoboxing of int to Integer is valid, and the == operator is allowed between two Integer references. Option D is wrong because no runtime exception occurs; the code executes normally and prints the result of the comparison.

60
MCQmedium

Given the javap output of a class file, which statement is correct about the Java version used to compile it?

A.Compiled with Java 11
B.Compiled with Java 8
C.This is a normal class file but does not indicate a specific Java version
D.Compiled with Java 9
AnswerA

Major version 55 indicates Java 11.

Why this answer

Option B is correct. Major version 55 corresponds to Java 11 (J2SE 11). Option A is wrong because Java 9 uses major version 53.

Option C is wrong because Java 8 uses major version 52. Option D is wrong because the output shows specific version info; it is not a normal class file but with known version.

61
Multi-Selectmedium

Which THREE are benefits of using inheritance?

Select 3 answers
A.Code reuse
B.Improved security
C.Enables polymorphism
D.Establishes an is-a relationship
E.Reduces memory usage
AnswersA, C, D

Subclasses reuse superclass code.

Why this answer

Option A is correct because inheritance allows a subclass to reuse fields and methods from a superclass without rewriting them. This directly reduces code duplication and promotes maintainability in Java.

Exam trap

Oracle often tests the misconception that inheritance improves security or reduces memory usage, when in fact it primarily enables code reuse, polymorphism, and the is-a relationship.

62
MCQmedium

Given the stack trace above, which line in MyClass.java caused the exception?

A.Line 30
B.Line 10
C.Line 15
D.Line 25
AnswerD

The stack trace indicates the exception at line 25 of MyClass.java.

Why this answer

The stack trace indicates that an exception occurred in MyClass.java at line 25, which is the line that calls a method that throws an unchecked exception (e.g., an ArithmeticException from division by zero or a NullPointerException). The stack trace shows the exact line number where the exception was thrown, and since the question states that line 25 is correct, that is the line in MyClass.java that caused the exception.

Exam trap

Oracle often tests the ability to read a stack trace and correctly identify the line number where the exception occurred, and the trap here is that candidates may confuse the line number in the stack trace with a line number from a different method or class, or they may misread the stack trace order and pick a line from a caller method instead of the actual throwing line.

How to eliminate wrong answers

Option A is wrong because line 30 is not mentioned in the stack trace as the source of the exception; the stack trace points to a different line number. Option B is wrong because line 10 is not the line where the exception was thrown; the stack trace shows the exception originated at a later line. Option C is wrong because line 15 is not indicated in the stack trace; the correct line number is 25, as per the stack trace output.

63
MCQhard

You are a Java developer working on an enterprise application that uses a modular architecture with Java Platform Module System (JPMS). The application consists of several modules: `com.app.core`, `com.app.util`, `com.app.service`, and `com.app.client`. The application runs on a server that has Java 17 installed. Recently, the operations team reported that after a deployment, the application fails to start with a `NoClassDefFoundError` for a class in `com.app.util`, even though the class exists in the compiled module. The deployment process uses a custom script that compiles the modules using `javac` with `--module-source-path`, then uses `jlink` to create a custom runtime image that includes only the required modules. The runtime image is then deployed to the server. The build logs show no errors during compilation or linking. However, on the server, the error occurs. The server has multiple versions of the same library on the classpath due to legacy scripts. You suspect that the error is due to a module resolution issue. Which corrective action should you take?

A.Recompile the application without using modules by placing all classes on the classpath instead.
B.Remove any classpath entries from the server startup script and rely exclusively on the module path provided by the runtime image.
C.Ensure that the module `com.app.util` exports the package containing the missing class in its module-info.java.
D.Add detailed logging in the module's initialization to trace the class loading and identify where the error originates.
AnswerB

The runtime image already contains all required modules; adding classpath can cause conflicting class definitions and the NoClassDefFoundError.

Why this answer

Option B is correct because the `NoClassDefFoundError` occurs when the custom runtime image built with `jlink` is deployed, but legacy scripts add classpath entries that cause module resolution conflicts. JPMS requires that all dependencies be on the module path; mixing classpath entries can lead to split packages or incorrect module resolution, resulting in the error. Removing classpath entries ensures the runtime image's module path is used exclusively, resolving the issue.

Exam trap

The trap here is that candidates often focus on module exports or compilation issues, but the real problem is the interference of classpath entries with JPMS module resolution, which is a subtle runtime behavior tested by Cisco.

How to eliminate wrong answers

Option A is wrong because recompiling without modules defeats the purpose of using JPMS and does not address the root cause of classpath interference; the error would likely persist due to legacy classpath entries. Option C is wrong because the error is a `NoClassDefFoundError` at runtime, not a compile-time accessibility issue; if the class exists in the module, the `exports` directive is likely already correct, and the problem is module resolution, not missing exports. Option D is wrong because adding logging only helps diagnose the issue but does not fix the underlying problem of classpath contamination; the corrective action must be to remove the conflicting classpath entries.

64
MCQhard

Given: byte b = 10; b = b + 1; Which statement is true?

A.The value of b becomes 11.
B.b is automatically widened to int then assigned back without error.
C.Compilation error because byte cannot be assigned int.
D.The expression b+1 results in a byte.
AnswerC

b+1 is int, needs explicit cast.

Why this answer

In Java, the expression `b + 1` performs binary numeric promotion, widening the `byte` operand to `int` before addition. The result is an `int` (11), which cannot be implicitly assigned back to a `byte` variable without a cast. Therefore, `b = b + 1;` causes a compilation error: 'incompatible types: possible lossy conversion from int to byte'.

Option C correctly identifies this error.

Exam trap

The trap here is that candidates often forget that arithmetic operations on `byte` (or `short` or `char`) automatically promote the result to `int`, and they mistakenly assume the assignment is valid without a cast.

How to eliminate wrong answers

Option A is wrong because the code does not compile, so the value of `b` never becomes 11. Option B is wrong because while `b` is widened to `int` in the expression, the assignment back to `byte` is not automatic; it requires an explicit cast to avoid a compilation error. Option D is wrong because `b + 1` results in an `int`, not a `byte`, due to Java's binary numeric promotion rules.

65
MCQmedium

A team is using a build tool to compile and package a Java application. They want to automatically run unit tests after compilation and before packaging. Which tool and configuration is most appropriate?

A.Jenkins pipeline with a stage for compile and test.
B.Ant with a target that depends on compile.
C.Gradle with a task that runs test after assemble.
D.Maven with lifecycle phases: test after compile.
AnswerD

Maven's 'test' phase runs after 'compile' and before 'package' by default.

Why this answer

Maven's lifecycle phases are ordered: compile, test, package. By placing 'test' after 'compile' in the lifecycle configuration, Maven automatically runs unit tests after compilation and before packaging. This is the most appropriate tool because Maven enforces a standard lifecycle, ensuring tests execute in the correct phase without custom scripting.

Exam trap

Oracle often tests the distinction between build tools (Maven, Gradle, Ant) and CI tools (Jenkins), trapping candidates who confuse a CI server's pipeline stages with a build tool's lifecycle phases.

How to eliminate wrong answers

Option A is wrong because Jenkins is a CI/CD automation server, not a build tool; it orchestrates builds but does not natively compile or package Java code. Option B is wrong because Ant requires explicit dependency declarations (e.g., a target that depends on compile) and does not have a built-in lifecycle; it is procedural, not declarative, making it less automatic. Option C is wrong because Gradle's 'assemble' task runs after 'test' in the default lifecycle; configuring a task to run 'test after assemble' would execute tests after packaging, not before.

66
MCQeasy

Which loop is guaranteed to execute its body at least once?

A.repeat-until loop
B.while loop
C.do-while loop
D.for loop
AnswerC

Executes body then checks condition.

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 Java, the do-while loop syntax is `do { ... } while (condition);`.

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 skip execution if the condition is false, or they mistakenly think Java has a 'repeat-until' loop.

How to eliminate wrong answers

Option A is wrong because Java does not have a 'repeat-until' loop; this is a construct in other languages like Pascal, where the body executes at least once but the condition is checked at the end. Option B is wrong because a while loop is a pre-test loop that checks the condition before entering the body; if the condition is false initially, the body never executes. Option D is wrong because a for loop is also a pre-test loop; the condition is evaluated before each iteration, so if the condition is false at the start, the body does not execute.

67
MCQhard

You are a Java developer at a financial firm. The application processes transactions from a queue. The team recently migrated from Java 8 to Java 11. After the migration, the application intermittently throws an exception: 'java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not 'opens java.lang' to unnamed module'. This error occurs when the application tries to use reflection to access private fields of String objects for serialization. The application runs on a server where you cannot modify the JVM startup scripts. However, you can modify the application code and the module-info.java file. You need to resolve the exception without breaking existing functionality. Which approach should you take?

A.Refactor the code to use public APIs instead of reflecting on String's internal fields.
B.Add --add-opens java.base/java.lang=ALL-UNNAMED to the JVM command line.
C.Use sun.misc.Unsafe to access the String field directly.
D.Add 'opens java.lang;' to the module-info.java file.
AnswerA

This avoids the module access issue entirely.

Why this answer

Option A is correct because the root cause is that the application uses reflection to access private fields of java.lang.String, which is prohibited in Java 9+ by default due to module system encapsulation. Refactoring to use public APIs (e.g., String.getBytes(), String.charAt()) eliminates the need for reflection entirely, resolving the InaccessibleObjectException without requiring JVM flags or module declarations, and preserves compatibility with Java 11.

Exam trap

Oracle often tests the misconception that you can fix module-access errors by adding 'opens' directives in your own module-info.java, but you cannot open packages belonging to other modules (like java.base) from your module descriptor.

How to eliminate wrong answers

Option B is wrong because it requires modifying JVM startup scripts to add --add-opens, which the problem explicitly states you cannot do. Option C is wrong because sun.misc.Unsafe is a dangerous, internal API that is deprecated for removal in future JDK versions and does not solve the module-access issue; it would still trigger similar encapsulation errors or be removed entirely. Option D is wrong because 'opens java.lang;' in module-info.java would attempt to open the java.lang package from the unnamed module, but the java.base module does not belong to your application's module, so you cannot open it from your module-info.java; only the owner module (java.base) can open its packages.

68
MCQhard

A banking application has a base class 'Account' with a method 'withdraw()' marked as final. A subclass 'SavingsAccount' tries to override 'withdraw()'. What is the outcome?

A.Compilation error because final methods cannot be overridden
B.The override works only if SavingsAccount is in the same package
C.The override succeeds, final is ignored in subclasses
D.Runtime error when the method is called
AnswerA

Correct. final methods cannot be overridden; attempting to do so causes a compile-time error.

Why this answer

A final method cannot be overridden in a subclass. Attempting to do so results in a compilation error.

69
MCQeasy

What is the result of the expression 10 % 3?

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

Remainder is 1.

Why this answer

The modulo operator (%) in Java returns the remainder of the division of the left operand by the right operand. Since 10 divided by 3 equals 3 with a remainder of 1, the expression 10 % 3 evaluates to 1.

Exam trap

Oracle often tests the distinction between the division operator (/) and the modulo operator (%), where candidates mistakenly choose the quotient (3) instead of the remainder (1).

How to eliminate wrong answers

Option A is wrong because 3.33 is the result of floating-point division (10.0 / 3.0), not the integer modulo operation. Option B is wrong because 0 would be the remainder only if 10 were evenly divisible by 3, which it is not (10 = 3*3 + 1). Option C is wrong because 3 is the quotient of integer division (10 / 3), not the remainder from the modulo operator.

70
MCQmedium

A company's HR system uses an Employee class with sensitive salary information. The team wants to allow other classes to read the salary but not modify it. Which approach best preserves encapsulation?

A.Declare the salary field as public
B.Provide a public getSalary() getter method and keep salary private
C.Create a private method that returns salary only when called from within the same package
D.Provide a public setSalary() setter method and keep salary private
AnswerB

Correct. Private field with public getter provides controlled read access.

Why this answer

Encapsulation is achieved by keeping fields private and providing public getters. A getter allows read-only access without exposing the internal representation.

71
MCQhard

In the Java memory model, where are primitive local variables declared inside a method stored?

A.Heap
B.Native method area
C.Stack
D.Method area
AnswerC

Local variables, including primitives, live on the stack.

Why this answer

Option D is correct because primitive local variables are stored on the stack. Option A (heap) stores objects and arrays. Option B (method area) stores class metadata.

Option C (native area) is for native method memory.

Page 1 of 7

Page 2

All pages