Casting char in java | Sololearn: Learn to code for FREE!

+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);}

12/17/2017 12:36:14 AM

D_Stark

7 Answers

New Answer

+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.

+9

You could also do something simple like this: for(char i = 'A'; i <= 'Z'; ++i) { System.out.println(i); }

+5

Just change the last line to System.out.println((char)(str+i));}

+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)

+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.

+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

+2

@boris thank you thats brilliant i understand it now and if the order of operation has parenthisis do that first 😉