In an earlier chapter we went over one example of a relational operator -the equality operator
==. In this lesson, we are going to broaden our possibilities in Java by learning about more relational operators and how we can implement them.
As you probably recall, we used the equality operator to see if two variables had equal values. For a quick refresher, look at the code below.
= is an assignment operator, and that
== is the equality operator. So in this example, we can see that we are telling the computer to print out “Coding is fun!” only if the boolean value
codingIsFun = true.
Let’s look at another example:
In the code above, we have the equality operator in the
if statement. However, the code above will only work if the age is exactly equal to 21 and not if it is 22 or higher.
If we were to change the
int age = 22, Java would ignore the if statement because 22 doesn’t equal 21 and it would print “I’ll have a Coke”. This is where other relational operators come to save the day.
Here is the list of the Relational operators:
|Not equal to||!=|
|Greater than or equal to||>=|
|Lesser than or equal to||<=|
Looking at the relational operators list, we can see that to fix the code above, we want an greater than or equal to relational operator, instead of the equality operator. Look at the code below for our final solution:
All of these relational operators are important to know as a programmer. Be sure to review the list and try to commit them to memory. The further we delve into Java,, the more often these statements are seen. Good job and see you next lesson.
Leave a Reply