Comparison operators
1. Comparison operators
Now that we're familiar with arithmetic operators, let's explore another type - comparison operators.2. Comparisons
Performing comparisons is a common task in programming. For example, we might check if a user's age is above the required threshold to complete a purchase. Comparisons in Java will always evaluate to `true` or `false`, meaning the result is a `boolean` data type.3. Greater than >, less than <
We will often need to perform numeric comparisons. To check if one value is greater than another we use the right arrow. Here, we check if five is less than six.4. Greater than >, less than <
To reverse the comparison, asking if one value is less than another, we use a left arrow. Recall that the result of a comparison is always a `boolean`. So, if we print a comparison, we get a value of `true` or `false`!5. Greater or equal to >=
Sometimes we need to check if a variable is greater than or equal to another. Say we have a minimum spend of $25 for free delivery on our website. We check if a customer's order is more than or equal to $25. To do this, we use a right arrow but now follow it with an equals sign.6. Less or equal to <=
Likewise, to ask if a variable is less than or equal to a value, we use a left arrow followed by an equals sign!7. Equal ==
What about comparing whether two variables are equal? Equal to is represented by two equal signs. Here, we check if `userAccountNumber` is equal to `submittedAccountNumber`, assigning the result as a `boolean` variable called `isUserAccountNumber`.8. Not equal !=
We can flip it, checking that two variables are not equal to each other. To do this, we change the first of the two equals signs to an exclamation mark. Here, we check that a player's health in a video game does not equal zero.9. Comparison summary
This table summarizes the comparison operators we covered. As your Java knowledge grows, you will see how these can be used in conditional workflows, where specific operations are performed depending on the results of comparisons!10. Let's practice!
For now, head to the exercises to make some comparisons.Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.