Beginner
Type Casting and Operators
📂 Phase 1: Java Foundations (Days 1–5) · JavaOperators let you perform calculations, comparisons, and logical operations. Type casting lets you convert a value from one data type to another when needed.
Arithmetic Operators
int a = 10, b = 3;
System.out.println(a + b); // 13 — addition
System.out.println(a - b); // 7 — subtraction
System.out.println(a * b); // 30 — multiplication
System.out.println(a / b); // 3 — integer division (drops decimal!)
System.out.println(a % b); // 1 — modulus (remainder)
Watch out: dividing two ints always gives an int result — 10 / 3 is 3, not 3.33. To get a decimal, cast at least one operand to double: (double) a / b.
Relational and Logical Operators
| Category | Operators | Example |
|---|---|---|
| Relational | == != > < >= <= | a > b returns true/false |
| Logical | && (AND), || (OR), ! (NOT) | (a > 5 && b < 10) |
Assignment Operators
int x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
Type Casting
Java supports two kinds of type conversion:
- Widening (implicit): smaller type → larger type — happens automatically, no data loss.
int → long → float → double - Narrowing (explicit): larger type → smaller type — must cast manually, can lose data
// Widening — automatic
int num = 100;
double d = num; // 100.0, no cast needed
// Narrowing — explicit cast required
double price = 99.99;
int rounded = (int) price; // 99 (truncated, NOT rounded)
Interview tip: (int) 9.9 gives 9, not 10 — narrowing casts truncate the decimal, they do not round to the nearest value.