Type Conversion
Implicit and Explicit |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
byte
(1 byte)short
(2 bytes)int
(4 bytes)long
(8 bytes)byte
to short
: pad with one byte of 0sshort
to int
: pad with two bytes of 0sint
to long
: pad with four bytes of 0s00010011 |
00000000 | 00010011 |
byte
(-19 base 10):
11101101 |
short
:
11111111 | 11101101 |
byte
):
10000000 |
short
):
00000000 | 10000000 |
short
):
11111111 | 10000000 |
float
:
double
:
float
to double
Conversions:
long
to float
Conversions:
int small; long large; . . . large = small;
large = large + small;
int small; long large; small = (int)large;
public class NarrowingExample { public static void main(String[] args) { float fmax, fmin; fmax = Float.POSITIVE_INFINITY; fmin = Float.NEGATIVE_INFINITY; JMUConsole.println("long: "+(long)fmin +".."+(long)fmax); JMUConsole.println("int: "+(int)fmin +".."+(int)fmax); JMUConsole.println("short: "+(short)fmin+".."+(short)fmax); JMUConsole.println("byte: "+(byte)fmin +".."+(byte)fmax); } }