While practicing Java I randomly came up with this:
class test { public static void main(String arg[]) { char x='A'; x=x+1; System.out.println(x); } }
I thought it will throw an error because we can't add the numeric value 1
to the letter A
in mathematics, but the following program runs correctly and prints
B
How is that possible?
You can't. Strings are immutable. You can just reference a new string object that has 0 characters.
The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.
In Java, char
is a numeric type. When you add 1
to a char
, you get to the next unicode code point. In case of 'A'
, the next code point is 'B'
:
char x='A'; x+=1; System.out.println(x);
Note that you cannot use x=x+1
because it causes an implicit narrowing conversion. You need to use either x++
or x+=1
instead.
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