This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma 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