5. bit 연산자(& | ^)
& (and 연산자) => 2개 bit 모두 1 일때만 1, 나머지는 0
| (or 연산자) => 2개 bit 중에서 적어도 1개가 1이면 1, 모두 0이어야만 0
^ (xor 연산자) => 2개 bit 중에서 서로 달라야만 1, 같으면 0
& | ^ 연산자는 연산되어지는 대상이 정수일때만 사용가능함.
int x1=3, y1=5;
System.out.println("x1 & y1 => " + (x1 & y1)); // x1 & y1 => 1
/*
00000011 <== 3
& 00000101 <== 5
--------
00000001
*/
System.out.println("x1 | y1 => " + (x1 | y1)); // x1 | y1 => 7
/*
00000011 <== 3
| 00000101 <== 5
--------
00000111
*/
System.out.println("x1 ^ y1 => " + (x1 ^ y1)); // x1 ^ y1 => 6
/*
00000011 <== 3
^ 00000101 <== 5
--------
00000110
*/
6. 논리 연산자(& | && ||)
수학에서는 T ∧& T ∧ F ==> F
수학에서는 T ∧ T ∧ T ==> T
수학에서는 T ∨ T ∨ F ==> T
수학에서는 T ∨ T ∨ T ==> T
수학에서는 F ∨| F ∨ F ==> F
int c=50, d=60, e=70;
bool = (c > d) && (d < e) && (c == 3);
// false && 스킵
System.out.println("bool => " + bool); // false
bool = (c > d) || (d < e) || (c == 3);
// false || true || 스킵
System.out.println("bool => " + bool); // true
///////////////////////////////////////////////
bool = (c > d) & (d < e) & (c == 3);
// false & true & false
System.out.println("bool => " + bool); // false
bool = (c > d) | (d < e) | (c == 3);
// false | true | false
System.out.println("bool => " + bool); // true
###### 정리 ######
int i=1;
int j=i++; // j=i; j=1; i++; i=2;
if( (i > ++j) & (i++ == j) ) {
// ++j; j=2; (i > j = 2 > 2)
// false &
// (i == j = 2 == 2) true i++; i=3;
i = i+j;
}
System.out.println("i="+i); // i=3
i=1;
j=i++; // j=i; j=1; i++; i=2;
if( (i > ++j) && (i++ == j) ) {
// ++j; j=2; i>j = 2>2
// false
i = i+j;
}
System.out.println("i="+i); // i=2
int m1=0;
int n1 = 1;
if( (m1++ == 0) | (n1++ == 2) ) {
// m1 == 0 true m1++; m1=1;
// n1 == 1 false n1++; n1=2;
m1=42; // m1=42;
}
System.out.println("m1 => " + m1 + " n1 => " + n1 );
// m1 => 42, n1 => 2
m1=0;
n1=1;
if( (m1++ ==0) || (n1++ == 2) ) {
// m1 == 0 0 == 0 true m1++; m1=1;
m1=42;
}
System.out.println("m1 => " + m1 + " n1 => " + n1 );
// m1 => 42, n1 => 1
'Java' 카테고리의 다른 글
스캐너(Scanner) (0) | 2022.06.06 |
---|---|
연산자(Operator) 7. 비교 연산자 8. 할당 연산자 9. 삼항 연산자 (0) | 2022.06.06 |
연산자(Opperator) 2. 증감연산자, 3. bit 별 not 연산자, 4. 논리 부정 연산자 (0) | 2022.06.06 |
연산자(Operator) 1. 산술 연산자 (0) | 2022.06.06 |
데이터형 변환하기(Casting) (0) | 2022.06.06 |