Casting and Range
| English | Chinese | Pinyin |
|---|---|---|
| casting | 类型转换 | lèi xíng zhuǎn huàn |
| truncates | 截断 | jié duàn |
| widening | 拓宽 | tuò kuān |
| narrowing | 收窄 | shōu zhǎi |
| range | 取值范围 | qǔ zhí fàn wéi |
| overflow | 溢出 | yì chū |
Changing a value's type
- Casting 类型转换 converts a value from one type to another.
- Write the target type in parentheses:
(double) 5gives5.0;(int) 3.9gives3. - Casting to
inttruncates 截断 — it drops the decimal part, it does not round. (int) 3.9is3, and(int) -2.7is-2(toward zero).
Widening happens automatically
- Going from a smaller type to a larger one (
int→double) is widening 拓宽. - Widening is safe, so Java does it automatically:
double d = 5;stores5.0. - No information is lost going from
inttodouble. - You rarely need to write a widening cast, but it's allowed.
Narrowing needs an explicit cast
- Going from larger to smaller (
double→int) is narrowing — it can lose data. - Java requires an explicit cast:
int n = (int) 3.9;(without the cast, it won't compile). - The cast is you promising "I know I'm dropping the decimals."
- Narrowing truncates toward zero.
Range and overflow
- Each type has a fixed range 取值范围:
intholds roughly ±2.1 billion. - Exceeding the range causes overflow 溢出 — the value wraps around to a wrong number.
- No error is raised; the result is just silently wrong.
- For huge whole numbers, a bigger type (like
long) is needed.
Casting to int truncates — it does NOT round. (int) 3.9 is 3, not 4; (int) 2.99 is 2. To force floating-point division, cast one operand: (double) 7 / 2 is 3.5, but (int)(7.0 / 2) is 3. And watch overflow: an int result beyond ±2.1 billion wraps silently, with no error.
Averaging two ints correctly:
int a = 7, b = 2;int avg = a / b;→3(int division drops the remainder — probably not what you want).double avg = (double) a / b;→3.5(casting one side forces decimal division).
Casting (type) value converts between types. int → double (widening) is automatic and safe; double → int (narrowing) needs an explicit cast and truncates toward zero (no rounding). Each type has a fixed range; exceeding it causes silent overflow.
Casting between int and double
(int) truncates 3.9 to 3; casting one side gives 3.5.
What is the value of (int) 3.9 in Java?
Casting to int truncates (drops decimals) → 3, not 4.
Converting int to double (a safe, automatic conversion) is called...
Small → large is widening, done automatically.
Which needs an explicit cast to compile?
double → int is narrowing and requires the explicit cast.
What is the value of (double) 7 / 2?
Casting one operand forces floating-point division → 3.5.
An int result beyond its range causes overflow, which Java reports as an error.
Overflow wraps silently — no error is raised.