This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line! See this thread for details.
its a simple question: would this work byte b=20+30 yes it would coz the addition is for constant values and the compiler can determine that the result would be in range of byte. Thats the case with the char values as well. But if u compile the following code: char ch='2'; char ab='3'; char a=ch+ab Then this wont compile,coz the addition is between variables and this will be subjected to binary numeric promotion.
Ana, check it out again, you should get the following: 1) char c='1'+'8' makes c='i' 2) char c='1'+'2' makes c='c' What happens here is that the compiler will make an integer calculation and then allocate that value to the char "c". In the first example it will calculate 49+56=106, which is the Unicode value of 'i'. In the second example it will calculate 49+50=99, which is the Unicode value of 'c'. Eduard
Originally posted by Asif Masood: I am bit confused from the different behaviour for almost same expresion. ... Why it's so.
Well, the hard-core answer is "because the Java language spec says so, and that is what you will be tested on". Practically, it is a mixture of language design (and hence arbitrary) and the difficulties in writing a compiler to make deductions about ranges of values based on variables and previous statements. The issue you've spotted may seem inconsistent, but oh well, it is there. Think of "+=" as having more in common with "++" than a sequence of "a+b; a=b" statements. "++" doesn't cause promotion either.