Originally posted by deepa:
thanks.
could u please give me some example of the following line.
1. The expression is a constant expression of type byte, short, char or int.
Sure, here are your examples :
byte b1 = 42; // 42 is a constant expression of type int
------------------------------------------------------
final int i = 10; // NOTE : s is a final variable
byte b2 = i; // i is a constant expression of type int
------------------------------------------------------
short s = 25; // 25 is an integer constant
------------------------------------------------------
char c = 65; // 65 is an integer constant
------------------------------------------------------
Therefore only integer constant expressions can be used as expressions.
According to my understanding, The JLS mentions byte, short, char along with int in the following statement :
"The expression is a constant expression of type byte, short, char or int"
because they want to include identity conversion as well such as :the following types :
char c = 'c';
Note :
A byte value must be an integer value in the range -128..127.
A short value must be an integer value in the range -32768..32767.
A character literal must be a valid unicode value - i.e., a character literal enclosed in single quotes or an integer value in the range 0..65535 or
an escaped 3-digit octal value in the range \000..\377.
(note that a character literal is not an integer value)
This point is important in
Java It means an 'a' is not equvalent to integer 97 like in C or C++.
a 'a' is simply an Unicode 'a' although internally they may be stored as an unsigned 16 bit integer.
Therefore its not possible to say byte b = 'a';
but byte b = 97 is allowed because 97 is representable in a byte.
Now I have a question for u deepa,
tell me why is the following code an error :
class Testdeepa {
final short s = 42;
byte b = s;
}
The above code is as per the JLS specificaition yet it gives an error !
Can anyone explain the reasoning that A byte value must be an integer value in the range -128..127.
Why can't it be a short like in the above example ?
[This message has been edited by Deepak M (edited July 18, 2000).]