0

I want to get next character and I am writing the code like this

char c = 'A';
c = c++;
System.out.println(c);

The printed character is A. But if I use preincrement operator with 'c' then I get next character (B). Here is the code with preincrement operator.

char c = 'A';
c = ++c;
System.out.println(c);

Can someone explain the difference?

2 Answers2

2

The increment operator doesn't make sense if you assign that result back to the variable. Doing

c = c++;

takes the return value of c++, which is 'A', and assigns that to c. Instead, simply do

c++;  // or ++c

In your case, you probably want to do

System.out.println(++c);  // prints 'B', and |c| is now 'B'
clabe45
  • 2,354
  • 16
  • 27
0

c = c++; means, first the current value will be used and then it will be incremented. Therefore it's first printing the current value

c = c++;
System.out.println(c);

translates to:

c = c; // since the actual value is returned first
System.out.println(c);

and hence, the value A get printed.

Whereas

c = ++c;
System.out.println(c);

translates to

c = c+1;
System.out.println(c);
mrid
  • 5,782
  • 5
  • 28
  • 71
  • 1
    The first example doesn't increment `c` at all if is a local variable (a field would be incremented for a very short time before the assignment resets it, possibly leading to multithreading issues) – Clashsoft Oct 13 '18 at 12:26
  • @Carcigenicate , oh my bad...thanks for correcting :) – mrid Oct 13 '18 at 12:27