Comparison and Logical Operators

These operators return a value to you of either “true” or “false” depending.

The first is the (==) equal to comparison operator. This is not an assignment operator. This operator compares two values to see if they are equal. It returns “true” only if value one “is equal to” value 2. Let’s look:

public class MyVariables {
  public static void main(String[] args) {
    int myCoolVariable = 30;
    myCoolVariable %= 7;
    System.out.println(myCoolVariable==2);
  }
}

The (==) operator, in this example, checks if the value of “myCoolVariable” “is equal to” 2. Since it is, the output is “true.”

The (!=) not equal operator returns “true” only if value one “is not equal to” value two.

The (>) greater than operator returns “true” only if value one “is greater than” value two.

The (<) less than operator returns “true” only if value one “is less than” value two.

The (>=) greater than or equal to operator returns “true” only if value one “is greater than or equal to” value two.

The (<=) less than or equal to operator returns “true” only if value one “is less than or equal to” value two.

The first logical operator is the (!) logical not operator. Basically it reverses a “true” or “false” result. For example, “!true” is equal to “false.” Watch it in action here:

public class MyVariables {
  public static void main(String[] args) {
    int myCoolVariable = 30;
    myCoolVariable %= 7;
    System.out.println(!(myCoolVariable==2));
  }
}

We know from earlier that “myCoolVariable” is equal to 2, but the output of this code will be “false” thanks to that mischievous (!) not operator.

The (||) logical “or” operator compares two “true or false” statements to see if either of them were “true”. If either of them were “true”, the (||) logical “or” operator will return “true.” Here is an example:

public class MyVariables {
  public static void main(String[] args) {
    int myCoolVariable = 5;
    System.out.println(myCoolVariable>10 || myCoolVariable<6);
  }
}

The output of this program is “true.” While “myCoolVariable” is not greater than 10, it is however less than 6. The (||) logical “or” operator finds at least one of the statments to be “true” so the final result is “true.”

The (&&) logical “and” operator compares two “true or false” statements to see if both of them are “true”. If both of them are “true”, the (&&) logical “and” operator will return “true.” Here is an example:

public class MyVariables {
  public static void main(String[] args) {
    int myCoolVariable = 5;
    System.out.println(myCoolVariable>10 && myCoolVariable<6);
  }
}

The output of this program is “false.” Since “myCoolVariable” is not greater than 10, the first statement is “false.” The (&&) logical “and” operator did not find both of the statments to be “true” so the final result is “false.”

Next Topic: Type Casting

Comments

Popular Posts