Relational Operators

Start course
Overview
Difficulty
Intermediate
Duration
2h 7m
Students
168
Ratings
5/5
starstarstarstarstar
Description

This course explores the fundamentals of Java and puts them to use with some real-life examples looking at an average of three program and a mad libs project.

Learning Objectives

  • Learn how to print information out to the user, how to create and use variables, values, and constants, how these things have data types, and the differences and similarities among the data types
  • Learn about arithmetic, relational, and logical operators
  • Understand how to obtain input from the user of our programs

Intended Audience

  • Beginner coders or anyone new to Java
  • Experienced Java programmers who want to maintain their Java knowledge
  • Developers looking to upskill for a project or career change
  • College students and anyone else studying Java

Prerequisites

This is a beginner-level course and can be taken by anyone with an interest in learning about Java.

Transcript

In the last lecture, we started our discussion of operators with the arithmetic operators which are used to perform arithmetic on different operands. They returned some numeric value as the results. In this lecture, we'll discuss Relational Operators which compare two values and return a Boolean result that is true or false. Let's look at the available relational operators. So, we have the >. We also have > =. Since we don't have a single key that makes it convenient to write the symbol for > =, ,it actually takes two keystrokes. So, you type the followed by the

The same thing for < =. And then there are two others that some actually classify separately as equality operators but they still relate or compare values so they can also be considered relational as well. That is the is equal to operator and the not equal to operator. So, to understand the relational operators better, let's create a file called Relational Fun inside of our Section2-Projects. So if I go over here, right click src and go to New, Java Class and call this RelationalFun. Let's write some code and see how this works with boolean variables and some relational operators. So, public static void main (String[] args). And inside of here boolean myBool = true;, boolean yourBool = false;. myAge  = 37;. yourAge = 20;. bobsAge = 20;. So, let's do some printing first just to see what happens. I'm going to put a little comment here. So, it makes it clear that that's the end of main and not the end of the class.

Sometimes the curly braces, you start getting a ton of curly braces and it starts getting a little bit confusing over time. For our purposes, it's probably not going to be bad but it might be a habit you want to get into but this is not required. It's just some little thing that I do. So, System.out.println("mybool is" and we can cut it, + myBool);. And then I want to use my little shortcut. We can say ("yourBool is " + yourBool);. Remember the shortcut again is S-O-U-T and then that if you hit tab, that will actually complete the System.out.println.

But again, if you can't do this, basically with your eyes closed in your sleep while driving a truck, then don't use the shortcuts. Do it until, type it out fully, until you are able to do it with no problem. And then like I have said before on numerous occasions, I actually type it out fully, for my own benefit, once in a while to make sure that my muscle memory stays good. So, let's also put some relational operations, relational. So, boolean ageComparison, we're going to say equals and I'm going to set it equal to something that's a boolean and one of the possibilities is comparing myAge_>yourAge;. This operation right here that is performed, this operator is applied to its operands and if my age is greater than your age, then that will return true otherwise it will return false. And then this variable is here to catch it. Next, we will print it out so I'll say System.out.println and then I'm going to put ("myAge > yourAge?:" and then concatenate + ageComparison);. You could in parentheses also put this directly without using the variable if you wanted to.

But this is just to keep it nice and clean and organized. So, the next thing we're going to do is we're going to  compare yourAge to BobsAge. So, I'm going to reuse ageComparison. Notice I do not re-declare it. I'm just reassigning its value. So, I'm saying yourAge >  bobsAge and then System.out.println and then in the string I'm saying is ("yourAge > bobsAge?:"). and then we concatenate + ageComparison); again. Good. So far so good. And then finally I'm going to say ageComparison =. Now, be careful here and you can always use parentheses to reinforce this if you're not clear or it's hard to read but this isn't really required.

So, yourAge = =, there's two equal signs bobsAge;. We have to be careful of that because the single equals performs an assignment of a value. So, we're assigning something to this boolean variable here. Some value. Now what value are we assigning? Well this has to complete first and it will because this actually has the double equals, the is equal to operator has priority over the assignment operator. So, we don't have to put parentheses around this but some people choose to do that because it makes it a little easier to read. So, yourAge = bobsAge and that will only return true if they are equal. Now, System.out.println, ("yourAge = = bobsAge?: and then we + ageComparison); one more time. And of course we want to run this. So, this is a little bit longer now and we want to run this program right here to see if everything looks nice to me. Compact some of this stuff a little bit and let's right click RelationalFun and go to Run 'RelationalFun.main()' and here we go. We have myBool is true and yourBool is false,

