String and Object Comparison Comparison operator.
-
Upload
kevin-ward -
Category
Documents
-
view
224 -
download
0
Transcript of String and Object Comparison Comparison operator.
![Page 1: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/1.jpg)
String and Object Comparison
Comparison operator
![Page 2: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/2.jpg)
Equality Testing vs. Assignment
· The = = operator tests for equality:if (x = = 0) . . // if x equals zero
· The = operator assigns a value to a variable:
x = 0; // assign 0 to x · Don't confuse them.
![Page 3: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/3.jpg)
String Comparison
· Don't use = = for strings!if (input = = "Y") // WRONG!!!
· Use equals method:if (input.equals("Y"))
· = = tests identity, equals tests equal contents
· Case insensitive test ("Y" or "y")if (input.equalsIgnoreCase("Y"))
![Page 4: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/4.jpg)
public class StringExample{ // instance variables - replace the example below with your own private String name; private String nickname;
/** * Constructor for objects of class StringExample */ public StringExample() { // initialize instance variables name = "Robert"; nickname = name.substring(0,3); } public void displayNames() { if (nickname == "Rob")
{ System.out.println("The nickname is Rob");
} else
{ System.out.println("There is no nickname");
}}
![Page 5: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/5.jpg)
Object Comparison· = = tests for identity, equals for identical content
Rectangle cerealBox = new Rectangle(5, 10, 20, 30);Rectangle oatmealBox = new Rectangle(5, 10, 20, 30);Rectangle r = cerealBox;
· cerealBox != oatmealBox, but cerealBox.equals(oatmealBox)
· cerealBox == r· Note: equals must be defined for the class
![Page 6: String and Object Comparison Comparison operator.](https://reader035.fdocuments.in/reader035/viewer/2022072110/56649ce35503460f949aeacb/html5/thumbnails/6.jpg)
Object Comparison