Skip to content

Java SE 21 Numbers, Text and Date-Time

Step 1 of 20

Java SE 21 Values: Numbers, Strings and Date-Time for 1Z0-830

Introduction

Java SE 21 values underpin the code-reading skills of the Oracle 1Z0-830 exam. This lesson explains numeric promotion, boxed values, strings, text blocks and date-time arithmetic. You will trace expressions and distinguish compilation errors, runtime exceptions and valid results using the Java 21 rules.

Learning objectives

After this lesson you will be able to:

  • Choose between primitives and wrapper classes and predict boxing, unboxing, caching and NullPointerException cases.
  • Evaluate arithmetic, bitwise and boolean expressions using operator precedence, promotion, implicit and explicit casts, overflow and integer division rules.
  • Manipulate text with String, StringBuilder and text blocks, including the whitespace rules of text blocks.
  • Use the Math API and know the surprising edge cases (Math.abs(Integer.MIN_VALUE), Math.round on negative halves, exact arithmetic).
  • Use the java.time API: LocalDate, LocalDateTime, Instant, Duration, Period, ZonedDateTime, and reason about daylight saving time transitions.

1. Primitives and wrapper classes

Java has eight primitive types: byte (8 bits), short (16), char (16, unsigned), int (32), long (64), float (32), double (64) and boolean. Integer literals are int by default (10), floating-point literals are double by default (10.5). Use L to make an integer literal long, such as 3_000_000_000L, and F to make a floating literal float. A smaller int literal can also widen in an assignment such as long n = 10;. Underscores are allowed in numeric literals (1_000_000), and prefixes select the base: 0b101 (binary), 017 (octal, so 15), 0x1F (hexadecimal).

Widening, narrowing and promotion

A widening primitive conversion follows the conversions defined by the language, such as int to long, long to float and char to int. It can be implicit, but widening an integer to a floating-point type can lose precision. A narrowing conversion can lose range or precision and usually needs a cast. Assignment of a representable constant to byte, short or char is a special case.

Two rules cause most exam traps:

  1. Binary numeric promotion. In an arithmetic expression, byte, short and char operands are promoted to int first. If one operand is long, float or double, the other is promoted to that type. Therefore byte b = 10; b = b + 5; does not compile (the result is int), but b += 5; does, because compound assignment includes an implicit cast.
  2. Compile-time constants. byte b = 10; compiles because 10 is a constant that fits in a byte. byte b = 200; does not compile. final int k = 10; byte b = k; compiles because k is a constant variable; without final it does not.
Java
int a = Integer.MAX_VALUE;
System.out.println(a + 1);            // -2147483648 (silent overflow)
System.out.println((byte) 200);       // -56  (200 - 256)
System.out.println((int) 3.99);       // 3    (truncation toward zero)
System.out.println((int) -3.99);      // -3
System.out.println((int) 3_000_000_000L); // -1294967296
System.out.println('a' + 1);          // 98   (int)
System.out.println((char) ('a' + 1)); // b
char c = 'a'; c++;                    // compiles, c is 'b'

Division, remainder and floating point

Integer division truncates toward zero and the remainder has the sign of the dividend: 5 / 2 is 2, -7 / 2 is -3, -7 % 3 is -1, 7 % -3 is 1. Integer division by zero throws ArithmeticException. For floating-point division, a nonzero finite value divided by zero gives a signed infinity, while zero divided by zero gives NaN. With the primitive == operator, NaN compares unequal to every value, including itself: Double.NaN == Double.NaN is false.

Floating-point types are binary, so 0.1 + 0.2 == 0.3 is false (the sum is 0.30000000000000004). When exactness matters, as with money, use BigDecimal built from a String (new BigDecimal("0.1")), not from a double.

Wrapper classes, boxing and the cache

Each primitive has a wrapper (Integer, Long, Character, Boolean, and so on). Autoboxing converts a primitive to its wrapper and unboxing does the reverse, both automatically.

Java
Integer a = 127, b = 127;
System.out.println(a == b);       // true  (cached instances)
Integer c = 128, d = 128;
System.out.println(c == d);       // not specified by the Java language for 128
System.out.println(c.equals(d));  // true

Integer n = null;
int x = n;                        // NullPointerException (unboxing null)

Integer.valueOf always caches -128 through 127 and may cache more values. Boxing those small constant values guarantees shared identity. For value comparison use equals, or Objects.equals when either reference can be null. For the distinction between reference identity and value equality, see Java objects, references and equality. Also remember that a conditional expression like flag ? 1 : null is an Integer, and assigning it to an int when flag is false throws NullPointerException. Wrappers also provide parsing: Integer.parseInt("42") returns an int, Integer.valueOf("42") returns an Integer, and both throw NumberFormatException on bad input such as "4 2".

