条件演算子(三項演算子)、あるいはハテナ演算子とは、ifみたいにある条件を作るために使われるもので、
String test = num1 > 0 ? "Positive" : "Negative";
みたいに使います。
このとき、
もしnum1が0より大きければ(?の左がtrueであれば)、?の右の左側「Positive」が変数testに代入されます。
もしnum1が0より小さければ(?の左がfalseであれば)、?の右の右側「Negative」が変数testに代入されます。
下は条件演算子を使いまくったサンプルプログラム。
public class QuestionTest
{
public static void main(String[] args)
{
String test;
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
num1 = 5;
test = num1 > 0 ? "Positive" : "Negative";
System.out.println(test);
num2 = 6;
test = num2 > 0 ? "Positive" : "Negative";
System.out.println(test);
num3 = -3;
test = num3 > 0 ? "Positive" : "Negative";
System.out.println(test);
num4 = 78;
test = num4 > 0 ? "Positive" : "Negative";
System.out.println(test);
test = num1 > 0
? num2 > 0
? num3 > 0
? num4 > 0
? "All numbers are positive"
: "Num4 isn't positive"
: "Num3 isn't positive"
: "Num2 isn't positive"
: "Num1 isn't positive";
System.out.println(test+"\n"); //Only num3 is negative.
num1 = 5;
test = num1 > 0 ? "Positive" : "Negative";
System.out.println(test);
num2 = 6;
test = num2 > 0 ? "Positive" : "Negative";
System.out.println(test);
num3 = 3;
test = num3 > 0 ? "Positive" : "Negative";
System.out.println(test);
num4 = 78;
test = num4 > 0 ? "Positive" : "Negative";
System.out.println(test);
test = num1 > 0
? num2 > 0
? num3 > 0
? num4 > 0
? "All numbers are positive"
: "Num4 isn't positive"
: "Num3 isn't positive"
: "Num2 isn't positive"
: "Num1 isn't positive";
System.out.println(test); //All numbers are positive.
}
}