Oracle · Free Practice Questions · Last reviewed May 2026
42real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
14% of exam · 6 sample questions below
Given the code snippet: int x = 5; int y = 2; double result = x / y; What is the value of result?
2.0
Both operands are int, so x / y performs integer division, truncating 5 / 2 to 2. That int result is then widened to double on assignment, giving 2.0. Casting either operand to double before division would yield 2.5 instead.
Compilation fails
2.5
2
Given: String str = "Java"; str = str.concat(" SE"); str.replace('a', 'A'); System.out.println(str); What is the output?
Java
JAVA SE
Java SE
The output is "Java SE" because Java String objects are immutable. The `str.concat(" SE")` operation creates a new String "Java SE" and successfully reassigns `str` to refer to this new object. However, `str.replace('a', 'A')` also creates a new String ("JAvA SE"), but its return value is not assigned back to `str`. Consequently, `str` continues to refer to the "Java SE" object established by the `concat` method, which is then printed to the console.
JAvA SE
Which operator is used to compare two strings for value equality in Java?
compareTo()
=
==
equals()
equals() compares the actual character content of two String objects, returning true when their values match. The == operator compares object references instead, so it fails for distinct String instances holding identical text, making equals() the correct value-equality operator.
What is the result of: System.out.println(10 + 20 + "30");
102030
3030
Java evaluates left to right: 10 + 20 performs integer addition giving 30, then 30 + "30" triggers string concatenation because one operand is a String, producing "3030". The numeric addition happens before the string operand is encountered.
30
Compilation fails
Given: boolean a = false; boolean b = true; boolean c = true; System.out.println(a || b && c); What is the output?
false
Compilation fails
None of the above
true
Correct due to operator precedence.
Which of the following is a valid Java identifier?
2variable
class
_myVar
Java identifiers may begin with a letter, underscore or dollar sign, so the leading underscore is legal. Subsequent characters may be letters, digits, underscores or dollar signs, and _myVar contains no reserved word. This satisfies the naming rules the compiler enforces.
my-var
Want more Primitives, Strings and Operators practice?
Practice this domain15% of exam · 6 sample questions below
A developer writes the following code: int x = 5; System.out.println(x++); What is the output?
Compilation error
5
The post-increment operator returns the variable's current value before incrementing it. So System.out.println(x++) prints 5, then x becomes 6. The printed output is therefore 5, not 6, because the increment happens after the value is supplied to println.
6
Runtime exception
A team decides to use a single Java source file for a small application. Which statement is true about the file structure?
It must have a main method to compile.
It can contain multiple public classes.
It can contain exactly one public class with the same name as the file.
Java permits at most one public top-level class per source file, and its name must match the filename exactly. Other non-public classes may coexist in the same file, so this constraint defines the file structure for the single-file application.
The public class name can differ from the file name.
Given the code: String s1 = "Java"; String s2 = new String("Java"); if (s1 == s2) { System.out.print("Equal"); } else { System.out.print("Not Equal"); } What is the output?
Runtime error
Compilation error
Equal
Not Equal
The == operator compares object references, not character content. s1 refers to the interned string pool instance, while s2 is a distinct heap object created by new String, so the references differ and the else branch prints Not Equal.
Which primitive data type should be used to store a single character?
int
byte
char
Storing one character requires a 16-bit primitive holding a single UTF-16 code unit, which is exactly what `char` provides. Unlike `String`, which is a reference type wrapping a character sequence, `char` satisfies the stem's single-character constraint directly and efficiently.
String
A method is declared as: public static void main(String[] args) { }. Which statement is true?
The method can be overridden in a subclass.
The method can return an int.
The method can be called without creating an instance of the class.
The static modifier binds the method to the class rather than any object, so the JVM invokes main through the class itself without instantiation. This satisfies the entry-point requirement, since no object exists when execution begins.
The method can be private.
What is the value of the expression (10 > 5) && (3 < 2)?
1
true
false
The && operator returns true only when both operands are true. Here (10 > 5) evaluates to true, but (3 < 2) evaluates to false, so the conjunction yields false. Short-circuit evaluation stops at the second operand, confirming the result.
0
Want more Java Basics and Syntax practice?
Practice this domainA developer writes a method that takes an int array and returns the sum of its elements. The method signature is: 'public static int sumArray(int[] arr)'. Which statement correctly calls this method?
int result = sumArray(new int[]{1,2,3});
This statement correctly invokes the `sumArray` method by providing an `int` array argument, precisely matching the `int[] arr` parameter defined in the method signature. The `new int[]{1,2,3}` syntax creates an anonymous integer array literal, which is then correctly passed to the static method. The method's `int` return value is subsequently assigned to the `int result` variable, ensuring type compatibility. This demonstrates the correct mechanism for passing an array argument to a static method.
int result = sumArray(true);
int result = sumArray([1,2,3]);
int result = sumArray(5);
Given the code snippet: 'int[] nums = {10, 20, 30, 40}; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; }'. What is the value of sum after execution?
100
The loop iterates all four elements, accumulating each value into sum: 10 + 20 + 30 + 40. Because i starts at 0 and runs while i < nums.length (4), every element is added exactly once, yielding 100.
30
60
140
A method 'public static void modifyArray(int[] arr) { arr[0] = 99; }' is called with 'int[] myArray = {1,2,3}; modifyArray(myArray); System.out.println(myArray[0]);'. What is the output?
99
The method modifies the array element.
1
0
Compilation error
Which of the following correctly uses the shorthand array initializer to declare and initialize an array of strings with the elements "A", "B", and "C"?
String[] arr = new String[] {"A", "B", "C"};
String[] arr = ("A", "B", "C");
String[] arr = ["A", "B", "C"];
String[] arr = {"A", "B", "C"};
The shorthand initialiser uses braces with comma-separated values and no new keyword or explicit size; the compiler infers length from the element count. String[] arr = {"A", "B", "C"}; is the only syntactically valid declaration and initialisation.
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?
An ArrayIndexOutOfBoundsException is thrown.
Accessing arr[1] on a length-1 array exceeds the valid index range of 0 to length−1, so the JVM throws an ArrayIndexOutOfBoundsException at runtime. The swap never completes, since the exception occurs during the second assignment, before temp is written back to arr[1].
The first element is swapped with itself.
A new array with length 2 is returned.
The array remains unchanged.
A developer writes a method that accepts a variable number of int arguments and returns their product. Which method signature correctly implements this?
public static int product(int[] nums)
public static int product(int nums...)
public static int product(int... nums)
Varargs syntax int... nums lets the method accept zero or more int arguments, which Java packages into an int array. This satisfies the variable-argument constraint, and the return type int matches the product of ints. The ellipsis must follow the type, not the parameter name.
public static int product(int... nums, int extra)
Want more Arrays and Methods practice?
Practice this domain14% of exam · 6 sample questions below
Which of the following is the best practice for resource management in Java?
Close resources in a finally block without null checks.
Rely on garbage collection to close resources.
Use try-with-resources statement.
Try-with-resources guarantees each declared resource's close() method runs automatically at block exit, even when exceptions are thrown. This satisfies the resource-management constraint by eliminating leaked file handles, streams and connections, replacing error-prone manual finally blocks.
Use a try-catch block and close resources in the catch block.
A developer encounters an ArrayIndexOutOfBoundsException while running a unit test. The stack trace shows the error occurs in a method that is called from many places. Which tool or technique would most efficiently identify the specific call path?
Review the code manually to trace all possible callers.
Set a breakpoint in the method and debug the test.
A breakpoint pauses execution inside the failing method, letting the debugger display the full call stack and step back through each invoking frame. This directly satisfies the constraint of identifying which of many callers produced the out-of-bounds index.
Run a static analysis tool to detect the issue.
Add log statements at the beginning of the method.
Which statement about the Java compiler is true?
It translates Java source code into native machine code.
It produces executable files that run directly on the OS.
It executes Java programs.
It translates Java source code into bytecode.
The Java compiler converts human-readable source files into platform-independent bytecode, satisfying the requirement that compiled output runs on any Java Virtual Machine. This translation produces .class files containing instructions for the JVM rather than native machine code, which is precisely what the statement describes.
Which command is used to run a Java application from the command line?
jar
javac
java
The java launcher starts a Java application from the command line, loading the specified class and invoking its main method on the JVM. It is distinct from javac, which compiles source into bytecode, and from jar, which packages classes.
javadoc
Which TWO statements about the finally block are true? (Choose two.)
A try block must be followed by either a catch or finally.
Java requires that a try block be followed by at least one handler: either a catch clause or a finally block, and both may appear together. A try with neither is a compile-time error, so this statement accurately describes the language's exception-handling syntax rule.
The finally block executes only if an exception is thrown.
The finally block is used for resource cleanup.
The finally block executes regardless of whether the try block completes normally, throws, or returns, making it the correct place to release files, sockets and locks. This guarantees cleanup even when exception handling diverts control flow.
The finally block cannot contain a return statement.
The finally block is executed after the catch block.
Which THREE are checked exceptions in Java? (Choose three.)
ArrayIndexOutOfBoundsException
SQLException
SQLException extends Exception, so the compiler forces callers to catch it or declare it in a throws clause. This checked status satisfies the stem's constraint, distinguishing it from RuntimeException subclasses such as NullPointerException, which are unchecked.
NullPointerException
IOException
IOException extends Exception but not RuntimeException, placing it in the checked hierarchy that the compiler verifies at compile time. Any method throwing it must declare it or catch it, satisfying the stem's requirement for checked exceptions. Unchecked exceptions, by contrast, derive from RuntimeException and escape compiler enforcement.
FileNotFoundException
FileNotFoundException extends IOException, a direct subclass of Exception but not RuntimeException, so the compiler enforces handling. This satisfies the stem's checked-exception constraint: any method throwing it must declare it or catch it, unlike unchecked RuntimeException subclasses. It arises from file I/O operations, making it a canonical checked exception.
Want more Exception Handling and Development Tools practice?
Practice this domainA team is designing a Java application that needs to run on different operating systems without modification. Which Java feature makes this possible?
The Java Virtual Machine
The Java Virtual Machine executes compiled bytecode, abstracting the underlying operating system so the same .class files run unmodified on Windows, Linux or macOS. This directly satisfies the stem's cross-platform requirement: portability comes from the JVM acting as an intermediary between bytecode and each platform's native instructions.
Just-in-time compilation
Garbage collection
The Java compiler
Which TWO statements correctly describe the Java language? (Choose two.)
Java supports multiple inheritance of implementation.
Java supports operator overloading.
Java supports object-oriented programming.
Java is primarily object-oriented.
Java supports multiple inheritance of classes.
Java is a statically typed language.
Variables must be declared with a type before use.
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?
Download and install a newer version of the JDK.
Running the application on an older JDK means the runtime cannot execute bytecode or expose APIs introduced in later releases, so newer language features fail regardless of source syntax. Installing a newer JDK updates the compiler and runtime, satisfying the requirement to use the latest available language features.
Enable lambda expressions by setting the -enable-lambdas flag.
Use the -source and -target flags to compile for a newer version.
Upgrade the JVM to the latest version.
Arrange the steps to compile and run a Java program from the command line in the correct order.
Write code, Open terminal, Navigate to file directory, Compile with javac, Run with java
This is the correct order because you first create the Java source file, then open a terminal, navigate to the directory containing the file, compile it using javac to generate a .class file, and finally run the compiled program using java.
Write code, Open terminal, Compile with javac, Navigate to file directory, Run with java
Open terminal, Write code, Navigate to file directory, Compile with javac, Run with java
Write code, Open terminal, Navigate to file directory, Run with java, Compile with javac
Arrange the steps to overload a method in Java in the correct order.
Define a method, then define another method with the same name but different parameters, then ensure the method signatures are unique, then call the method with arguments that match one of the signatures.
This is the correct order because you must have at least one method defined before you can overload it, then you create a second method with the same name but a different parameter list, verify that the signatures are indeed different, and finally call the method with appropriate arguments.
Define a method, then ensure the method signatures are unique, then define another method with the same name but different parameters, then call the method with arguments.
Define another method with the same name but different parameters, then define a method, then ensure unique signatures, then call the method.
Call the method with arguments, then define a method, then define another method with the same name but different parameters, then ensure unique signatures.
Match each Java term to its correct definition.
JDK: Software development kit that includes tools for compiling, debugging, and running Java programs
JDK (Java Development Kit) provides compilers, debuggers, and other tools needed to develop Java applications.
JRE: Runtime environment that includes the JVM and core libraries required to run Java programs
JRE (Java Runtime Environment) provides the JVM and class libraries to execute compiled Java programs.
JVM: Platform-independent execution engine that interprets Java bytecode into machine code
JVM (Java Virtual Machine) translates bytecode into native instructions for the underlying OS and hardware.
Java bytecode: Intermediate representation of Java source code that runs on the JVM
Java bytecode is the compiled output from Java source code, executed by the JVM.
JDK: Runtime environment that includes the JVM and core libraries required to run Java programs
JVM: Software development kit that includes tools for compiling, debugging, and running Java programs
Want more What is Java practice?
Practice this domain14% of exam · 6 sample questions below
Which loop is guaranteed to execute its body at least once?
repeat-until loop
while loop
do-while loop
A do-while loop evaluates its condition after executing the body, so the body always runs at least once before any test. A while or for loop checks the condition first, allowing zero iterations when it is initially false.
for loop
What is the output of the following code?
int i = 0;
while (i < 5) {
if (i == 3) {i++; continue;
}
System.out.print(i + " "); i++;
}
0 1 2 4
The `continue` statement skips the remaining loop body when `i` equals 3, so `System.out.print` never executes for that value; the preceding `i++` prevents an infinite loop by advancing past 3. All other iterations print 0, 1, 2 and 4, satisfying the `i < 5` bound.
0 1 2 3
0 1 2 4 5
0 1 2 3 4
A developer writes: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); }. What is the output?
0123456789
13579
The continue statement skips the current iteration when i is even, so only odd values are printed. Iterating i from 0 to 9 and printing just the odds yields 1, 3, 5, 7 and 9 concatenated as 13579.
02468
123456789
Which loop best suits a scenario where the number of iterations is unknown and depends on user input?
for loop
while loop
A while loop tests its condition before each iteration, so it continues until the condition becomes false, suiting an unknown iteration count driven by user input. A for loop requires a known range, making it unsuitable here.
for-each loop
do-while loop
Which THREE statements are true about the switch statement in Java? (Choose three.)
It can be used with boolean expressions.
The default case must be placed at the end of the switch block.
Without a break statement, execution falls through to the next case.
Java switch labels act as entry points rather than exclusive branches, so reaching a case without a preceding break continues executing subsequent statements. This fall-through satisfies the statement's truth and is why break statements are typically inserted to terminate each case deliberately.
The default case is optional.
Java permits a switch to omit the default label entirely; the compiler raises no error, and unmatched values simply execute nothing. This satisfies the statement's truth because default is a convenience for handling residual cases, not a mandatory syntactic element of the switch construct.
It can be used with String objects.
Java 7 onwards permits switch on String, comparing via String.equals() rather than reference identity, so case labels can be string literals. This satisfies the stem's requirement that the statement works with String objects, alongside int-compatible types and enums.
Which THREE statements are true about the break and continue statements in Java? (Choose three.)
A labeled break can be used to exit an outer loop.
Correct: labeled break exits outer loop.
The continue statement skips the current iteration and proceeds to the next iteration.
Correct: continue moves to next iteration.
The break statement terminates the innermost enclosing loop or switch.
Correct: break exits the innermost loop/switch.
The continue statement can be used to exit a loop entirely.
The break statement cannot be used outside a loop.
Want more Control Flow and Loops practice?
Practice this domain14% of exam · 6 sample questions below
A developer writes a class 'Vehicle' with a method 'move()' that prints 'Vehicle moves'. A subclass 'Car' overrides 'move()' to print 'Car moves'. Given: Vehicle v = new Car(); v.move(); What is the output?
Vehicle moves
Runtime exception
Compilation fails
Car moves
Runtime polymorphism: the variable's declared type is Vehicle, but the object is a Car, so the JVM dispatches move() to Car's overridden implementation, printing 'Car moves'. Overriding is resolved dynamically at runtime based on the actual object, not the reference type.
In a banking application, a class 'Account' has a private field 'balance'. Which is the best way to allow subclasses to read but not directly modify 'balance'?
Make balance public
Provide a public getBalance() method
A public `getBalance()` method returns the field's value without exposing the field itself, so subclasses inherit read access while direct assignment stays impossible. This satisfies the stem's constraint of read-only access for subclasses, since encapsulation preserves the private modifier and modification remains confined to the `Account` class's own methods.
Use a static variable
Make balance protected
A class 'Base' has a method 'public void display() throws IOException'. Subclass 'Derived' overrides display(). Which exception specifications are allowed in the overriding method?
public void display() throws SQLException
public void display() throws FileNotFoundException
Overriding methods may narrow the checked exception, and FileNotFoundException is a subclass of IOException, so it satisfies the constraint that the override cannot throw broader checked exceptions than the parent. The method signature remains compatible, permitting this declaration while still allowing the subclass to signal a more specific failure.
public void display() throws Exception
public void display() throws Throwable
Which design principle is violated by making all fields public in a class?
Inheritance
Abstraction
Encapsulation
Public fields expose internal state directly, letting any code read or modify it without validation, which breaks encapsulation — the principle of hiding implementation details behind controlled accessors. This directly answers the stem's violation: fields should be private, with getters and setters mediating access to preserve invariants.
Polymorphism
Which is the correct way to call a superclass constructor from a subclass constructor?
super(); anywhere
super(); as first statement
Java requires super() to be the first statement in a subclass constructor, ensuring the superclass is fully initialised before subclass fields are set. Omitting it triggers an implicit no-arg super() call; placing it later causes a compile-time error.
super(); at the end
this.super();
A developer wants to prevent a method from being overridden. Which modifier should be used?
private
abstract
final
Marking a method `final` blocks subclasses from overriding it, which directly satisfies the stem's requirement to prevent overriding. The compiler rejects any attempt to redefine that method in a derived class, unlike `static`, which hides rather than overrides, or `abstract`, which mandates overriding.
static
Want more Object-Oriented Programming practice?
Practice this domainThe 1Z0-811 exam has 75 questions and must be completed in 75 minutes. The passing score is 650/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 7 domains: Primitives, Strings and Operators, Java Basics and Syntax, Arrays and Methods, Exception Handling and Development Tools, What is Java, Control Flow and Loops, Object-Oriented Programming. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official Oracle 1Z0-811 exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.