Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

String Equality, Compare Java Strings

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 Constructor    String Manipulation 1 >>
No votes yet
Share this

Post new comment