In this snippet of code:
c = (char)(c - 'A' + 'a');
Why do we need the (char)
? That's type casting right?
Assume the c
on the right side of the assignment statement is a capital letter. I assume we're doing Unicode addition and subtraction here.
This is the snippet from the Java book that I'm reading:
When arithmetic is done on a char, it is first converted to the int that represents it in the Unicode system. Subtracting ’A’ from a variable c essentially asks “How far into the upper-case letters is the character in c?” Adding ’a’ then yields the int that is the same distance into the sequence of lower-case alphabetic character code. The cast to char is needed because char is a special kind of int with a more limited range of values. By using the cast, the programmer acknowledges that he or she understands the special nature of the assignment and expects the value to be in the correct range, 0 through 66535.
I don't understand the point of the (char)
cast? What would be different if we didn't use the (char)
cast? What is casting more generally?
char
is an integral type in Java, and when you perform arithmetic the result is an int
(JLS-4.2.2. Integer Operations says, in part, the numerical operators, which result in a value of type int
or long
and adds that does include the additive operators +
and -
).
char c = 'A';
System.out.printf("'%c' = %d%n", c, (int) c);
int d = (c - 'A' + 'a'); // c - 65 + 97
System.out.printf("'%c' = %d%n", (char) d, d);
And I get
'A' = 65
'a' = 97
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With