Search code examples
javasubtractionpostfix-operatorprefix-operator

Java: Prefix - Postfix issue


I have a small issue performing a subtraction on numbers using prefix and postfix operators. This is my program:

public class postfixprefix  
{  
  public static void main (String args[])  
  {  
    int a = 5;  
    int b;  
    b = (a++) - (++a);  
    System.out.println("B = " +b);  
  }  
}  

Doing this, theoretically I am supposed to get 0 as the answer, but however, I am getting a -2.

When I try to individually try to increment the values like in this program:

public class postfixprefix  
{  
  public static void main (String args[])  
  {  
    int a = 5;  
    int b, c;  
    b = a++;  
    c = ++a;  
    System.out.println("B = " +b);  
    System.out.println("C = " +c);  
  }  
}

I get the values as B = 5, C = 7.

So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is

  1. How can I have it not take the value of 'a' from 'b', and
  2. using prefix - postfix, can I have 0 as an answer when they're subtracted.

Solution

  • b = a++; means:

    1. assign to b the value of a
    2. increase a by 1

    c = ++a means:

    1. increase a by 1
    2. assign to c the value of a

    b = (a++) - (++a) means:

    1. get the value of a (5) (a without the ++)
    2. increase the value of a by 1 (thus making it 6) (the result of a++)
    3. increase a by 1 (++a) (thus making it 7)
    4. assign to b thae value 5-7=-2 (5 from step 1, 7 from step 3)