Courseiva

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

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

Page 6

Page 7 of 7

451
MCQhard

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

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

This satisfies the compiler and preserves the exception chain.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

452
Multi-Selectmedium

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

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

Yes, closure happens automatically on any exit.

Why this answer

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

Exam trap

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

453
Multi-Selecthard

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

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

int is a primitive integer type.

Why this answer

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

Exam trap

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

454
MCQhard

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

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

Java ME is tailored for embedded and mobile devices.

Why this answer

Java ME (Micro Edition) is specifically designed for embedded devices and mobile devices with constrained resources. Option A (Java Card) is for smart cards and very small devices like SIM cards. Option B (Java FX) is a UI framework for rich client applications, not an edition of Java.

Option C (Java EE) is for enterprise server applications.

455
MCQeasy

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

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

x++ returns 5, then x becomes 6.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

456
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

457
MCQmedium

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

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

Correct: concatenation yields 'Hello World'.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

458
MCQmedium

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

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

JIT identifies hot spots and compiles them for faster execution.

Why this answer

JIT compilation improves execution speed by compiling frequently used bytecode into native machine code at runtime. Option A is incorrect because JIT does not translate bytecode into an intermediate language; it compiles to native code. Option C is incorrect because JIT compiles bytecode, not source code.

Option D is incorrect because JIT's primary purpose is performance, not security.

459
Multi-Selecthard

Which THREE statements are true about method overloading in Java?

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

Return type alone does not distinguish overloads.

Why this answer

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

Exam trap

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

460
MCQmedium

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

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

Exception handling can catch failures and trigger rollback.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

461
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

462
MCQmedium

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

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

Directly initializes with the needed values.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

463
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

464
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

465
Multi-Selectmedium

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

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

Correct.

Why this answer

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

Exam trap

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

466
MCQhard

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

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

Correct because equals compares values.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

467
Multi-Selectmedium

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

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

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

Why this answer

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

468
MCQeasy

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

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

a and b refer to same array.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

469
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

470
MCQhard

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

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

Accessing length on null row causes NPE.

Why this answer

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

Option C correctly identifies this as the most likely cause.

Exam trap

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

How to eliminate wrong answers

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

471
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

472
MCQeasy

What is the output? ```java public class Test { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; System.out.println(s1.equals(s2)); } } ```

A.No output
B.True
C.Compilation error
D.False
AnswerB

True: Correct because String.equals() compares content, and both strings have the same content 'hello'.

Why this answer

The code compares two String objects 's1' and 's2' using the equals() method. Since both strings have the same content "hello", equals() returns true. The System.out.println statement then prints 'True'.

Exam trap

Candidates often confuse == with equals(). In this code, using == would also return true due to string interning, but the question uses equals() to compare content. The trap is that some may think equals() compares references or that the output would be 'False' if they misremember the behavior.

How to eliminate wrong answers

Option A is wrong because the code does produce output — `System.out.println()` is called and prints the boolean result. Option C is wrong because the code compiles successfully; `String.equals()` is a valid method and the comparison is syntactically correct. Option D is wrong because the strings contain identical characters, so `equals()` returns `true`, not `false`.

473
MCQeasy

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

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

Correct. A final class cannot be extended.

Why this answer

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

474
Multi-Selecthard

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

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

Correct: hexadecimal literal 0xA equals 10 decimal.

Why this answer

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

Exam trap

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

475
MCQeasy

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

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

The second condition is false.

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

476
MCQhard

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

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

Changing the loop condition to i < arr.length ensures that the loop runs only for indices 0 through arr.length-1 (0-4), which are all valid. This correctly fixes the off-by-one error and prevents the ArrayIndexOutOfBoundsException.

Why this answer

The exception occurs because the loop condition `i <= arr.length` causes the loop to iterate one index beyond the array's last valid index (arr.length - 1). When `i` equals `arr.length` (5), `arr[5]` is accessed, which throws an ArrayIndexOutOfBoundsException. Changing the condition to `i < arr.length` ensures the loop runs only for indices 0 through 4, fixing the exception.

Option D, changing `arr.length` to `arr.length - 1` in the condition, also technically fixes the exception, but it is not the standard or recommended fix; the intended correct answer is to use the `<` operator.

Exam trap

The most common mistake in array iteration is using `<=` instead of `<`. Since arrays are zero-indexed, the last valid index is `arr.length - 1`. Using `<=` with array length causes an `ArrayIndexOutOfBoundsException` because it tries to access `arr[arr.length]`.

How to eliminate wrong answers

Option A is wrong because changing the array declaration to `int[] arr = new int[6];` creates an array of size 6 with default values (0), but the loop still uses `i <= arr.length` (now 6), causing an exception when accessing `arr[6]`. Option B is wrong because changing loop initialization to `i = 1` skips the first element (index 0) but does not prevent the out-of-bounds access when `i` reaches `arr.length`. Option D is wrong because changing `arr.length` to `arr.length - 1` in the loop condition `i <= arr.length - 1` is functionally equivalent to `i < arr.length`, but the option is incorrect as written because it does not specify the condition change; it only changes the bound, and the loop still uses `<=` which would make the condition `i <= 4`, which works, but the option is misleading and not the standard fix.

477
MCQeasy

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

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

Correct. The variable x is not initialized.

Why this answer

B is correct because in Java, a local variable (such as `int x;` declared inside a method) must be initialized before it is used. The code attempts to print `x` without assigning a value, which violates the definite assignment rule and causes a compilation error.

Exam trap

The Java Foundations exam often tests the distinction between local variables (which require explicit initialization) and instance/class variables (which receive default values), leading candidates to incorrectly assume that `int x` will default to 0.

How to eliminate wrong answers

Option A is wrong because `null` is a value that can only be assigned to reference types, not to primitive types like `int`; local variables of primitive type are not automatically assigned any value. Option C is wrong because the error occurs at compile time, not at runtime — the Java compiler catches the uninitialized variable before the code can execute. Option D is wrong because while instance variables of type `int` are default-initialized to 0, local variables are not given any default value and must be explicitly initialized.

478
MCQeasy

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

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

Extending Exception (not RuntimeException) creates a checked exception.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

479
MCQmedium

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

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

Encapsulation hides internal data; public fields expose it.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

480
MCQhard

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

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

Switch on strings is valid since Java 7.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

481
MCQmedium

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

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

equals() is the standard method for comparing string content.

Why this answer

Option B uses equals(), the standard method for comparing string content, correctly checking character sequences. Option A uses compareTo(), which is intended for ordering; although compareTo() == 0 indicates equality, it is not the idiomatic approach and is considered a trap. Option C uses ==, comparing references, not content.

Option D uses hashCode(), which may collide and does not guarantee equality.

Exam trap

The trap is that compareTo() can return 0 for equal strings, tempting candidates to select it. However, equals() is the expected method for simple equality checks.

Page 6

Page 7 of 7

All pages