Courseiva

1Z0-811 · domain

scenario questions

Practise Oracle Java Foundations 1Z0-811 scenario questions practice questions — original exam-style scenarios with answer choices, explanations, and analysis of common mistakes.

481 questions144 easy185 medium152 hard

Focused practice

Practice scenario questions questions

Scored sessions drawing only from this domain — pick a length below.

Start 20-question practice test →

What this domain covers

What to know about scenario questions

scenario questions questions test whether you can apply the concept in context, not just recognise a definition.

How the topic appears in realistic exam-style scenarios.

Which detail in the question changes the correct answer.

How to eliminate plausible but wrong options.

How to connect the question back to the wider exam objective.

Watch out for

Common scenario questions exam traps

  • Answering from memory before reading the full scenario.
  • Missing a constraint such as cost, availability, security, scope or command context.
  • Choosing a broad answer when the question asks for the most specific fix.
  • Ignoring why the wrong options are tempting.

Question index

All scenario questions questions (481)

Click any question to see the full explanation, or start a practice session above.

1

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?

Hard
2

Refer to the exhibit. What is the likely cause?

Easy
3

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

Hard
4

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?

Medium
5

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

Easy
6

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

Hard
7

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?

Easy
8

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?

Medium
9

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

Hard
10

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

Medium
11

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?

Easy
12

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?

Medium
13

Which method overloading is valid?

Easy
14

Refer to the exhibit. What is the result?

Hard
15

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

Hard
16

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

Easy
17

What is the output?

Medium
18

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

Medium
19

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

Hard
20

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

Medium
21

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

Easy
22

Which TWO statements are true about method overloading in Java?

Easy
23

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?

Medium
24

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?

Medium
25

What is the output of the following code? int x = 5; int y = 16; System.out.print(x + "," + y);

Hard
26

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?

Hard
27

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

Hard
28

Match each OOP concept to its Java implementation.

Medium
29

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

Easy
30

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?

Easy
31

What is the output?

Medium
32

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?

Hard
33

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

Medium
34

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?

Medium
35

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

Hard
36

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

Easy
37

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

Easy
38

Arrange the steps to use the Scanner class to read user input in Java in the correct order.

Medium
39

What is printed by the program? ```java for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { System.out.print(i + "," + j + " "); if (i == 1) break; } } ```

Hard
40

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

Easy
41

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

Medium
42

Refer to the exhibit. What is the output?

Hard
43

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

Easy
44

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?

Medium
45

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?

Easy
46

Which statement about the Java compiler is true?

Easy
47

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

Hard
48

Match each Java tool to its function.

Medium
49

Which of the following is NOT a primitive data type?

Easy
50

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

Hard
51

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

Hard
52

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:

Easy
53

Which TWO of the following are valid Java identifiers?

Easy
54

Refer to the exhibit. What is the output?

Hard
55

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

Easy
56

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?

Hard
57

Arrange the steps to declare and initialize a one-dimensional array in Java in the correct order.

Medium
58

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?

Hard
59

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?

Easy
60

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

Hard
61

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

Hard
62

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

Medium
63

Which THREE are benefits of using inheritance?

Medium
64

Given the stack trace above, which line in MyClass.java caused the exception? Exception in thread "main" java.lang.NullPointerException at MyClass.methodC(MyClass.java:25) at MyClass.methodB(MyClass.java:15) at MyClass.methodA(MyClass.java:10) at MyClass.main(MyClass.java:30)

Medium
65

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

Hard
66

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?

Medium
67

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

Easy
68

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?

Hard
69

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?

Hard
70

What is the result of the expression 10 % 3?

Easy
71

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?

Medium
72

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

Hard
73

Which two of the following are primitives in Java? (Choose two.)

Medium
74

What is the output when the main method is executed? ```java public class Test { public static double add(double a, double b) { return a + b; } public static void main(String[] args) { System.out.println(add(5, 10)); } } ```

Easy
75

Given the code snippet: int x = 5; int y = 2; double result = x / y; What is the value of result?

Easy
76

What is the output of: int i = 1; i = i++; System.out.println(i);

Easy
77

int count = 0; for (int i = 0; i < 5; i++) { if (i == 2) { continue; } count++; } System.out.println(count); What is the output of the program?

Easy
78

A developer writes: char c = 'A'; int i = c + 1; System.out.println(i); What is the output?

Hard
79

A developer encounters a ClassNotFoundException at runtime. The class is present in the source code and compiles fine. Which is the most likely cause?

Easy
80

What is the output if an ArithmeticException occurs in the try block and there is a finally block?

Medium
81

Given the code snippet: double d = 10.5; int i = (int) d; System.out.println(i); What is the output?

Easy
82

A developer writes a method that reads a file and parses its contents. Which exception handling approach is best practice for ensuring the file is properly closed even if an exception occurs?

Easy
83

You are developing a high-frequency trading application where performance is critical. You need to parse and concatenate trade messages. The messages are received as strings and must be combined into a single output string for logging. Each message is appended to the log string. Currently, you are using String concatenation with the '+' operator inside a loop that processes up to 10,000 messages per second. However, performance monitoring shows that the application experiences frequent garbage collection pauses, affecting throughput. Which approach should you take to reduce garbage collection overhead and improve performance?

Medium
84

Which statement about try-catch is true?

Hard
85

What is the output of the following? int x = Integer.MAX_VALUE; x++; System.out.println(x);

Medium
86

A banking application uses a method to calculate interest: double calculateInterest(double balance) { return balance * 0.05; }. The method is called with an int argument: int accountBalance = 1000; double interest = calculateInterest(accountBalance); System.out.println(interest); The output is 50.0, but the expected output is 50.0. However, the developer notices that if the method is changed to return int, the output becomes 50.0 as well. Which statement about implicit casting is true?

Medium
87

