Free Java 21 1Z0-830 Practice Questions: Object-Oriented Java
Practice 10 free Oracle Java SE 21 Developer Professional (Java 21 1Z0-830) questions on Object-Oriented Java, with answers, explanations, and the IT Mastery next step.
Try the IT Mastery web app for a richer interactive practice experience with mixed sets, timed mocks, topic drills, explanations, and progress tracking.
Topic snapshot
| Field | Detail |
|---|---|
| Practice target | Java 21 1Z0-830 |
| Topic area | Using Object-Oriented Concepts in Java |
| Blueprint weight | 20% |
| Page purpose | Focused sample questions before returning to mixed practice |
How to use this topic drill
Use this page to isolate Using Object-Oriented Concepts in Java for Java 21 1Z0-830. Work through the 10 questions first, then review the explanations and return to mixed practice in IT Mastery.
| Pass | What to do | What to record |
|---|---|---|
| First attempt | Answer without checking the explanation first. | The fact, rule, calculation, or judgment point that controlled your answer. |
| Review | Read the explanation even when you were correct. | Why the best answer is stronger than the closest distractor. |
| Repair | Repeat only missed or uncertain items after a short break. | The pattern behind misses, not the answer letter. |
| Transfer | Return to mixed practice once the topic feels stable. | Whether the same skill holds up when the topic is no longer obvious. |
Blueprint context: 20% of the practice outline. A focused topic score can overstate readiness if you recognize the pattern too quickly, so use it as repair work before timed mixed sets.
Sample questions
These are original IT Mastery practice questions aligned to this topic area. They are not official Oracle questions, copied live-exam content, or exam dumps. Use them to preview question style and explanation depth before continuing with topic drills, mixed sets, and timed mocks in IT Mastery.
Question 1
Topic: Using Object-Oriented Concepts in Java
An application test drops the last strong reference to a large temporary array and wants to continue only after the memory is reclaimed.
class Check {
static byte[] data = new byte[10_000_000];
public static void main(String[] args) {
data = null;
System.gc();
System.out.println("continuing");
}
}
Which statement correctly applies Java SE 21 object-lifecycle rules?
Options:
A.
System.gc()is only a request; timing is not guaranteed.B.
Runtime.getRuntime().gc()would guarantee reclamation.C. Assigning
nullimmediately destroys the array object.D. The array is reclaimed before
println()executes.
Best answer: A
Explanation: The array becomes eligible for garbage collection after its last strong reference is removed. However, System.gc() is only a request to the JVM and does not guarantee collection before the next statement or before program termination.
Garbage collection in Java is managed by the JVM. Setting data to null removes the static reference, so the array may become eligible for collection if no other strong references exist. Calling System.gc() is a hint that the JVM may choose to act on, but Java SE does not require collection to occur at any particular time.
The key takeaway is that program correctness must not depend on garbage collection happening immediately after a request.
- Forced collection fails because
System.gc()does not require the JVM to collect beforeprintln(). - Immediate destruction fails because removing a reference only makes an object eligible for collection.
- Runtime call guarantee fails because
Runtime.getRuntime().gc()has the same request-style behavior.
Question 2
Topic: Using Object-Oriented Concepts in Java
A catalog service needs a Sku record to normalize non-null input by stripping leading and trailing whitespace, then reject an empty result. Which constructor replacement compiles and makes new Sku(" x9 ").code() return "x9"?
public record Sku(String code) {
// constructor goes here
}
Options:
A.
public Sku(String code) { this.code = code; code = code.strip(); if (code.isEmpty()) throw new IllegalArgumentException(); }B.
public Sku { code = code.strip(); if (code.isEmpty()) throw new IllegalArgumentException(); }C.
public Sku { this.code = code.strip(); if (this.code.isEmpty()) throw new IllegalArgumentException(); }D.
public Sku(String code) { code = code.strip(); if (code.isEmpty()) throw new IllegalArgumentException(); }
Best answer: B
Explanation: In a compact canonical constructor, the component name code is a constructor parameter inside the body. Assigning code = code.strip() changes the value that will later be implicitly assigned to the final record component field. Direct assignment to this.code is not allowed in a compact constructor.
Records have final component fields, but compact constructors are designed for validation and normalization. During the compact constructor body, code refers to the canonical constructor parameter, not a mutable component field. The compiler inserts the field assignment after the compact constructor body completes normally, using the current parameter value. Therefore normalizing the parameter before validation is valid and the stripped value is stored. An explicit canonical constructor does not get this implicit assignment, so it must assign the field itself; assigning the field before changing the parameter stores the unnormalized value.
- Field assignment fails because compact constructors may not assign component fields such as
this.code. - Early explicit assignment compiles but stores the original value before
code.strip()changes only the parameter. - Missing explicit assignment fails because a non-compact canonical constructor must definitely assign the final component field.
Question 3
Topic: Using Object-Oriented Concepts in Java
No imports are required. What is the result of compiling and running this Java 21 code?
public class Project {
private final String name;
Project(String name) { this.name = name; }
class Task {
String label() { return name + "-task"; }
}
static class TaskFactory {
Task create(Project p) {
return new Task();
}
}
public static void main(String[] args) {
var factory = new TaskFactory();
System.out.print(factory.create(new Project("alpha")).label());
}
}
Options:
A. It prints
alpha-task.B. It throws
NullPointerExceptionwhenlabel()is called.C. It does not compile;
TaskFactorymust be instantiated through aProjectobject.D. It does not compile;
new Task()must be qualified asp.new Task().
Best answer: D
Explanation: Task is a non-static inner class, so each Task object is tied to a Project instance. The static nested TaskFactory has no implicit Project.this, even though create() receives a Project parameter. The allocation must use that parameter explicitly, as in p.new Task().
Member nested classes split into static nested classes and non-static inner classes. A static nested class is not associated with an instance of the enclosing class. A non-static inner class is associated with an enclosing instance, so creating it from a context without an implicit Project instance requires a qualified allocation, such as p.new Task(). In the snippet, TaskFactory is static; its create() method has a Project parameter, but the compiler will not infer that new Task() should use p. The Task object’s access to name would be valid after a correctly qualified creation.
- Automatic enclosing instance fails because a parameter named
pis not automatically used fornew Task(). - Runtime exception fails because compile-time legality is checked before any call to
label(). - Factory lifecycle fails because
TaskFactoryis static and does not require aProjectobject.
Question 4
Topic: Using Object-Oriented Concepts in Java
Assume the file name supports the public class; no imports are required. Which statement describes the compile-time result and, if the invalid inheritance declaration were removed, the output?
record Receipt(String id) { }
class GiftReceipt extends Receipt { GiftReceipt(String id) { super(id); } }
final class Badge {
private final int id, shard;
Badge(int id, int shard) { this.id = id; this.shard = shard; }
@Override public boolean equals(Object o) {
return o instanceof Badge b && id == b.id;
}
@Override public int hashCode() { return shard; }
}
public class Demo {
public static void main(String[] args) {
var a = new Badge(10, 1);
var b = new Badge(10, 2);
System.out.print(a.equals(b) + ":" + (a.hashCode() == b.hashCode()));
}
}
Options:
A. Compilation succeeds and prints
true:true.B. Compilation fails at
GiftReceipt; removing it would printtrue:false.C. Compilation fails at
Badge.hashCode().D. Compilation succeeds and prints
true:false.
Best answer: B
Explanation: The code fails at compilation because a record class is implicitly final. GiftReceipt cannot extend Receipt, so no runtime output is produced. Removing that invalid type would expose the Badge contract problem: equals() can be true while hashCode() differs.
Records are implicitly final, so no class can extend Receipt. That makes GiftReceipt an invalid inheritance declaration and the source fails to compile before main() can run. If that class declaration were removed, the two Badge objects would compare equal because equals() tests only id; their hash codes would differ because hashCode() returns shard. This breaks the Object method contract: whenever equals() is true for two objects, their hash codes must be equal. The compiler checks method signatures and inheritance legality, not semantic consistency between equals() and hashCode().
- Runtime-first reasoning is wrong because compile-time errors are resolved before considering what
main()would print. - Contract violation as syntax is wrong because Java does not reject a
hashCode()body merely for being inconsistent withequals(). - Automatic hash alignment is wrong because
equals()returningtruedoes not make the JVM coordinate hash-code values.
Question 5
Topic: Using Object-Oriented Concepts in Java
No imports are needed. What is the result of compiling and running this code?
class ScopeCheck {
private String code = "field";
void run(Object code) {
String result = "start";
if (code instanceof String s && s.length() > 3) {
result = s.substring(0, 2);
}
for (int i = 0; i < 1; i++) {
result += i;
}
System.out.print(result + ":" + this.code + ":" + s);
}
public static void main(String[] args) {
new ScopeCheck().run("java");
}
}
Options:
A. It prints
ja0:field:java.B. It prints
ja0:java:java.C. Compilation fails because
codecannot be both a field and a parameter.D. Compilation fails because
sis not in scope after theif.
Best answer: D
Explanation: The code does not compile because the pattern variable s is used outside its valid scope. In this if statement, s is available in the right side of && and inside the if block, but not after the if completes.
Pattern variables have flow-dependent scope. For code instanceof String s && s.length() > 3, s is in scope on the right side of && because that side runs only if the pattern matched. It is also in scope inside the if block. After the if, however, execution could continue when code was not a String or when the length test failed, so s is not in scope at the final System.out.print statement. The field and parameter named code are legal; the parameter shadows the field, and this.code explicitly refers to the field.
- Field shadowing is legal here; a parameter may have the same name as a field.
- Assuming
ssurvives fails because pattern variable scope does not extend past thisifstatement. - Field versus parameter output is irrelevant because compilation stops before any printing occurs.
Question 6
Topic: Using Object-Oriented Concepts in Java
In Java 21, a developer inserts one member into this record body. Which member would make the record declaration invalid?
public record Order(int id, String name) {
// inserted member
}
Options:
A.
public int nameLength() { return name.length(); }B.
static final int DEFAULT_ID = 0;C.
private final int cachedHash = 0;D.
public Order { if (name == null) throw new IllegalArgumentException(); }
Best answer: C
Explanation: Records may declare methods, static members, and valid constructors, but they cannot declare extra instance fields. The component list already defines the record’s instance state, so adding cachedHash as an instance field is illegal.
A record class gets a private final field for each record component, along with accessors and other generated members. Java does not allow a record body to add more instance fields, because the component list is the complete state description for the record. Static fields are allowed, ordinary instance methods are allowed, and a compact canonical constructor can validate component parameters before the compiler assigns them to the generated fields.
The key distinction is instance state versus behavior or class-level state.
- Extra instance state fails because
cachedHashwould be a non-static field declared in the record body. - Static field is allowed because it does not add per-instance record state.
- Instance method is allowed because records can declare behavior that uses component fields.
- Compact constructor is allowed because it validates constructor parameters without manually assigning component fields.
Question 7
Topic: Using Object-Oriented Concepts in Java
Assume this code is in one source file and no imports are required. What is the result of compiling and running this Java 21 program?
public class InitOrder {
static String log = "";
static int a = mark("A");
static { mark("B"); }
{ mark("C"); }
int b = mark("D");
InitOrder() { mark("E"); }
static int mark(String s) {
log += s;
return 0;
}
public static void main(String[] args) {
new InitOrder(); new InitOrder();
System.out.print(log);
}
}
Options:
A.
CDEABCDEis printed.B.
ABCDECDEis printed.C.
ABDCEDCEis printed.D.
ABCDEis printed.
Best answer: B
Explanation: The class initializes before main, so the static field initializer and static block add A and B once. Each call to new InitOrder() then runs the instance block, instance field initializer, and constructor body, adding CDE. Two objects produce ABCDECDE.
Java executes initialization in well-defined phases. When InitOrder is initialized, static fields and static initializer blocks run in textual order, so mark("A") runs before the static block that marks B. For each object creation, instance fields and instance initializer blocks also run in textual order before the constructor body. In this class, the instance block appears before the instance field, so each object adds C, then D, then constructor E. The two constructor calls therefore append CDE twice after the one-time static AB.
- Single object assumption fails because
maincreates twoInitOrderinstances, so instance initialization occurs twice. - Fields before blocks fails because instance fields and instance initializer blocks are ordered textually, not by kind.
- Instance before static fails because the class is initialized before
mainbegins executing object creation statements.
Question 8
Topic: Using Object-Oriented Concepts in Java
A developer is troubleshooting this Java 21 code. The Meter class does not compile.
import java.io.*;
class Device {
public Number read() throws IOException { return 0; }
}
class Meter extends Device {
@Override
private static Object read() throws Exception { return 1; }
}
Which replacement for private static Object read() throws Exception fixes the compilation problem, still overrides Device.read(), and prevents further overriding by subclasses of Meter?
Options:
A.
public final Object read() throws ExceptionB.
public final Integer read() throws FileNotFoundExceptionC.
public static Integer read() throws FileNotFoundExceptionD.
protected final Integer read() throws FileNotFoundException
Best answer: B
Explanation: An overriding method may not reduce visibility, may use a covariant return type, and may throw only the same checked exception type or a narrower one. Because Device.read() is a public instance method returning Number and throwing IOException, Meter.read() can be public final, return Integer, and throw FileNotFoundException.
Java decides overriding from the inherited instance method’s signature. The subclass method must be at least as accessible as the superclass method, cannot change between instance and static, and must return the same type or a subtype for reference returns. It also cannot declare broader checked exceptions than the overridden method; FileNotFoundException is a subclass of IOException. Declaring the overriding method final is legal when the superclass method is not final, and it prevents further subclasses from overriding that method. The replacement must therefore be public, non-static, covariant in return type, narrowed in checked exception, and final.
- Protected access fails because it narrows the public inherited method.
- Static replacement fails because a static method cannot override an instance method.
- Object and Exception fail because
Objectis not covariant withNumber, andExceptionis broader thanIOException.
Question 9
Topic: Using Object-Oriented Concepts in Java
Assume this Java 21 code is in one source file and any missing imports are not material. What is the result?
record Product(String code, int quantity) {
Product {
code = code.strip().toUpperCase();
if (quantity < 0) {
quantity = 0;
}
}
}
public class Test {
public static void main(String[] args) {
var p = new Product(" ab-7 ", -3);
System.out.print(p.code() + ":" + p.quantity());
}
}
Options:
A. It prints
AB-7:0.B. The code does not compile because compact constructors must assign every component explicitly.
C. The code does not compile because record components are final.
D. It prints
ab-7 :-3.
Best answer: A
Explanation: The compact constructor may reassign its implicit parameters, such as code and quantity, to normalize record state. After the compact constructor body finishes, the compiler inserts the assignments from those parameter values to the private final component fields.
A record compact constructor does not list parameters or explicitly assign component fields. The component names inside the constructor body act as constructor parameters, so they can be reassigned for validation or normalization. When the body completes normally, Java implicitly assigns the final record fields from the current parameter values. Here, code becomes AB-7, and negative quantity becomes 0, so the accessors return those normalized values.
The key distinction is that assigning code = ... is valid parameter reassignment; assigning to this.code in a compact constructor would be invalid.
- Original values is wrong because the implicit field assignments use the normalized parameter values.
- Final components is wrong because the code assigns constructor parameters, not component fields.
- Explicit assignment requirement is wrong because compact constructors perform component field assignments implicitly.
Question 10
Topic: Using Object-Oriented Concepts in Java
In Java 21, a method declares a local variable or parameter, and a local class or anonymous class declared in that method reads it from the class body. Which rule applies to that captured variable?
Options:
A. Only anonymous classes require effective finality.
B. It may be reassigned before object creation.
C. It must be final or effectively final.
D. It may be reassigned if its type is mutable.
Best answer: C
Explanation: Java permits local and anonymous class bodies to access enclosing method variables only when those variables are final or effectively final. The rule applies to both local variables and parameters, and to both local classes and anonymous classes.
The core rule is local-variable capture. A local class or anonymous class can read a local variable or parameter from the enclosing method only if that variable is final or effectively final. Effectively final means the variable is not declared final, but it is not reassigned after its initial assignment. The object referenced by such a variable may still be mutated, but the variable itself cannot be reassigned. This restriction applies equally to local classes and anonymous classes.
- Reassignment timing fails because reassignment after initialization breaks effective finality, even if it occurs before creating the nested object.
- Mutable object type fails because mutating the object may be allowed, but reassigning the captured variable is not.
- Anonymous-only rule fails because local classes have the same capture restriction for enclosing method variables.
Continue in the web app
Use IT Mastery for interactive Java 21 1Z0-830 practice with mixed sets, timed mocks, topic drills, explanations, and progress tracking.