Free Java 17 1Z0-829 Practice Questions: Core Value Types
Practice 10 free Oracle Java SE 17 Developer (Java 17 1Z0-829) questions on Core Value Types, 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 17 1Z0-829 |
| Topic area | Handling Date, Time, Text, Numeric, and Boolean Values |
| Blueprint weight | 11% |
| Page purpose | Focused sample questions before returning to mixed practice |
How to use this topic drill
Use this page to isolate Handling Date, Time, Text, Numeric, and Boolean Values for Java 17 1Z0-829. 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: 11% 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: Handling Date, Time, Text, Numeric, and Boolean Values
A developer is checking how a small mixed numeric expression behaves. What is printed by this Java 17 program?
class Demo {
public static void main(String[] args) {
byte b = 4;
short s = 3;
char c = 2;
long l = 4L;
float f = 1.0f;
boolean result = (b += s) > c + l && f + l == 5.0f;
System.out.println(result + ":" + b);
}
}
Options:
A.
true:7B.
false:7C.
true:4D. The program does not compile.
Best answer: A
Explanation: Compound assignment performs the arithmetic using numeric promotion and then casts the result back to the left-hand type. Here, b += s stores 7 in b. The later mixed numeric comparisons are both true, so the program prints true:7.
The core rule is binary numeric promotion plus compound assignment conversion. A compound assignment such as b += s is roughly equivalent to b = (byte)(b + s), so it compiles even though b + s alone would have type int. After this assignment, b is 7. Then c + l is promoted to long, giving 6L, so 7 > 6L is true. Also, f + l is promoted to float, giving 5.0f, which equals 5.0f. Since both sides of && are true, result is true and the updated b value is printed.
- Compilation error trap fails because compound assignment can implicitly cast the arithmetic result back to the left-hand type.
- False comparison trap fails because
7 > 6Land5.0f == 5.0fboth evaluate to true. - Original value trap fails because
b += smutatesbbeforeSystem.out.println()runs.
Question 2
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
A team is refactoring this Java 17 method. It should reverse a non-empty code, add a leading #, remove the last character after the reversal, and append !. For input ABCD, the expected result is #DCB!, but the current method fails at runtime. Which change is the best fix?
static String tag(String code) {
var sb = new StringBuilder(32);
sb.append(code)
.reverse()
.insert(0, '#')
.delete(sb.capacity() - 1, sb.capacity())
.append('!');
return sb.toString();
}
Options:
A. Replace
StringBuilderwithStringBufferand keep the chain unchanged.B. Replace the
deletecall with.deleteCharAt(sb.capacity() - 1).C. Replace the
deletecall with.delete(sb.length() - 1, sb.length()).D. Initialize
sbwithnew StringBuilder(code)and remove.append(code).
Best answer: C
Explanation: StringBuilder operations such as append, reverse, insert, delete, and deleteCharAt mutate the same builder and return it for chaining. Character operations use valid indexes based on length(), not capacity(). The capacity is only storage space and can be larger than the number of characters.
The defect is using capacity() as if it were the last valid character index. After appending ABCD, reversing, and inserting #, the builder content is #DCBA and its length() is 5. Its capacity is still much larger, so attempting to delete near capacity() - 1 uses an invalid character index and fails. delete(start, end) removes characters from start up to but not including end, so delete(sb.length() - 1, sb.length()) removes only the current last character. The chained calls are fine because these methods mutate and return the same StringBuilder.
- Constructor capacity fails because
new StringBuilder(code)still gives extra capacity and does not make capacity equal to the current content length. - StringBuffer swap solves synchronization, not the invalid index caused by using capacity.
- deleteCharAt with capacity still uses an invalid character index because capacity is not the number of stored characters.
Question 3
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
A service compares a cached status code with a value read from a request. Status text should match when the characters are the same, regardless of whether a String came from a literal or was constructed at runtime. Two null status values should be treated as matching, and numeric retry counts should be compared by value.
import java.util.Objects;
class StatusCheck {
static boolean matches(String cached, String received,
int attempts, int limit) {
return cached == received && attempts == limit;
}
}
Which refactor is the best correction?
Options:
A. Use
return cached == received && Integer.valueOf(attempts) == Integer.valueOf(limit);B. Use
return Objects.equals(cached, received) && attempts == limit;C. Use
return cached.intern() == received.intern() && attempts == limit;D. Use
return cached.equals(received) && Objects.equals(attempts, limit);
Best answer: B
Explanation: The defect is using == for String values, which checks reference identity rather than character equality. Objects.equals(cached, received) gives null-safe String equality, and primitive int values should continue using == for numeric comparison.
For objects, == compares references; for primitives, == compares values. String literals are interned, so two identical literals may share one reference and make == seem to work, but a String built at runtime can have the same characters and a different reference. Objects.equals(cached, received) safely handles both normal String.equals() comparison and nulls. The retry counts are primitive int values, so attempts == limit already compares their numeric values directly. The key refactor changes only the object equality check and leaves the primitive equality check alone.
- Interning workaround fails because calling
intern()on null throws and interning is not the right general-purpose equality test. - Direct equals call compares characters but can throw when
cachedis null, and boxing theintvalues is unnecessary. - Wrapper references leave the
Stringreference comparison defect and add another reference-equality comparison for boxed integers.
Question 4
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
During troubleshooting, a developer runs this Java 17 diagnostic and gets true false true:
public class Probe {
public static void main(String[] args) {
int p = 7, q = 7;
String a = "OK";
String b = new String("OK");
String c = b.intern();
System.out.println((p == q) + " " + (a == b) + " " + (a == c));
}
}
What is the best explanation for the unexpected middle value?
Options:
A.
a == bcompares two different object references.B.
intern()creates a new nonliteralStringobject.C. Primitive
intvalues are compared by reference.D.
Stringvalues useequals()automatically with==.
Best answer: A
Explanation: The middle comparison is false because == on String compares references, not character content. The literal "OK" is interned, while new String("OK") creates a separate object. Use equals() when the goal is string content comparison.
Java uses == differently for primitives and references. For primitives such as int, == compares numeric values, so p == q is true. For object references such as String, == compares whether both variables refer to the same object. The literal "OK" refers to the interned string, but new String("OK") creates a separate String object with the same contents, so a == b is false. Calling b.intern() returns the canonical interned instance, so a == c is true. The key takeaway is to use a.equals(b) for string content comparison.
- Primitive confusion fails because primitive
intequality compares values, not references. - Interning reversal fails because
intern()returns the canonical pooled string rather than a fresh nonliteral object. - Automatic equals fails because
==does not callString.equals()implicitly.
Question 5
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
No imports are needed. Given this Java 17 code, what is the result?
public class Limits {
public static void main(String[] args) {
int min = -2_147_483_648;
long next = 2_147_483_648;
long fixed = 2_147_483_648L;
System.out.println(min + "," + next + "," + fixed);
}
}
Options:
A. It prints
-2147483648,2147483648,2147483648.B. Compilation fails;
2_147_483_648needs anLsuffix.C. It throws
ArithmeticExceptionbefore printing.D. Compilation fails at
int min; the value is belowintrange.
Best answer: B
Explanation: Integer literals without a suffix are treated as int literals first. The positive literal 2_147_483_648 is not valid in that long assignment unless it has an L suffix, even though the variable type is long.
Java determines a numeric literal’s type before considering the assignment target. An unsuffixed decimal integer literal is an int literal, with a special allowance for -2_147_483_648 so Integer.MIN_VALUE can be written directly. However, the positive literal 2_147_483_648 cannot be assigned to long unless it is written as a long literal, such as 2_147_483_648L.
The fixed declaration is valid, but compilation stops because the earlier next declaration is invalid.
- Printed values assumes the
longtarget type changes the literal type, but literal validity is checked first. - Minimum int is valid here because Java permits
-2_147_483_648as theintminimum value. - Runtime exception confuses compile-time literal checking with runtime arithmetic behavior.
Question 6
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
A scheduling test fails on the U.S. DST fallback. The next run must be the same New York wall-clock time on the next calendar day. This code prints 2024-11-04T00:30-05:00[America/New_York], but the expected value is 2024-11-04T01:30-05:00[America/New_York].
var zone = ZoneId.of("America/New_York");
var start = ZonedDateTime.ofLocal(
LocalDateTime.of(2024, 11, 3, 1, 30),
zone,
ZoneOffset.of("-04:00"));
var next = start.toInstant()
.plus(Duration.ofDays(1))
.atZone(zone);
System.out.println(next);
What is the best fix?
Options:
A. Store the time with fixed offset
-04:00.B. Use
start.plusDays(1)and convert afterward.C. Use
start.toInstant().plus(Period.ofDays(1)).D. Call
withZoneSameInstant(zone)before adding.
Best answer: B
Explanation: The bug comes from adding a 24-hour duration to an Instant, which is a timeline calculation. The requirement is a local calendar-day adjustment in America/New_York, so the addition should be done on the ZonedDateTime before converting to an Instant.
Instant represents a point on the UTC timeline, so Duration.ofDays(1) means exactly 24 hours later. Starting at 2024-11-03T01:30-04:00, adding 24 hours lands at 2024-11-04T05:30Z, which is 00:30 in New York after the offset changes to -05:00. For “same local time tomorrow,” add the calendar day in the zone: start.plusDays(1). That adjusts the local date-time to November 4 at 01:30, then resolves the correct zone offset. The key distinction is timeline duration versus zone-aware calendar adjustment.
- Period on Instant still adjusts an instant, not a New York wall-clock calendar date.
- Fixed offset ignores the zone rule change to
-05:00after the fallback. - Same instant zone call does not change the value because the
ZonedDateTimealready uses that zone.
Question 7
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
No imports are needed. What is the result of compiling and running the following Java 17 code?
public class TextTest {
static void normalize(String s) {
s.trim();
s.replace("java", "Java");
s += "!";
}
public static void main(String[] args) {
String msg = " java ";
normalize(msg);
System.out.print("[" + msg + "]");
}
}
Options:
A. It does not compile.
B. It prints
[Java!].C. It prints
[ java ].D. It prints
[ java !].
Best answer: C
Explanation: String objects are immutable in Java. Methods such as trim() and replace() return new String values rather than modifying the existing object, and this code ignores those return values.
The core rule is String immutability. The parameter s initially refers to the same String object as msg, but calling s.trim() and s.replace(...) does not change that object. Each method returns a new String when a change is needed, and the returned values are discarded here. The statement s += "!" is also a reassignment of the local parameter s to a new String; it does not reassign the caller’s variable msg. After normalize(msg) finishes, msg still refers to the original string containing one leading and one trailing space.
- Mutable String assumption fails because
trim()andreplace()do not alter the originalStringobject. - Caller reassignment assumption fails because
s += "!"updates only the local parameter variable. - Compilation failure is not supported because the snippet uses valid Java 17 syntax and no imports are required.
Question 8
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
What is the output of this Java 17 code? Each option lists the printed lines in order.
import java.time.*;
import java.time.temporal.ChronoUnit;
public class Dates {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024, 3, 10);
start.plusDays(2);
LocalDate end = start.withMonth(4).plusDays(5);
System.out.println(start);
System.out.println(end);
System.out.println(ChronoUnit.DAYS.between(start, end));
System.out.println(start.until(end).getDays());
}
}
Options:
A. 2024-03-10; 2024-04-15; 5; 5
B. 2024-03-12; 2024-04-17; 36; 5
C. 2024-03-10; 2024-04-15; 36; 36
D. 2024-03-10; 2024-04-15; 36; 5
Best answer: D
Explanation: Java date-time classes such as LocalDate are immutable, so start.plusDays(2) has no effect unless its result is assigned. ChronoUnit.DAYS.between(start, end) returns the total number of days, while start.until(end).getDays() returns only the day component of the resulting Period.
The core rule is immutability plus the difference between a unit-based count and a Period. The ignored plusDays(2) call does not change start, so it remains 2024-03-10. The expression start.withMonth(4).plusDays(5) creates 2024-04-15. From March 10 to April 15, ChronoUnit.DAYS.between counts 36 total days. However, start.until(end) is a Period of 1 month and 5 days, so getDays() returns 5, not 36. The key takeaway is that Period.getDays() is a component value, not a total duration in days.
- Mutation assumption fails because
plusDays(2)returns a newLocalDateand does not modifystart. - Total Period days fails because
Period.getDays()returns only the day component after months are accounted for. - Unit-count confusion fails because
ChronoUnit.DAYS.betweencounts total days, not thePeriodday component.
Question 9
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
Which statement is correct for Java 17 primitive numeric expressions?
Options:
A. Casting a
doubleto anintrounds to nearest.B. Integer division by zero evaluates to
Infinity.C. Combining
intandfloatpromotes the result todouble.D. Overflow in
intaddition wraps around silently.
Best answer: D
Explanation: Java integer arithmetic has defined overflow behavior: it silently wraps around for operations such as int addition. This is different from integer division by zero, which throws ArithmeticException, and from floating-point promotion rules.
For primitive integer arithmetic, Java does not signal overflow for operations such as addition, subtraction, or multiplication. If an int addition exceeds the range of int, the result is the low-order 32 bits of the mathematical result, commonly described as wraparound. Separate rules handle other numeric cases: integer division truncates toward zero, integer division by zero throws ArithmeticException, and binary numeric promotion with int and float produces a float result.
The key distinction is that overflow is silent, while integer division by zero is not.
- Division by zero fails because
intdivision by zero throwsArithmeticException, notInfinity. - Narrowing conversion fails because a
doublecast tointtruncates toward zero, not nearest. - Promotion rule fails because
intcombined withfloatpromotes tofloat, notdouble.
Question 10
Topic: Handling Date, Time, Text, Numeric, and Boolean Values
A developer compares a Java 17 text block with a regular string literal. What is printed?
public class TextCheck {
public static void main(String[] args) {
String a = """
red
blue\s
green\
""";
String b = "red\n blue \ngreen";
System.out.print(a.equals(b) + ":" + a.length());
}
}
Options:
A. It prints
false:17.B. It prints
true:18.C. It prints
false:18.D. It prints
true:17.
Best answer: D
Explanation: The text block content matches the regular string literal exactly. Java removes the common incidental indentation, translates \s to one space, and uses the trailing \ to omit the line terminator after green.
Text blocks are processed by normalizing line terminators, removing incidental indentation, and then translating escape sequences. Here, the common leading indentation is removed from each content line, leaving red, two spaces before blue, and green. The \s escape contributes a real space after blue; using an actual trailing space in source would be unreliable because trailing whitespace is stripped. The backslash at the end of the green line suppresses that line terminator, so there is no final newline.
The resulting value is red\n blue \ngreen, whose length is 17 characters.
- Extra newline fails because the trailing
\removes the line terminator before the closing delimiter. - Missing preserved space fails because
\sbecomes one actual space afterblue. - Indentation mismatch fails because common incidental indentation is stripped from the text block.
Continue in the web app
Use IT Mastery for interactive Java 17 1Z0-829 practice with mixed sets, timed mocks, topic drills, explanations, and progress tracking.
Related focused pages
- Free Java 17 1Z0-829 Full-Length Practice Exam
- Controlling Program Flow
- Object-Oriented Java
- Handling Exceptions
- Working with Arrays and Collections
- Streams and Lambdas
- Packaging and Modules
- Managing Concurrent Code Execution
- Using Java I/O API
- Accessing Databases Using JDBC
- Implementing Localization
- Logging and Annotations