Lesson 4 of 36Article15 min
Type Casting & Operators
Widening (automatic): int to double. Narrowing (manual): double to int — you must cast: (int) 9.99 becomes 9.
Type Casting — converting between types
Widening (automatic): int to double. Narrowing (manual): double to int — you must cast: (int) 9.99 becomes 9.
Casting can lose data — 9.99 becomes 9 when cast to int.
Real-life example: Pouring a large bottle into a small cup — some water spills (data loss). Casting double to int drops the decimal part.
Widening and narrowing
int a = 10;
double b = a; // automatic widening
double x = 9.99;
int y = (int) x; // manual narrowing → 9
System.out.println(y);Operators — arithmetic and assignment
+ - * / % for math. ++ and -- add or subtract 1. +=, -= combine assignment with operation.
Comparison: == != > < >= <=. Logical: && || ! for combining boolean conditions.
Real-life example: Operators are calculator buttons. + adds, == checks if two numbers are equal, && means both conditions must be true.
Arithmetic and logical operators
int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1 (remainder)
boolean ok = (a > 5) && (b < 10);
System.out.println(ok); // true