Video lecture
Watch on YouTube(opens in a new tab)Sub topic 12
Conversions and Casts
A conversion changes a value from one Java type to another. For example, you might store an int value in a long variable or turn a double value into an int.
Some conversions happen automatically. Others need a cast, which is an instruction that tells Java which type you want. A cast can remove a fractional part or lose other information, so it is important to know what it does.
This chapter assumes you can declare variables, use primitive types, and write simple Java expressions.
Automatic widening conversions
A widening conversion changes a numeric value to a type that can represent a wider range of values. Java permits these conversions automatically in assignments.
For example, if count is an int, you can write long total = count;. Java converts the value of count to long before storing it in total.
The table shows the widening conversions Java allows for primitive numeric types. A value can also stay in its original type without conversion.
| Starting type | Types it can widen to |
|---|---|
| `byte` | `short`, `int`, `long`, `float`, `double` |
| `short` | `int`, `long`, `float`, `double` |
| `char` | `int`, `long`, `float`, `double` |
| `int` | `long`, `float`, `double` |
| `long` | `float`, `double` |
| `float` | `double` |
A char holds a numeric character value. When it widens to int, the result is that number. For example, the character 'A' becomes the integer 65.
A boolean value is not a number in Java. You cannot convert it to or from a numeric primitive type, even with a cast.
Widening can still lose detail
Widening does not always preserve the exact value. A float can hold values over a wider range than an int, but it cannot keep every digit of every int.
For example, 16_777_217 becomes 16_777_216 when converted to float. This happens because a float has limited precision: it can keep only a limited amount of numeric detail.
A long converted to float or double can also lose precision. By contrast, every int value can be represented exactly as a double.
Narrowing with a cast
A narrowing conversion changes a numeric value to a type that may not be able to represent it fully. Java usually requires a cast for this conversion.
Write the desired type in parentheses before the value:
int whole = (int) 9.8;
The cast (int) converts 9.8 to the integer 9. It does not change the original value if that value came from another variable.
Floating-point values to whole numbers
When a floating-point value is cast to an integer type, Java removes the fractional part. It does not round to the nearest whole number. It moves toward zero:
(int) 9.8gives9.(int) -9.8gives-9.
For a double cast directly to int, a value outside the int range becomes the nearest int limit. A special value called NaN, which means “not a number,” becomes 0.
There is an extra step when casting a floating-point value to byte, short, or char: Java first converts it to int, then narrows that int to the requested type. Do not assume the result will stop at the smaller type’s limit.
Whole numbers to smaller whole-number types
When you cast an integer to byte, short, or char, Java keeps only the bits used by the target type. A bit is a single binary digit, either 0 or 1.
This can change the value. For example, (byte) 130 gives -126, because 130 is outside the byte range. The cast tells Java to perform the conversion; it does not check that the result is what you intended.
A worked example
Save this program as ConversionExample.java:
class ConversionExample {
public static void main(String[] args) {
int count = 42;
long total = count;
System.out.println("Widened to long: " + total);
int precise = 16_777_217;
float approximate = precise;
System.out.println("After float conversion: " + (int) approximate);
double measurement = -9.8;
int whole = (int) measurement;
System.out.println("Fraction removed: " + whole);
int number = 130;
byte small = (byte) number;
System.out.println("Narrowed to byte: " + small);
char letter = 'A';
int characterNumber = letter;
System.out.println("Character number: " + characterNumber);
int points = 7;
int games = 2;
double earlyCast = (double) points / games;
double lateCast = (double) (points / games);
System.out.println("Cast before division: " + earlyCast);
System.out.println("Cast after division: " + lateCast);
}
}Compile and run it from the folder containing the file:
javac ConversionExample.java
java ConversionExampleThe output is:
Widened to long: 42
After float conversion: 16777216
Fraction removed: -9
Narrowed to byte: -126
Character number: 65
Cast before division: 3.5
Cast after division: 3.0The int-to-long conversion preserves 42. The int-to-float conversion loses one unit of detail. The cast from double to int removes .8, while the cast from int to byte changes 130 to -126.
The final two lines show why the place where you cast matters.
Cast before or after an operation
An expression is a piece of code that produces a value. In points / games, the expression divides two int values. Java performs integer division, so the result is 3, not 3.5.
In the worked example:
(double) points / gamesconvertspointsfirst. The division then uses floating-point values and produces3.5.(double) (points / games)performs integer division first. The cast turns the result3into3.0; it cannot bring back.5.
The same timing issue matters with multiplication. Two int values can produce a result too large for int. That is called overflow. Casting the result afterward cannot repair it. Cast an operand to long before multiplying if the result needs the larger range. For example, (long) 50_000 * 50_000 produces 2_500_000_000.
Conversions inside numeric expressions
Java often converts values before it performs a numeric operation. This is called numeric promotion.
For an operation such as addition or division, Java generally chooses the type in this order:
- If either operand is
double, convert the other todouble. - Otherwise, if either is
float, convert the other tofloat. - Otherwise, if either is
long, convert the other tolong. - Otherwise, use
int. Values of typebyte,short, andcharbecomeint.
An operand is a value used by an operation. In points / games, both variables are operands.
Promotion explains a common surprise: adding two byte values produces an int, not a byte. You can store the result in an int. If you need a byte, you must cast the result and accept the risk that it may be out of range.
A special rule for integer constants
Java allows some assignments to byte, short, or char without a cast when the expression is a whole-number constant that fits the target type.
For example, byte small = 100; is allowed because 100 fits in a byte. But if you first write int number = 100;, the assignment byte small = number; is not allowed without a cast. Java checks the type of number, not just the value it happens to hold at that moment.
Casts are not text parsing
A cast converts between compatible numeric values. It does not read digits from text. To turn a String such as "42" into an int, use a method such as Integer.parseInt. That method reads the text; a cast does not.
Exercises
Exercise
What values do int a = (int) 6.9; and int b = (int) -6.9; assign?
Show answer
a is 6 and b is -6. The cast removes the fractional part toward zero.
Exercise
If int x = 7; and int y = 2;, why does (double) (x / y) give 3.0 rather than 3.5?
Show answer
x / y is evaluated first using integer division, which gives 3. The cast then converts that result to 3.0.
Exercise
Is assigning an int to a float automatically allowed, and does it always preserve the exact value?
Show answer
Yes, Java allows the widening conversion automatically. No, a float can lose precision for some int values.