What makes something true or false?
Before we go into this lesson, let's think about what makes something true or false.
For one, there are only two choices: true and false.
And these two choices can only be yes and no. There's no maybe.
Let me ask you a question: Do you like Pizza?
You can answer it with a "maybe", but a more decisive answer is yes or no.
If I ask you, How old are you? You can't respond with a yes or no. But you can respond with a number (an integer, in fact.)
Keep this in mind as we go on.
Comparisons
Is 3 greater than 2? Yes, it is.
Is 2 greater than 3? No, it is not.
Is 3 equal to 3? Yes, it is.
And there you have it. You understand comparisons. We use <, >, and = for comparisons in Math. It works the same way in Java.
We can create expressions to identify comparisons. Like this:
boolean expOne = 2 < 3;
boolean expTwo = 2 > 3;
boolean expThree = 3 == 3;
System.out.println(expOne);
System.out.println(expTwo);
System.out.println(expThree);
These results will match the above questions perfectly.
Equals
You may notice the ==. This is the same as equals since = sets the value of a variable, == checks if one value/variable is equal to the other.
We already used greater than and less than above (they are interchangeable based on the values), but what if we want to check greater than or equal or **greater than or equal?
We can use <= and >= for that. Here's how this works:
boolean expOne = 2 <= 3;
boolean expTwo = 2 => 3;
boolean expThree = 3 >= 3;
System.out.println(expOne);
System.out.println(expTwo);
System.out.println(expThree);
Now all of these are true. Makes sense?
String .equals()
However, for Strings, we need to do something different.
Rather than using == to check if two strings are equal, we use .equals(). Especially with nextLine(), this helps. == will work in some cases, but not always. That's why it's better to use .equals().
Here's an example:
String word1 = "car";
String word2 = "car";
String word3 = "bar";
System.out.println(word1.equals(word2));
System.out.println(word2.equals(word3));
Review
In the end, here's a quick cheatsheet on how comparisons work:
int a = 3;
int b = 8;
boolean outcome;
boolean result = true;
outcome = a < b; // this statement is TRUE
outcome = a > b; // this statement is FALSE
outcome = a <= 4; // less than or equal to 4 - TRUE
outcome = b >= 10; // greater than or equal to 6 - FALSE
outcome = a == b; // a equal to b - FALSE
The
//are just comments, which we will talk about in the future. You can keep or remove them.