「Java」三項演算子(条件式)を使うサンプル

構文
条件式 ? 式1 : 式2
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class CondDemo {
private static final String cftRes = "nullまたは空白";
private static void printRes(String target) {
// 三項演算子
String res = (target != null && target.length() > 0) ? target : cftRes;
System.out.println("対象文字列の判定結果:" + res);
}
public static void main(String[] args) {
String strA = "test 123";
String strB = "";
String strC = null;
printRes(strA);
printRes(strB);
printRes(strC);
}
}
package com.arkgame.study; public class CondDemo { private static final String cftRes = "nullまたは空白"; private static void printRes(String target) { // 三項演算子 String res = (target != null && target.length() > 0) ? target : cftRes; System.out.println("対象文字列の判定結果:" + res); } public static void main(String[] args) { String strA = "test 123"; String strB = ""; String strC = null; printRes(strA); printRes(strB); printRes(strC); } }
package com.arkgame.study;

public class CondDemo {

      private static final String cftRes = "nullまたは空白";

      private static void printRes(String target) {
            // 三項演算子
            String res = (target != null && target.length() > 0) ? target : cftRes;
            System.out.println("対象文字列の判定結果:" + res);
      }

      public static void main(String[] args) {
            String strA = "test 123";
            String strB = "";
            String strC = null;
            printRes(strA);
            printRes(strB);
            printRes(strC);
      }

}

実行結果
対象文字列の判定結果:test 123
対象文字列の判定結果:nullまたは空白
対象文字列の判定結果:nullまたは空白

Java

Posted by arkgame