This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Given these declarations: int i = 5; short s = 3; char c = 'a'; byte b = 2; The following stuff compiles and I don't know why... s += i; c += i; b += i; The following stuff does NOT compile (needs explicit cast) and I don't understand WHY NOT if the first stuff did! s = s + i; c = c + i; b = b + i;
int i = 5; short s = 3; char c = 'a'; byte b = 2; The following stuff compiles and I don't know why... s += i; c += i; b += i; the way the above above works is s+=i; is actually seen by JVM as s=(short)(s+i); casting is done by JVM whereas s=s+i; //it needs an explicit cast similarly for the other cases
Thats because when you use the operation and the assignment at the same time i.e += there is an implicait cast included...hence s+=i is equivalent to s = (short)s+i; but when you say s = s + i,there is no casting done and you get a compile time error. Rashmi