An overload trap: with methods m(long) and m(Integer), calling m(5) selects m(long), because overload resolution first considers applicable fixed-arity methods without boxing. Only later phases allow boxing and variable arity.

Conversion needed Example Compiles without cast?
int to long long l = 5; Yes (widening)
long to int int i = 5L; No (narrowing)
int constant to byte byte b = 5; Yes (fits)
int variable to byte byte b = i; No
int to Integer Integer w = 5; Yes (boxing)
int to Long Long w = 5; No (boxes to Integer, not Long)
int to double double d = 5; Yes

2. Operators and precedence

From highest to lowest precedence: postfix (x++), unary (++x, -x, !, ~), multiplicative (* / %), additive (+ -), shift (<< >> >>>), relational (< > <= >= instanceof), equality (== !=), bitwise &, ^, |, logical &&, ||, ternary ?:, and assignment. Evaluation of operands is always left to right, even when precedence says otherwise.

Java
int i = 1;
int r = i++ + ++i;   // 1 + 3 = 4, i becomes 3
int s = 2 + 3 * 4;   // 14
boolean t = 1 + 2 == 3 && 4 > 3; // true

Short-circuit evaluation. && and || skip the right operand when the left one decides the result. For boolean operands, & and | evaluate both sides. These expressions determine which branches run in Java 21 short-circuit conditions and control flow.

Java
int x = 0;
boolean b1 = (x != 0) && (10 / x > 1);  // false, no exception
boolean b2 = (x != 0) & (10 / x > 1);   // ArithmeticException

Compound assignment and increment. For the numeric variable examples here, compound assignment includes conversion back to the variable type. The left-hand expression is evaluated once, which matters for array elements and expressions with side effects. This is why short s = 1; s += 70000; compiles and wraps around. Shifts: >> keeps the sign, >>> fills with zeros, and the shift distance of an int is masked to 5 bits (1 << 33 equals 1 << 1). String concatenation is left to right: 1 + 2 + "a" is "3a", but "a" + 1 + 2 is "a12".

Boolean values. Only true and false exist; if (x = 5) does not compile for an int (but if (flag = true) does, as an assignment). boolean cannot be cast to or from int. The ^ operator on booleans is exclusive or.

3. Text: String, StringBuilder and text blocks

String

A String is immutable. Transformation methods return a result without changing the original string. The returned reference can be the original object when the API permits it.

Java
String s = "Java";
s.concat(" 21");
System.out.println(s);                    // Java
s = s.concat(" 21");                      // Java 21

String literals are stored in the string pool, so two identical literals are the same object: "a" == "a" is true, while new String("a") == "a" is false. Compile-time constant expressions are also pooled ("a" + "b" == "ab" is true), but a concatenation that is not a constant expression is computed at runtime. Declaring a variable final is not sufficient unless it also meets the constant-variable rules. intern() returns the pooled instance. Use equals for content and equalsIgnoreCase when case does not matter.

Frequently used methods and their results

Method Result for " Hello, World " or the shown input
length() Number of char units
charAt(i) The char at index i; StringIndexOutOfBoundsException if invalid
substring(b, e) From b inclusive to e exclusive: "Java 21".substring(5, 7) is "21"
indexOf("a") First index or -1
strip() / trim() Remove leading and trailing whitespace (strip is Unicode-aware)
isBlank() / isEmpty() " ".isBlank() is true, " ".isEmpty() is false
repeat(n) "ab".repeat(3) is "ababab"
replace(a, b) Replaces all occurrences (not regex)
lines() A Stream<String> of lines
formatted(args) Same as String.format(this, args)
compareTo Lexicographic difference; negative if less

StringBuilder

StringBuilder is a mutable sequence. Methods such as append, insert, delete and reverse mutate the builder and return it for chaining. Other methods have different signatures. For example, setLength returns void. It is not thread-safe (use StringBuffer for a synchronized version, rarely needed).

Java
StringBuilder sb = new StringBuilder("abcdef");
sb.append(1).append('x');       // abcdef1x
sb.insert(0, "->");             // ->abcdef1x
sb.deleteCharAt(2);             // ->bcdef1x
sb.delete(0, 2);                // bcdef1x
sb.reverse();                   // x1fedcb
sb.setLength(3);                // x1f
System.out.println(sb);         // x1f

Beware of equals: StringBuilder does not override it, so new StringBuilder("a").equals(new StringBuilder("a")) is false. Compare with compareTo or toString().equals(...).

Text blocks

A text block starts with """ followed by a line break and ends with """. The compiler removes the incidental whitespace: it finds the smallest indentation among all non-blank lines and the line holding the closing delimiter, and strips that much from each line. Trailing spaces on each line are removed too. Line endings are normalized to \n.

Java
String json = """
        {
          "name": "Ada",
          "age": 36
        }
        """;

