Casting is the term used when you change one primitive data type into another one.
You do not need to cast when you're going from a smaller data container to a larger one.
For example, a long is a longer integer than an int is, so there is no problem putting an int into a long.
However, if you want a long to become an int, you have to tell the compiler that you actually know what you're doing
(and that you haven't just made a sloppy mistake).
int i = 5; int j = 2; double result; result = i / j; //integer division; result=2 EVEN THOUGH IT IS A DOUBLE result = (double) i / (double) j //real division; result=2.5 (only one of i or j needs to be cast)
Java will implicity cast operants in a mixed expression to match the precision of the variable storing the result.
Sample Code snippet:
double d = 8.8e15; int x = (int)d; System.out.println(x);
| starting type | starting value | final type | final value (after casting) | comments |
|---|---|---|---|---|
| double | 5.777 | int | 5 | It just takes the integer portion. No rounding. |
| double | 8.8e15 | int | 2147483647 | The original number is bigger than the biggest int, so it's turned into the biggest int possible. |
You can also cast objects to their daughter class (if they are the correct type)
abstract class Animal{
public abstract void move();
}
class Shark extends Animal{
public void move(){
swim();
}
public void swim(){}
public void bite(){}
}
class Dog extends Animal{
public void move(){
run();
}
public void run(){}
public void bark(){}
}
...
void somethingSpecific(Animal animal){
// Here you don't know and may don't care which animal enters
animal.move(); // You can call parent methods but you can't call bark or bite.
if(animal instanceof Shark){
Shark shark = (Shark)animal;
shark.bite(); // Now you can call bite!
}
//doSomethingSharky(animal); // You cannot call this method.
}
This doesn't change the original object.