Sub topic 15
Casting and Testing Types
Java gives every value a type. Sometimes you need to use a value as a different type. A cast is an expression that asks Java to treat or convert a value as a specified type.
A cast can help with two different jobs:
- Convert between numeric types, such as
doubleandint. - Treat an object reference as a more specific type, such as
String.
These jobs have different rules. Numeric casts can change the value. Reference casts do not change the object, but they can fail if the object has the wrong type.
Casting numeric values
A primitive type stores a basic value, such as an integer or a decimal number. Java can convert some primitive numeric values without a cast:
int count = 7;
double amount = count;Here, Java converts the int value to a double. This is a widening conversion: the destination type has a wider range of values. For int to double, the value is preserved exactly.
Other conversions need an explicit cast. Write the destination type in parentheses before the value:
int whole = (int) 3.9;This is a narrowing conversion. It can lose information. The cast from double to int removes the fractional part, so whole is 3. It does not round to the nearest integer. For a negative number, it removes the fractional part in the same way: (int) -3.9 is -3.
Without the cast, Java rejects an assignment from double to int because the conversion could lose information.
Try numeric casts
Save this program as NumericCasts.java, then compile and run it.
public class NumericCasts {
public static void main(String[] args) {
int count = 7;
double widened = count;
int positive = (int) 3.9;
int negative = (int) -3.9;
byte small = (byte) 130;
double castFirst = (double) 7 / 2;
double castAfter = (double) (7 / 2);
System.out.println(widened); // 7.0
System.out.println(positive); // 3
System.out.println(negative); // -3
System.out.println(small); // -126
System.out.println(castFirst); // 3.5
System.out.println(castAfter); // 3.0
}
}The byte type holds whole numbers from -128 to 127. The value 130 is outside that range. The cast keeps the low-order bits that fit in a byte, producing -126.
The last two lines show why cast placement matters. In castFirst, Java converts 7 to double before division, so the result is 3.5. In castAfter, Java first performs integer division, which gives 3. The cast then converts that result to 3.0. It cannot bring back the lost fraction.
A cast produces a converted value. It does not change the original variable:
double price = 4.75;
int wholePrice = (int) price;
// price is still 4.75; wholePrice is 4.Check for lost information
A cast is not a safety check. Before narrowing a value, decide what should happen if it does not fit or has a fractional part.
- A cast from
doubletointremoves the fractional part. - If a
doubleis too large or too small forint, the result is the nearestintlimit. A special value calledNaN, meaning “not a number,” becomes0. - A cast from
inttobytecan produce a very different number when the value is outside thebyterange.
Even some widening conversions can lose precision. Precision is the ability to keep the exact value. For example, float has a wider range than int, but it cannot represent every int exactly. Java permits int to float without a cast, even when the result is only an approximation.
Object references and casts
An object is a value created from a class. A reference is a value that refers to an object. For example, a String reference can refer to a string object.
Object is a general class in Java. A String is also an Object, so this assignment is allowed:
Object value = "Java";The object is still a string. But the variable value has type Object, so Java only allows operations available through that type. For example, you cannot call the string method length() directly on value.
A reference cast can let you use the more specific type:
String text = (String) value;This cast does not turn the object into a new string. It checks that the existing object can be used as a String, then gives you a String reference to it.
If the object is not a String, the cast fails while the program is running. Java throws a ClassCastException. An exception is a signal that something went wrong during a program’s execution.
Test a type with `instanceof`
The instanceof operator tests whether a reference refers to an object that can be used as a given type. Its result is a boolean: either true or false.
Test before casting when you are not sure of the object’s type. Save and run this program as TypeTests.java:
public class TypeTests {
public static void main(String[] args) {
Object value = "Java";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length()); // 4
}
Object number = Integer.valueOf(42);
if (number instanceof String) {
String text = (String) number;
System.out.println(text);
} else {
System.out.println("Not a string"); // Not a string
}
Object missing = null;
System.out.println(missing instanceof String); // false
}
}The first test is true, so the cast succeeds. The second object is an Integer, not a String, so the program skips the cast and prints Not a string.
null means a reference does not refer to an object. An instanceof test on null is always false. Casting null to String is allowed and still gives null, but calling a method on that reference would cause a NullPointerException.
A shorter form in Java 16 and later
Java 16 added a way to combine the test and cast. In this example, text is a pattern variable: a variable that Java provides when the type test succeeds.
Save this program as PatternTest.java and run it with Java 16 or later:
public class PatternTest {
public static void main(String[] args) {
Object value = "Java";
if (value instanceof String text) {
System.out.println(text.length()); // 4
}
}
}Inside the if block, text is a String, so the program can call length(). The variable is available there because the test succeeded.
Choose the right operation
| Goal | Operation | Important point |
|---|---|---|
| Convert `int` to `double` | Assign it directly | Java widens the value. |
| Convert `double` to `int` | Use `(int)` | The fractional part is removed. |
| Check an object’s type | Use `instanceof` | The result is `false` for `null`. |
| Use an object as a more specific type | Test, then cast | A wrong reference cast throws an exception. |
A reference cast is not a general way to change one kind of object into another. For example, casting an Integer object to String does not create text from the number. Use an appropriate conversion method when you need a new value of a different kind.
Exercise
What do (int) 8.9, (int) -8.9, and (double) (9 / 2) produce?
Show answer
They produce 8, -8, and 4.0. The first two casts remove the fractional part. In the last expression, integer division happens before the cast.
Exercise
If Object item = null;, what does item instanceof String return? Does (String) item throw a ClassCastException?
Show answer
The test returns false. The cast does not throw a ClassCastException; it returns null. Calling a method on that null reference would fail.