Java Programming
Control statements
Compare string variables
To test two strings for equality, you must call one of the methods of the String object.
Two methods of the String class
Method | Description |
---|---|
equals(String) | Compares the value of the String object with a String argument and returns a true value if they are equal. Comparison is case-sensitive. |
equalsIgnoreCase(String) | Works like the equals method but is not case-sensitive. |
Examples
userEntry.equals("Y") // equal to a string literal
userEntry.equalsIgnoreCase("Y") // equal to a string literal
(!lastName.equals("Jones")) // not equal to a string literal
code.equalsIgnoreCase(productCode) // equal to another string variable
Code that compares strings (case sensitive).
import java.util.Scanner;
public class CompareStrings
{
public static void main(String[] args)
{
String aName = "Carmen";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name > ");
anotherName = input.nextLine();
if(aName.equals(anotherName))
System.out.println(aName + " equals " + anotherName);
else
System.out.println(aName + " does not equal " + anotherName);
}
}
The console after the program finishes
Code that compares strings (ignore case).
import java.util.Scanner;
public class CompareStrings2
{
public static void main(String[] args)
{
String aName = "Carmen";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name > ");
anotherName = input.nextLine();
if(aName.equalsIgnoreCase(anotherName))
System.out.println(aName + " equals " + anotherName);
else
System.out.println(aName + " does not equal " + anotherName);
}
}
The console after the program finishes