youngfromnowhere
[Java] Bitwise 논리연산자의 우선순위 본문
점수를 입력받아서 if-else if 문을 통해
등급을 메기는 코드를 작성하려고 한다.
그런데 이 때 논리 연산자인 &&을 bitwise-and인 &으로 바꾸어도
결과가 같다는 것을 알게 된다.
public class score {
static char bitwise_method(int score) {
if (score >= 91 & score <= 100) {
return 'A';
}
else if (score >= 81 & score <= 90) {
return 'B';
}
else if (score >= 71 & score <= 80) {
return 'C';
}
else {
return 'D';
}
}
static char method(int score) {
if (score >= 91 && score <= 100) {
return 'A';
}
else if (score >= 81 && score <= 90) {
return 'B';
}
else if (score >= 71 && score <= 80) {
return 'C';
}
else {
return 'D';
}
}
public static void main(String[] args) {
for (int score=1; score <= 100; score++) {
if (bitwise_method(score) == method(score)) {
System.out.printf("Results match for score = %d\n", score);
}
else {
System.out.printf("Results don't match for score = %d\n", score);
}
}
}
}
bitwise_method와 method의 결과를 main에서 비교한다.
결과는..
Results match for score = 1
Results match for score = 2
Results match for score = 3
Results match for score = 4
Results match for score = 5
Results match for score = 6
Results match for score = 7
Results match for score = 8
Results match for score = 9
Results match for score = 10
Results match for score = 11
Results match for score = 12
Results match for score = 13
Results match for score = 14
Results match for score = 15
Results match for score = 16
Results match for score = 17
Results match for score = 18
Results match for score = 19
Results match for score = 20
.
.
.
/*생략*/
.
.
.
Results match for score = 84
Results match for score = 85
Results match for score = 86
Results match for score = 87
Results match for score = 88
Results match for score = 89
Results match for score = 90
Results match for score = 91
Results match for score = 92
Results match for score = 93
Results match for score = 94
Results match for score = 95
Results match for score = 96
Results match for score = 97
Results match for score = 98
Results match for score = 99
Results match for score = 100
어째서 bitwise 연산자를 쓴 코드가 무리없이 돌아가고 결과도 같은가 하면..
Java에서는 bitwise-and의 우선순위가 논리연산자와 같이, 비교연산자보다 낮기 때문이다.
따라서 따로 괄호처리를 안했더라도 똑같은 결과가 나온다.
물론 Java의 일반적인 논리연산자는 short-circuit이기 때문에 처리 속도는
일반 논리연산자를 쓰는 쪽이 더 빠르다.
short-circuit에 대해서는 <Data Structures and Lgorithms in Python>, Michael T. Goodrich의 설명을
인용하겠다.
"The and and or operators are short-circuit, in that they do not evaluate the second operand if the
result can be determined based on the value of teh first operand."
이 특성 때문에 해당 연산자들을 쓸 때 condition test의 우선순위를 정할 수 있고,
불필요한 test를 줄일 수 있다.
한 편, Python에서는 똑같이 두 코드의 결과를 비교했을때 결과가 다르게 나온다.
Python은 bitwise-and를 비교연산자보다 먼저 처리하기 때문이다.
'Java' 카테고리의 다른 글
[Java] 의도한대로 작동하지 않은 clearScreen() (0) | 2022.11.30 |
---|---|
[Java] Java compile. 디렉토리 설정 옵션 (0) | 2022.11.25 |
[Java] 수동 컴파일할 때, 소스코드 수정사항이 반영되지 않는 경우 (0) | 2022.11.25 |
[Java] Abstract Class 간단한 메모 (0) | 2022.11.18 |
[Java]Array 선언, 생성, 초기화 (0) | 2022.11.08 |