단항 연산자 : 피연산자가 단 하나뿐인 연산자
1. 증감 연산자(++, --) : 피연산자의 값을 1 증가, 감소
++ 피연산자, -- 피연산자 : 다른 연산을 수행하기 전에 피연산자의 값을 1 증가, 감소
public class IncreaseDecreaseOperators {
public static void main(String[] args) {
int x = 1;
System.out.printf("x = %d\n", ++x); // 증감연산자 실행 -> printf 실행
System.out.printf("x = %d\n", --x);
}
}
출력결과
x = 2
x = 1
피연산자 ++, 피연산자 -- : 다른 연산을 수행한 후에 피연산자의 값을 1 증가, 감소
public class IncrementDecrementOperators {
public static void main(String[] args) {
int y = 1;
System.out.printf("y = %d\n", y++); // printf 실행 -> 증감연산자 실행
System.out.printf("y = %d\n", y--);
System.out.printf("y = %d\n", y);
}
}
출력결과
y = 1
y = 2
y = 1
2. 부호 연산자(+, -) : 양수 및 음수를 표시
public class UnaryPlusMinusOperators {
public static void main(String[] args) {
int x = 100;
int y = 100;
int z = -y;
System.out.printf("x = %d\n", +x);
System.out.printf("y = %d\n", -y);
System.out.printf("z = %d\n", -z); //음수 -100인 -y에 -가 붙어서 양수 100으로 값 변경
}
}
출력결과
x = 100
y = -100
z = 100
3. 논리 부정 연산자( ! ) : true -> false / false -> true로 변경
public class LogicalComplementOperator {
public static void main(String[] args) {
boolean result = true;
System.out.printf("result = %b\n", result);
System.out.printf("result = %b\n", !result); // !로 인해 true -> false로 변경
}
}
출력결과
result = true
result = false
'Java > 4. 연산자(Operators)' 카테고리의 다른 글
| Java - 비트연산자 (0) | 2023.05.05 |
|---|---|
| Java - 이항연산자 (0) | 2023.05.04 |