Sub topic 15
Casting and Testing Types
A type tells Java what kind of value a variable can hold. Sometimes you need to use a value as a different type. A conversion changes a value from one type to another. A cast asks Java to perform a conversion by putting the target type in parentheses before the value.
This chapter uses int, double, and String, and assumes you can run a simple Java program.
Numeric casts
A widening conversion moves a number to a type with a wider range. Java performs some widening conversions automatically. For example, an int can become a double.
A narrowing conversion moves a number to a type with a smaller range or less precision. It usually needs an explicit cast. The cast is explicit because you write it yourself.
For example, (int) 9.8 produces 9. For a decimal number within the int range, the cast removes the part after the decimal point. It does not round. So (int) -9.8 produces -9.
A narrowing cast can also produce an unexpected value when the target type cannot hold the original number. A byte holds whole numbers from -128 to 127. Casting the int value 130 to byte produces -126.
Testing an object’s type
An object is a value created from a Java class. A reference is a value that points to an object. A variable declared as Object can hold a reference to a String object, but Java treats the variable as an Object until you use a cast.
The instanceof operator tests whether an object is an instance of a type. An instance is an object created from a class. The test also succeeds for objects created from a subclass, which is a more specific kind of that class.
A reference cast does not turn one object into another kind of object. It lets Java use the same object as the target type. If the object is not compatible with that type, the cast fails while the program runs. Use instanceof first when you are not sure.
Try it
Save this program as CastDemo.java and run it:
public class CastDemo {
public static void main(String[] args) {
int whole = 7;
double widened = whole;
int trimmed = (int) -9.8;
byte small = (byte) 130;
System.out.println(widened); // 7.0
System.out.println(trimmed); // -9
System.out.println(small); // -126
Object value = "Java";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length()); // 4
}
Object empty = null;
System.out.println(empty instanceof String); // false
}
}The if statement runs its block only when the test is true. Inside the block, the cast lets the program use value as a String. The length() method reports the number of characters.
null means a reference points to no object. An instanceof test on null is always false.
Exercises
Exercise
What does (int) -4.7 produce, and why?
Show answer
It produces -4. The cast removes the decimal part rather than rounding.
Exercise
If an Object variable holds null, what does value instanceof String produce?
Show answer
It produces false because there is no object to test.