Java Reference
In-Depth Information
static int a = 4;
double x = (double) a;
In Java, the following widening conversions are possible:
➤
From a
byte
to a
short
, an
int
, a
long
, a
float
, or a
double
➤
From a
short
to an
int
, a
long
, a
float
, or a
double
➤
From a
char
to an
int
, a
long
, a
float
, or a
double
➤
From an
int
to a
long
, a
float
, or a
double
➤
From a
long
to a
float
or a
double
➤
From a
float
to a
double
A narrowing conversion is when a value of a broader (higher precision) data type is converted to a
value of a narrower (lower precision) data type. This will typically involve loss of information. An
example of this is as follows:
static float b = 6.82f;
int y = b;
Because of Java's strict type checking, this code will not compile and an error will be generated, as
follows:
Type mismatch: cannot convert from float to int
Here, the casting is not done implicitly by the JVM and should be made explicit by the programmer
using the following statement:
int y = (int) b;
In Java, the following narrowing conversions are possible:
➤
From a
byte
to a
char
➤
From a
short
to a
byte
or a
char
➤
From a
char
to a
byte
or a
short
➤
From an
int
to a
byte
, a
short
, or a
char
➤
From a
long
to a
byte
, a
short
, a
char
, or an
int
➤
From a
float
to a
byte
, a
short
, a
char
, an
int
, or a
long
➤
From a
double
to a
byte
, a
short
, a
char
, an
int
, a
long
, or a
float
To conclude, consider the following
TypeCastingExample
class in Java:
public class TypeCastingExample {
// This is our main method.
public static void main(String[] args){
int intA = 4;
Search WWH ::
Custom Search