Java allows you to assign a value of 1 type to a variable of another type. If 2 types are compatible then the java will perform type conversion automatically.
However , not all types are compatible in java. To do so and convert types explicitly , we use Cast , which performs an explicit type conversion B/W incompatible types.
Java's Automatic conversion
When 1 type of data is assigned to another type of variable , an automatic type conversion will take place.
It occurs under 2 conditions:
- The 2 types are compatible.
- The destination type is larger than source type.
When the 2 conditions are met , a Widening conversion takes place.
Ex- the int type is large enough to hold all valid byte values, so no explicit cast statement is required.
When the 2 conditions are not met , a narrowing conversion takes place.
Ex- If we want to store int values in byte then we need to create a conversion b/w 2 types using a cast .
The Syntax for the same is ( target type ) value
Here , target type specifies the desired type to convert the specified value to.
When a floating type value is assigned to an integer type , then different type of conversion will occur called as Truncation .
Ex- when a floating point value is assigned to an integer type , the fractional component is lost.
By: Knowledge Bits
No comments:
Post a Comment