Widening conversions do not lose information about the magnitude of a value.
For example, an int
value is assigned to a double
variable.
This conversion is legal because doubles are wider than ints.
Java's widening conversions are
Widening conversions:
char->int
byte->short->int->long->float->double
Here are the Type Promotion Rules:
byte
and short
values are promoted to int
. long
, the whole expression is promoted to long
.float
, the entire expression is promoted to float
. double
, the result is double
.
In the following code, f * b
, b
is promoted to a float
and the result of the subexpression is float
.
public class Main {
public static void main(String args[]) {
byte b = 4;
float f = 5.5f;
float result = (f * b);
System.out.println("f * b = " + result);
}
}
The output:
f * b = 22.0
In the following program, c
is promoted to int
,
and the result is of type int
.
public class Main {
public static void main(String args[]) {
char c = 'a';
int i = 50000;
int result = i / c;
System.out.println("i / c is " + result);
}
}
The output:
i / c is 515
In the following code the value of s
is promoted to double
,
and the type of the subexpression is double
.
public class Main {
public static void main(String args[]) {
short s = 1024;
double d = .1234;
double result = d * s;
System.out.println("d * s is " + result);
}
}
The output:
d * s is 126.3616
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |