?

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++一樣,使用&&表示邏輯與,使用||表示邏輯或。由于你能輕易記得!=運算符,所以感嘆號!就表示邏輯非。 && 和 || 運算符采用“短路”方式求值。如果第一個參數(shù)的值已經(jīng)確定,則不需要考慮第二個參數(shù)的值。如果你將兩個表達式用&&連接,

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