Java Primitive Types, Promotion, Casting, Characters, Booleans & Related Concepts

Integer Primitive Types

  • Four signed integer primitives, each allocated, stored in two’s-complement encoding
    • byte88 bits, range 128  to  +127-128 \;\text{to}\;+127 (unsigned 1-byte counters max at 255255)
    • short1616 bits, range 32768  to  +32767-32\,768 \;\text{to}\;+32\,767 ➜ rarely used, too small
    • int3232 bits, ≈ ±2.147×109\pm2.147\times10^{9} (≈ ±231\pm2^{31}) ➜ default whole-number type in Java
    • long6464 bits, ≈ ±9.22×1018\pm9.22\times10^{18} (≈ ±263\pm2^{63}) ≈ 8–9 quintillion
  • When integers must exceed long, import java.math.BigInteger for arbitrary-precision arithmetic (much slower)

Real-Number Primitive Types (Floating Point)

  • Float – 3232 bits total
    • 1 sign bit, 8-bit exponent, 23-bit mantissa (significand)
    • About 4–5 decimal digits of reliable precision
  • Double – 6464 bits total (1 + 11 + 52)
    • Default for literals that contain a decimal point
    • About 15–16 reliable decimal digits
  • Neither type can store irrationals (e.g. π\pi) exactly; they approximate using binary fractions ➜ rounding error inevitable

Floating-Point Precision & Rounding Error Demo

  • Processor stores halves, quarters, eighths … ; many decimals (e.g. 0.10.1) have no exact binary form
  • Example in JShell
    • double change = 10 - 9.40; // 0.6000000000000001 (close to 60 ¢ but not exact)
  • Equality test with == fails: change == 0.60 // false
  • Proper comparison pattern (tolerance, "epsilon"):
    • boolean close = Math.abs(change - 0.60) < 0.0001;
  • Float error grows faster (only 23-bit mantissa) – repeated operations can accumulate cents-level differences into dollars

Arithmetic Operators (Primitive)

  • Addition +, subtraction -, multiplication *
  • Integer division / – truncates toward 00
    • 13 / 4 // 3
    • Negative numbers also truncate (-13/4 // -3)
  • Remainder % – same sign as dividend
    • 13 % 4 // 1
  • Math class supplies exponentiation Math.pow, Math.log, trig, etc.

Order of Operations (Precedence)

  1. Parentheses () – explicit grouping (use for clarity)
  2. Unary + - ++ -- (type)
  3. Multiplicative * / %
  4. Additive + -
  5. Relational < > <= >= instanceof
  6. Equality == !=
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment = += -= *= ...
  • Evaluation left-to-right within the same level except assignment (right-to-left)

Type Promotion & Casting

  • Java automatically promotes smaller/wider types when it will not lose information (up-casting)
    • 3 + 5.0 // 3 promoted to 3.0, result double
    • An integer operand combined with a floating operand ➜ int ⟶ double (or float)
  • Down-casting (narrowing) can lose data ➜ compiler error unless you explicitly cast:
    • (int) 12.7 // 12 (decimal chopped)**
    • (short) 1_000_000 // 16_960 (overflow, garbage)
  • Syntax: (TargetType) expression
    • Cast operator is high-precedence: (int) y / 3 differs from (int) (y / 3)
  • Numeric literals may use underscores for readability: 1_000_000

Overflow & Underflow

  • Fixed-size integers wrap around two’s-complement range
    • int a = 2_000_000_000 + 2_000_000_000; // –294,967,296 (overflow)
  • Same risk when casting large values into smaller containers

The char Type & Unicode

  • char16-bit unsigned code unit, range 0655350 – 65\,535 (UTF-16)
  • Covers BMP (Basic Multilingual Plane); characters > 6553565\,535 are represented via surrogate pairs (two chars)
  • Unicode keeps expanding (≈ 149 000+ code points in v15, emoji, ancient scripts, etc.)
  • On the wire the Web prefers UTF-8 (variable-length 1–4 bytes per code point)

Escape Sequences for Special char Literals

  • \t tab | \n newline (ENTER)
  • \' single quote (since 'x' uses quotes to delimit)
  • \\ backslash itself
  • Any code unit: \uXXXX (4 hex digits)

String Concatenation & char Arithmetic

  • When one operand is a String, + promotes the other operand to String
    • "Hello" + '!' // "Hello!"
  • char + char without a String first ➜ integer addition (using code points!)
    • 'A' + 'B' // 131
  • ASCII letter case gap: 'a' - 'A' == 32'C' + 32 yields 'c'

Character Utilities & Wrapper Classes

  • Primitive ≠ object, so call static helpers in java.lang.Character
    • Character.isLetter(ch) | isDigit | isWhitespace
    • Character.toUpperCase(ch) | toLowerCase(ch)
  • Each primitive has a companion wrapper class providing constants & utilities:
    • Byte, Short, Integer, Long, Float, Double, Character, Boolean

Parsing Strings to Numbers

  • Cannot cast a String directly ➜ use wrapper parse methods
    • int n = Integer.parseInt("12345");
    • double d = Double.parseDouble("3.14159");
  • Input string must be properly formatted; underscores/spaces disallowed

Boolean Primitive & Logical Operators

  • Only two literal values: true, false
  • Operators
    • Logical AND && (both operands true)
    • Logical OR || (either operand true)
    • NOT !
    • Exclusive OR ^ – true when operands differ
    • Truth table: 1-true/0-false ➜ 10  or  011;  11or  0001\,0 \;\text{or}\; 0\,1 \Rightarrow 1;\; 1\,1 \text{or}\; 0\,0 \Rightarrow 0

Reference Types vs Primitive Types

  • Primitives contain the value itself; reference types store a memory address (pointer)
  • All user-defined classes & arrays are reference types
  • == compares addresses for references ➜ use .equals() for logical equality (e.g. Strings)
  • String a = new String("hi"); String b = new String("hi"); a == b // false

Type Inference with var (Java 10+)

  • var lets compiler deduce the type from the initializer
    • var wheel = new Wheel(); (type = Wheel)
  • Invalid if no initializer: var y; // ERROR – cannot infer type
  • Still resolved at compile-time, not dynamically like JavaScript

Creating Objects (Quick Reminder)

  • Syntax
    • ClassName identifier = new ClassName(arguments);
    • Example: Wheel w = new Wheel(23);
    • Behind scenes: new allocates memory, constructor initializes, variable holds reference

Summary of Key Take-Aways

  • Choose int/double as everyday numeric defaults; upgrade to long/BigInteger or BigDecimal (currency) when scale/precision demand it
  • Never trust floating-point equality – compare with an epsilon
  • Understand automatic promotion rules; add explicit (type) casts when narrowing
  • Beware integer overflow & truncation when casting
  • char holds UTF-16 code unit; use escape sequences for tabs, newlines, quotes, backslash
  • Wrapper classes give parsing & utility helpers; Integer.parseInt, Character.isLetter, etc.
  • Booleans support logical AND/OR/NOT plus XOR ^
  • For reference types, == checks identity; .equals() checks content
  • var reduces repetition but still enforces static typing at compile time
  • Java’s extensive standard library (Math, Character, Integer, …) plus docs = your toolkit for nearly any operation