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
- How can I have it not take the value of 'a' from 'b', and
- using prefix - postfix, can I have 0 as an answer when they're subtracted.
b = a++; means:
c = ++a means:
b = (a++) - (++a) means:
About this code b has a value 5 because posting fix increment/decrement happens after assingment is completed. So the value is 5.
c has a value 7 because prefix increment/decrement happens before assingment is completed. So the value is 7 beause previous statement made the value of a as 6.
About this code
when brackets are applied, your prefix/postfix operations will be completed first in
(a++) - (++a);
from left to right fashion.So firstly if we go left to right
Solutions for you first query -- How can I have it not take the value of 'a' from 'b', and
**Solutions for you first query has been well explained by Sir @Keppil **
If you go through this step by step, you can see what happens:
If you do it the other way, you get:
Its not like this, in
c = ++a;
value is taken from a only, inb = a++;
statement, a was incremented but after assigning value to b, and then whilec = ++a;
a is again incremented and assigned to c (as this is pre-increment now)you can have like:
b = (++a) - (a++);
as first a increments first and then the second a (which is now 6) is substracted from first a (still 6). And then the final value of a is 7