|
public class Caveat2
{
public static void main(String[] args)
{
short a, b, c;
a = 2;
b = 3;
c = a + b; // Compilation error !
}
}
|
Can you see why the statement c = a + b will cause a compilation error ?
|
|
public class Caveat2
{
public static void main(String[] args)
{
short a, b;
a = 2;
b = -a; // Compilation error !
}
}
|
Can you see why the statement b = -a will cause a compilation error ?
|
|
byte ⇒ short ⇒ int ⇒ long |
long a;
int b;
short c;
byte d;
/* ---------------------------------
Automatic conversion happens in
all the following assignments
--------------------------------- */
a = b;
a = c;
a = d;
b = c;
b = d;
c = d;
|
long a;
int b;
short c;
byte d;
/* -----------------------------------
Unsafe assignment requires casting
------------------------------------ */
b = (int) a;
c = (short) a;
c = (short) b;
d = (byte) a;
d = (byte) b;
d = (byte) c;
|
| Type name (keyword) | Range of values |
|---|---|
| byte | −128 . . . 127 |
| short | −32768 . . . 32767 |
| int | −2,147,483,648 . . . 2,147,483,647 |
| long | −9,223,372,036,854,775,808 . . . 9,223,372,036,854,775,807 |
public class Overflow
{
public static void main(String[] args)
{
int x, y, z;
long a, b, c;
x = 1000000;
y = 3000;
z = x * y; // 3,000,000,000 is outside the range of int
System.out.println(z);
a = 1000000;
b = 3000;
c = a * b; // 3,000,000,000 is within the range of long
System.out.println(c);
}
}
|
Output:
-1294967296 (not 3000000000 !!!)
3000000000
|
Explanation:
|
How to run the program:
|
|