Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Comparing Strings
To compare two Strings...
-
Do not use = = ! This compares the actual String objects,
not the contents of those objects. This will be of little use when
comparing Strings.
-
Example:
String a = "UC";
String b = "UC";
String c = "uc";
if (a = = b) {
// this statement will usually return false. a and b are
not the same object!
-
Instead, use the equals() method of the String object if the case is equal,
or equalsIgnoreCase() if the case does not matter..
if (a.equals(b)) {
// this will return true.
if (a.equals(c)) {
// This will return false, the case is different.
if (a.equalsIgnoreCase(c)) {
// This will return true.
if (a.equalsIgnoreCase(d)) {
// I put this in just to see if you were paying attention.
String Demo/Lab
Created by: Brandan
Jones January 4, 2002