Testing Strings for EqualityI. The “==” Operator vs. the equals() MethodII. ExamplesIII. To Test Strings for Inequality, Use the “!” OperatorIV. The equalsIgnoreCase MethodComputer Programming I Instructor: Greg ShawCOP 2210 Testing Strings for EqualityI. The “==” Operator vs. the equals() Method- To test whether two strings are equal, we cannot use the “==”operator- “==” tells us whether the contents of two variables are equal- For primitive types, this is the meaning of equality andprecisely what we want to test - However, for Strings (and other objects) we must rememberthat what is stored in an object variable is the address ofan object (i.e., a reference to an object)and not the objectitself- So, if two object variables contain the same address, thatmeans that they are both “pointing to” the same Stringobject. It does not mean that they are pointing to twodifferent objects containing the same String, which is whatwe want to test- To test whether two different String objects are equal, wemust call the equals method:if ( obj1.equals(obj2) )Assuming obj1 and obj2 are Strings – String objectvariables, literals, or expressions - method equals willreturn true if the two Strings are equal, and false if theyare not Two Strings are equal if they contain exactly the samecharacters. I.e., if they have the same number ofcharacters and every pair of corresponding characters isequal, including caseII. ExamplesString word = “Java” ;word.equals(“java”) is false (“J” vs. “j”)word.equals(“Java ”) is false (note the extra space)word.equals(“Java”) is trueIII. To Test Strings for Inequality, Use the “!”Operatorif ( ! obj1.equals(obj2) )IV. The equalsIgnoreCase MethodAs the name implies, if we have two stringsString s1 = "ABcdE" ;String s2 = "aBCdE" ;thens1.equals(s2) is falses1.equalsIgnoreCase(s2) is
View Full Document