For string comparison in two of the useful methods are:
equals() method
String class overrides the equals() method of the object class.The overriden method compares the contents of one string with another to check for equality.
The following method compares the two strings using the equals method.
public static void main(String []args) throws IOException { String string1 = new String("java string"); String string2 = new String("java string"); String string3 = new String("hello"); boolean boolean1, boolean2,boolean3; boolean1 = string1.equals(string2); // false will be assigned to b1 boolean2 = string1.equals(string3); System.out.println(boolean1); System.out.println(boolean2); }
Above code prints the following values
true
false
comapreTo() method
compareTo method is used for comparing two strings for equality.It is used as:
int retrunValue=string1.compareTo(string2)
retrunValue is 0 if the two strings are equal.
retrunValue is >1 if string1 is greater than string2
retrunValue is <1 if string1 is less than string2
Following example program compares strings for equality
public static void main(String []args) throws IOException { String string1 = new String("java string"); String string2 = new String("java string"); String string3 = new String("hello"); int areEqual1="java string".compareTo("java string"); int areEqual2="java string".compareTo("hello"); System.out.println(areEqual1); System.out.println(areEqual2); }
Above code prints the following values
0
2
Leave a Reply