112 Part II: Writing Your Own Java Programs (Ecommerce web host)

112 Part II: Writing Your Own Java Programs Figure 5-4: The result of using == and using Java s equals method. In Listing 5-3, the call myScanner.next()grabs whatever word the user types on the computer keyboard. The code shoves this word into the variable named password. Then the program s ifstatements use two different techniques to compare passwordwith swordfish . The more appropriate of the two techniques uses Java s equalsmethod. The equalsmethod looks funny because when you call it you put a dot after one string and put the other string in parentheses. But that s the way you have to do it. In calling Java s equalsmethod, it doesn t matter which string gets the dot and which gets the parentheses. For instance, in Listing 5-3, you could have written if ( swordfish .equals(password)) The method would work just as well. A call to Java s equalsmethod looks imbalanced, but it s not. There s a reason behind the apparent imbalance between the dot and the parentheses. The idea is that you have two objects: the passwordobject and the swordfish object. Each of these two objects is of type String. (However, password is a variable of type String, and swordfish is a Stringliteral.) When you write password.equals( swordfish ), you re calling an equals method that belongs to the password object. As you call that method, you re feeding swordfish to the method as the method s parameter (pun intended). You can read more about methods belonging to objects in Chapter 7. When comparing strings with one another, use the equals method not the double equal sign.
We are the cheapest Catholic web hosting provider, check Catholic Web Hosting services and make sure of alone.

Leave a Reply