You are maintaining a multi-threaded banking application that processes transactions. In the `processTransaction` method, you have a try-catch block that catches `Exception` to handle any unexpected errors. Recently, the application intermittently fails to update account balances correctly due to unhandled exceptions. The logs show that sometimes a `RuntimeException` is thrown from a nested method, but it is not being logged or handled properly, leading to inconsistent state. The team wants to improve the exception handling to ensure that all exceptions are caught, logged, and the transaction is rolled back properly. The method currently uses a primitive try-catch-finally where the finally block commits the transaction if no exception occurred. Which approach best addresses the issue while maintaining clarity and correctness?

Medium
88

What is the output of this program?

Medium
89

Which TWO keywords are used for decision-making in Java? (Choose two.)

Easy
90

Which two of the following are fundamental principles of Object-Oriented Programming? (Choose two.)

Easy
91

A subclass overrides a method from its superclass. Which annotation should be used to indicate the overriding intention?

Hard
92

A team decides to use a single Java source file for a small application. Which statement is true about the file structure?

Medium
93

A method has parameters: int x, double y. It performs x += y; and returns x. What is the range behavior?

Hard
94

Refer to the exhibit. A Java source file fails to compile with the given error. What change should be made to fix the error?

Hard
95

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

Easy
96

Refer to the exhibit. Given the code, what is the value printed to the console?

Hard
97

Given: double d = 5.0; int i = d; What is the result?

Hard
98

Consider the following code snippet: public int getValue() { try { return 1; } catch (Exception e) { return 2; } finally { return 3; } } What does the method return?

Medium
99

Which statement about method overloading with array parameters is true?

Hard
100

Which TWO statements about constructors are true? (Choose two.)

Medium
101

Which THREE statements about custom exceptions in Java are correct? (Select exactly 3)

Hard
102

In a Java application, a class 'OrderProcessor' contains a method that processes orders. The method currently handles multiple responsibilities: validating order data, calculating totals, updating inventory, and sending notifications. The team wants to refactor this method to follow the Single Responsibility Principle. Which action should they take?

Medium
103

A company wants to develop a Java application that can run on Windows, Linux, and macOS without any code changes. Which Java feature makes this possible?

Easy
104

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

Medium
105

Which TWO are valid ways to declare and initialize an array of Strings?

Easy
106

What is the cause of the compilation error?

Medium
107

Match each Java exception class to its category.

Medium
108

What is the most likely cause of this error?

Medium
109

A developer writes the following code: for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { System.out.print(j); } } How many times does the inner loop execute in total?

Hard
110

Given an array arr of length 5, which code snippet correctly creates a copy using System.arraycopy?

Easy
111

Arrange the steps to implement an interface in a Java class in the correct order.

Medium
112

A method 'public static int[] generate() { int[] result = new int[10]; for (int i = 0; i < result.length; i++) result[i] = i * 2; return result; }' is defined. Which statement correctly calls this method and stores the result?

Hard
113

Which THREE of the following are checked exceptions in Java?

Easy
114

Which assignment requires an explicit cast to compile?

Medium
115

A developer receives a ticket that a batch processing job is running indefinitely. The job reads records from a database and processes them in a loop. The code uses a while(true) loop with a break condition when a sentinel value is encountered. However, due to a data anomaly, the sentinel value is never reached, causing the loop to run forever. The developer needs to fix the loop to prevent infinite execution while still allowing processing of all records until the sentinel is reached. Which approach is most appropriate?

Medium
116

You are part of a team maintaining a legacy order processing system. The system stores order totals as primitive double values. A recent bug report shows that for very large orders (around $1,000,000.00), the total after adding a tax of 8.25% is sometimes off by a few cents. The calculation is: total = orderTotal * (1 + taxRate). The taxRate is defined as double taxRate = 0.0825; The orderTotal is received as a double. The application needs exact monetary precision to two decimal places. Which solution best addresses the precision issue while minimizing changes to the existing code?

Hard
117

A financial trading application processes high-volume transactions. The system uses a multithreaded architecture where multiple threads update a shared Account object's balance field. Recently, intermittently incorrect balance calculations have been reported. Developers suspect a race condition on the balance field. The Account class is defined as follows: public class Account { private double balance = 0.0; public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } } Threads are created using ExecutorService with a fixed thread pool. The issue occurs only under heavy load. Which course of action should the development team take to resolve the issue while maintaining performance?

Hard
118

Which TWO are best practices for using control flow statements? (Choose two.)

Hard
119

A junior developer writes a method that attempts to modify a String: public void update() { String s = "Hello"; s.concat(" World"); System.out.println(s); } What will be printed when update() is called?

Easy
120

Which two of the following are valid ways to check if two String objects contain the same characters? (Assume s1 and s2 are non-null String references.)

Easy
121

What is the result of compiling and running this code?

Medium
122

Given the code: public class Test { public static void change(int[] arr) { arr = new int[]{10, 20}; } public static void main(String[] args) { int[] arr = {1, 2}; change(arr); System.out.println(arr[0]); } } What is the output?

Hard
123

Which approach does NOT create a new array that is independent of the original?

Hard
124

Which two of the following are valid ways to declare and initialize an array of integers? (Select two.)

Easy
125

Which TWO statements about the finally block are true? (Choose two.)

Medium
126

Which TWO are valid ways to create a String object?

Easy
127

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

Easy
128

Refer to the exhibit. What is the output?

Easy
129

Given the code fragment: ```java int[] data = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i <= data.length; i++) { sum += data[i]; } System.out.println(sum); ``` What is the result?

Medium
130

A programmer writes a switch statement to handle different cases. The code compiles and runs, but the output is unexpected: 'A' prints when the input is 'B'. Which is the most likely cause?

Medium
131

A developer writes the following code: int a = 5; int b = 2; double result = a / b; System.out.println(result); What is the output?

Medium
132

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

Easy
133

Which of the following is not a valid array variable declaration in Java?

