共計 414 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用條件語句來為 null 設置默認值。下面是兩種常用的方法:
- 使用三元運算符:
String str = null;
String defaultValue = "Default";
String result = (str != null) ? str : defaultValue;
System.out.println(result); // 輸出 "Default"
- 使用 if 語句:
String str = null;
String defaultValue = "Default";
String result;
if (str != null) {result = str;} else {result = defaultValue;}
System.out.println(result); // 輸出 "Default"
在上面的例子中,如果變量 str 為 null,則將默認值 defaultValue 賦給 result 變量。否則,將 str 的值賦給 result 變量。
丸趣 TV 網 – 提供最優質的資源集合!
正文完