Widening
Description
A smaller numeric type can become a larger compatible type.
Explanation
No explicit cast is needed because the destination can represent the original value.
Example
double average = 87;← Chapter 2 — Core Syntax & Data
mixed
Type casting converts a value from one type to another. Widening conversions, such as int to double, are safe and happen automatically.
Narrowing conversions, such as double to int, need an explicit cast because information can be lost. Check whether that loss is acceptable before casting.
A smaller numeric type can become a larger compatible type.
No explicit cast is needed because the destination can represent the original value.
double average = 87;A larger numeric type can be forced into a smaller type.
The fractional part is removed when casting double to int.
int wholeScore = (int) 87.9;Casting does not round a decimal value. If you need rounding, use Math.round and understand that it returns a long for a double argument.
public class CastingDemo {
public static void main(String[] args) {
double score = 87.9;
int displayedScore = (int) score;
System.out.println(displayedScore);
}
}