1.

Is it possible to compare Strings using the == operator? If so, what is the risk involved?

Answer»

Yes, you can compare strings using the == operator. One can use == operators for reference comparison (address comparison). The majority of the time, DEVELOPERS compare strings with the == operator, instead of using the equals() method, resulting in an error.

Example:

PUBLIC class StringComparison{ public STATIC void main(String args[]) { String str1="Scaler"; String str2="Scaler"; String str3=new String("Scaler"); System.out.println(str1==str2); //true because both POINTS to same memory allocation  System.out.println(str1==str3);  //false because str3 refers to instance CREATED in heap System.out.println(str1.equals(str3)); //true because both share same content  //even if both are different string objects } }

Output: 

truefalsetrue


Discussion

No Comment Found