Java: Type Conversion
Type Conversion
Conversion of one data type by deducing the structure of the expression and the types of literals, variables and methods mentioned in the expression, to another data type is known as Type Conversion or Type Casting.
Following are the types of Type Conversion:
Widening Conversion.
Narrowing conversion.
Narrowing conversion.
Following are the types of Type Conversion:
Widening Conversion.
Narrowing conversion.
Narrowing conversion.
Widening Conversion
- Converting a data type of smaller size to a data type of larger size is known as Widening conversion.
- This type of casting/conversion is done automatically hence, it is also known as implicit type casting.
- The condition for this case of conversion is that the data types should be compatible with each other.
- In this type of data conversion we neither have any error nor any loss of data whatsoever.
Let us understand through an example-
Run
public class Main { public static void main(String[] args) { int num = 500; long l = num; float f = l; System.out.println("Int type value "+num); System.out.println("Long type value "+l); System.out.println("Float type value "+f); } }
Output :
Int type value 500
Long type value 500
Float type value 500.0
Narrowing Conversion
- Converting a data type of larger size to a data type of smaller size is known as Narrowing conversion.
- This type of conversion does not occur automatically, hence we need to convert explicitly using the cast operator “( )” explicitly. Thus, it is also known as explicit type casting.
- This is useful for incompatible data types where automatic conversion cannot be done.
- One of the drawbacks of narrowing conversion is the loss of data.
Let us understand through an example-
Run
class Main { public static void main(String[] args) { double d = 560.025; long l = (long)d; int num = (int)l; System.out.println("Double type value "+d); System.out.println("Long type value "+l); System.out.println("Int type value "+num); } }
Output :
Double type value 560.025
Long type value 560
Int type value 560
Permitted Conversions
Widening conversion
byte | short, int, long, float, double |
short | int, long, float, double |
char | int, long, float, double |
int | long, float, double |
long | float, double |
float | double |
Narrowing Conversion
short | byte, char |
char | byte, short |
int | byte, short, char |
long | byte, short, char, int |
float | byte, short, char, int, long |
double | float, byte, short, char, int, long |
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment