Casting and Range · Conversão e Intervalo
| English | Português |
|---|---|
| casting/ˈkæstɪŋ/ | conversão |
| truncates/ˈtrʌŋkeɪts/ | trunca |
| widening/ˈwaɪdənɪŋ/ | ampliação |
| narrowing/ˈnærəʊɪŋ/ | redução |
| range/reɪndʒ/ | range |
| overflow/ˌəʊvəˈfləʊ/ | overflow |
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).
Alterando o tipo de um valor
- Casting 类型转换 converte um valor de um tipo para outro.
- Escreva o tipo alvo entre parênteses:
(double) 5dá5.0;(int) 3.9dá3. - Casting para
inttrunca 截断 — ele descarta a parte decimal, não arredonda. (int) 3.9é3, e(int) -2.7é-2(em direção a 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.
Widening acontece automaticamente
- Passar de um tipo menor para um maior (
int→double) é widening 拓宽. - Widening é seguro, então Java o faz automaticamente:
double d = 5;armazena5.0. - Nenhuma informação é perdida indo de
intparadouble. - Raramente você precisa escrever um casting widening, mas é permitido.
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.
Narrowing exige um cast explícito
- Passar de maior para menor (
double→int) é narrowing — pode perder dados. - Java exige um cast explícito:
int n = (int) 3.9;(sem o cast, não compila). - O cast é sua promessa "sei que estou descartando os decimais."
- Narrowing truncna em direção a 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.
Intervalo e overflow
- Cada tipo possui um intervalo fixo 取值范围:
intarmazena aproximadamente ±2.1 bilhões. - Exceder o intervalo causa overflow 溢出 — o valor gira para um número errado.
- Nenhum erro é lançado; o resultado é apenas silenciosamente errado.
- Para números inteiros enormes, um tipo maior (como
long) é necessário.
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.
A conversão para int truncará — NÃO arredondará. (int) 3.9 é 3, não 4; (int) 2.99 é 2. Para forçar a divisão de ponto flutuante, converta um dos operandos: (double) 7 / 2 é 3.5, mas (int)(7.0 / 2) é 3. E fique atento ao estouro: um resultado int além de ±2.1 bilhões será ajustado silenciosamente, sem gerar erro.
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).
Média de dois ints corretamente:
int a = 7, b = 2;int avg = a / b;→3(divisão int descarta o resto — provavelmente não é o que você quer).double avg = (double) a / b;→3.5(castear um lado força divisão decimal).
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 (type) value converte entre tipos. int → double (widening) é automático e seguro; double → int (narrowing) precisa de um cast explícito e trunca em direção a zero (sem arredondamento). Cada tipo tem um intervalo fixo; excedê-lo causa overflow silencioso.
Casting between int and double · Conversão entre int e double
(int) truncates 3.9 to 3; casting one side gives 3.5. · (int) truncar 3.9 para 3; converter um lado resulta em 3.5.
What is the value of (int) 3.9 in Java? · Qual é o valor de (int) 3.9 em Java?
Casting to int truncates (drops decimals) → 3, not 4. · Converter para int truncar (descarta decimais) → 3, não 4.
Converting int to double (a safe, automatic conversion) is called... · Converter int para double (uma conversão segura e automática) é chamado...
Small → large is widening, done automatically. · Pequeno → grande é ampliação, feito automaticamente.
Which needs an explicit cast to compile? · Qual precisa de conversão explícita para compilar?
double → int is narrowing and requires the explicit cast. · double → int é redução e requer a conversão explícita.
What is the value of (double) 7 / 2? · Qual é o valor de (double) 7 / 2?
Casting one operand forces floating-point division → 3.5. · Converter um operando força a divisão com ponto flutuante → 3.5.
An int result beyond its range causes overflow, which Java reports as an error. · Um resultado int além do seu intervalo causa overflow, que Java relata como erro.
Overflow wraps silently — no error is raised. · Overflow gira silenciosamente — nenhum erro é levantado.