- 雙語版Java程序設計
- 何月順主編
- 178字
- 2018-12-27 20:14:16
4.3 Boolean Logical Operators
The boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. Table 4.3 lists logical operators.
Table 4.3 Logical Operators
class example4 { public static void main(String args[]) { boolean b; b = (2 > 3) && (3 < 2); System.out.println("b = "+b); b = false || true ; System.out.println("b = "+b); } }
The output of the program is shown here:
b = false
b = true
Ternary Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statement.
Java包含一個特殊的運算符(三元運算符),可以替代語句if-then-else類型。
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same type, which can’t be void.
先求解表達式1的布爾值,若為真則求解表達式2的值,否則求解表達式3的值。?運算的結果是被求解的表達式的值。要求表達式2和表達式3返回相同類型的值,這個值不能為空。
eg: int i=20; int j=30; int max = ( i > j ) ? x : j;
this section checks for the condition, if i is greater than j then value of i is assigned to max else value of j is assigned to max.
class example5 { public static void main(String args[]) { int i,k; i = 10; k = i < 0 ? -i : i; System.out.print("Absolute value of "); System.out.println(i + " is " + k); i = -10; k = i < 0 ? -i : i; //get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k); } }
when you run this program you will get following output:
Absolute value of 10 is 10
Absolute value of -10 is 10
- JavaScript實例自學手冊
- Hadoop 2.x Administration Cookbook
- 數據中心建設與管理指南
- PIC單片機C語言非常入門與視頻演練
- CorelDRAW X4中文版平面設計50例
- 控制系統計算機仿真
- 計算機網絡安全
- 網絡安全與防護
- 我也能做CTO之程序員職業規劃
- Blender 3D Printing by Example
- 工業機器人運動仿真編程實踐:基于Android和OpenGL
- MCGS嵌入版組態軟件應用教程
- LMMS:A Complete Guide to Dance Music Production Beginner's Guide
- 在實戰中成長:C++開發之路
- ZigBee無線通信技術應用開發