Easy
134

A method is needed to return a new array where each element is doubled. Which method signature correctly accomplishes this?

Easy
135

A developer says Java is platform-independent because of the JVM. Which statement best explains this?

Easy
136

Which TWO of the following development tools are specifically designed to analyze module dependencies or create custom runtime images?

Hard
137

Which keyword is used to declare a constant in Java?

Medium
138

Match each Java term to its correct definition.

Medium
139

A developer is writing a program to find the maximum value in an array of integers. The code is: int[] nums = {10, 20, 5, 30, 15}; int max = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; } } System.out.println(max); The output is 30, which is correct for this array. However, the developer is concerned that if all numbers are negative, the output would be 0 instead of the highest negative number. Which modification ensures the algorithm works correctly for all integer arrays?

Easy
140

A method receives an int parameter and modifies its value inside the method. Does this change affect the caller's argument?

Medium
141

A company manages employee data stored in an array of Employee objects. The HR application frequently needs to find an employee by ID. The current implementation uses a linear search through the array each time. Performance reports indicate that this search is becoming a bottleneck as the company grows. The array is not sorted, and the company does not want to sort it because the order is meaningful for display. The array is large and frequently updated. The development team considers several options to improve the search performance without changing the array order. Which approach should they implement?

Medium
142

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

Medium
143

Which TWO methods correctly modify the passed array in place?

Medium
144

What is the value of the expression: 2 + 3 * 4 / 2 - 1?

Medium
145

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

Medium
146

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

Easy
147

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

Easy
148

Refer to the exhibit. What is the output?

Medium
149

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

Medium
150

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

Medium
151

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

Easy
152

A class that does not define any constructor has:

Easy
153

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

Easy
154

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

Medium
155

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

Easy
156

What does the java command with -jar option do?

Easy
157

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

Medium
158

Which of the following best demonstrates polymorphism in Java?

Hard
159

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

Medium
160

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

Hard
161

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

Hard
162

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

Hard
163

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

Easy
164

Which two expressions evaluate to true? (Choose two)

Medium
165

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

Hard
166

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

Hard
167

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

Medium
168

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

Medium
169

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

Medium
170

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

Medium
171

What is the output?

Hard
172

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

Easy
173

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

Medium
174

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

Easy
175

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

Hard
176

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

Hard
177

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

Hard
178

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

Hard
179

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?

Easy
180

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

Hard
181

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

Easy
182

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

Medium
183

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

Medium
184

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

Medium
185

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

Medium
186

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

Easy
187

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

Medium
188

Which TWO statements are true about the Java programming language?

Easy
189

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

Medium
190

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

Easy
191

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'?

Easy
192

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

Medium
193

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

Hard
194

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

Hard
195

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

Medium
196

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

Medium
197

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

Hard
198

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

Medium
199

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

Medium
200

Which TWO statements are true about the main method?

Medium
201

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

Hard
202

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

Hard
203

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

Easy
204

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

Easy
205

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

Medium
206

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

Hard
207

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

Easy
208

Refer to the exhibit. What is the output?

Easy
209

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

Hard
210

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

Medium
211

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

Medium
212

Arrange the steps to handle an exception using try-catch-finally in Java in the correct order.

Medium
213

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

Hard
214

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

Easy
215

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

Medium
216

The code does not compile. What is the error?

Medium
217

Arrange the steps to create and use a simple Java inheritance hierarchy in the correct order.

Medium
218

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

Medium
219

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

Medium
220

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

Easy
221

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

Medium
222

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

Medium
223

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

Hard
224

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

Hard
225

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

Hard
226

Which primitive type can store a single character?

Medium
227

You are responsible for deploying a Java desktop application that uses JavaFX and various third-party libraries. The application is modular and uses JPMS. To reduce the footprint and startup time, you decide to use jlink to create a custom runtime image that includes only the required modules. The application has a main module `com.myapp` that requires `javafx.controls`, `javafx.base`, and some other modules. After creating the runtime image using the command `jlink --module-path $JAVA_HOME/jmods:lib --add-modules com.myapp --output myapp-image`, you test the image on a development machine, and it works. However, when deploying to a customer's machine, the application fails to start with an error: "Error: Could not find or load main class com.myapp.Main". The customer's machine has no Java installed. The runtime image includes the `com.myapp` module. You verify that the `myapp-image/bin/java` launcher exists. The main class is correctly declared in the module-info.java of `com.myapp`. What is the most likely cause of this error?

Medium
228

Refer to the exhibit. What is the output?

Easy
229

A junior developer wrote the following code to calculate the sum of an array: int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 1; i <= numbers.length; i++) { sum += numbers[i]; } System.out.println("Sum: " + sum); The developer expects the output to be 15, but the program throws an exception. What is the root cause and the correct fix?

Easy
230

A banking application stores daily transaction amounts in an array. Which declaration correctly creates an array of 31 double values?

Easy
231

Given: String s1 = "Java"; String s2 = new String("Java"); What does (s1 == s2) evaluate to?

Medium
232

A team is developing a library management system. They have a base class 'Item' with a method 'getTitle()' that returns the title. They also have a subclass 'Book' that overrides 'getTitle()'. In some places, they have a method that accepts an Item reference but actually receives a Book object. They want to call a method specific to Book, such as 'getISBN()', that is not in Item. They attempt to cast the parameter: ((Book) item).getISBN(). However, occasionally the program crashes with ClassCastException. What is the best practice to avoid this exception?

Medium
233

Which TWO of the following are valid loop constructs in Java? (Choose two.)

Easy
234

A company develops a payroll system in Java with a hierarchy: Employee, Manager (extends Employee), and Director (extends Manager). Each class overrides a method getDetails() that returns a string with employee information. Employee's getDetails() returns name and ID. Manager's getDetails() adds department. Director's getDetails() adds division. The system uses a single method printDetails(Employee e) that calls e.getDetails(). After a recent deployment, the system prints only the name and ID for all employees, even for managers and directors. The code review reveals that Employee's getDetails() is declared with default (package-private) access, while the overridden versions in Manager and Director are public. The printDetails method and the Manager/Director classes are in different packages. What is the most likely cause and the correct solution?

