14.Q. Is it possible to compare Strings using the == operator? If so, what is the problem?

Category: JAVA STRING INTERVIEW QUESTIONS AND ANSWERS

Answer:

Yes, it is possible to compare two strings using == operator . If you compare two strings using == operator , it compares the reference or adress value, but don’t compare the actual content . If you use equals() method to compare two strings , then it will compare the actual content of two strings .

Example:

public class StringComparision {

public static void main (String args[] ) {

String str1= “Beautiful” ;

String str2 =”Beautiful” ;

String str3 =new String (“Beautiful” ) ;

System.out.println(str1==str2);

//true because both points to same memory allocation

System.out.println(str1==str3));

// false because str3 refers to the instance created in the heap memory .

System.out.println(str1.equals(str3));

// true because both have the same content even though both are different string objects .

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *