Sunday, 12 February 2012

Type casting

Type casting is the technique which we can use to convert the type of value in the variable from one data type to another data type. The syntax of it is as follow:
 int a=34;
// now you can see that a variable 'a' has value 34 of integer type and if we want to convert it in double type then,
double b;
b=(double)a;
It will change the type of a and store it into b.
This technique is very useful in many cases like
int c=3,d=2,e;
e=c/d;
As we know it will store the quotient 1 in e when we will divide 3/2. But a question arises in our mind that why does it not store 1.5 in e. To do this
double g;
g=(double)c/d;

It creates many logical errors in our programs so we have to take care of it. Type casting automatically occur if value store from a data type having large space to a data type having small space in it. but in opposite case it will store wrong value in that particular variable. So we have to take care of the capacity of variable and then store values as a byte data type variable can't store more then 256 value and similarly with other variables.

No comments:

Post a Comment