Java - short and casting
Posted
by chr1s
on Stack Overflow
See other posts from Stack Overflow
or by chr1s
Published on 2010-04-27T11:34:40Z
Indexed on
2010/04/27
11:43 UTC
Read the original article
Hit count: 549
Hi all,
I have the following code snippet.
public static void main(String[] args) {
short a = 4;
short b = 5;
short c = 5 + 4;
short d = a;
short e = a + b; // does not compile (expression treated as int)
short z = 32767;
short z_ = 32768; // does not compile (out of range)
test(a);
test(7); // does not compile (not applicable for arg int)
}
public static void test(short x) { }
Is the following summary correct (with regard to only the example above using short)?
- direct initializations without casting is only possible using literals or single variables (as long as the value is in the range of the declared type)
- if the rhs of an assignment deals with expressions using variables, casting is necessary
But why exactly do I need to cast the argument of the second method call taking into account the previous summary?
© Stack Overflow or respective owner