Here the closing """ sits on its own line at the same indentation as {, so the result is the JSON with no left margin and a trailing newline. If the closing delimiter is placed on the last text line (}"""), there is no trailing newline. If the closing delimiter is indented less than the content, the difference is kept as leading spaces. Escapes: \n, \" (needed only for three quotes in a row), \s (a space that survives trailing-space stripping), and \ at the end of a line to join the next line without a newline.

4. The Math API

Math methods are static. Know these behaviors:

  • Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE (still negative) because +2147483648 does not fit.
  • Math.round(double) returns a long; Math.round(float) returns an int. It rounds half up toward positive infinity: Math.round(2.5) is 3, Math.round(-2.5) is -2, Math.round(-2.6) is -3.
  • Math.ceil and Math.floor return double: Math.ceil(-0.5) is -0.0.
  • Math.floorDiv(-7, 2) is -4 (while -7 / 2 is -3), and Math.floorMod(-7, 3) is 2 (while -7 % 3 is -1).
  • Math.addExact, subtractExact, multiplyExact and toIntExact throw ArithmeticException on overflow instead of wrapping.
  • Math.pow(2, 10) returns the double 1024.0; Math.sqrt(-1) is NaN; Math.max(1, 2.5) is the double 2.5.

5. The Date-Time API (java.time)

The main date-time value classes used here are immutable and thread-safe. Methods like plusDays return a new object, so ignoring the result is again a bug. Months are numbered from 1 and constructed with of or parse, never new.

Class Represents Example
LocalDate Date without time or zone LocalDate.of(2025, 3, 9)
LocalTime Time without date or zone LocalTime.of(14, 30)
LocalDateTime Date and time, no zone LocalDateTime.of(2025, 3, 9, 14, 30)
ZonedDateTime Date, time and zone rules ZonedDateTime.of(ldt, ZoneId.of("America/New_York"))
OffsetDateTime Date, time and fixed offset ...-05:00
Instant A point on the timeline, represented by epoch seconds and a nanosecond fraction Instant.now()
Duration Time-based amount (seconds, nanos) Duration.ofMinutes(135) prints PT2H15M
Period Date-based amount (years, months, days) Period.of(1, 2, 3) prints P1Y2M3D

Invalid values throw DateTimeException: LocalDate.of(2025, 13, 1) and LocalDate.of(2025, 2, 29) both fail. LocalDate.parse("2025-03-09") uses ISO format; for others use DateTimeFormatter.ofPattern("dd/MM/yyyy"). In patterns, MM is month and mm is minutes, HH is 24-hour and hh is 12-hour.

Month arithmetic clamps to the end of the month. LocalDate.of(2025, 1, 31).plusMonths(1) is 2025-02-28, not an exception.

Period versus Duration. Period.between(LocalDate.of(2024, 1, 15), LocalDate.of(2025, 3, 10)) is P1Y1M23D: one year to 2025-01-15, one month to 2025-02-15, then 23 days (13 left in February 2025, plus 10). A Period is not normalized automatically: Period.ofDays(45) stays P45D and Period.ofMonths(14) stays P14M; call normalized() to get P1Y2M. A Duration works on time units: Duration.between on two LocalDate objects throws UnsupportedTemporalTypeException, because a date has no time of day. Use ChronoUnit.DAYS.between(d1, d2) for a plain count of days.

Instant and conversion. Instant has no concept of month or year in its API: instant.plus(1, ChronoUnit.DAYS) works (a day is 24 hours) but instant.plus(1, ChronoUnit.MONTHS) throws UnsupportedTemporalTypeException. To go from local to instant you need a zone or offset: ldt.atZone(zone).toInstant() or ldt.toInstant(ZoneOffset.UTC).

Daylight saving time

A ZonedDateTime applies the zone's rules. In America/New_York the clocks jump forward on 2025-03-09 (02:00 becomes 03:00, so a local hour does not exist) and back on 2025-11-02 (the clock moves from 02:00 to 01:00, so local times in the 01:00 hour occur twice).

Java
ZoneId ny = ZoneId.of("America/New_York");
ZonedDateTime start = ZonedDateTime.of(2025, 3, 8, 12, 0, 0, 0, ny);
System.out.println(start.plusDays(1));
// 2025-03-09T12:00-04:00[America/New_York]   (same local time)
System.out.println(start.plus(Duration.ofHours(24)));
// 2025-03-09T13:00-04:00[America/New_York]   (exactly 24 elapsed hours)
System.out.println(Duration.between(start, start.plusDays(1)));
// PT23H   (one hour was skipped)

The rule: date-based methods (plusDays, plus(Period)) work on the local timeline; time-based methods (plusHours, plus(Duration)) work on the instant timeline. If you build a local time inside the gap, such as 2025-03-09T02:30 in New York, Java moves it forward by the gap length to 03:30-04:00. In the overlap, Java picks the earlier offset by default; withLaterOffsetAtOverlap() selects the second occurrence.

