Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What this code does

 
Noorulain Khan
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What this code does
public class ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t && ((i++) == 0)); //This code
b = (f && ((i+=2) > 0)); //And this code
System.out.println(i);
}
}

------------------
 
bami bal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first line evaluates t (true). Both operands must be true for b to become true, so the second operand will also be evaluated. The second operand adds 1 to i. i is not equal to 0, so the second operand = false. Therefore, b becomes false.
The second line first evaluates f. Because f = false, b cannot become true. The operator && prevents the second operand to be evaluated, so (i+=2) won't be executed, and the value of i remains 1.
[This message has been edited by bami bal (edited August 27, 2001).]
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually the first line is the same as
b= true && (0 == 0); //the incrementing happens AFTER the compare
so b=true.
Now i is incremented to 1
b = false && (skipped) > 0);
b = false
Try it this way:

Prints out
true
1
false
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic