javastringcomparecan be done in many ways as shown below. Depending on the type ofjavastringcompareyou need, each of them is used.
public class StringComparision1 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob"); String name3 = "Bob"; // 1st case if (name1 == name2) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1 == name3) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } }
public class StringComparision2 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob1"); String name3 = "Bob"; // 1st case if (name1.equals(name2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1.equals(name3)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } }
public class StringComparision3 { public static void main(String[] args) { String name1 = "bob"; String name2 = new String("cob"); String name3 = "Bob"; // 1st case if (name1.compareTo(name2) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name2) < 0) { System.out.println("name2 follows name1"); } else { System.out.println("name1 follows name2"); } // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case if (name1.compareTo(name3) == 0) { System.out.println("The strings are equal."); } else if (name1.compareTo(name3) < 0) { System.out.println("name3 follows name1"); } else { System.out.println("name1 follows name3"); } } }