Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all programming needs because they apply only to widening conversions between compatible types. For all other cases you must employ a cast. A cast is an instruction to the compiler to convert one type into another. Thus, it requests an explicit type conversion. A cast has this general form:
(target-type) expression
Here, target-type specifies the desired type to convert the specified expression to. For example, if you want to convert the type of the expression x/y to int, you can write
Here, even though x and y are of type double, the cast converts ...
Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.