Chapter 2 of 16Foundation

Types, Nullability, Money, and Time

Use primitives, references, null, BigDecimal, java.time, operators, and casting correctly; treat Scanner as a small console example.

25 minJava 21
01

Why it matters

Start from the concept, not the syntax

Meet a concrete situation where this idea earns its place, then state the boundary it guards.

Types are the first line of defense: the compiler checks every value before the program ever runs. Once you know what each primitive holds and how operators promote and convert values, most beginner surprises—overflow, truncation, odd string results—become predictable.

By the end of this chapter

Silent widening and careless casting turn simple arithmetic into overflow, truncation, and money bugs that only surface after the program ships.

  • Primitive vs reference types
  • Promotion and casting
  • Safe string building
02

Mechanism

How Java expresses the concept

Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.

The mental model

Java has eight primitive types: `byte`, `short`, `int`, `long`, `float`, `double`, `char`, and `boolean`. Primitives hold the value directly; assigning one copies the bits. Reference types (everything that is a class, including `String`) hold references to objects. The exact memory layout and storage location are JVM implementation details.

Integer literals are `int` by default and `long` when suffixed with `L`. Floating-point literals are `double` by default and `float` when suffixed with `f`. Use `long` for values past 2^31 and `BigDecimal` for money because binary floating point cannot represent decimal amounts such as 0.1 exactly. Use `java.time` types such as `Instant`, `LocalDate`, and `OffsetDateTime` instead of legacy date types.

Operators follow precedence: unary, multiplicative (`* / %`), additive (`+ -`), shift, relational, equality, then logical. Mixing types triggers binary numeric promotion: a smaller primitive is widened to the larger type before the operation. Casting (`(int) x`) narrows explicitly and can lose information.

`String` is immutable. Concatenation with `+` creates a new `String` object; in loops, use `StringBuilder` to avoid quadratic cost. `Scanner` reads console or file input token by token.

03

Concept map

Inspect the building blocks as a whole

Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.

Core Java

Primitive types, variables, and operators

Java separates primitive values (int, double, boolean) from reference values (objects), and that split explains most beginner surprises.

  1. 01Eight primitive types
  2. 02Primitives vs references
  3. 03Widening and narrowing
  4. 04Operator precedence
  5. 05String immutability
  6. 06Scanner for input
04

Implementation

Encode the smallest runnable example

Write and run the code, then observe the behavior you just predicted with a real Java program.

Runnable snippet path

Predict, run, and change each example

2 focused examples
01

Overflow and casting

int max + 1 wraps around. Casting double to int truncates, it does not round.

Numbers.java
public class Numbers {
    public static void main(String[] args) {
        int max = Integer.MAX_VALUE;
        System.out.println(max + 1); // wraps to negative
        double price = 9.99;
        int truncated = (int) price; // 9, not 10
        System.out.println(truncated);
    }
}

Remember

Use long or BigDecimal before you can overflow; casting never rounds.

Expected output

-2147483648
9
02

Read input with Scanner

nextInt reads the next token as an integer; nextLine reads the rest of the line.

Input.java
import java.util.Scanner;

public class Input {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Age: ");
        int age = scanner.nextInt();
        System.out.println("In 10 years: " + (age + 10));
    }
}

Remember

After nextInt, a stray newline often remains; call nextLine to consume it when mixing reads.

Change one input, predict the result, then compile or test it before continuing.

05

Watch out

Break it on purpose, then repair the right layer

Predict the symptom before running the failure case, and close with the completion checklist.

Deliberate failure

  1. Break

    Store a price as double and cast it to int for display

  2. Observe

    The amount is truncated toward zero and pennies disappear

  3. Repair

    Keep a precise type until formatting time and use BigDecimal for currency rather than casting doubles

Why it matters

Keep a precise type until formatting time and use BigDecimal for currency rather than casting doubles

Completion checklist

  • Choose the right primitive for each value
  • Predict widening and narrowing results
  • Concatenate and build strings safely
06

Go deeper

Official references

The primary sources behind this chapter. Every claim above stays consistent with them.