Hi friends i am going to you the type conversion and cast of java if the two variables are compatible then java perform the conversion automatically.
For example it is always possible to assign an integer value to long type of variable.And if the variables are not compatible then there is not any explicit conversion in the assignment for instance there is no conversion from double to int.
Java's automatic conversion:
When one type of variable is assigned to another type of variable,an automatic conversion will take place if the following conditions are met:
If we have two incompatible types then we have to a cast it.What if you want to assign a int value to a byte type of variable then implicit conversion cannot take place in Java. We have to put the value of integer into byte so this kind of conversion is sometimes called narrowing conversion since you are explicitly making the value in narrower.
How to create a conversion between two incompatible types we have to use a general form:
target type( value) ;
the target type specifies the target type to convert a specified value
for example
int a;
byte b;
b=(byte) a;
Automatic Type Promotion in Expressions
byte b=50;
b=b*2;//error
because the sub expression b*2 is converted to int and then this is evaluated.So the correct expression is
b=(byte)b*2;
For example it is always possible to assign an integer value to long type of variable.And if the variables are not compatible then there is not any explicit conversion in the assignment for instance there is no conversion from double to int.
Java's automatic conversion:
When one type of variable is assigned to another type of variable,an automatic conversion will take place if the following conditions are met:
- The two types are compatible
- The destination type is larger than source type
If we have two incompatible types then we have to a cast it.What if you want to assign a int value to a byte type of variable then implicit conversion cannot take place in Java. We have to put the value of integer into byte so this kind of conversion is sometimes called narrowing conversion since you are explicitly making the value in narrower.
How to create a conversion between two incompatible types we have to use a general form:
target type( value) ;
the target type specifies the target type to convert a specified value
for example
int a;
byte b;
b=(byte) a;
Automatic Type Promotion in Expressions
byte b=50;
b=b*2;//error
because the sub expression b*2 is converted to int and then this is evaluated.So the correct expression is
b=(byte)b*2;
0 comments:
Post a Comment