Page 124 - Introduction to Programming with Java: A Problem Solving Approach
P. 124
90 Chapter 3 Java Basics
equals method, and it does the tedious comparison operation automatically, behind the scenes. More suc- cinctly, the equals method returns true if two strings contain the exact same sequence of characters. It returns false otherwise.
We recommend that you now go through a trace to make sure you thoroughly under- stand the equals method. See the code fragment in Figure 3.12. Try to trace the code fragment on your own prior to looking at the solution.
Put yourself in computer’s place.
1 String animal1 = "Horse";
2
String animal2 = "Fly";
String newCreature;
newCreature = animal1 + animal2;
System.out.println(newCreature.equals("HorseFly"));
System.out.println(newCreature.equals("horsefly"));
Enhancer
3
4
5
6
7
line#
animal 1
animal 2
newCreature
output
1
Horse
2
Fly
3
?
5
HorseFly
6
Apago PDF
true
false
7
Figure 3.12 Code fragment that illustrates the equals method and its associated trace
Since newCreature contains the value “HorseFly”, the equals method returns a value of true when newCreature is compared to “HorseFly”. On the other hand, when newCreature is compared to lowercase “horsefly”, the equals method returns a value of false.
The equalsIgnoreCase Method
Sometimes, you might want to disregard uppercase versus lowercase when comparing strings. In other words, you might want “HorseFly” and “horsefly” to be considered equal. To test for case-insensitive equal- ity, call the equalsIgnoreCase method.
What does this code fragment print?
System.out.println("HorseFly".equalsIgnoreCase("horsefly"));
Since equalsIgnoreCase considers “HorseFly” and “horsefly” to be equal, the code fragment prints true.
3.23 Input—the Scanner Class
Programs are normally a two-way street. They produce output by displaying something on the computer screen, and they read input from the user. Up to this point, all our Java programs and code fragments have