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.
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:Hopefully now you can see why your code is failing to change
x
. If you expand it, it looks like: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 justx = x + 1
would do the same thing.