위의 b = ++a;, b = a++;에서는 차이가 있지만
++a; a++;처럼 증감 연산자가 독립적으로 사용되면 차이가 없다.
public class op{
public static void main(String[] args) {
int x = 0, y = 0;
y = ++x;
x = x + 1;
y = x;
System.out.printf("x: %d, y: %d%n", x, y);
y = x++;
System.out.printf("x: %d, y: %d%n", x, y);
y = -x;
System.out.printf("x: %d, y: %d%n", x, y);
}
}
output
x: 2, y: 2
x: 3, y: 2
x: 3, y: -3
Sysntax : (조건문) ? 참 : 거짓
Example
public class Ternary {
public static void main(String[] args) {
int a = 3; int b = 5;
System.out.println("두 수의 차는 " + ((a>b)?(a-b):(b-a))); //2
}
}
public class Ternary {
public static void main(String[] args) {
int score = 83;
System.out.println((score>80)?("pass"):("fail"));
}
}
public class Ternary {
public static void main(String[] args) {
String name = "name";
System.out.println((name.equals("name") ? "name" : "who?"));
}
}
public class Ternary {
public static void main(String[] args) {
int num1 = 3;
int num2 = 5;
int num3 = (num1 < num2) ? ++ num1 : ++ num2;
System.out.println(num3); //4
}
}
삼항연산자의 중첩
public class Ternary {
public static void main(String[] args) {
int x = 4; int y = 6;
System.out.println((x<y)?((x==4)?4:6):(y));
}
}
이 코드를 풀어쓰면 아래와 같다.
public class Ternary {
public static void main(String[] args) {
int x = 4;
int y = 6;
if (x < y) {
if (x == 4)
System.out.println(4);
else
System.out.println(6);
} else
System.out.println(y);
}
}