Java Primitive Types, Promotion, Casting, Characters, Booleans & Related Concepts
Integer Primitive Types
- Four signed integer primitives, each allocated, stored in two’s-complement encoding
- byte – 8 bits, range −128to+127 (unsigned 1-byte counters max at 255)
- short – 16 bits, range −32768to+32767 ➜ rarely used, too small
- int – 32 bits, ≈ ±2.147×109 (≈ ±231) ➜ default whole-number type in Java
- long – 64 bits, ≈ ±9.22×1018 (≈ ±263) ≈ 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 – 32 bits total
- 1 sign bit, 8-bit exponent, 23-bit mantissa (significand)
- About 4–5 decimal digits of reliable precision
- Double – 64 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. π) 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.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 013 / 4 // 3- Negative numbers also truncate (
-13/4 // -3)
- Remainder
% – same sign as dividend - Math class supplies exponentiation
Math.pow, Math.log, trig, etc.
Order of Operations (Precedence)
- Parentheses
() – explicit grouping (use for clarity) - Unary
+ - ++ -- (type) - Multiplicative
* / % - Additive
+ - - Relational
< > <= >= instanceof - Equality
== != - Logical AND
&& - Logical OR
|| - Assignment
= += -= *= ...
- Evaluation left-to-right within the same level except assignment (right-to-left)
- 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
char – 16-bit unsigned code unit, range 0–65535 (UTF-16)- Covers BMP (Basic Multilingual Plane); characters > 65535 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!)- 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 | isWhitespaceCharacter.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 ➜ 10or01⇒1;11or00⇒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 initializervar 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