File: /home/cs255001/demo/java/JavaExprEval.java
public class JavaExprEval
{
public static void main(String[] arg)
{
byte b1 = 44, b2 = 22;
short s;
s = b1; // Will this statement cause an error ?
s = b1+b2; // Will this statement cause an error ?
}
}
|
The answer is below...
In other words: one code (= representation) must be converted into another code (= representation) before the operation can take place.
Java's safe conversions:
byte ---> short ---> int
|
You may also remember that:
|
That means:
|
See if you can apply this Java rule and figure out what's going on in this program.
File: /home/cs255001/demo/java/JavaExprEval.java
public class JavaExprEval
{
public static void main(String[] arg)
{
byte b1 = 44, b2 = 22;
short s;
s = b1; // Will this statement cause an error ?
s = b1+b2; // Will this statement cause an error ?
}
}
|
Answer:
cheung@aruba> javac JavaExprEval.java
JavaExprEval.java:12: error: incompatible types: possible lossy conversion from int to short
s = b1+b2; // Error, because Java converts byte to int before adding
^
|
|
Examples:
Value byte (8 bits 2s compl code) int (32 bits 2s compl code)
------- ---------------------------- ----------------------------------
127 01111111 00000000000000000000000001111111
...
3 00000011 00000000000000000000000000000011
2 00000010 00000000000000000000000000000010
1 00000001 00000000000000000000000000000001
0 00000000 00000000000000000000000000000000
-1 11111111 11111111111111111111111111111111
-2 11111110 11111111111111111111111111111110
-3 11111101 11111111111111111111111111111101
...
-128 10000000 11111111111111111111111110000000
|
Notice that:
|
Quiz on int --> byte casting:
|
Answer:
b = (byte) i will assign 00000100 to b 00000100 represents the value 4 |
To show you that this is the correct answer, I have written this Java program:
/home/cs255001/demo/java/JavaByteIntCast.java |
I will compile and run it in class. You can try it out yourself if you did not attend class....
|
Examples:
Value short (16 bits 2s compl code) int (32 bits 2s compl code)
------- ---------------------------- ----------------------------------
32767 0111111111111111 00000000000000000111111111111111
...
3 0000000000000011 00000000000000000000000000000011
2 0000000000000010 00000000000000000000000000000010
1 0000000000000001 00000000000000000000000000000001
0 0000000000000000 00000000000000000000000000000000
-1 1111111111111111 11111111111111111111111111111111
-2 1111111111111110 11111111111111111111111111111110
-3 1111111111111101 11111111111111111111111111111101
...
-32768 1000000000000000 11111111111111111000000000000000
|
Notice that:
|
Quiz on int --> short casting:
|
Answer:
s = (byte) i will assign 0000000000000110 to s 0000000000000110 represents the value 6 |
To show you that this is the correct answer, I have written this Java program:
/home/cs255001/demo/java/JavaShortIntCast.java |
I will compile and run it in class. You can try it out yourself if you did not attend class....