Casting
You can cause the compiler to ignore its rules of type safety and treat an object of one type as though it were an object of another type, if the types are compatible. This is called casting. Casting can be either implicit or explicit.
An implicit conversion happens automatically; the compiler takes care of it for you. If you have a short, and you assign it to a variable of type int, the compiler automatically (and silently) casts it for you. You don’t have to take any action. This is safe, because an int variable can hold any value that might have been in a short variable.
short myShort = 5; // other code here... int myint = myShort; // implicit conversion
Programmers often talk about this as though the short were being turned into an int. What is actually happening is that the compiler is accepting a short where it expects to find an int, because that is a safe thing to do.
Implicit conversion works only when there is no possibility of loss of data, though. Take a look at this:
int myInt; double myDouble = 4.7; myInt = myDouble;
If you try that assignment, the compiler gives you an error message because you can’t squeeze a decimal number into an integer space. You would lose the fractional part (.7). In fact, even if you wrote:
int myInt; double myDouble = 4 myInt = myDouble;
the compiler would still generate an error. Although there is no fractional part to lose in this case (the double is holding a whole number), the compiler can’t take the chance that something might happen ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access