1.三元運算符的格式
/* 三元運算符 (條件表達式)?表達式1:表達式2; 如果條件為true,整個表達式結果是表達式1; 如果條件為false,整個表達式結果是表達式2; 注意:三元運算符不能單獨使用,要么賦值,要么當成參數傳遞給方法 */ public class TenaryDemo{ public static void main(String[] args){ // int i = (1>2)?1:2; // System.out.println(i); // int a = 10; // int b = 10; // // String res = (a > b)?"S1":"S2"; // int max = (a > b)?a:b; // System.out.println(max); int i = 10; int ii = 20; // boolean res = i > ii ? true:false; System.out.println(i > ii ? true:false); } }
2,eg
三元運算符求三個數的最大值
/* 三元運算符求三個數最大值 1.普通做法:先求前兩個數中的最大值,然后再求三個數中的最大值 2.三元運算符的嵌套(不利於閱讀) 特點: 三元運算符的兩個表達式會隱式進行類型轉換. */ public class TenaryDemo2{ public static void main(String[] args){ /* int a = 70; int b = 90; int c = 30; //先求前兩個數的最大值 // int m1 = (a > b)?a:b; //在求三個數中的最大值 // int res = (m1 > c)?m1:c; //三元運算符的嵌套 int res = (a > b)?(a > c?a:c):(b > c?b:c); System.out.println("三個數中的最大值是: " + res); */ System.out.println(2>1?2:1.0);//2.0,系統自動判斷兩個表達式的類型,並進行隱式轉換 } }