CHAPTER 4 ■ OPERATORS
Listing 4-15. Equality operator examples
int a = 0;
int b = 1;
String s = "s";
String sToo = "s";
System.out.println(a == b);
System.out.println(s == sToo);
That bit of code prints “true” for a == b and “false” for s == sToo. That's because s and sToo are
references to different instances of the String object. So, even though they have the same value, they are
not equal in the eyes of the equality operators. Also, s == “s” prints false, because the string literal
produces yet another instance of the String class.
To compare objects (including instances of the String class), Java programmers use the equals
method. Any object whose instances can be compared to each other should implement the equals
method (which is defined in the Object class). Because it makes sense for String objects to be compared
to one another, the String class implements the equals method. That way, we can use code similar to
Listing 4-16 to compare instances of String.
Listing 4-16. Testing equality for objects
String s = "s";
String sToo = "s";
System.out.println(s.equals(sToo));
System.out.println(s.equals("s"));
Both of these print statements produce “true” in the console. We cover comparing objects in more
depth later in this chapter.
Bitwise AND Operator (&)
The bitwise AND operator (&) compares two binary values and sets each bit to 1 where each bit in the
two values being compared is 1. As usual, an example helps (see Listing 4-17).
Listing 4-17. Bitwise AND operator (&)
Byte byte1 = Byte.parseByte("01010101", 2); // byte1 = 85
Byte byte2 = Byte.parseByte("00111111", 2); // byte2 = 63
int result = byte1 & byte2; // result = 21
The value of result is 21 because taking the bits where both bits in the compared value is 1 gives a
binary result of 00010101 , which happens to be the binary representation of 21.
Bitwise Exclusive OR Operator (^)
The bitwise Exclusive OR (often shortened to XOR) operator (^) compares two binary values and sets
each bit to 1 if the bits differ. Again, examples make the best explanations for this kind of thing (see
Listing 4-18).