Easy
235

An integer counter variable is incremented in a loop that runs 3 billion times. Initially counter = 0. After the loop, the value is printed. Which code snippet correctly handles potential overflow?

Hard
236

Which TWO are valid ways to handle a checked exception in a method?

Medium
237

A developer tries to compile a modular Java application using the command shown in the exhibit. The compilation fails with the error shown. What is the most likely cause?

Medium
238

Refer to the exhibit. A developer runs the command java -version on a system. Which statement about this Java installation is correct?

Medium
239

Arrange the steps to overload a method in Java in the correct order.

Medium
240

A developer is using try-with-resources with a custom resource class that implements AutoCloseable. The class's close() method throws a custom exception `ResourceException`. In the try block, an IOException occurs. Which of the following best describes the exception that is propagated to the caller?

Hard
241

A team is developing a financial application that processes large arrays of market data. They have a method that calculates moving averages by copying a subarray for each window. The current implementation creates a new array for each window using System.arraycopy. The application is running slowly in production. The team identifies that the method is called millions of times per minute. The array is large and the window size is small. The garbage collector overhead is high due to many short-lived arrays. Which optimization should they apply to reduce object creation and improve performance?

Hard
242

A developer writes: Object obj = new String("Hello"); System.out.println(obj.length()); What will be the output?

Medium
243

A class defines two methods with the same name but different parameter lists. This is known as:

Easy
244

A class has a static variable counter initialized to 0. Two threads increment counter 1000 times each using counter++. What is a possible final value of counter?

Hard
245

A method is designed to compute the average of an array of test scores. What should the method return if the array is empty (length 0)?

Easy
246

A team deploys a Java application and observes frequent Full GC pauses. Which garbage collector is designed to minimize pause times?

Hard
247

What is the result of the following code snippet? int a = 5; int b = 2; double c = (double) (a / b); System.out.println(c);

Medium
248

A team is designing a library that handles network timeouts. They create a custom exception `NetworkTimeoutException` that extends `Exception`. They want to ensure that callers are forced to handle this exception. Which declaration is appropriate for a method that throws this exception?

Hard
249

What is the result of the following code? int a = 8; int b = 3; System.out.println(a >> 1);

Hard
250

Which TWO statements are correct about array declaration and initialization in Java?

Easy
251

A junior developer writes a simple 'Hello World' program and saves it as HelloWorld.java. He compiles it successfully with 'javac HelloWorld.java', confirming that HelloWorld.class is created in the current directory. When he tries to run it with the command 'java HelloWorld', the system returns 'Error: Could not find or load main class HelloWorld'. The current directory is indeed the one containing HelloWorld.class. He has JAVA_HOME set to the JDK installation directory and has verified that java is in the PATH. What is the most likely cause?

Easy
252

Which TWO access modifiers allow access from a subclass in a different package?

Easy
253

A mobile app backend uses Java streams to process user data. The code snippet filters users who are active and older than 18, then collects them into a list: List<User> result = users.stream() .filter(u -> u.isActive()) .filter(u -> u.getAge() > 18) .collect(Collectors.toList()); Performance metrics show that this stream operation is slow when the user list has millions of entries. The team wants to improve performance without changing the business logic. Which change would most likely improve performance?

Hard
254

A web application uses a HashMap to cache user session data. The keys are String objects representing session IDs, and values are Session objects. After some time, the cache memory usage grows excessively, causing OutOfMemoryError. The cache is never cleared. The team decides to implement a cache eviction policy. Which approach is best suited for this scenario in terms of Java standard library?

Medium
255

In a login system, the authentication method receives an array of user roles as a String[] and checks if a specific role is present. The array may be large (thousands of roles), and the method is called frequently for each user request. Performance is critical. The array is static and does not change after initialization. Which approach is most efficient for repeated checks?

Medium
256

Which of the following exceptions is a checked exception?

Easy
257

Which THREE are checked exceptions in Java? (Choose three.)

Hard
258

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

Easy
259

A developer needs to search an unsorted array of 100,000 customer IDs (int) for a specific ID. Which approach is most efficient for a single search?

Hard
260

A developer is troubleshooting a performance issue in a reporting application. A nested loop iterates over a large dataset: the outer loop processes each row, and the inner loop performs a complex computation on each column. The application is taking longer than expected. Upon reviewing the code, the developer notices that the inner loop's termination condition is recalculated each iteration, which involves a costly method call. Which optimization should the developer implement to improve performance?

Hard
261

What is the value of z after executing: int x = 3; int y = 2; int z = x++ * --y;

Hard
262

A developer wants to ensure that a class cannot be subclassed. Which keyword should be used?

Easy
263

Given the compilation error above, which fix would resolve the error?

Hard
264

Given methods: void print(Integer i) { System.out.println("Integer"); } void print(int i) { System.out.println("int"); } What is output of print(10);?

Medium
265

Refer to the exhibit. What is the output?

Medium
266

Based on the command, which garbage collector is configured for this application?

Hard
267

A method 'public static double average(int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; i++) sum += numbers[i]; return sum / numbers.length; }' is called with array {10, 20, 30}. What change is needed to return the correct average?

Medium
268

Which THREE of the following are valid loop constructs in Java?

Easy
269

Which TWO are characteristics of the Java Runtime Environment (JRE)?

Hard
270

Which two of the following operators are logical operators in Java? (Choose two.)

Easy
271

Which TWO statements correctly describe the Java language? (Choose two.)

Hard
272

