+ 1

Casting char in java

Can anyone tell me why this doesn't work please as i thought this would cast letters from A upwards but keep getting numbers? char str = 'A'; for(int i = 0; i<100;++i){ System.out.println((char)str+i);}

17th Dec 2017, 12:36 AM
D_Stark
D_Stark - avatar
7 Respostas
+ 7
That's because 'str' is already a char type variable. And statements are executed from left to right. And when doing math, the result is casted automatically to the larger type (char to int - in that case). It's executed like that: ((char) str) + i - and you get an integer result It should be: (char) (str + i) - gets the integer result first, and then casting it to char.
17th Dec 2017, 12:55 AM
Boris Batinkov
Boris Batinkov - avatar
+ 9
You could also do something simple like this: for(char i = 'A'; i <= 'Z'; ++i) { System.out.println(i); }
17th Dec 2017, 1:00 AM
ChaoticDawg
ChaoticDawg - avatar
+ 5
Just change the last line to System.out.println((char)(str+i));}
17th Dec 2017, 12:46 AM
MuzzRK
MuzzRK - avatar
+ 5
It naturally comes from the mathematic. Example: x = 4 + 4 / 2 * 4 x = 4 + 2 * 4 x = 4 + 8 x = 12 As we know, the multiplying and the dividing comes before the addition and the subtraction. But what's in the parentheses is calculated first. x = (4 + 4) / (2 * 4) x = 8 / 8 x = 1 Or: x = ((4 + 4) / 2) * 4 x = (8 / 2) * 4 x = 4 * 4 x = 16 In the programming is recomended to use parentheses, even when the calculations are obvious. x = 5 + 3 - 2 => x = (5 + 3) - 2 Or: x = 5 > 6 || 8 > 6 => x = (5 > 6) || (8 > 6)
17th Dec 2017, 11:20 AM
Boris Batinkov
Boris Batinkov - avatar
+ 4
It's because you're casting str then adding 1 to it. So, all you need to do is as @MuzzRK stated to make sure that the cast happens after the value is chnged.
17th Dec 2017, 12:50 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
thanks for your help guys ☺ @ boris were do i learn to use parenthisis like this properly as i havent been taught this in school and i see alot of people using this with multiple numbers and parenthisis in for() loops. thanks
17th Dec 2017, 8:54 AM
D_Stark
D_Stark - avatar
+ 2
@boris thank you thats brilliant i understand it now and if the order of operation has parenthisis do that first 😉
17th Dec 2017, 7:54 PM
D_Stark
D_Stark - avatar