Skip to content

Instantly share code, notes, and snippets.

@madevelopers
Created June 27, 2015 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madevelopers/fc6257d9df0521dc435c to your computer and use it in GitHub Desktop.
Save madevelopers/fc6257d9df0521dc435c to your computer and use it in GitHub Desktop.
How to compare strings in Java #java #flashcard

To compare Strings, we have to use the equals and compareTo methods. For example:

String name1 = "Alan Turing";
String name2 = "Ada Lovelace";

if (name1.equals (name2)) {
  System.out.println("The names are the same.");
}

int flag = name1.compareTo (name2);
if (flag == 0) {
  System.out.println("The names are the same.");
} else if (flag < 0) {
  System.out.println("name1 comes before name2.");
} else if (flag > 0) {
  System.out.println("name2 comes before name1.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment