Construction. Casts

[comp1110-4B]

A cast tells the compiler to treat a value as a more specific type than it currently knows about. The syntax is to write the target type in parentheses before the expression:

Object x = "hello"; String s = (String) x; // cast from Object to String

Casts are necessary when retrieving values from a collection that stores Object, since the compiler only knows the value is an Object, not what type it originally was when created.

However, if the cast is wrong (for example, casting a String to an Integer), Java throws an exception called ClassCastException at runtime. The compiler cannot catch this mistake. This is one of the key motivations for type parameters, which avoid the need for casts entirely.

bars magnifying-glass caret-down plus minus arrow-right xmark