布爾運算符
- 關系運算符:>, >=, <, <=, ==,!=
- 與運算 &&
- 或運算 |
- 非運算 !
int n = 5;boolean t = n > 0;//trueboolean f = n < 0;//falseboolean isFive = n == 5;//trueboolean isNotFive = n != 5;//falseSystem.out.println(t);System.out.println(f);System.out.println(isFive);System.out.println(isNotFive);boolean and = t && f;//flaseboolean or = t || f;//trueboolean not = !t;//falseSystem.out.println(or);System.out.println(and);System.out.println(not);
短路運算符
表達式1 && 表達式2 :如果表達式1為false,表達式2將不在執行
表達式1 || 表達式2: 如果表達式1為true,表達式2將不在執行
int n = 0;//boolean b = 5 / n > 0;除數為0,將會報錯boolean and = (n > 5) && (5 / n > 0);boolean or = (n < 5) || (5 / n > 0);System.out.println(and);System.out.println(or);
三元運算符
- 根據條件b計算x或y b ? x : y
- x和y只計算其中一個
- x和y類型必須相同
//利用三元運算符求絕對值int n = 199;boolean positive = n >= 0;int abs = positive ? n : -n;System.out.println(abs);//199
總結:
- 與運算和或運算是短路運算
- 布爾類型計算結果仍是布爾類型
- 三元運算符b ? x: y;x和y的類型必須相同