📜  java operator == char - Java (1)

📅  最后修改于: 2023-12-03 14:42:15.612000             🧑  作者: Mango

Java Operator == with char

In Java, == is the equality operator used to compare values of primitives and object references. When it comes to comparing char values with ==, there are some things to keep in mind.

Comparing Char Values with ==

In Java, a char is a primitive data type that represents a single character. When two char variables, say c1 and c2 are compared using ==, what is actually compared is their Unicode values.

char c1 = 'A';
char c2 = '\u0041';
if (c1 == c2) {
    System.out.println("Equal");
} else {
    System.out.println("Not Equal");
}

Output:

Equal

In the above example, c1 is assigned the literal character 'A' while c2 is assigned the Unicode value for 'A' which is \u0041. The if statement compares the values of c1 and c2 using == which returns true because their Unicode values are the same.

Comparing Char Objects with ==

When == is used to compare Character objects, it compares their references and not their values. If two Character objects have the same char value, they may or may not refer to the same object.

Character c1 = 'A';
Character c2 = '\u0041';
if (c1 == c2) {
    System.out.println("Equal");
} else {
    System.out.println("Not Equal");
}

Output:

Not Equal

In the above example, c1 and c2 are Character objects that both have the same char value of 'A'. When they are compared using ==, the result is false because they do not refer to the same object.

Comparing Char Values using equals

When comparing Character objects with the equals method, their values are compared and not their references.

Character c1 = 'A';
Character c2 = 'A';
if (c1.equals(c2)) {
    System.out.println("Equal");
} else {
    System.out.println("Not Equal");
}

Output:

Equal

In the above example, c1 and c2 are Character objects that both have the same char value of 'A'. When they are compared using the equals method, their values are compared and the result is true.

Conclusion

When comparing char values with ==, their Unicode values are compared. When comparing Character objects with ==, their references are compared. When comparing Character objects with equals, their values are compared.