Java
permits mixing of constants and variables of different types, but during
execution it follows type conversions.
In Java, type casting can be done in two ways. They are
1. Implicit Type Casting 2. Explicit Type Casting
1.
Implicit Type Casting: In an expression, if the operands are of
different types the lower type is automatically converted to the higher type
before the operation preceeds by the Java Interpreter. The result is of the higher type. Such type of casting is called Implicit Type
Casting. In Implicit Type Casting there
is no loss of data. The following are some
of implicit type castings with no loss of data
from to
byte short, char, int, long,
float, double
short char, int, long, float,
double
char int, long, float, double
int long, float, double
long float, double
float double
2.
Explicit Type Casting: If we want to force to convert the
operands of an expression from one type to another type depending on user
choice, such type of casting is called Explicit Type Casting. In Explicit Type Casting there is a chance of
data loss when we convert the operands from higher type to lower type. The process of converting the value is known
as Casting a value. The general form of
casting is as
Syntax: (datatype) expression;
Example: x = (int) 7.5;
Note: The final result of an expression is
converted to the type of the variable before assigning to the left hand side
variable. In such case following chances
are introduced.
Ø
float to int causes truncation of the fractional
part
Ø
double to float causes rounding of digits
Ø
long to int causes dropping of the excess of
higher order bits
No comments:
Post a Comment