xxxxxxxxxx
double decimalNum = 10.75;
int num = (int) decimalNum; // Explicit casting from double to int
System.out.println(num); // Output: 10
xxxxxxxxxx
// 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!
xxxxxxxxxx
Lowest to highest primitive data types: Byte-->Short-->Int-->Long-->Float-->Double
xxxxxxxxxx
Narrowing Casting (manually) - larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
xxxxxxxxxx
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
}
}
xxxxxxxxxx
Animal animal = new Dog ();
animal.fetch(); // Compiler error
(Dog) animal.fetch();
xxxxxxxxxx
int num = 10;
double decimalNum = num; // Implicit casting from int to double
System.out.println(decimalNum); // Output: 10.0
xxxxxxxxxx
// Sample code to demonstrate type casting in Java
// Casting from int to double
int num1 = 10;
double num2 = (double) num1;
System.out.println("Casting int to double: " + num2);
// Casting from double to int
double num3 = 5.67;
int num4 = (int) num3;
System.out.println("Casting double to int: " + num4);
// Casting from string to integer
String str = "123";
int num5 = Integer.parseInt(str);
System.out.println("Casting string to int: " + num5);