執行結果截圖:
代碼:
public class TernaryOperator {
public static void main(String[] args) {
int a = 10;
int b = 20;
// a += b 與 a=a+b的區別:前者的+=帶自動強制轉換數據類型,后者如果是高轉低必須手動強制轉換
a += b;
// a -= b 與 a=a-b的區別:前者的-=帶自動強制轉換數據類型,后者如果是高轉低必須手動強制轉換
a -= b;
System.out.println(a);
// 在這里的+是字符串連接符
System.out.println(a + b);
// 如果前面是字符串,后面的a和b都會自動轉換為字符串,不會計算
System.out.println("" + a + b);
// 如果后面跟字符串,前面的a和b不會自動轉換字符串,會計算
System.out.println(a + b + "");
boolean x = true;
String y = "ok";
String z = "not ok";
// ?: 是三目運算符,如果x==true,則結果為y,否則結果為z
System.out.println(x ? y : z);
System.out.println(!x ? y : z);
int score = 80;
String type = score < 60 ? "failing grade" : "passing grade";
System.out.println(type);
score = 50;
type = score < 60 ? "failing grade" : "passing grade";
System.out.println(type);
}
}