Context:
String comparison using equals with double quotes and single quotes
I tried checking the value of the field "parentId" (String) of one of my business objects as below:
System.out.println("Status 1 = "+myBusObj.getParentId().equals("0"));
System.out.println("Status 2 = "+myBusObj.getParentId().equals('0'));
I get the below output:
Status 1 = true //where parentId was of value 0 (String)
Status 2 = false //where parentId was of value 0 (String)
Problem: Why Status 1 is true
but Status 2 is false
?
The difference is that in the first case you are comparing with a one character String
, and in the second case you are comparing with a Character
object.
Strings and Characters are not comparable using equals(Object)
; hence the false
in the second case.
(There is a slight subtlety here ... in that '0'
is a char
literal that is being autoboxed to give you the Character
object. Prior to Java 5 where autoboxing was added to the language, the .equals('0')
call would be a compilation error. This is one of those examples where autoboxing is actually a hinderance ...)
Status 1 : You try to compare string object to string object("String" String object) so result will be true.
Status 2 : You try to compare string object to character object('Character' character object) so that result will be false.
Thanks.
双引号将字符串括起来,单引号将字符括起来。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.