I have 2 questions with this code segments
//method 1
static byte m1() {
final char c = 'b'-'a';
return c;
}
//method 2
static byte m3(final char c) {
return c; // 3
}
char
in Java is a 16 bit unsigned value, while byte
is 8 bit signed value. Allowed range for byte is [-128, 127]
. So, not all character can be assigned in byte
.
In your first method, you are returning a char
with code point = 1 ('b' - 'a'
). Now since you have defined char
as final
, and assigning to it a constant expression, it becomes a compile time constant. So, compiler doesn't give any compiler error.
From JLS Section 5.2:
If the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Emphasis mine.
However, if you make c
non-final, it will also result in a compiler error:
static byte m1() { // This will be an error
char c = 'b'-'a';
return c;
}
The reason is, c
is not a compile time constant any more, and compiler doesn't do an implicit downcast.
In 2nd method you are returning the char
that you passed. The parameter c
there is not a compile time constant. It isn't known at compile time what value the method might get.
Like, if you pass a char
with code points not in range of allowed byte
value, it won't work.
To make the 2nd method work, you can do an explicit cast:
static byte m3(final char c) {
return (byte)c; // 3
}