[JAVA] Evaluation of logical operators

How to evaluate logical operators

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

Evaluation of logical operators
[Java] Summary of operators (operator)
Order of route evaluation in Spark
11 Corresponds to comparison and logical operators
[Ruby] Boolean values ​​and logical operators
Differences between preface and postfix of operators
Java starting from beginners, logical operators / conditional operators