A company is developing a Java-based inventory management system. The system runs on a single server and processes up to 1000 concurrent requests. The development team has implemented the code using multiple threads to handle requests. Recently, the system has been experiencing intermittent data corruption in the inventory counts. After reviewing the code, the team suspects that the issue is related to thread safety. The team is considering the following solutions: (A) Use the 'synchronized' keyword on all methods that update inventory counts. (B) Use 'volatile' keyword on the inventory count variables. (C) Use 'AtomicInteger' for inventory counts. (D) Increase the number of threads to handle requests faster. Which solution should the team implement to fix the data corruption issue with minimal performance impact?

Hard
273

A developer is writing a bitmask validation method. The method should return true if both input integers (x and y) have exactly the same least significant bit set. The developer writes: if (x & y == 1) { return true; } However, the condition never evaluates to true even when both numbers are odd (least significant bit = 1). Debugging shows that x and y are positive integers. What is the root cause and the correct fix?

Hard
274

Which TWO command-line tools are included in the Oracle JDK for monitoring and troubleshooting Java applications? (Select exactly 2)

Medium
275

Which THREE are valid Java identifiers?

Easy
276

A team is designing a system where a 'Report' class can be generated in different formats (PDF, Excel, HTML). They want to avoid modifying the Report class when adding new formats. Which OOP principle or pattern should they use?

Medium
277

Which THREE statements are correct about the 'main' method signature in Java?

Hard
278

Refer to the exhibit. What is the result of attempting to compile and run the code?

Medium
279

Consider: for(int i=0;i<10;i++) { int x = i; } System.out.println(x); What is the result?

Hard
280

A junior developer wrote the following code to compare two strings entered by a user: if (username == "admin") { grantAccess(); } else { denyAccess(); }. The code always denies access even when the user enters 'admin'. What is the most likely cause, and how should the code be fixed?

Easy
281

A custom exception class must extend which class to be a checked exception?

Hard
282

Given: String str = "Java"; str = str.concat(" SE"); str.replace('a', 'A'); System.out.println(str); What is the output?

Hard
283

Which statement about abstract classes and interfaces is true in Java?

Hard
284

Given boolean a = true, b = false, c = true; What is the result of (a || b) && (b || c)?

Hard
285

A method is declared as: public static int[] generateSequence(int n) { ... }. Which return statement is valid inside this method?

Hard
286

A package named com.example.util is declared in a file. Where should the file be placed in the directory structure?

Easy
287

A junior developer wrote a while loop that never terminates. What is the most likely cause?

Medium
288

Which THREE are valid components of the Java Virtual Machine (JVM)?

Medium
289

Which three of the following code snippets produce the output '5'?

Medium
290

A company is developing a security-sensitive banking application. Which Java feature most directly enhances security?

Medium
291

A developer needs to iterate over a 2D array row by row and exit early if a specific value is found in any cell. Which nested loop structure with control statements is most efficient?

Hard
292

Which primitive type can store a single character?

Easy
293

A parent class has a static method display() and an instance method show(). A child class attempts to override both. What is the outcome?

Hard
294

Which THREE are true about Java constructors?

Medium
295

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?

Hard
296

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

Easy
297

A developer is working on a Java application that processes sensor data. The code uses a class 'SensorDataProcessor' which directly instantiates specific sensor classes like 'TemperatureSensor' and 'PressureSensor' inside its methods. The team wants to make the system extensible to support new sensor types without modifying the processor class. Which design change best achieves this?

Medium
298

Match each Java operator to its description.

Medium
299

Given: int[] arr = {10,20,30}; System.out.println(arr[3]); What is the result?

Hard
300

Which TWO of the following are best practices for exception handling in Java?

Medium
301

When using try-with-resources, which interface must the resource implement?

Medium
302

A developer wants to iterate over an array of integers named 'numbers'. Which loop declaration will correctly access each element?

Easy
303

A junior developer created a class 'BankAccount' with public fields for balance and account number. After deployment, users are able to set negative balances, causing issues. Which OOP principle should have been applied to prevent this?

Easy
304

A developer writes a method that accepts an array and returns the sum of all elements. Which implementation is correct if the array might be null?

Medium
305

A method is designed to reverse an array of integers. The method signature is: public static void reverse(int[] arr). The method correctly reverses the array. Which statement is true about the method?

Easy
306

A new developer writes a method that accepts an array and intends to swap the first and last elements. The code is: public static void swapEnds(int[] arr) { int temp = arr[0]; arr[0] = arr[arr.length-1]; arr[arr.length-1] = temp; } What is a potential issue with this method if the array is empty?

Easy
307

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

Easy
308

Which THREE statements about the final keyword in Java are true?

Hard
309

A developer writes the following code: int x = 5; int y = x++; What are the values of x and y after execution?

Easy
310

Refer to the exhibit. Why does the code fail to compile?

Easy
311

A company is upgrading from Java 8 to Java 11. Which advantage does the module system introduced in Java 9 provide?

Medium
312

What is the output?

Medium
313

A developer needs to build a SQL query string by concatenating many parts. Which approach is most efficient for repeated concatenation?

Medium
314

A developer writes: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); }. What is the output?

Hard
315

Refer to the exhibit. What is the output?

Easy
316

Given: int a = 10; int b = 20; boolean flag = a++ > 10 && ++b > 20; What are the values of a and b after execution?

Hard
317

Which THREE of the following are valid Java operators?

Hard
318

Given: int i = 1; int j = i++ + ++i; What is the value of j?

Medium
319

Refer to the exhibit. Which action would best resolve this error without changing the code?

Medium
320

A method is declared as 'public void printElements(int... numbers)'. Which invocation will cause a compilation error?

Easy
321

A developer writes: int a = 9; int b = 2; double result = a / b; System.out.println(result); What is the output?

Easy
322

Arrange the steps to use a for loop to iterate over an array in Java in the correct order.

Medium
323

Given: int x = 10; int y = 20; What is the output of System.out.println(x + y * 2);?

