When one type of
variable (source) is assigned to another type of variable (destination), an
automatic type conversion will occur if the type of the destination variable wide
is enough and able to hold the entire range of the source variable. Automatic
type conversion is also called as widening conversion.
Following table shows
the width and ranges of primitive data types.
|
Type
|
Width in bits
|
How range is derived
|
Range
|
|
Char
|
16
|
2^16
|
0 to 65,536
|
|
Integer
data types
|
|||
|
Byte
|
8
|
(-2^7) to (2^7-1)
|
-128 to +127
|
|
Short
|
16
|
(-2^15) to (2^15-1)
|
-32,768 to +32,767
|
|
Int
|
32
|
(-2^31) to (2^31-1)
|
-2,147,483,648 to +2,147,483,647
|
|
Long
|
64
|
(-2^63) to (2^63-1)
|
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
|
|
Floating-point
data types
|
|||
|
Float
|
32
|
IEEE-754 standard
|
1.4e-045 to 3.4e+038
|
|
Double
|
64
|
IEEE-754 standard
|
4.9e-324 to 1.8e+308
|
In the below table,
cells highlighted in Green results in the widening conversion and the cells highlighted
in blue results in the “narrowing conversion”.
The cells highlighted in
blue will result in compilation error unless we explicitly cast the source
variable type to the destination variable type.
|
char = char
|
byte = byte
|
short = byte
|
int = char
|
long = char
|
float = char
|
double = char
|
|
char = byte
|
byte = char
|
short = short
|
int = byte
|
long = byte
|
float = byte
|
double = byte
|
|
char = short
|
byte = short
|
short = char
|
int = short
|
long = short
|
float = short
|
double = short
|
|
char = int
|
byte = int
|
short = int
|
int = int
|
long = int
|
float = int
|
double = int
|
|
char = long
|
byte = long
|
short = long
|
int = long
|
long = long
|
float = long
|
double = long
|
|
char = float
|
byte = float
|
short = float
|
int = float
|
long = float
|
float = float
|
double = float
|
|
char = double
|
byte = double
|
short = double
|
int = double
|
long = double
|
float = double
|
double = double
|
Example for widening
conversion
In the below example, char variable ‘charVar’ is assigned to an integer
variable ‘intVar’. Since integer can hold entire range of char values, this assignment
is allowed. Java internally converts the Unicode value of the ‘charVar’ to 32 bit
integer value and assigns it to ‘intVar’.
class MyClass {
public static void main(String arg[]) {
int intVar;
char charVar = 'x';
intVar = charVar;
}
}
Example for narrowing
conversion
A ‘char’ variable cannot
be assigned integer, floating-point variables because it won’t be able to hold
entire range of those data types. So, to make the assignment to work, we
need to explicitly cast the source variable type to char.
In the below example, integer variable ‘intVar’ is cast to ‘char’ to
avoid the compilation error.
class MyClass {
public static void main(String arg[]) {
int intVar = 100;
char charVar;
charVar = (char)intVar;
}
}
Note that narrowing conversion may result in the loss of
precision.
No comments :
Post a Comment