Java运算符记录本,以此记下容易出错的地方。
来自于 Thinking in Java
Relational Operators
The relational operators == and != also work with all objects. Here is an example:
|
|
The statement System.out.println(n1==n2) will print the result of the boolean comparison within it. While the contents of the objects are the same, the references are not the same. The operators == and != compare object references, so the output is actually “false” and then “true”.
What if we want to compare the actual contents of an object for equivalences? We must use the special method equals() that exits for all objects (not primitives, which work fine with == and !=). Example:
|
|
But default equals() does not compare contents. Here is an example:
|
|
The result is false. This is because the default behavior of equals() is to compare references. So unless you override equals() in your new class you won’t get the desired behavior. Most of the Java library classes implement equals() so that it compares the contents of objects instead of their references.
Bitwise Operators
The bitwise operators allow you to manipulate individual bits in an integral primitive data type. Bitwise operators perform Boolean algebra on the corresponding bits in the two arguments to produce the result.
The bitwise operators come from C’s low-level orientation, where you often manipulate hardware directly and must set the bits in hardware registers. Java was originally designed to be embedded in TV set-top boxes, so this low-level orientation still made sense.
The bitwise AND operator (&) produces a one in the output bit if both input bits are one; otherwise, it produces a zero.
|
|
The bitwise OR operator (|) produces a one in the output bit if either input is a one and produces a zero only if both input bits are zero.
|
|
The bitwise EXCLUSIVE OR, or XOR (^) , produces a one in the output bit if one or the other input bit is a one, but not both, which means if the bits are same, producing 0, if the bits are different, producing 1.
|
|
The bitwise NOT, also called the ones complement operator, (~), is a unary operator; it takes only one argument. (All other bitwise operators are binary operators.) Bitwise NOT produces the opposite of the input bit - a one if the input bit is zero, a zero if the input bit is one.
|
|