So I've heard that if I compare 2 strings with == then I will only get true back if they both refer to the same object/instance. That's strings. What about Booleans?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It depends if you are talking about value types like:
int
,boolean
,long
or about reference types:Integer
,Boolean
,Long
. value types could be compared with==
, reference types must be compared withequals
.If you have an Object use equals, when not you can run in things like this. (VM cache for autoboxing primitives)
the output is TRUE and FALSE
It depends on whether you're talking about
Boolean
s (the object wrapper, note the capitalB
) orboolean
s (the primitive, note the lower caseb
). If you're talking aboutBoolean
s (the object wrapper), as with all objects,==
checks for identity, not equivalence. If you're talking aboutboolean
s (primitives), it checks for equivalence.So:
But
Regarding strings:
It's not really an "and":
==
will only check whether the twoString
variables refer to the sameString
instance. Of course, oneString
instance can only have one set of contents, so if both variables point to the same instance, naturally the contents are the same... :-) The key point is that==
will reportfalse
for differentString
instances even if they have the same characters in the same order. That's why we useequals
on them, not==
. Strings can get a bit confusing because ofintern
ing, which is specific to strings (there's no equivalent forBoolean
, although when you useBoolean.valueOf(boolean)
, you'll get a cached object). Also note that Java doesn't have primitive strings like it does primitiveboolean
,int
, etc.