Java 三目運算符


執行結果截圖:

 

 代碼:

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);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM