Its very important to understand when implicit type conversion happens and when we need explicit conversion, in case of primitive types.
Implicit narrowing conversion for primitives assignment happens in situations where ALL of the following conditions are satisfied:
1. The source value/variable(so it should be final) is a CONSTANT EXPRESSION of types: byte/short/char/int
2. The target variable must be of type: byte/short/char
3. The value of the source is determined to be in the range of the target type during compile time.
eg:
Implicit conversions:
short s1 = 11;
short s2 = 'b';
char c1 = 33;
char c2 = (byte) 36;
byte b1 = 45;
byte b2 = (short) 43;
final int i1 = 22;
byte b3 = i1;
Explicit Conversion cases:
int i2 = -20;
final int i3 = i2;
final int i4 = 200;
short s3 = (short) i2; //since i2 is not a constant expression
char c3 = (char) i3; //since i3 value cannot be determined, as it is depending on i2
char c4 = (char) i2; //since i2 is not a constant expression
byte b4 = (byte) 128; //int value not in range
byte b5 = (byte) i4; //final value of i4 variable is not in range
Implicit narrowing conversion for primitives assignment happens in situations where ALL of the following conditions are satisfied:
1. The source value/variable(so it should be final) is a CONSTANT EXPRESSION of types: byte/short/char/int
2. The target variable must be of type: byte/short/char
3. The value of the source is determined to be in the range of the target type during compile time.
eg:
Implicit conversions:
short s1 = 11;
short s2 = 'b';
char c1 = 33;
char c2 = (byte) 36;
byte b1 = 45;
byte b2 = (short) 43;
final int i1 = 22;
byte b3 = i1;
Explicit Conversion cases:
int i2 = -20;
final int i3 = i2;
final int i4 = 200;
short s3 = (short) i2; //since i2 is not a constant expression
char c3 = (char) i3; //since i3 value cannot be determined, as it is depending on i2
char c4 = (char) i2; //since i2 is not a constant expression
byte b4 = (byte) 128; //int value not in range
byte b5 = (byte) i4; //final value of i4 variable is not in range
No comments:
Post a Comment