Be especially careful when incrementing or decrementing
Increment.java
public class Increment {
public static void main(String[] args) {
int x = 10;
int y = 10;
if (x >= 10 && ++y >= 10) {
//Do not evaluate y if x is false
System.out.println("x = " + x);
System.out.println("y = " + y);
}
System.out.println("------");
if (x >= 10 || ++y >= 10) {
//Do not evaluate y if x is true
System.out.println("x = " + x);
System.out.println("y = " + y);
}
System.out.println("------");
if (x >= 10 | ++y >= 10) {
//Evaluate y even if x is true
System.out.println("x = " + x);
System.out.println("y = " + y);
}
System.out.println("------");
if (x > 10 & ++y > 10) {
//Evaluate y even if x is false
System.out.println("nothing");
}
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
x = 10
y = 11
------
x = 10
y = 11
------
x = 10
y = 12
------
x = 10
y = 13
Recommended Posts