Easy
324

Which THREE are valid ways to declare and initialize a two-dimensional int array in Java?

Medium
325

A developer compiles a Java program successfully but gets 'ClassNotFoundException' when running it. What is the most likely cause?

Medium
326

Given the output, which statement is true about this Java installation?

Easy
327

Consider a method that processes a two-dimensional array (matrix). It uses nested for loops. The inner loop uses a label 'outer' to break out of the outer loop. Under what condition is this label beneficial?

Hard
328

Which of the following statements about the String class is true?

Hard
329

Which two statements are true about primitive data types in Java?

Medium
330

What is the output?

Easy
331

Which three of the following are valid Java operators that can be used with primitive numeric types?

Medium
332

A developer is writing a method to compute the average of an array of scores. The method should handle edge cases gracefully. The scores array may be empty or contain null values if the collection was interrupted. The scores are stored as primitive doubles. Which implementation is safest and follows best practices?

Easy
333

Arrange the steps to compile and run a Java program from the command line in the correct order.

Medium
334

Refer to the exhibit. Which overloaded methods cause this compilation error?

Medium
335

A team is implementing a search algorithm that iterates over an array of integers. The loop should stop as soon as the target value is found. Which loop construct is most appropriate?

Medium
336

A scientific application performs calculations with double precision. A specific formula divides two double values: result = a / b; where a and b are calculated from sensor readings. The result is expected to be at most 10 decimal digits of precision. However, the output often shows small rounding errors, e.g., 0.1 + 0.2 = 0.30000000000000004. The application must meet strict accuracy requirements and cannot tolerate these small errors. Which strategy should be used to achieve exact decimal representation?

Medium
337

Which TWO of the following are valid declarations and initializations of primitive variables?

Medium
338

Which primitive type has a default value of 0.0f?

Easy
339

Which of the following is a valid Java primitive type?

Easy
340

A team is developing a Java application for an online store. The application has a class 'Inventory' that maintains an array of 'Product' objects. The method 'public void addProduct(Product p)' is intended to add a product to the array. The current implementation uses a fixed-size array of length 100. However, the business has grown, and the array may exceed its capacity. The team needs a solution that allows dynamic resizing without changing the method signature. Which approach should the team take?

Medium
341

Refer to the exhibit. What is the output?

Hard
342

Which loop best suits a scenario where the number of iterations is unknown and depends on user input?

Medium
343

Refer to the exhibit. What is the output?

Medium
344

What likely caused this compilation error?

Hard
345

A team is designing a Java application that needs to run on different operating systems without modification. Which Java feature makes this possible?

Easy
346

Match each Java collection interface to its characteristics.

Medium
347

What is the primary purpose of Java bytecode?

Easy
348

A developer writes the following code: if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else { grade = 'D'; } What is the value of grade if score is 75?

Easy
349

A development team is building a modular Java application using Java 17. They have defined a module named com.myapp with a module-info.java that includes 'requires com.thirdparty.lib;'. The com.thirdparty.lib module is a third-party library packaged as a modular JAR with its own module-info.class. The application compiles successfully using javac with the module path pointing to the directory containing the JAR. However, when starting the application with java --module-path <path> --module com.myapp, a NoClassDefFoundError occurs for a class from com.thirdparty.lib. The error message indicates the class is not found. The team has confirmed that the JAR file is present in the specified module path and that the class exists in the JAR. No other errors or warnings are displayed. The team is puzzled because the code compiles without issues. What is the most likely cause of this runtime error?

Hard
350

A 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?

Medium
351

What is the value of sum printed? int sum = 0; for (int i = 0; i < 3; i++) { sum = sum + i; } System.out.println(sum);

Hard
352

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

Medium
353

Which two statements about method parameter passing in Java are true? (Choose two.)

Hard
354

Which TWO statements are true about the finally block in exception handling? (Select exactly 2)

Medium
355

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?

Medium
356

Refer to the exhibit. What is the output?

Medium
357

A company requires a method that accepts an integer and returns true if the integer is even, otherwise false. Which implementation best follows Java conventions?

Medium
358

Refer to the exhibit. What is the potential issue with this singleton implementation in a multithreaded environment?

Hard
359

What is the output of the following code? int i = 0; i = i++ + ++i; System.out.println(i);

Medium
360

Refer to the exhibit. A developer encounters this exception when running the application. The method divide is intended to handle division by zero. What is the most likely cause of the exception?

Hard
361

A developer writes a method that reads a file and processes its contents. The method uses a BufferedReader wrapped around a FileReader. Which of the following approaches ensures that both resources are properly closed even if an exception occurs?

Medium
362

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

Hard
363

A Java application uses an interface 'Drawable' with a default method 'draw()'. A class 'Circle' implements Drawable but does not override draw(). Another class 'Square' implements Drawable and overrides draw(). Which statement is true about calling draw() on instances of Circle and Square?

Hard
364

Which method invocation is ambiguous given these overloaded methods? public void process(int[] a) and public void process(int... a)

Medium
365

Refer to the exhibit. What happens when you compile this code?

Medium
366

What is the output?

Easy
367

Which THREE of the following are valid types that can be used as a switch expression in Java (as of Java 8)?

Medium
368

What is the value printed?

Hard
369

A method 'public static int findMax(int[] numbers)' returns the maximum value in the array. Which implementation correctly handles an empty array by returning 0?

Medium
370

Refer to the exhibit. What is the most likely cause?

Medium
371

A company's application uses a switch statement to handle different user roles. The code currently has a bug where after processing one role, it unintentionally executes the next role's logic. Which concept is being misused?

Medium
372

An application throws 'java.lang.OutOfMemoryError: Java heap space'. Which JVM option can help generate diagnostic information to identify the cause?

Easy
373

Given a method that catches Exception and then throws a RuntimeException, what is the effect?

Hard
374

Match each Java keyword to its use.

Medium
375

