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)
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.
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(%).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With