1. 논리연산자 : 두 피연산자간의 논리적 관계를 나타내는 연산자.
- 참(ture), 거짓(false)을 반환
- 주로 조건문의 판별식에 사용됨
- 이항 연산자, 단항 연산자가 있음
ex) A = 3>2, B = 2<1
A && B : 논리 and, 두 항의 논리가 모두 true일 경우 true 반환 -> A : true, B : false -> false
A || B : 논리 Or, 두 항의 논리가 하나라도 true인 경우 true 반환 -> True
ㄴ> 이항 연산자
!A : A의 논리 연산 결과를 반전 -> A가 true이므로 결과 -> false
ㄴ> 단항연산자
A = B && C || D;
2. 조건연산자 : 조건식에 따라 결과가 true일 경우와 false일 경우 각각 다른 처리를 함.
- 조건문을 연산자 형태로 구현한 것 -> 삼항 연산자라고도 함
조건식? 수식1:수식2
조건식이 참(true)일 경우 수식1을, 거짓(false)일 경우 수식2를 시행
ex) 3>2?A=1:A=2
true -> A 변수에는 1을 저장함
public class Exam4_1 {
public static void main(String[] args) {
int iNum1 = 10, iNum2 = 20, iResult;
double dNum1 = 3.14, dResult;
iResult = iNum1 + iNum2;
System.out.prinln(iResult); -> 30
iResult = iNum1 + 30;
System.out.println(iResult); -> 40
//iResult = iNum1 + dNum1; -> 에러남(iResult는 정수형 변수)
System.out.println(iResult); -> 40
dResult = iNum1 + dNum1;
System.out.println(dresult); -> 13.4
}
}
타입을 잘 결정해야 함!
정수형 = 정수형 + 정수형 (연산 결과가 변수가 저장할 수 있는 범위여야 함)
더블형 = 정수형 + 더블형 (더 큰 데이터 타입으로!)
public class Exam4_2 {
public static void main(String[] args) {
int iNum1 = 10, iNum2 = 20;
boolean result;
result = iNum1 > iNum2;
system.out.println(result); -> false
result = iNum < iNum2;
system.out.println(result); -> true
result = iNum1 == iNum2;
system.out.println(result); -> false
//<=(이하), >=(이상), !=(같지않다)
}
}
public class Exam4_3 {
public static void main(String[] args) {
int iNum1 = 10, iNum2 = 20, iNum3 = 30;
boolean result;
result = (iNum1 < iNum2) && (iNum2 < iNum3);
system.out.println(result); -> true
result = (iNum > iNum2) || (iNum2 < iNum3);
system.out.println(result); -> true
result = !result;
system.out.println(result); -> false
iNum3 = (iNum1 >= 100) ? 200 : 300;
system.out.println(iNum3); -> 300
}
}
논리 And 연산자가 논리 Or 연산자보다 우선순위가 높다.
boolean result;
result = 5 > 3 || 6 < 5 && 7 > 8;
false
일 때, && 연산자 먼저 처리됨
System.out.println(result); -> true || false -> true
'프로그래밍 > 자바(java) 융합개발자 2차' 카테고리의 다른 글
[취성패] 자바 배우기 - 선수학습(조건분기문-if else, switch case) (0) | 2020.12.12 |
---|---|
[취성패] 자바 배우기 - 선수학습(연산자II-증감, 대입, 비트논리, 비트시프트) (0) | 2020.12.12 |
[취성패] 자바 배우기 - 선수학습(연산자I-산술, 관계) (0) | 2020.12.11 |
[취성패] 자바 배우기 - 사전학습(변수와 상수) (0) | 2020.12.10 |
[취성패] 자바 배우기 - 사전학습(자바의 자료형 - 기본형, 참조형) (0) | 2020.12.10 |