Java has the full complement of relational operators. To test for equality you use a double equal sign, ==. For example, the value of
Java有完全的关系运算符补充。要测试相等,你可以使用一个双等号,==。比如,
3 == 7
is false.
3==7的值是false。
Use a != for inequality. For example, the value of
使用!=来测试不等。比如:
3 != 7
is true.
3 != 7的值是true。
Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal) operators.
最后,还有普通的< (小于),> (大于),<= (小于等于),和 >= (大于等于) 运算符。
Java, following C++, uses && for the logical "and" operator and || for the logical "or" operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The && and || operators are evaluated in "short circuit" fashion. The second argument is not evaluated if the first argument already determines the value. If you combine two expressions with the && operator,
Java,和C++一样,使用&&表示逻辑与,使用||表示逻辑或。由于你能轻易记得!=运算符,所以感叹号!就表示逻辑非。 && 和 || 运算符采用“短路”方式求值。如果第一个参数的值已经确定,则不需要考虑第二个参数的值。如果你将两个表达式用&&连接,
expression1 && expression2
and the truth value of the first expression has been determined to be false, then it is impossible for the result to be TRue. Thus, the value for the second expression is not calculated. This behavior can be exploited to avoid errors. For example, in the expression
并且第一个表达式的真值是false,那么运算结果不可能为true。因此第二个表达式的值不参与运算。该特性可以用来避免错误。例如,在表达式
x != 0 && 1 / x > x + y // no division by 0
the second part is never evaluated if x equals zero. Thus, 1 / x is not computed if x is zero, and no divide-by-zero error can occur.
当中,第二部分如果x等于0的话就不被计算。
Similarly, the value of expression1 || expression2 is automatically true if the first expression is true, without evaluation of the second expression.
类似的,表达式expression1 || expression2 中,如果第一表达式为true,那么整个表达式的值就为true,而不计算第二个表达式的值。
Finally, Java supports the ternary ?: operator that is occasionally useful. The expression
最后,Java支持偶尔很有用的三目运算符?:。表达式
condition ? expression1 : expression2
evaluates to the first expression if the condition is TRue, to the second expression otherwise. For example,
如果condition为ture则计算expression1的值,否则计算expression2的值。例如:
x < y ? x : y
gives the smaller of x and y.
求得x和y当中较小的一个。
文章来源:
http://x-spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!312.entry