Java Char increment

952 views Asked by At

I was executing the following code

class First
{

 public static void main(String arg[])
        {
            char x= 'A';
            x = x++;
            System.out.println(x);
        }
}

Here the output is A. My question is why didn't x get incremented before printing.

2

There are 2 answers

0
Andrzej Doyle On BEST ANSWER

You're using the post-increment operator incorrectly - you don't need to use assignment as well. And in this case it undermines what you're trying to do.

For context, remember that the post-increment operator increases the value, and returns the old value. That is, x++ is roughly equivalent to:

int x_initial = x;
x = x + 1;
return x_initial;

Hopefully now you can see why your code is failing to change x. If you expand it, it looks like:

char x= 'A';
char y;
{
    y = x;
    x = x + 1;
}
x = y;
System.out.println(x);

and the net effect of the assignment, is to set x back to what it was originally.


To fix - you can simply call x++. Or, if you want to make it clear there's some sort of assignment happening, x += 1 or even just x = x + 1 would do the same thing.

0
kirti On
class First
{

 public static void main(String arg[])
        {
            char x= 'A';
            x = x++;   // it is post increment as ++ sign is after x
            System.out.println(x);
        }
}

Post Increment(x++) : First execute the statement then increase the value by one.

Pre Increment (++x) : First increase the value by one then execute the statement.