String Compare in Java

Advertisements

Prev Tutorial Next Tutorial

String Compare in Java

There are three way to compare string object in java:

string compare in java
  • By equals() method
  • By == operator
  • By compreTo() method

equals() Method in Java

equals() method always used to comparing contents of both source and destination String. It return true if both string are same in meaning and case otherwise it returns false. It is case sensitive method.

Equals method in java

Example

class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy"; 
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}

Output

Compare String: false
Compare String: true

== or Double Equals to Operator in Java

== Operator is always used for comparing references of both source and destination objects but not their contents.

double Equals to Operator in java

Example

class StringHandling
{
public static void main(String arg[])
{
String s1=new String("java");
String s2=new String("java");
if(s1==s2)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}

Output

Strings are not same

compareTo() Method in Java

comapreTo() method can be used to compare two string by taking Unicode values. It returns 0 if the string are same otherwise returns either +ve or -ve integer.

Example

class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}

Output

Strings are not same

Difference between equals() method and == operator

equals() method always used to comparing contents of both source and destination String.

== Operator is always used for comparing references of both source and destination objects but not their contents.


Prev Tutorial Next Tutorial

Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

Download Projects

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements