Implicit Casting: A lower size data type can be assigned to a higher size data type automatically. It is also called Widening.
byte -> short -> char -> int -> long -> float -> double
Example: char c = 'A';
int i = c;
Explicit Casting: A higher size data type can be assigned to a lower size data type manually. It is also called Narrowing.
double -> float -> long -> int -> char -> short -> byte
Example: long val = 10;
int x = (int)val;
Example of Implicit Casting.
public class Main
{
public static void main(String[] args) {
int x = 8;
double y = x; //Implicit casting
System.out.println(x);
System.out.println(y);
}
}
Output
8 8.0
Example of Explicit Casting.
public class Main
{
public static void main(String[] args) {
double x = 8.23;
int y = (int)x; //Implicit casting
System.out.println(x);
System.out.println(y);
}
}
Output:
8.23 8
No comments:
Post a Comment