1 / 6

String and Object Comparison

String and Object Comparison. Comparison operator. 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. String Comparison.

Download Presentation

String and Object Comparison

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. String and Object Comparison Comparison operator

  2. 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.

  3. 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"))

  4. 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"); } }

  5. 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

  6. Object Comparison

More Related