The purpose of casting is to allow conversions from one type to another.

To get your mind around casting, it is helpful to think of the primitive types as being buckets of bits. Some buckets are bigger than others: `long` is a bucket of 64 bits, `float` is a bucket of 32 bits like `int`, and so forth.

Here is an example using primitives:

short s = 16; //this is okay without cast, since int //is a bigger bucket (32 bits) than short (16 bits) int i = s;

So we can do this, right?

short s2 = s + 26; //Wrong!! Here's the output: net\javagarage\casts\Casting.java:21: possible loss of precision found : int required: short short s2 = s + 26; ^ 1 error

Where does Java say the error is? At the + operator. And what exactly is wrong with trying to ...

Start Free Trial

No credit card required