Incrementing Char Type In Java

前端 未结 10 1575
鱼传尺愫
鱼传尺愫 2020-12-03 05:08

While practicing Java I randomly came up with this:

class test
{
    public static void main(String arg[])
    {
        char x=\'A\';
        x=x+1;
                


        
相关标签:
10条回答
  • 2020-12-03 05:26

    you have to type cast the result after adding using parenthesis like this:

    x='A';
    x = (char) (x+1);
    

    else you will get loose of data error.

    0 讨论(0)
  • 2020-12-03 05:30

    char is a numeric type (2 bytes long), and is also the only unsigned numeric primitive type in Java.

    You can also do:

    int foo = 'A';
    

    What is special here is that you initialize the char with a character constant instead of a number. What is also special about it is its string representation, as you could witness. You can use Character.digit(c, 10) to get its numeric value (as an int, since 2 ^ 16 - 1 is not representable by a short!).

    0 讨论(0)
  • 2020-12-03 05:30

    char are stored as 2 byte unicode values in Java. So if char x = 'A', it means that A is stored in the unicode format. And in unicode format, every character is represented as an integer. So when you say x= x+1, it actually increments the unicode value of the A, which prints B.

    0 讨论(0)
  • 2020-12-03 05:34

    Because type char effectively works like a 16-bit unsigned int.

    So setting char x='A' is almost equivalent to int x=65 When you add one; you get 66; or ASCII 'B'.

    0 讨论(0)
提交回复
热议问题