Worked example: scheduling a maintenance window

Problem. A system runs a job every day at 01:30 New York time. A developer writes:

Java
ZoneId ny = ZoneId.of("America/New_York");
ZonedDateTime run = ZonedDateTime.of(2025, 3, 8, 1, 30, 0, 0, ny);
ZonedDateTime next = run.plusDays(1);
ZonedDateTime third = next.plusDays(1);
System.out.println(next + " | " + third);

What is printed, and what would change if run.plus(Duration.ofHours(48)) were used to reach the third run directly?

Step 1. run is 2025-03-08T01:30-05:00 (EST). The offset is -05:00 because DST starts the next day.

Step 2. plusDays(1) is date-based. The local result is 2025-03-09T01:30, which exists (the gap is 02:00 to 03:00). The offset on that morning is still -05:00, so next is 2025-03-09T01:30-05:00[America/New_York].

Step 3. third adds another local day: 2025-03-10T01:30, now after the change, so the offset is -04:00: 2025-03-10T01:30-04:00[America/New_York].

Output: 2025-03-09T01:30-05:00[America/New_York] | 2025-03-10T01:30-04:00[America/New_York].

With run.plus(Duration.ofHours(48)): 48 real hours after 2025-03-08T01:30-05:00 (06:30Z) is 2025-03-10T06:30Z, which in New York is 02:30 EDT (-04:00): 2025-03-10T02:30-04:00[America/New_York]. The job would drift by one hour because one local hour was skipped in between. The calendar-based method keeps the schedule at 01:30, which is why it is the better choice for a daily job.

Common pitfalls and exam tips

  • Exam tip: read the types before the values. Many "what is the output" questions are really "does it compile" questions (byte b = a + 1;, int i = 5L;, long l = 3000000000;, the last failing because the literal is an int that is too large).
  • Ignoring the return value of String, LocalDate or Duration methods leaves the original unchanged.
  • When both operands are references, == tests identity. A wrapper compared with a primitive can be unboxed, and unboxing null throws.
  • substring(begin, end): the end index is exclusive, and substring(3, 2) throws.
  • A char in + with an int produces an int, but "" + 'a' + 1 produces "a1".
  • Math.round returns long for double: int r = Math.round(2.5); does not compile.
  • Period and Duration are not interchangeable and Duration.between(LocalDate, LocalDate) fails at runtime.
  • MM versus mm in DateTimeFormatter patterns, and yyyy versus YYYY (week-based year) cause wrong dates.

Mini case study: invoice due dates

An invoicing service stores each invoice as LocalDate issued and a payment term of 1 month. The code due = issued.plusMonths(1) is used, and a late fee of 2% is charged when the invoice is more than 30 days overdue. A new developer writes Duration.between(due, today).toDays() > 30 and price * 0.02 with double.

Questions. (1) What happens at runtime? (2) What is the due date for an invoice issued on 2025-01-31? (3) How would you fix the money calculation?

Solution. (1) Duration.between with two LocalDate objects throws UnsupportedTemporalTypeException ("Unsupported unit: Seconds"). Use ChronoUnit.DAYS.between(due, today) > 30. (2) plusMonths(1) clamps to the last valid day: 2025-02-28; there is no exception and no overflow into March, which the business must accept or document. (3) Binary floating point cannot represent most decimal fractions; use BigDecimal created from strings, for example new BigDecimal("199.90").multiply(new BigDecimal("0.02")).setScale(2, RoundingMode.HALF_UP), which gives 4.00.

Key terms

  • Binary numeric promotion: automatic widening of operands to int or larger before arithmetic.
  • Autoboxing / unboxing: automatic conversion between a primitive and its wrapper.
  • Integer cache: shared Integer instances for -128 to 127.
  • String pool: the area where equal literals share one String.
  • Text block: a multi-line string literal delimited by """ with incidental whitespace removed.
  • Instant: a machine timeline point, independent of any calendar.
  • Period / Duration: date-based versus time-based amounts of time.
  • Gap / overlap: local times skipped or repeated at a DST transition.

Summary checklist

  • I can predict results of mixed byte, char, int, long, float and double expressions, and spot missing casts.
  • I know that += casts implicitly and that overflow is silent.
  • I can explain Integer caching and when unboxing throws NullPointerException.
  • I know the precedence and short-circuit rules, and that & evaluates both sides.
  • I can use String and StringBuilder methods and remember that strings are immutable.
  • I can compute the content of a text block, including the effect of the closing delimiter.
  • I know the edge cases of Math.round, abs, floorMod and the *Exact methods.
  • I can choose between LocalDate, ZonedDateTime, Instant, Period and Duration, and reason about DST gaps and overlaps.

Official sources