Type conversion in Java with Examples
In a
mixed java expression the data type get converted to a higher type without any intervention
and this conversion converted into a single type is known as data type
conversion.
What is typecasting?
When
data type converted to another type by the user then that is called type
casting.
How many types of type conversion?
There
are two types of type conversion as follows
- Implicit or Widening or Automatic Type Conversion
- Explicit or Narrowing Conversion
Implicit or Widening or Automatic Type Conversion
In implicit
or Widening type conversion the data type convert automatically from lower to
higher
byte
------->char ------->short ------->int ------->long ------->float
------->double
int x;
float
y;
double
z;
z =
x + y + x * y;
In
the above code int and float automatically converted to double and this
widening or implicit typecasting.
In
the following code ‘variable a’ is defined as int and while division it
converted to double and the result comes as 3.3333333333333335
public
class ImplicitConversion
{
public static void main(String args[])
{
int a;
double b, c;
a = 10;
b = 3.0;
c = a / b;
System.out.println(c);
}
}
Explicit or Narrowing Conversion
double ------->float ------->long ------->int ------->short ------->char ------->byte
The explicit or narrowing type casting done by the user requirement.
Say
double
a;
int
b;
now
if we want (a that is double data type) to be converted into int type then we
need do so as
b =
(int) a;
double
is converted to int in the above expression.
Example
public
class ExplicitConversion
{
public static void main(String args[])
{
int a;
double c, b;
c = 10.0;
b = 3.0;
a =(int)(c/b);
System.out.println(a);
}
}
In the
above code, double is converted to int type and after the division it prints
3
Not
3.3333333333333335
Conclusion
Explicit the conversion must be done properly otherwise error will be there or might be the exact result will not come.
Java program