Type Casting:
We can assign primitive datatypes one to another. This is called casting. The process of casting is governed by some rules.Rules of Casting:
1. The data types must be compatible. That is a boolean value is incompatible and cannot be assigned to any other type.2. A datatype of lower size can be assigned to data type of higher size and is done implicitly.
3.A data type of higher size cannot be assigned to data type lower size implicitly and is done explicitly.
Implicit Casting:
When we assign variable of data type of lesser memory size to variables of higher memory size, the system does casting implicitly. For example:
int x=100;
double d=x;
In the above case casting is done implicitly by the system as we are assigning x of data type int to d of data type double. This is called 'widening conversion' and is done implicitly.
Explicit casting:
When we assign variables of data type of higher memory size to variables of lesser memory size, system does not perform implicit casting. We have to do ourselves the casting. This is called explicit casting. In explicit casting data will be truncated or precison of the value is lost. For example:double d=10.5;
//int x=d; //raises compilation error
int x=(int) d;
In the above example, casting is done explicitly by us as we are assigning d of data type double to x of data type int. This is called narrowing conversion.
No comments:
Post a Comment