Glossary
Casting
The process of converting a value from one data type to another in Java. It can be automatic (widening) or manual (narrowing).
Example:
To convert a double value like 3.14 into an int, you would use casting like (int) 3.14.
Integer overflow
Occurs when an arithmetic operation attempts to create a numeric value that is outside the range that can be represented by the integer data type, causing the value to 'wrap around'.
Example:
If int x = Integer.MAX_VALUE; and you then do x = x + 1;, x will become Integer.MIN_VALUE due to integer overflow.
Integer.MAX_VALUE
The largest possible integer value that can be stored in a 32-bit signed integer variable in Java.
Example:
If you try to add 1 to Integer.MAX_VALUE, it will result in an integer overflow.
Integer.MIN_VALUE
The smallest possible integer value that can be stored in a 32-bit signed integer variable in Java.
Example:
Subtracting 1 from Integer.MIN_VALUE would also cause an integer overflow, wrapping around to Integer.MAX_VALUE.
Narrowing (Manual Conversion)
A type conversion in Java where a value of a larger data type (like `double`) is converted to a smaller data type (like `int`), which requires an explicit cast and can lead to loss of precision.
Example:
Converting double pi = 3.14; to int wholePi = (int) pi; is a narrowing conversion, resulting in wholePi being 3.
Negative Rounding
A technique to round a negative double value to the nearest integer by subtracting 0.5 before casting it to an integer.
Example:
To round -1.8 to -2, you would use (int) (-1.8 - 0.5), which performs negative rounding.
Order of Operations (Casting Precedence)
Refers to the rules that determine the sequence in which operations are performed in an expression. Casting has a high precedence, applying only to the immediately following value or expression in parentheses.
Example:
In int result = (int) 1.5 + 2.0;, the cast applies only to 1.5 first, then 2.0 is added as a double, demonstrating the order of operations for casting.
Positive Rounding
A technique to round a positive double value to the nearest integer by adding 0.5 before casting it to an integer.
Example:
To round 1.8 to 2, you would use (int) (1.8 + 0.5), which performs positive rounding.
Truncates
The action of cutting off the decimal part of a floating-point number when it is converted to an integer type, without rounding.
Example:
When (int) 5.9 is evaluated, the value truncates to 5, not 6.
Widening (Automatic Conversion)
An automatic type conversion in Java where a value of a smaller data type (like `int`) is converted to a larger data type (like `double`) without loss of precision.
Example:
When you assign int num = 5; to double d = num;, Java performs widening and d becomes 5.0.