// You can typecast to convert a variable of one data type to another.
// Wide Casting converts small data types to larger ones.
// Narrow Casting converts large data types to smaller ones.
// Java can automatically Wide Cast.
// Java will throw an error when trying to automatically Narrow Cast.
// This is because data is often lost when Narrow Casting.
// Narrow Casting must be done manually.
//Wide Cast:
int SomeNumber = 5;
double WideCastedNumber = (double)SomeNumber;
//Narrow Cast:
double SomeNumber = 5.39;
int NarrowCastedNumber = (int)SomeNumber;
//Note: The data that holds the decimal places will be lost!
JAVA: Example of cast:
int SomeNumber = 5; //int
double WideCastedNumber = (double)SomeNumber; //from int to double
double myDouble = 9.78;
int myInt = (int) myDouble; // from double to int
Narrowing Casting (manually) - larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
int x = 0;
x += 1.1; // just fine; hidden cast, x == 1 after assignment
x = x + 1.1; // won't compile! 'cannot convert from double to int'
Animal animal = new Dog ();
animal.fetch(); // Compiler error
(Dog) animal.fetch();
Lowest to highest primitive data types: Byte-->Short-->Int-->Long-->Float-->Double
Byte-->short-->char-->Int-->long-->float-->double