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.
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.
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?
Hard2Refer to the exhibit. What is the likely cause?
Easy3Given: boolean a = false; boolean b = true; boolean c = true; System.out.println(a || b && c); What is the output?
Hard4A 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?
Medium5A developer writes the following code: String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); What is the output?
Easy6Which TWO statements about the enhanced for loop (for-each) are correct?
Hard7A 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?
Easy8A 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?
Medium9Which of the following is a valid declaration of a float variable?
Hard10Which operator is used to compare two strings for value equality in Java?
Medium11In 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?
Easy12A 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?
Medium13Which method overloading is valid?
Easy14Refer to the exhibit. What is the result?
Hard15Which three of the following statements about primitive type conversion are true?
Hard16Which two statements about the break statement in Java are true?
Easy17What is the output?
Medium18Which TWO are valid ways to pass an array to a method in Java?
Medium19A method declares throws FileNotFoundException and SQLException. Which statement about the caller is true?
Hard20Which TWO statements are true about the String class in Java? (Choose 2)
Medium21What is the result of: System.out.println(10 + 20 + "30");
Easy22Which TWO statements are true about method overloading in Java?
Easy23A 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?
Medium24A 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?
Medium25What is the output of the following code? int x = 5; int y = 16; System.out.print(x + "," + y);
Hard26You 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?
Hard27A developer uses the following array initialization: int[] nums = new int[]{1, 2, 3}; Which of the following is true?
Hard28Match each OOP concept to its Java implementation.
Medium29A developer needs to store a currency value with two decimal places. Which primitive type is most appropriate?
Easy30A 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?
Easy31What is the output?
Medium32A 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?
Hard33What is the output of the following code? int i = 0; while (i < 5) { if (i == 3) { i++; continue; } System.out.print(i + " "); i++; }
Medium34A 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?
Medium35Which of the following scenarios demonstrates the most appropriate use of a continue statement?
Hard36Which tool is used to generate documentation comments from Java source code?
Easy37Which THREE are fundamental principles of Object-Oriented Programming? (Choose three.)
Easy38Arrange the steps to use the Scanner class to read user input in Java in the correct order.
Medium39What 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; } } ```
Hard40Given the array declaration: int[] data = new int[5];, what is the value of data[2] after initialization?
Easy41Which three statements about method overloading are true? (Select three.)
Medium42Refer to the exhibit. What is the output?
Hard43Which two control flow statements can be used to terminate a loop prematurely?
Easy44A 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?
Medium45Consider 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?
Easy46Which statement about the Java compiler is true?
Easy47Given the loop: for (int i=0; i<5; i++) { if (i==2) continue; System.out.print(i); } What is the output?
Hard48Match each Java tool to its function.
Medium49Which of the following is NOT a primitive data type?
Easy50Given: byte b = 10; b = b + 1; What is the result?
Hard51Given method: static void change(String s) { s = "new"; } What is output of: String name = "original"; change(name); System.out.println(name);
Hard52A 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:
Easy53Which TWO of the following are valid Java identifiers?
Easy54Refer to the exhibit. What is the output?
Hard55A developer writes: boolean b = !true && false; What is the value of b?
Easy56Given 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?
Hard57Arrange the steps to declare and initialize a one-dimensional array in Java in the correct order.
Medium58A 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?
Hard59A 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?
Easy60A developer wants to achieve loose coupling between components. Which two practices support loose coupling? (Choose two.)
Hard61What is the result of the following code? Integer a = 100; Integer b = 100; System.out.println(a == b);
Hard62Given the javap output of a class file, which statement is correct about the Java version used to compile it?
Medium63Which THREE are benefits of using inheritance?
Medium64Given 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)
Medium65Given: byte b = 10; b = b + 1; Which statement is true?
Hard66A 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?
Medium67Which loop is guaranteed to execute its body at least once?
Easy68You 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?
Hard69A 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?
Hard70What is the result of the expression 10 % 3?
Easy71A 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?
Medium72In the Java memory model, where are primitive local variables declared inside a method stored?
Hard73Which two of the following are primitives in Java? (Choose two.)
Medium74What 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)); } } ```
Easy75Given the code snippet: int x = 5; int y = 2; double result = x / y; What is the value of result?
Easy76What is the output of: int i = 1; i = i++; System.out.println(i);
Easy77int 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?
Easy78A developer writes: char c = 'A'; int i = c + 1; System.out.println(i); What is the output?
Hard79A developer encounters a ClassNotFoundException at runtime. The class is present in the source code and compiles fine. Which is the most likely cause?
Easy80What is the output if an ArithmeticException occurs in the try block and there is a finally block?
Medium81Given the code snippet: double d = 10.5; int i = (int) d; System.out.println(i); What is the output?
Easy82A 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?
Easy83You 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?
Medium84Which statement about try-catch is true?
Hard85What is the output of the following? int x = Integer.MAX_VALUE; x++; System.out.println(x);
Medium86A 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?
Medium87You 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?
Medium88What is the output of this program?
Medium89Which TWO keywords are used for decision-making in Java? (Choose two.)
Easy90Which two of the following are fundamental principles of Object-Oriented Programming? (Choose two.)
Easy91A subclass overrides a method from its superclass. Which annotation should be used to indicate the overriding intention?
Hard92A team decides to use a single Java source file for a small application. Which statement is true about the file structure?
Medium93A method has parameters: int x, double y. It performs x += y; and returns x. What is the range behavior?
Hard94Refer to the exhibit. A Java source file fails to compile with the given error. What change should be made to fix the error?
Hard95Which TWO are valid Java identifiers? (Choose two.)
Easy96Refer to the exhibit. Given the code, what is the value printed to the console?
Hard97Given: double d = 5.0; int i = d; What is the result?
Hard98Consider the following code snippet: public int getValue() { try { return 1; } catch (Exception e) { return 2; } finally { return 3; } } What does the method return?
Medium99Which statement about method overloading with array parameters is true?
Hard100Which TWO statements about constructors are true? (Choose two.)
Medium101Which THREE statements about custom exceptions in Java are correct? (Select exactly 3)
Hard102In 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?
Medium103A 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?
Easy104What is the output of the following code? String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2);
Medium105Which TWO are valid ways to declare and initialize an array of Strings?
Easy106What is the cause of the compilation error?
Medium107Match each Java exception class to its category.
Medium108What is the most likely cause of this error?
Medium109A 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?
Hard110Given an array arr of length 5, which code snippet correctly creates a copy using System.arraycopy?
Easy111Arrange the steps to implement an interface in a Java class in the correct order.
Medium112A 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?
Hard113Which THREE of the following are checked exceptions in Java?
Easy114Which assignment requires an explicit cast to compile?
Medium115A 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?
Medium116You 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?
Hard117A 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?
Hard118Which TWO are best practices for using control flow statements? (Choose two.)
Hard119A 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?
Easy120Which 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.)
Easy121What is the result of compiling and running this code?
Medium122Given 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?
Hard123Which approach does NOT create a new array that is independent of the original?
Hard124Which two of the following are valid ways to declare and initialize an array of integers? (Select two.)
Easy125Which TWO statements about the finally block are true? (Choose two.)
Medium126Which TWO are valid ways to create a String object?
Easy127Which operator is used to compare two values for equality in Java?
Easy128Refer to the exhibit. What is the output?
Easy129Given 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?
Medium130A 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?
Medium131A developer writes the following code: int a = 5; int b = 2; double result = a / b; System.out.println(result); What is the output?
Medium132Which THREE are primitive data types in Java? (Choose three.)
Easy133Which of the following is not a valid array variable declaration in Java?
Easy134A method is needed to return a new array where each element is doubled. Which method signature correctly accomplishes this?
Easy135A developer says Java is platform-independent because of the JVM. Which statement best explains this?
Easy136Which TWO of the following development tools are specifically designed to analyze module dependencies or create custom runtime images?
Hard137Which keyword is used to declare a constant in Java?
Medium138Match each Java term to its correct definition.
Medium139A 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?
Easy140A method receives an int parameter and modifies its value inside the method. Does this change affect the caller's argument?
Medium141A 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?
Medium142Given 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?
Medium143Which TWO methods correctly modify the passed array in place?
Medium144What is the value of the expression: 2 + 3 * 4 / 2 - 1?
Medium145Which access modifier allows members to be accessed only by classes in the same package?
Medium146Which TWO of the following are valid Java identifiers? (Choose two.)
Easy147Refer to the exhibit. What is the likely cause of this error?
Easy148Refer to the exhibit. What is the output?
Medium149A method throws a checked exception. Which of the following is the correct way to handle it in the calling method?
Medium150Which TWO statements are true about the 'super' keyword in Java?
Medium151A programmer wants to iterate over a list of strings and print each that starts with 'A'. Which loop construct is best suited?
Easy152A class that does not define any constructor has:
Easy153What is the output of: System.out.println(new Manager("Alice", 5).getName());
Easy154Refer to the exhibit. What is the output when the following code is executed? Vehicle v = new Car(); v.accelerate(); System.out.println(v.speed);
Medium155Which command compiles a Java file and generates a .class file?
Easy156What does the java command with -jar option do?
Easy157A 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?
Medium158Which of the following best demonstrates polymorphism in Java?
Hard159Which THREE are valid loop constructs in Java? (Choose three.)
Medium160Given: abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() {} } Which is true?
Hard161A team is designing a new system that requires deploying independent services communicating over a network. Which Java technology is most suitable for this architecture?
Hard162A 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?
Hard163What is the output of the following code? String str1 = "Java"; String str2 = new String("Java"); System.out.println(str1 == str2);
Easy164Which two expressions evaluate to true? (Choose two)
Medium165Which THREE statements are true about passing arrays to methods in Java?
Hard166Which THREE are valid ways to declare and initialize an integer variable in Java? (Choose three.)
Hard167A developer writes a method that accepts a variable number of int arguments and returns their product. Which method signature correctly implements this?
Medium168A 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?
Medium169Given two String objects s1 = "Hello" and s2 = "Hello", what does the expression (s1 == s2) return?
Medium170A developer writes two methods: public void process(int a) { ... } and public void process(double a) { ... }. Which method is called by process(10)?
Medium171What is the output?
Hard172Which is the correct way to declare an array of integers in Java?
Easy173Which TWO of the following are valid benefits of using inheritance in Java? (Choose two.)
Medium174Given: int a = 9; int b = 2; double c = a / b; System.out.println(c); What is the output?
Easy175Which THREE of the following are primitive data types in Java?
Hard176Consider the following interface: public interface Drawable { void draw(); } A developer implements Drawable in class Circle. Which statement about the implementation is correct?
Hard177Which three statements about String immutability are true? (Choose three)
Hard178Consider 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?
Hard179Given 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?
Easy180A 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?
Hard181Which THREE of the following are key features of the Java programming language?
Easy182Which loop construct guarantees that the body executes at least once?
Medium183A 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?
Medium184Arrange the steps to define a class with a main method in Java in the correct order.
Medium185A method is declared as: public static void main(String[] args) { }. Which statement is true?
Medium186Which TWO of the following are primitive data types in Java?
Easy187A 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?
Medium188Which TWO statements are true about the Java programming language?
Easy189Which of the following correctly uses the ternary operator to set int max to the larger of two ints x and y?
Medium190Which TWO are true about the Java Runtime Environment (JRE)? (Choose two.)
Easy191In 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'?
Easy192A 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.)
Medium193Given: String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); Which of the following is true?
Hard194A 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]?
Hard195Which TWO of the following are legal ways to declare and initialize an array?
Medium196Which THREE statements are true about the switch statement in Java? (Choose three.)
Medium197Which THREE statements are true about interfaces in Java? (Choose three.)
Hard198Consider 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]);
Medium199A 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?
Medium200Which TWO statements are true about the main method?
Medium201A 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?
Hard202A developer implements a method to check if a number exists in an array using binary search. The array is not sorted. What will happen?
Hard203Which two of the following are primitive data types in Java? (Choose two)
Easy204A developer declares an integer variable inside a method but does not assign a value. What is the result of attempting to print the variable?
Easy205What is the output of the code? ```java for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.print(i + " "); } ```
Medium206Which THREE statements are true about the Java logging API (java.util.logging)?
Hard207A 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?
Easy208Refer to the exhibit. What is the output?
Easy209Which THREE are benefits of Java's platform independence? (Choose three.)
Hard210Which access modifier makes a member visible only within its own class?
Medium211A developer is debugging a Java application that throws a NullPointerException. Which two actions help identify the source of the exception? (Choose two.)
Medium212Arrange the steps to handle an exception using try-catch-finally in Java in the correct order.
Medium213Which THREE statements are true about the break and continue statements in Java? (Choose three.)
Hard214Given: String s = "Java"; s.concat(" Rocks"); System.out.println(s); What prints?
Easy215A 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?
Medium216The code does not compile. What is the error?
Medium217Arrange the steps to create and use a simple Java inheritance hierarchy in the correct order.
Medium218A novice developer wrote a condition: if (x = 10) { ... } What is the result?
Medium219A class has a method that is marked as protected. Which statement is true about its accessibility?
Medium220A method is expected to receive an integer and return its square. Which method signature is correct?
Easy221Given: 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?
Medium222Which two statements about the Arrays class are true? (Choose two.)
Medium223Which three statements about the switch statement in Java are true?
Hard224You 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?
Hard225Which THREE of the following expressions compile without error? (Choose 3)
Hard226Which primitive type can store a single character?
Medium227You 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?
Medium228Refer to the exhibit. What is the output?
Easy229A 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?
Easy230A banking application stores daily transaction amounts in an array. Which declaration correctly creates an array of 31 double values?
Easy231Given: String s1 = "Java"; String s2 = new String("Java"); What does (s1 == s2) evaluate to?
Medium232A 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?
Medium233Which TWO of the following are valid loop constructs in Java? (Choose two.)
Easy234A 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?
Easy235An 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?
Hard236Which TWO are valid ways to handle a checked exception in a method?
Medium237A 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?
Medium238Refer to the exhibit. A developer runs the command java -version on a system. Which statement about this Java installation is correct?
Medium239Arrange the steps to overload a method in Java in the correct order.
Medium240A 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?
Hard241A 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?
Hard242A developer writes: Object obj = new String("Hello"); System.out.println(obj.length()); What will be the output?
Medium243A class defines two methods with the same name but different parameter lists. This is known as:
Easy244A 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?
Hard245A 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)?
Easy246A team deploys a Java application and observes frequent Full GC pauses. Which garbage collector is designed to minimize pause times?
Hard247What is the result of the following code snippet? int a = 5; int b = 2; double c = (double) (a / b); System.out.println(c);
Medium248A 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?
Hard249What is the result of the following code? int a = 8; int b = 3; System.out.println(a >> 1);
Hard250Which TWO statements are correct about array declaration and initialization in Java?
Easy251A 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?
Easy252Which TWO access modifiers allow access from a subclass in a different package?
Easy253A 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?
Hard254A 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?
Medium255In 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?
Medium256Which of the following exceptions is a checked exception?
Easy257Which THREE are checked exceptions in Java? (Choose three.)
Hard258Which TWO statements are true about the switch statement in Java? (Choose two.)
Easy259A 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?
Hard260A 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?
Hard261What is the value of z after executing: int x = 3; int y = 2; int z = x++ * --y;
Hard262A developer wants to ensure that a class cannot be subclassed. Which keyword should be used?
Easy263Given the compilation error above, which fix would resolve the error?
Hard264Given methods: void print(Integer i) { System.out.println("Integer"); } void print(int i) { System.out.println("int"); } What is output of print(10);?
Medium265Refer to the exhibit. What is the output?
Medium266Based on the command, which garbage collector is configured for this application?
Hard267A 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?
Medium268Which THREE of the following are valid loop constructs in Java?
Easy269Which TWO are characteristics of the Java Runtime Environment (JRE)?
Hard270Which two of the following operators are logical operators in Java? (Choose two.)
Easy271Which TWO statements correctly describe the Java language? (Choose two.)
Hard272A 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?
Hard273A 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?
Hard274Which TWO command-line tools are included in the Oracle JDK for monitoring and troubleshooting Java applications? (Select exactly 2)
Medium275Which THREE are valid Java identifiers?
Easy276A 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?
Medium277Which THREE statements are correct about the 'main' method signature in Java?
Hard278Refer to the exhibit. What is the result of attempting to compile and run the code?
Medium279Consider: for(int i=0;i<10;i++) { int x = i; } System.out.println(x); What is the result?
Hard280A 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?
Easy281A custom exception class must extend which class to be a checked exception?
Hard282Given: String str = "Java"; str = str.concat(" SE"); str.replace('a', 'A'); System.out.println(str); What is the output?
Hard283Which statement about abstract classes and interfaces is true in Java?
Hard284Given boolean a = true, b = false, c = true; What is the result of (a || b) && (b || c)?
Hard285A method is declared as: public static int[] generateSequence(int n) { ... }. Which return statement is valid inside this method?
Hard286A package named com.example.util is declared in a file. Where should the file be placed in the directory structure?
Easy287A junior developer wrote a while loop that never terminates. What is the most likely cause?
Medium288Which THREE are valid components of the Java Virtual Machine (JVM)?
Medium289Which three of the following code snippets produce the output '5'?
Medium290A company is developing a security-sensitive banking application. Which Java feature most directly enhances security?
Medium291A 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?
Hard292Which primitive type can store a single character?
Easy293A parent class has a static method display() and an instance method show(). A child class attempts to override both. What is the outcome?
Hard294Which THREE are true about Java constructors?
Medium295Given 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?
Hard296Which loop construct guarantees that the loop body executes at least once?
Easy297A 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?
Medium298Match each Java operator to its description.
Medium299Given: int[] arr = {10,20,30}; System.out.println(arr[3]); What is the result?
Hard300Which TWO of the following are best practices for exception handling in Java?
Medium301When using try-with-resources, which interface must the resource implement?
Medium302A developer wants to iterate over an array of integers named 'numbers'. Which loop declaration will correctly access each element?
Easy303A 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?
Easy304A 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?
Medium305A 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?
Easy306A 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?
Easy307Which TWO of the following are valid Java identifiers? (Choose 2)
Easy308Which THREE statements about the final keyword in Java are true?
Hard309A developer writes the following code: int x = 5; int y = x++; What are the values of x and y after execution?
Easy310Refer to the exhibit. Why does the code fail to compile?
Easy311A company is upgrading from Java 8 to Java 11. Which advantage does the module system introduced in Java 9 provide?
Medium312What is the output?
Medium313A developer needs to build a SQL query string by concatenating many parts. Which approach is most efficient for repeated concatenation?
Medium314A developer writes: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); }. What is the output?
Hard315Refer to the exhibit. What is the output?
Easy316Given: int a = 10; int b = 20; boolean flag = a++ > 10 && ++b > 20; What are the values of a and b after execution?
Hard317Which THREE of the following are valid Java operators?
Hard318Given: int i = 1; int j = i++ + ++i; What is the value of j?
Medium319Refer to the exhibit. Which action would best resolve this error without changing the code?
Medium320A method is declared as 'public void printElements(int... numbers)'. Which invocation will cause a compilation error?
Easy321A developer writes: int a = 9; int b = 2; double result = a / b; System.out.println(result); What is the output?
Easy322Arrange the steps to use a for loop to iterate over an array in Java in the correct order.
Medium323Given: int x = 10; int y = 20; What is the output of System.out.println(x + y * 2);?
Easy324Which THREE are valid ways to declare and initialize a two-dimensional int array in Java?
Medium325A developer compiles a Java program successfully but gets 'ClassNotFoundException' when running it. What is the most likely cause?
Medium326Given the output, which statement is true about this Java installation?
Easy327Consider 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?
Hard328Which of the following statements about the String class is true?
Hard329Which two statements are true about primitive data types in Java?
Medium330What is the output?
Easy331Which three of the following are valid Java operators that can be used with primitive numeric types?
Medium332A 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?
Easy333Arrange the steps to compile and run a Java program from the command line in the correct order.
Medium334Refer to the exhibit. Which overloaded methods cause this compilation error?
Medium335A 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?
Medium336A 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?
Medium337Which TWO of the following are valid declarations and initializations of primitive variables?
Medium338Which primitive type has a default value of 0.0f?
Easy339Which of the following is a valid Java primitive type?
Easy340A 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?
Medium341Refer to the exhibit. What is the output?
Hard342Which loop best suits a scenario where the number of iterations is unknown and depends on user input?
Medium343Refer to the exhibit. What is the output?
Medium344What likely caused this compilation error?
Hard345A team is designing a Java application that needs to run on different operating systems without modification. Which Java feature makes this possible?
Easy346Match each Java collection interface to its characteristics.
Medium347What is the primary purpose of Java bytecode?
Easy348A 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?
Easy349A 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?
Hard350A 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?
Medium351What is the value of sum printed? int sum = 0; for (int i = 0; i < 3; i++) { sum = sum + i; } System.out.println(sum);
Hard352Which TWO statements are true about passing arrays to methods in Java?
Medium353Which two statements about method parameter passing in Java are true? (Choose two.)
Hard354Which TWO statements are true about the finally block in exception handling? (Select exactly 2)
Medium355A 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?
Medium356Refer to the exhibit. What is the output?
Medium357A company requires a method that accepts an integer and returns true if the integer is even, otherwise false. Which implementation best follows Java conventions?
Medium358Refer to the exhibit. What is the potential issue with this singleton implementation in a multithreaded environment?
Hard359What is the output of the following code? int i = 0; i = i++ + ++i; System.out.println(i);
Medium360Refer 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?
Hard361A 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?
Medium362Which THREE of the following are primitive data types in Java?
Hard363A 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?
Hard364Which method invocation is ambiguous given these overloaded methods? public void process(int[] a) and public void process(int... a)
Medium365Refer to the exhibit. What happens when you compile this code?
Medium366What is the output?
Easy367Which THREE of the following are valid types that can be used as a switch expression in Java (as of Java 8)?
Medium368What is the value printed?
Hard369A method 'public static int findMax(int[] numbers)' returns the maximum value in the array. Which implementation correctly handles an empty array by returning 0?
Medium370Refer to the exhibit. What is the most likely cause?
Medium371A 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?
Medium372An application throws 'java.lang.OutOfMemoryError: Java heap space'. Which JVM option can help generate diagnostic information to identify the cause?
Easy373Given a method that catches Exception and then throws a RuntimeException, what is the effect?
Hard374Match each Java keyword to its use.
Medium375A method returns a String. The team debates using == vs equals(). Which correctly describes String comparison in Java?
Hard376What is the value of y after executing the following code? ```java int y = 10 + 12; ```
Hard377Which TWO statements about interfaces in Java are true?
Hard378What is the primary role of the Java Development Kit (JDK) compared to the JRE?
Easy379A class 'Base' has a method 'public void display() throws IOException'. Subclass 'Derived' overrides display(). Which exception specifications are allowed in the overriding method?
Hard380Which TWO statements are true about interfaces in Java?
Hard381Given: int x = 3 + 4 * 2; What is x?
Easy382Given the following code, String s1 = new String("example"); String s2 = "example"; System.out.println(s1 == s2); Why does the code output false?
Hard383What is the value of 10 % 3?
Easy384A 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?
Hard385A 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?
Hard386Which THREE of the following statements about operators in Java are true?
Easy387A developer needs to concatenate several string values in a loop. Which approach is most efficient for performance?
Medium388A 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?
Hard389Which TWO are valid identifiers in Java? (Choose two.)
Medium390Match each access modifier to its visibility level.
Medium391Which THREE of the following expressions evaluate to true? (Assume int a=5, b=10)
Medium392Given the following try-catch block: try { // some code } catch (IOException | NumberFormatException e) { e = new IOException("wrapper"); // throw e; } Which line causes a compilation error?
Hard393Consider 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?
Medium394What is the result of the following code snippet? int x = 5; int y = 2; double z = x / y; System.out.println(z);
Easy395A developer writes: String s = "Hello"; s.concat(" World"); System.out.println(s); What is the output?
Medium396Which of the following is the best practice for resource management in Java?
Easy397A developer wants to assign the largest possible long value to a variable. Which is correct?
Medium398You 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?
Easy399Given 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]);
Medium400What is printed when the main method runs?
Medium401class 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?
Medium402Which command is used to run a Java application from the command line?
Easy403A 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?
Hard404Refer to the exhibit. What is the output?
Hard405A developer wants to prevent a method from being overridden. Which modifier should be used?
Medium406Which primitive data type should be used to store a single character?
Easy407Consider 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?
Hard408A 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?
Easy409A 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?
Hard410A developer wants to sort an array of primitive ints in descending order. Which approach will work without using third-party libraries?
Hard411Which access modifier allows a member to be accessed only within the same class?
Easy412A 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?
Easy413A 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?
Easy414Evaluate the following expression: int x = 5; int y = (x > 5) ? 10 : 20; What is y?
Medium415A 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?
Easy416What is the result of the following code? int[] arr = new int[3]; arr[3] = 5; System.out.println(arr[3]);
Easy417A developer writes a method that takes a variable number of integer arguments and returns the maximum. Which method signature is correct?
Medium418Which of the following is a valid Java identifier?
Medium419Which of the following correctly describes the effect of the method call 'Arrays.sort(myArray)' on an array of objects that do not implement Comparable?
Hard420In 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?
Hard421Refer to the exhibit. What is the output?
Hard422You 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?
Medium423Which two statements about passing arrays to methods are correct? (Select two.)
Hard424Given 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?
Hard425Refer to the exhibit. A Java program throws a NullPointerException. Which is the most likely cause?
Medium426Given: short s = 10; s = s + 5; What is the result?
Hard427Given '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?
Hard428What is the result of: Integer a = null; int b = (a != null) ? a : 0; System.out.println(b);
Hard429A developer writes: int x = 5; int y = x++ + ++x; What is the value of y after execution?
Hard430What is the output of System.out.println(1 + 2 + "3" + 4 + 5);?
Easy431A developer compiles a Java application using the command `javac -d bin src/com/example/App.java`. Which of the following is true?
Easy432Refer to the exhibit. What is the problem with this class?
Medium433What is the output of the program?
Medium434Which is the correct way to call a superclass constructor from a subclass constructor?
Easy435A developer writes: if (x = 5) { System.out.println("x is 5"); } What is the result?
Medium436A 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?
Easy437Which TWO keywords are used to control access to class members? (Choose two.)
Medium438Which TWO of the following operations on String objects result in a new String object?
Hard439A 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?
Easy440Which two of the following are valid ways to create a String object?
Medium441Which of the following correctly uses the shorthand array initializer to declare and initialize an array of strings with the elements "A", "B", and "C"?
Easy442What is the result of: int[] arr = new int[5]; System.out.println(arr[5]);
Easy443Arrange the steps to create an object from a class in Java in the correct order.
Medium444What is the default value of a boolean variable in Java?
Easy445A 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?
Hard446A 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?
Hard447Which data type should be used to store a single character like 'A'?
Easy448A 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.
Hard449Given the code: int[] arr = {1,2,3}; for(int x : arr) { if(x==2) continue; System.out.print(x); } What is the output?
Hard450A 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?
Easy451A 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?
Hard452Which TWO are benefits of using try-with-resources?
Medium453Which THREE are primitive data types in Java? (Choose three.)
Hard454A company wants to run existing Java SE application code on an embedded device with limited resources. Which Java edition is designed for such environments?
Hard455A developer writes the following code: int x = 5; System.out.println(x++); What is the output?
Easy456A 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?
Medium457What is the result of the following code? String s1 = "Hello"; String s2 = " World"; String s3 = s1 + s2; System.out.println(s3);
Medium458During execution, the JVM uses Just-In-Time (JIT) compilation. What is its primary benefit?
Medium459Which THREE statements are true about method overloading in Java?
Hard460A 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?
Medium461A 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?
Medium462An application requires storing a fixed set of 12 monthly temperatures. Which initialization is most appropriate?
Medium463A 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?
Hard464Given int[] arr = {1,2,3}; which correctly creates a new array with length 5 and copies the contents of arr?
Hard465Which TWO of the following are valid ways to create a String?
Medium466A 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?
Hard467Which three statements about constructors in Java are true? (Choose three.)
Medium468What is the output of the following code? int[] a = {1,2,3}; int[] b = a; b[0] = 99; System.out.println(a[0]);
Easy469What is the scope of a variable declared inside a for loop?
Medium470A 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?
Hard471Which three statements about arrays are correct? (Choose three.)
Easy472What 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)); } } ```
Easy473A security-sensitive class should not be extended by any other class. Which modifier should be applied to the class declaration?
Easy474Which three of the following are valid ways to declare and initialize a variable of type int? (Choose three.)
Hard475What is the value of the expression (10 > 5) && (3 < 2)?
Easy476Refer 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?
Hard477A developer writes: int x; System.out.println(x); What is the result?
Easy478Refer to the exhibit. Which statement is true about the InvalidInputException class?
Easy479Which design principle is violated by making all fields public in a class?
Medium480A developer uses a switch statement with a String variable. Which is true about this usage?
Hard481A 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?
MediumOther domains
All 1Z0-811 exam domains
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.