A method returns a String. The team debates using == vs equals(). Which correctly describes String comparison in Java?

Hard
376

What is the value of y after executing the following code? ```java int y = 10 + 12; ```

Hard
377

Which TWO statements about interfaces in Java are true?

Hard
378

What is the primary role of the Java Development Kit (JDK) compared to the JRE?

Easy
379

A class 'Base' has a method 'public void display() throws IOException'. Subclass 'Derived' overrides display(). Which exception specifications are allowed in the overriding method?

Hard
380

Which TWO statements are true about interfaces in Java?

Hard
381

Given: int x = 3 + 4 * 2; What is x?

Easy
382

Given the following code, String s1 = new String("example"); String s2 = "example"; System.out.println(s1 == s2); Why does the code output false?

Hard
383

What is the value of 10 % 3?

Easy
384

A developer writes a multi-threaded application that runs on Windows. To ensure the same bytecode runs without modification on Linux and macOS, which Java feature is essential?

Hard
385

A financial trading application processes a batch of 10 million trade transactions every night. Each transaction is a String containing trade details such as ID, symbol, quantity, and price. The current implementation uses string concatenation with the += operator in a loop to build a summary report string. The application frequently runs out of memory and takes hours to complete. The server has 16 GB of RAM and runs Java 11. The code cannot be restructured significantly due to regulatory requirements, but performance improvements are allowed. Which course of action will most effectively resolve the performance and memory issues?

Hard
386

Which THREE of the following statements about operators in Java are true?

Easy
387

A developer needs to concatenate several string values in a loop. Which approach is most efficient for performance?

Medium
388

A developer writes the following code to compare two strings: String s1 = "Java"; String s2 = new String("Java"); if (s1 == s2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } What is the output?

Hard
389

Which TWO are valid identifiers in Java? (Choose two.)

Medium
390

Match each access modifier to its visibility level.

Medium
391

Which THREE of the following expressions evaluate to true? (Assume int a=5, b=10)

Medium
392

