-1
public static void main(String []args)
{    
     char x = 'A';    
     System.out.println(x++ + ++x);         //In Java
     Console.WriteLine(x++ + ++x);          // In C#
}

In the sample program above I was expecting the output to be 133 .Here is how I evaluated . Since both post and pre increments take precedence over '+' ,it will get evaluated first

Step 1: System.out.println(66 + 67)

Step 2: System.out.println(133)

When will the x become 66 in the post increment operation . Is it in the next line that the value becomes 66 , I am a bit confused in this regard .

user1400915
  • 1,933
  • 6
  • 29
  • 55

2 Answers2

0

65 + 67 because x++ will perform after the line has finished executing and ++x will perform during execution.

  • 3
    `x++` increments the value by 1 not "after the line", but after expression `x++` returned the value. And expression `++x` increments the value by 1 before it returns the value. – Jaroslaw Pawlak Jun 18 '18 at 10:09
  • @JaroslawPawlak To be very pedantic, the postfix operator will temporarily save the contents of `x`, then increment the variable `x` and then return the saved contents. An operator is very similiar to a function and a function cannot *do* something after it has returned. – Freggar Jun 18 '18 at 10:20
0

The x becomes 66 soon, after the + operator. After that operator, the x is again incremented so it becomes 66+1. Therefore, it looks like this: 65+67 which is 132.

When considering what the computer actually does...

x++: load x from memory, use, increment, store back to memory.

++x: load x from memory, increment, use, store back to memory.