Reputation: 20856
If the below "if" stmt evalutes to TRUE then the value of Output = 20 or else 10..
Can someone explain how the increment operator works here.?
public class Test {
public static void main(String[] args) throws IOException {
int Output = 10;
boolean b1 = true;
if ((b1 == true ) && ((Output += 10) == 20)){
System.out.println("We are Equal = " + Output);
}
else{
System.out.println("Not Equal = " + Output);
}
}
}
Upvotes: 0
Views: 81
Reputation: 1
1) +=
means a "Pre-increment". So, with Output=10
the if block would proceed as below
if ((b1 == true ) && ((Output = Output + 10) == 20)){
here, value of Output will be compared with 20 once incrementation is done..So, during the first time execution of the if block.. it would proceed as below..
if ((b1 == true ) && ((20) == 20)){
2)=+
means a "post-increment". So, value of Output will be compared with 20 before incrementation..So, during the first time execution of the if block.. it would proceed as below..
if ((b1 == true ) && ((10) == 20)){
hope this explaination helps :-)
Upvotes: -1
Reputation: 359
The integer value 10
is added to the current value of Output
. After this, the value of output is compared using the ==
operator, which only operates on booleans.
In this particular piece of code, since b1
is true and and Output is 20 after its value is increased by 10, the condition of the if
block is true, therefore the else
will be discarded and whatever code is inside the if
block will be executed.
Upvotes: 1
Reputation: 26502
It's not so much the +=
operator that is working differently; it's the &&
operator.
The &&
operator short circuits. If b1
is false, there's no way that b1 && (anything else)
can be true, so it stops evaluating. As such, Output += 10
is not evaluated if b1
is not true, so Output
will be 10.
If b1
is true, then it must continue to see if the remainder of the condition is true. In doing so, it must evaluate Output += 10
, thereby increasing the value of Output
by 10, making the value of Output
20.
Upvotes: 5