The process of converting the value of one data type(int,float,double) to another data type is called as Type casting.
There are two types:
1. Primitive casting
a. Widening/implicit
b. Narrowing/explicit
2. Derived casting
a.Upcasting
b. Downcasting
1.Primitive casting :
Converting one primitive type to another primitive type is called as Primitive casting.
a.Widening:
Converting a lower datatype to higher data type is called as widening.
- Widening will be performed by the compiler implicitly.
ex: class Vijay{
public static void main (String [ ]args){
int x=10;
double y=x;
System.out.println("x="+ x);
System.out.println("y="+ y);
}
}
Output:
x=10
y=10.0
b.Narrowing:
Converting higher datatype value to lower data type value is called as narrowing.
- Narrowing should be done by the programmer explicitly by writing the casting statement.
Syntax: (datatype) variable/value;
ex:
class Vijay{
public static void main (String [ ] args){
double y=36.59;
int x=(int)y;
System.out.println("y="+y);
System.out.println("x="+x);
}
}
output: y=36.59
x=36
1. To convert int to double
int a=10;
double b=a;
output: 10.0
2. To convert double to int
double a= 10.99;
int b=(int)a;
output: 10
3. To convert int to String
int a= 10;
String b=String.valueOf(a);
output: 10
4. To convert String to int
String a= "10";
int b= Integer.parseInt(a);
5. To convert String to Boolean
String s="true";
boolean b = Boolean.parseBoolean(s);
output: true
2. Derived casting:
Converting one reference to another reference is called Derived casting.
a.Upcasting:
Converting subclass reference to superclass reference is called as upcasting.
- To perform upcasting create object of subclass and store the address in superclass reference variable.
Superclass ref= new subclass();
Subclass ref= new Subclass();
Superclass ref1=ref;
- If the object is upcasted then from the upcasted object it is not possible to access subclass properties.
- Once the object is upcasted, it hides all the subclass properties and shows only superclass properties.
b.Downcasting:
Converting upcasted reference back to subclass reference is called as downcasting.
- We can perform downcasting only after upcasting.
- Downcasting should be done by the programmer explicitly by writing the casting statement.
- Superclass object cannot be downcasted directly because super class object do not contain subclass properties.