官术网_书友最值得收藏!

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

主站蜘蛛池模板: 南和县| 莱西市| 安庆市| 栾川县| 茌平县| 仙游县| 安新县| 镇原县| 黄梅县| 五大连池市| 房山区| 得荣县| 灯塔市| 凤山县| 康保县| 济阳县| 潼南县| 娄烦县| 溧水县| 建水县| 汕头市| 宜兰市| 乌兰察布市| 东明县| 邛崃市| 察雅县| 会宁县| 崇阳县| 潮州市| 桑日县| 千阳县| 都兰县| 棋牌| 游戏| 阿拉善右旗| 浦县| 刚察县| 克拉玛依市| 金川县| 林周县| 湘阴县|