1.4 Arithmetic Operators

Conditional operators(삼항 연산자)

time < 12 ? "am" : "pm";

C++과 동일하게 삼항 연산자를 지원한다.

Bit-wise operators and shift operators

- op1 & op2 : and 연산
- op1 | op2 : or 연산
- op1 ^ op2 : xor 연산
- ~op1 : not 연산
- op1>>op2 : op2 만큼 비트를 오른쪽으로 이동
	- 한 번 이동에 값이 1/2 + 맨 오른쪽에 있는 비트는 사라짐(소수점 버림)
- op1<<op2 : op2 만큼 비트를 왼쪽으로 이동
	- 한 번 이동에 값이 2배 + 맨 왼쪽에 있는 비트는 사라짐(소수점 버림)

ex) when a = 0xA7 (16진수)

https://images.velog.io/images/tonyhan18/post/ccd87e18-14df-4b10-be16-0816aa30afd7/image.png

a = a&b
a &=b

위의 두가지 표현은 같은 결과를 가지고 온다.

class opBit{
	public static void main(String[] args){
		char a = 0xA7
        System.out.println("a		: "
        	+ Integer.toString(a,16) + '\\\\n');
        System.out.println("a  & F0 : "
        	+ Integer.toString(a & 0xF0,16) + '\\\\n');
        System.out.println("a  | F0 : "
        	+ Integer.toString(a | 0xF0,16) + '\\\\n');
        System.out.println("a  ^ F0 : "
        	+ Integer.toString(a ^ 0xF0,16) + '\\\\n');
        }
}

여기에서 Integer.toString은 Integer 클래스의 toString static 메소드를 사용한 것으로 Integer.toString(연산, 출력방식) 의 형태로 연산의 결과를 출력방식에 맞추어 반환한다. 여기에서는 16으로 입력하였기 때문에 16진수 문자열로 반환이 된다.

연산자 우선순위(시험)

https://images.velog.io/images/tonyhan18/post/94dc3ffe-2356-4412-b24b-132cdb1a75db/image.png

https://images.velog.io/images/tonyhan18/post/d0bb9086-6a15-48a8-af93-12c9e89c2079/image.png

1 // 2 // 3-4 // 5-7 // 8 // 9 만약 우선순위가 같다면 왼쪽에서 오른쪽으로 연산을 진행한다. 1순위의 assignment는 오른쪽에서 왼쪽으로 연산을 진행한다.

ex>

int x = 1,y=2,z;

z = x + y*2 - ++x + (y+=3);