Is it safe to use ==/!=
while comparing Character
?
Character being a boxed type is it safe to use ==/!=
while comparing Character types?
public static void main(String[] args) {
Character c1 = 'd';
Character c2 = (char) getInt();
System.out.println(c1 == c2);
}
public static int getInt() {
return 100;
}
The following works as expected (true). However, are there cases where comparing Character with same value using ==
would lead to false? (Hence, do we have to use '.equals()' while comparing boxed primitive types?
CodePudding user response:
No, it's not safe. You must use equals()
.
Demonstration:
System.out.println(Character.valueOf('Ü') == Character.valueOf('Ü'));
// -> false
Note that if you use autoboxing or Character.valueOf()
, then some characters (ASCII characters) are cached and the same Character
instance is reused, so ==
may return true
for the same value:
System.out.println(Character.valueOf('A') == Character.valueOf('A'));
// -> true (on my machine)
But it doesn't work for all characters, and it won't work if you call the deprecated new Character(...)
explicitly.
CodePudding user response:
tl;dr
Use code points, not char
/Character
.
"d".codePointAt( 0 ) == 100 // true.
Details
The Answer by Alex Shesterov is correct. But bigger picture, you should not be using Character
objects.
Character
is broken
The Character
class is a wrapper class for the primitive type char
. The char
/Character
type is legacy as of Java 2, and is essentially broken. As a 16-bit value, it is physically incapable of representing most characters.
For example, try running:
System.out.println( Character.valueOf( '