In this exercise we will see something that causes trouble for beginners trying to learn Java: the regular relational operators do not work with Strings, only numbers.
The second line doesn’t even compile! You can’t use
< to see if a word
comes before another word in Java. And in the third line, b does get
set to the value
true here, but not if you read the value into a variable
b will always get set to the value
false, no matter if the human types
"horse" or not!
I don’t want to try to explain why this is. The creators of Java do have a good reason for this apparently weird behavior, but it’s not friendly for beginners and explaining it would probably only confuse you more at this point in your learning.
Do you remember when I warned you that Java is not a language for beginners?
So there is a way to compare Strings for equality, so let’s look at it.
So Strings have a built-in method named
.equals() (“dot equals”) that compares
itself to another String, simplifying to the value
true if they are equal and
to the value
false if they are not. And you must use the not operator (
together with the
.equals() method to find out if two Strings are different.
“Learn Java the Hard Way” is ©2013–2016 Graham Mitchell