which they were. They were directly set. And then myAge which 37, yourAge is 20. When we did that comparison, is myAge greater than yours. The answer is true. yourAge greater than bobs. The answer is false because they're the same. Now, if it was greater than or equal to, greater than and then the equals sign, then it would return true because they are the same. So, the double equals tells us that. Sounds good. So, we see the result is true or false for each of these comparisons. You can clearly see that when we compare my age to your age with a greater than operator that returns true because 37 is clearly greater than 20. Since myAge and yourAge are both 20, when we compare them with greater than results false but when we compare them with the equal to operator, the result is in fact true.

So, when you use the relational operators in Java, you must compare numeric values. The equality operators, the subset of the relational operators, are more frequently applied to primitive types in which case they compare the values that are inside the primitives. However, the equality operators unlike the other relational operators, this is probably why it's classified differently, can also be used to compare reference types. So, you might think then that you can use them to compare the values like those of strings but you shouldn't actually. The equality operators when used with reference types, performs a comparison of the values contained by the references just like they do with primitives. It compares the values in those variables.

The differences that we know, that reference types contain memory addresses. And in fact, what the equality operators will perform the comparison on will be those memory addresses. So, if you try to compare two string objects using equal to or not equal to operators, it will compare their addresses, not the values inside of them. This goes for any reference types. So briefly, how would you compare to string objects properly if you want to know their lexical graphic or alphabetic order? So, if I have my name and your name, let's create those. String_myName = "John"; which I'll put up here and then String yourName = "John";. That would be a great name to have. That's an awesome name. And then if I later on decide that I'm going to name comparison down here maybe boolean_nameComparison because it's not really an ageComparison so we won't reuse that. I'd say myName.equals. There we go. (yourName);. So, System.out.println ("do names match?:" and we will put nameComparison.

Let's run it to verify. We right click, go to run RelationalFun.main and as you know it, at the bottom we'll say do the names match?:. So, that will return true if both of them are John. If one of them is something different like Johnny and we try to run a RelationalFun, we will get false because they are not the same. Pretty cool.

So, when comparing reference types again, you should only use the equals methods to see if they're the same object meaning does the memory address held by each of the variables point to or contain the address of the same object. Some languages like C++ allow operator overloading where you can redefine operators and their meaning when used on different types. However, Java does not allow operator overloading so you will need to use the equals method. Now before moving on, I'd like to issue you a challenge. In the same RelationalFun file that we've been working on, I'd like you to create an integer variable called current age and set it equal to your own current age. Then, print out the Boolean value of true or false, whether your current age is greater than or equal to 21. So, pause the video and give this your best try. Come back when you're finished or if you need some help. How did that go for you? Were you able to complete this challenge?

Let's work on it together. So, I'm just going to pop all this stuff down at the bottom. So, we're going to put int currentAge  = 37. and then we're going to say boolean isGreater21. And notice we can put numbers in these identifiers but they just can't be the first character in the identified name. So, if I put two here, that's now not going to work. Big old compiler error. But this one's fine. So, I'm going to test currentAge > = 21; then System.out.println("currenAage > = 21?: and then we'll put isGreater21); like that. Now, of course, let's run the code and see what it does. Right click and then run RelationalFun.main and there we go. We get what we probably expect at least for me, 37 is >  = 21. If you are 21, then it will still be true because of the equals. If it was strictly greater than, that would be false. Now, your answer maybe different than mine. If you're 16 and you're taking this course, then this will be false, of course. But if you're 40 or 50 or 60 or 70 or 80, I've had students all the way from 8 - 88. So, whatever age you are, that's perfectly great and it will return either true or false. There's only two possibilities because it's boolean.

Great job everyone. Relational operators and boolean values will become incredibly important later on in the course when we learn how our code can help us make decisions. To give you a simple idea of a relevant scenario, imagine you're making a video game and you have to test if the user is pressing the space bar to fire their magic missile at the enemy that may require some sort of relational operator. At a high informal level, I might say if the player is pressing space bar fire missile. So, you see how that's conditional. That is, it's based on a condition. If they have the space bar down, then we fire the missile. If they don't have the space bar down, then we don't. So, maybe that will help you think of other scenarios. In the next lecture, we'll take a look at how we could combine different boolean values, for example, in situations where more than one condition has to be true in order to perform an operation or when one of many possible conditions could be true. So, let's get started with logical operators up next. I'll see you there.

 

About the Author
Students
759
Courses
20
Learning Paths
4

John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.

Covered Topics