
이전 변수 관련 포스팅 후 연산자 관련 포스팅도 해야겠다 싶었다.
연산자(Operator)란 어떤 특정한 기능을 수행하는 Symbol이다.
Java또한 다른 언어와 마찬가지로 다양한 연산자가 존재하며, 각 연산자별 우선 순위가 존재한다. 연산자 우선 순위를 다 외울수는 없지만가능한가 알고리즘 문제를 풀며 불편함을 느꼈던 기억이 흐릿하게 있어 그래도 한 번 정리 해보고자 한다.
연산자는 크게 산술(Arithmetic), 시프트(Bit Shift), 비교(Comparator), 비트(Bit), 논리(Logical), 삼항(Trinomial) 연산자와 할당(=)으로 나눌 수 있다.
Java 연산자의 우선 순위는 대략(대충) 말하자면
산술 > 시프트 > 비교 > 비트 > 논리 > 삼항 > 할당 정도로 볼 수 있다. 이정도로만 알아 두어도 될 것 같다고 생각한다.
무튼 우선 순위를 정리하면 아래와 같다.
| Operator | direction | Priority |
|---|---|---|
| ( ) , . | - | TOP |
| ++/-- +/-(Sign) ! ~ casting | ← | HIGH |
| * / % | → | |
| +/-(Arithmetic) | → | |
| << >> >>> | → | |
| <(=) >(=) instanceof | → | |
| == != | → | |
| & > ^ > | → | |
| && > | ||
| ? : | → | |
| = *= /= += -= <<= … | ← | LOW |
산술연산자 중 삼항연산자가(Trinomial) 아닌 이항연산자(Binomial)의 경우 피연산자(Operand)의 type이 다를 경우 이를 자동으로 변환하는 type matching을 수행한다. 타입 변환의 규칙으로는
int형으로 변환후 연산을 수행한다.byte b1 = 10;
byte b2 = 20;
// byte b3 = b1 + b2;
// this causes Error : type mismatch
// calculation is done at int domain
byte b3 = (byte)(b1 + b2);
int i1 = 10;
long l1 = 20;
// int i2 = i1 + l1;
// type mismatch; calc follows bigger type
long i2 = i1 + l1;
int와 double이다.float f1 = 10.0f; // default type is double
// float f2 = f1 + 20.0;
double f2 = f1 + 20.0;
String의 +연산과 정수형, 실수형 데이터의 +연산은 그 기능이 다르며, 정수형의 /연산과 실수형의 /은 그 결과가 다르다. Java는 다른 데이터 타입간 연산을 아래와 같이 처리한다.
String + int = Stringint / int = intfloat / int = floatBit shift연산자의 경우 산술 shift(Arithmetic shift)와 논리 shift(Logical shift)로 나뉜다.
Arithmetic shift(>>)의 경우 MSB(Most Significatn Bit)를 부호(sign) bit를 유지한 채 채운다.
Logical shift(>>>)의 경우 음수/양수에 관련 없이 MSB를 0으로 채운다.
left shift의 경우 arithmetic shift, logical shift 모두 결과가 같으므로 <<< 같은 연산자는 없다.
16 >> 3
// 0000 0000 0000 0000 0000 0000 0001 0000
// -> 0000 0000 0000 0000 0000 0000 0000 0010
-16 >> 3
// 1111 1111 1111 1111 1111 1111 1111 0000
// -> 1111 1111 1111 1111 1111 1111 1111 1110
-16 >>> 3
// -> 0001 1111 1111 1111 1111 1111 1111 1110 (536870910)
11....10을 32번 left shift를 하면 overflow가 나지 않을까. 밀려서 0이 될 것 같은데 사실 -1이된다.
그 이유는
If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
int형에 대한 bit shift는 하위 5bit만 쓴다. 이거 때문에 삽질해봄. 생각나서 쓰게 되었다