Home » Java

How to compare strings in Java?

11 July 2015 Written by: No Comment

To compare strings in java you should always use equals() method instead of == operator. == operator will work with constants but not for runtime objects.
compare strings in java

public static void main(String[] args) {

String str1="Techvark";
String str2="Techvark";

String str3=new String("Techvark");
String str4=new String("Techvark");

String str5="Techvark.com";

if(str1==str2){ //if both are constants
System.out.println("case 1: equal");

if(str2.equals(str3)){ //if one is constant and str3 is created at runtime
System.out.println("case 2: equal");
if(str3.equals(str4)){ //if both string created at runtime
System.out.println("case 3: equal");
if(str3.equals(str4.intern())){ //if both string created at runtime and use of intern method
System.out.println("case 4: equal");
if(!str4.equals(str5)){ //use of Not equals
System.out.println("case 5: not equal");

Leave your response!

Please add your comment below. Here is the trackback Link and subscribe to these comments Comment RSS Link.

Be nice. Keep this blog clean. Please dont spam.

We support Gravatar. To get your own gravatar, please register at Gravatar.