Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ++ operator

So I was testing out operators, because im helping my friend with java and i stumbled across a weird order of programming. What is happening when I run the following code

public static void main(String[] args) {
    int B = 6;
    //First console print out
    System.out.println(B+=++B);
    System.out.println(B);
    B = 6;
    //Second Console print out
    System.out.println(B+=B++);
    System.out.println(B);
}

The output for the following code is

13
13

12   
12

What causes the second console B math output = 12 when it adds 6 to itself, followed by ++ (which is +1)

like image 850
Loligans Avatar asked Sep 09 '13 22:09

Loligans


People also ask

What is an operator in Java?

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence.

What does '%' mean in Java?

modulus: An operator that works on integers and yields the remainder when one number is divided by another. In Java it is denoted with a percent sign(%).

What is i += 2 in Java?

Using += in Java Loops The += operator can also be used with for loop: for(int i=0;i<10;i+=2) { System. out. println(i); } The value of i is incremented by 2 at each iteration.


2 Answers

The difference here is in the increment operators.

In the case of B += ++B, B is incremented to 7 and added to its old self (6) to achieve 13.

In the case of B += B++, B is added to itself, giving 12, then the ++ is performed and the result stored in B, but the result of the calculation is then stored over the ++ in B. Thus giving 12 as the output.

like image 166
Sinkingpoint Avatar answered Oct 03 '22 00:10

Sinkingpoint


ACTION       EFFECT   NOTES
----------   ------   -----
B = 6        B = 6
B += (++B)   B += 7   // B is incremented and the value is returned
B            B = 13

B = 6        B = 6
B += (B++)   B += 6   // The current value of B is the result of (B++) and B is
                      // incremented *after* the (B++) expression; however, the
                      // assignment to B (+=) happens after the (++) but it does
                      // not re-read B and thereby covers up the post increment.
B            B = 12
like image 40
user2246674 Avatar answered Oct 03 '22 00:10

user2246674