Quick summary

  • A way of converting one value type to another

Eclipse example: casting

Detailed description

Casting is a way of converting one value type to another. In Java, values have value types allotted for them. You don’t just create a variable and set it to any number, because the system has to reserve space for that value. Larger values need larger amounts of space reserved.

byte 2;
int 600;

It would be inefficient to allot all values the same space in your system. You can change the value types from one to another. This is called casting.

Suppose you have this:

byte myByte = 20; // max is 27
short myShort = 67;
int myInt = 899;
long myLong = 88;
float myFloat = 235.5f;
double myDouble = 8000.7;

Now you want to convert your long to a double. You can’t do it because the double doesn’t fit into the long.

myLong = myDouble;

However, the reverse would work:

myDouble = myLong;

But now you have the problem that you’re using more memory than needed to accommodate the myDouble. It only needs to hold a long value. So you cast it like this:

myDouble = (double)myLong;

This changes the value type to double.

More reading

Casting in Java

Get new posts delivered straight to your inbox.

Subscriber count: 3,505