Given the following try-catch block: try { // some code } catch (IOException | NumberFormatException e) { e = new IOException("wrapper"); // throw e; } Which line causes a compilation error?

Hard
393

Consider the following code: int[] arr = new int[5]; for (int i = 0; i <= arr.length; i++) { arr[i] = i; } System.out.println(arr[0]); What is the result?

Medium
394

What is the result of the following code snippet? int x = 5; int y = 2; double z = x / y; System.out.println(z);

Easy
395

A developer writes: String s = "Hello"; s.concat(" World"); System.out.println(s); What is the output?

Medium
396

Which of the following is the best practice for resource management in Java?

Easy
397

A developer wants to assign the largest possible long value to a variable. Which is correct?

Medium
398

You are a junior developer tasked with generating API documentation for a large Java project. The project uses Javadoc comments extensively, and you need to generate HTML documentation that includes all public and protected classes and methods. You have access to the source files in the `src` directory, and you want the output to be placed in a `docs` folder. Additionally, you want to include a custom header and footer in each generated page. The project uses multiple packages like `com.example.app`, `com.example.util`, and `com.example.data`. You plan to run the javadoc command from the project root. Which command should you use?

Easy
399

Given the method: public static void modify(int[] data) { data = new int[]{10,20}; } What is the output of: int[] vals = {1,2}; modify(vals); System.out.println(vals[0]);

Medium
400

What is printed when the main method runs?

Medium
401

class Parent { void show() { System.out.print("Parent"); } } class Child extends Parent { void show() { System.out.print("Child"); } } public class Test { public static void main(String[] args) { Parent p = new Child(); p.show(); } } What is the output?

Medium
402

Which command is used to run a Java application from the command line?

Easy
403

A developer implements a loop that processes a list of transactions. The loop must ensure that at least one transaction is processed even if the list is empty. Which loop construct guarantees this?

Hard
404

Refer to the exhibit. What is the output?

Hard
405

A developer wants to prevent a method from being overridden. Which modifier should be used?

Medium
406

Which primitive data type should be used to store a single character?

Easy
407

Consider a Java application that throws a NullPointerException deep inside a library method. The stack trace does not include the caller's line numbers because the library was compiled without debug information. Which approach would best help identify the root cause?

Hard
408

A method that calculates the average of an array of doubles is defined as: public static double average(double[] values) { double sum = 0; for (double v : values) sum += v; return sum / values.length; } Which call is valid?

Easy
409

A developer is writing a batch processing application that reads a list of orders and processes each one. The orders are stored in an array of Order objects. The processing logic is complex and involves multiple conditional checks. The developer uses a for-each loop to iterate over the array. However, during testing, the application throws an IndexOutOfBoundsException when processing orders that have a status of "CANCELLED". The developer wants to skip the processing of cancelled orders but still record that the order was skipped in a log. The current code is: for (Order order : orders) { if (order.getStatus().equals("CANCELLED")) { // Skip } // process order process(order); log(order); } The developer considers four options: A. Change the for-each loop to a traditional for loop with an index and increment only when order is not cancelled. B. Add a continue statement inside the if block. C. Change the if condition to check for non-cancelled orders and wrap only the process(order) call inside the if block, leaving log(order) outside. D. Use a while loop with an iterator and remove cancelled orders from the array. Which option best solves the problem without modifying the array and while still logging all orders?

Hard
410

A developer wants to sort an array of primitive ints in descending order. Which approach will work without using third-party libraries?

Hard
411

Which access modifier allows a member to be accessed only within the same class?

Easy
412

A developer is maintaining a Java backend service for order processing. The service uses a third-party library that throws a checked PaymentException when a payment fails. The current processOrder method catches Exception generically, logs the error, and returns null. The business requires that when a payment fails, the order status must be updated to 'FAILED' in the database, and a notification must be sent to the customer. However, due to the generic catch, these actions are not performed. The developer must modify the code to meet the business requirements without changing the external API of the class (i.e., the method signature must remain the same and must not throw any exceptions to the caller). Which course of action should the developer take?

Easy
413

A developer needs to iterate over an array of integers and compute the sum of its elements. Which loop construct is most appropriate for this task?

Easy
414

Evaluate the following expression: int x = 5; int y = (x > 5) ? 10 : 20; What is y?

Medium
415

A developer needs to handle a specific checked exception, FileNotFoundException, but also wants to catch any other IOException that might occur. Which catch block ordering is correct?

Easy
416

What is the result of the following code? int[] arr = new int[3]; arr[3] = 5; System.out.println(arr[3]);

Easy
417

A developer writes a method that takes a variable number of integer arguments and returns the maximum. Which method signature is correct?

Medium
418

Which of the following is a valid Java identifier?

Medium
419

Which of the following correctly describes the effect of the method call 'Arrays.sort(myArray)' on an array of objects that do not implement Comparable?

Hard
420

In a nested loop structure, a developer wants to exit completely from the outer loop when a certain condition is met inside the inner loop. Which approach is correct?

Hard
421

Refer to the exhibit. What is the output?

Hard
422

You are writing a program that processes a list of transactions. Each transaction has a timestamp (long), amount (double), and type (String). The program needs to iterate through the transactions in the order they were added. Which collection should you use to maintain insertion order and allow fast iteration?

Medium
423

Which two statements about passing arrays to methods are correct? (Select two.)

Hard
424

Given the following code: class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } } class C extends B { C() { System.out.print("C"); } public static void main(String[] args) { new C(); } } What is the output when running the main method?

Hard
425

Refer to the exhibit. A Java program throws a NullPointerException. Which is the most likely cause?

Medium
426

Given: short s = 10; s = s + 5; What is the result?

Hard
427

Given 'int[] source = {1,2,3,4,5};' and 'int[] dest = new int[3];' which code correctly copies the first three elements from source to dest using System.arraycopy?

Hard
428

What is the result of: Integer a = null; int b = (a != null) ? a : 0; System.out.println(b);

Hard
429

A developer writes: int x = 5; int y = x++ + ++x; What is the value of y after execution?

Hard
430

What is the output of System.out.println(1 + 2 + "3" + 4 + 5);?

Easy
431

A developer compiles a Java application using the command `javac -d bin src/com/example/App.java`. Which of the following is true?

Easy
432

Refer to the exhibit. What is the problem with this class?

Medium
433

What is the output of the program?

Medium
434

Which is the correct way to call a superclass constructor from a subclass constructor?

Easy
435

A developer writes: if (x = 5) { System.out.println("x is 5"); } What is the result?

Medium
436

A developer writes a loop that iterates over an array of integers. The loop should stop when it encounters a negative number. Which control flow construct best achieves this?

Easy
437

Which TWO keywords are used to control access to class members? (Choose two.)

Medium
438

Which TWO of the following operations on String objects result in a new String object?

Hard
439

A developer writes a class 'Animal' with a method 'sound()'. The 'Cat' subclass overrides 'sound()'. If an Animal reference points to a Cat object, which method is called when sound() is invoked?

Easy
440

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

Medium
441

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"?

Easy
442

What is the result of: int[] arr = new int[5]; System.out.println(arr[5]);

Easy
443

Arrange the steps to create an object from a class in Java in the correct order.

Medium
444

What is the default value of a boolean variable in Java?

Easy
445

A developer creates an interface 'Drawable' with a single abstract method 'draw()'. They then create a class 'Circle' that implements Drawable but forgets to provide the draw() method. Circle is not declared abstract. What will happen when compiling Circle?

Hard
446

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?

Hard
447

Which data type should be used to store a single character like 'A'?

Easy
448

A developer is working on a Java application that processes user input. The application reads an integer from the command line using args[0], converts it to an int, and uses it in a loop. When testing, the application throws a NumberFormatException when the user provides an alphabetic string. The developer needs to handle this exception gracefully by prompting the user to enter a valid number and retrying. However, the developer must avoid infinite loops. The current code uses a while loop with a flag. Which approach ensures the code handles the exception, provides feedback, and terminates if the user enters 'quit'? The environment is a standard Java SE 11 application. The developer wants a robust solution without using external libraries.

Hard
449

Given the code: int[] arr = {1,2,3}; for(int x : arr) { if(x==2) continue; System.out.print(x); } What is the output?

Hard
450

A developer writes a catch block that handles multiple exception types that have a subclass relationship. Which of the following is a valid use of the multi-catch feature?

Easy
451

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?

Hard
452

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

Medium
453

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

Hard
454

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?

Hard
455

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

Easy
456

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?

Medium
457

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

Medium
458

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

Medium
459

Which THREE statements are true about method overloading in Java?

Hard
460

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?

Medium
461

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?

Medium
462

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

Medium
463

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?

Hard
464

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

Hard
465

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

Medium
466

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?

Hard
467

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

Medium
468

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

Easy
469

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

Medium
470

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?

Hard
471

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

Easy
472

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)); } } ```

Easy
473

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

Easy
474

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

Hard
475

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

Easy
476

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?

Hard
477

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

Easy
478

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

Easy
479

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

Medium
480

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

Hard
481

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?

Medium

Frequently asked questions

What does the scenario questions domain cover on the 1Z0-811 exam?
scenario questions questions test whether you can apply the concept in context, not just recognise a definition.
How many questions are in this domain?
This page lists all 481 scenario questions questions in the 1Z0-811 question bank. The actual exam draws from this domain proportionally to its weighting in the official exam blueprint.
What is the best way to practise this domain?
Start with a short focused session (10 questions) to identify gaps, then work through explanations. Repeat with a longer session once the weak areas feel solid.
Can I practise only scenario questions questions?
Yes — the session launcher on this page filters questions to this domain only. Choose any session length for inline explanations and scoring.