How to judge string types are equal

1. The comparison of strings in java is == to compare references, and equals to compare values

We often write if(str1==str2) habitually, which may cause problems in java

 String a="abc";String b="abc",

then a==b will return true. Because the value of a string in java is immutable, the same string will only be stored in memory

 A copy, so a and b point to the same object;

String a=new String("abc"); String b=new String("abc");

 Then a==b will return false, at this time a and b point to different objects.

 2. Use the equals method to compare whether the contents of the strings are the same,

  String a=new String("abc"); 

 String b=new String("abc"); a.equals(b); will return true.

Usually, in order to avoid the above problems, the equals method is used to judge whether the strings are equal.

 if(str1.equals(str2) ){
System.out.println("strings are equal");
}else{
System.out.println("strings are not equal");
}

1. The comparison of strings in java is == to compare references, and equals to compare values

We often write if(str1==str2) habitually, which may cause problems in java

 String a="abc";String b="abc",

then a==b will return true. Because the value of a string in java is immutable, the same string will only be stored in memory

 A copy, so a and b point to the same object;

String a=new String("abc"); String b=new String("abc");

 Then a==b will return false, at this time a and b point to different objects.

 2. Use the equals method to compare whether the contents of the strings are the same,

  String a=new String("abc"); 

 String b=new String("abc"); a.equals(b); will return true.

Usually, in order to avoid the above problems, the equals method is used to judge whether the strings are equal.

 if(str1.equals(str2) ){
System.out.println("strings are equal");
}else{
System.out.println("strings are not equal");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324652164&siteId=291194637