Comparison operators

Introduction to Java

Jim White

Java Developer

Comparisons

 

 

  • Always evaluate to true or false (result is a boolean)

Comparing age to minAge

Introduction to Java

Greater than >, less than <

class GreaterThan {
  public static void main(String[] args){
    System.out.println(5 < 6); // Will print true, 5 is less than 6
  }
}
true
Introduction to Java

Greater than >, less than <

// Check if 5 is less than 6
boolean x = 5 < 6; // Value is true, because 5 < 6

// Check if 5 is greater than 6
boolean y = 5 > 6; // Value is false, 5 < 6
Introduction to Java

Greater or equal to >=

int minSpend = 25;
int total = 25;


// Check if total is greater or equal to minSpend boolean freeDelivery = total >= minSpend; // Value is true, total is equal to minSpend
Introduction to Java

Less or equal to <=

int minSpend = 25;
int total = 23;

// Check if total is less or equal to minSpend

boolean paidDelivery = total <= minSpend; // Value is true, total is less than minSpend
Introduction to Java

Equal ==

  • We need to use ==, = is for assignment
int userAccountNumber = 567346;
int submittedAccountNumber = 456777;

// Check if userAccountNumber is equal to submittedAccountNumber
boolean isUserAccountNumber = useraccountNumber == submittedAccountNumber;
// Value is false

Introduction to Java

Not equal !=

  • Use !=
int userHealth = 235;

// Check whether userHealth is not zero
boolean alive = userHealth != 0; // Value is true, userHealth is not zero
Introduction to Java

Comparison summary

Operator Name Example Result of example
> Greater than 6 > 6 false
< Less than 5 < 6 true
>= Greater or equal to 5 >= 6 false
<= Less or equal to 5 <=6 true
== Equal to 5 == 5 true
!= Not equal to 5 != 5 false
  • Output of all operations is a boolean
Introduction to Java

Let's practice!

Introduction to Java

Preparing Video For Download...