1.5 Casting and Range of Variables

49 阅读2分钟

1. Exam Points

  • Range of the int type: [Integer.MIN_VALUE , Integer.MAX_VALUE]
  • Integer overflow(int): if a value is outside of the allowed range, an integer overflow occurs.
  • Round-off error(double) - if a value is more precise than can be stored in the allotted memory, a round-off error occurs. (Ex. 2.3 is stored as 2.29999)
  • Casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
    • (int)0.3*11 is 0
    • (int)(0.3*11) is 3
  • Casting a double value to an int value causes the digits to the right of the decimal point to be truncated. (Ex. 10.9 -> 10)
  • int to double conversion is done automatically. (Ex. double b = 10, b is 10.0)

2. Knowledge Points

(1) Range of Variables

  • An int variable is stored using 4 bytes.
  • Range of int variables: [Integer.MIN_VALUE , Integer.MAX_VALUE]
  • Integer overflow: if a value is outside of the allowed range, an integer overflow(溢出错误) occurs.
  • 如果尝试在int变量中存储超出其范围的值,发生溢出错误。
  • Example:
       int x = 100; 
       x = Integer.MAX_VALUE;
       
       // y is out of the range of int, leading to overflow error
       int y = x * 100 ; 
    
  • A double variable is stored using 8 bytes.
  • Round-off error(舍入误差): If a value is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. (对于double变量,有的值无法准确表示,会得到一个四舍五入的值,这种Java能表示的值和实际值之间的误差叫做舍入误差)
  • Example:
    3.1433 is 28.26, but is represented as 28.259999999999998 in Java. image.png

(2) Type Casting (类型转换)

  • Casting(转换) means converting from one type to another.
  • Casting from a small range to a large range:
    • Example: int to double
    int x = 100 ;
    double y = 20.9 ;
    y = x;  // int -> double , casted automatically
    
  • Casting from a large range to a small range:
    • Example: double to int
    double y = 20.9 ;
    
    // convert from double to int, 
    // must be done manually by adding (int) before y
    int x =(int) y ;  
    
  • Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
    • int a = (int) 20.9
    • result is 20
  • Double values can be rounded to the nearest integer by:
    • (int) (x + 0.5) for non-negative numbers
    • (int)(x - 0.5) for negative numbers
    • Example:\ image.png
  • Precedence(优先级) : casting has a higher precedence over arithmetic operations.
    • Example: (int)0.3*11 will evaluate (int)0.3 first, and then *
      image.png

3. Exercises