What is type casting and why do we need it?
Suppose we have a variable of type float and we are assigning it a value of type int then there is no problem since it will automatically converted to float but suppose we have a variable of type int and we are assigning it a value of type double then what will happen? Compiler will throw an error (Type mismatch: cannot convert from double to int) since it cannot convert the double to int implicitly,we have to do it explicitly by casting that double value to int value.
for example: int i=10.0 //error
int i =(int) 10.0;//no error since casted to int implicitly
So in this case we need type casting.Type casting is needed where we can have the data loss.Since if we want to convert value double to int then there will be data loss, all the digits after dot(.) will be lost.
For example:
1) int i=10;
valid since we are assigning int value to int type of variable.
Output: i=10
2) float f=10;
valid since automatic conversion will be done with no data loss.
Output: f=10.0
3)float f=12.0;
error since we cannot assign double to a float.Here you can think why it is double, so i can tel you if you write any number with dot(.) then it will be by default double.We can convert it into float in two ways:
typecasting or apply f
float f= (float) 12.0;
or float f=12.0f;
4)int i=12.0;
error since cannot assign double value to int variable.
int i=(int) 12;
no error
So in this way we can use typecasting in Java.
Suppose we have a variable of type float and we are assigning it a value of type int then there is no problem since it will automatically converted to float but suppose we have a variable of type int and we are assigning it a value of type double then what will happen? Compiler will throw an error (Type mismatch: cannot convert from double to int) since it cannot convert the double to int implicitly,we have to do it explicitly by casting that double value to int value.
for example: int i=10.0 //error
int i =(int) 10.0;//no error since casted to int implicitly
So in this case we need type casting.Type casting is needed where we can have the data loss.Since if we want to convert value double to int then there will be data loss, all the digits after dot(.) will be lost.
For example:
1) int i=10;
valid since we are assigning int value to int type of variable.
Output: i=10
2) float f=10;
valid since automatic conversion will be done with no data loss.
Output: f=10.0
3)float f=12.0;
error since we cannot assign double to a float.Here you can think why it is double, so i can tel you if you write any number with dot(.) then it will be by default double.We can convert it into float in two ways:
typecasting or apply f
float f= (float) 12.0;
or float f=12.0f;
4)int i=12.0;
error since cannot assign double value to int variable.
int i=(int) 12;
no error
So in this way we can use typecasting in Java.
0 comments:
Post a Comment