Home Java SCJP SCWCD Servlet Submit News Contact Us Site Map


Over 500 magazines for free (including Oracle Magazine)!

Yes all of them are FREE. You can subscribe to ALL of them.
Click here to apply today!

Home > Java > Java Articles

String equality - Compare Java String

String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value accordingly.

For example,

String str1=”Hello”;
String str2=”Hello”;
String str3=new String(”Hello”) //Using constructor.

If(str1 == str2)
System.out.println(“Equal 1”);
Else
System.out.println(“Not Equal 1”);


If(str1 == str3)
System.out.println(“Equal 2”);
Else
System.out.println(“I am constructed using constructor, hence not interned”);

If( str1.equals(str3) )
System.out.println(“Equal 3”);
Else
System.out.println(“Not Equal 3”);


The output would be,
Equal 1
Not Equal 2
Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.

Apart from these methods String class also provides compareTo methods.

int compareTo(String str2)

This method compares two Strings and returns an int value. It returns
-  value 0, if this string is equal to the string argument
-  a value less than 0, if this string is less than the string argument
-  a value greater than 0, if this string is greater than the string argument

int compareTo(Object object)

This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.

 

<< String Consturctor

String Manipulation -1 >>


Home Java SCJP SCWCD Servlet Site map