위로 아래

연산 우선순위 

단항 연산자 -> 이항 연상자 -> 삼항 연산자

괄호 -> 산술 -> 비교 -> 비트 -> 논리 -> 대입

not -> and -> or 순서

 

쇼트서킷

 

쇼트서킷(short circuit)

  1. &&와 || 연산 중 앞의 항으로 이미 true인지 false인지 결정되면 뒤에 항은 보지 않는다.
  2. &&, || : 쇼트서킷 사용
  3. &, | : 쇼트서킷 사용 X
  4. 프로그램 성능을 높이기 위해선, 더 확실한 항을 앞쪽에 놓는 편이 좋다.
public class ArithmeticDemo{
	public static void main(String[] args) {
		int x = 0, y = 1;
		System.out.println( (x<1) || (y--<1) );
		System.out.println("x = " + x + ", y = " + y);  // y--는 반영이 안 된다
		
		x = 0;
		y = 1;
		System.out.println((x<1)|(y--<1));
		System.out.println("x = " + x + ", y = " + y);  // y--도 반영된다
	}
}
public class OperatorPrecedenceDemo {
	public static void main(String[] args) {
		int year = 2020;
		System.out.println(year%4 ==0 && year %100 !=0 || year %400==0);  // 결과 true
	}
}

 


시프트 연산자

시프트 연산자 

  1. 산술적 왼쪽 시프트(arithmetic left shift)
    1. <<
    2. 이진수 비트를 왼쪽으로 밀고 최하위 비트에 0 채우기
    3. 2^(이동 숫자)만큼 곱하기
  2. 산술적 왼쪽 시프트(arithmetic right shift)
    1. >>
    2. 이진수 비트를 오른쪽으로 밀고 최상위 비트와 동일한 비트로 채우기
    3. 최상위 비트가 0이면, 2^(이동 숫자)만큼 나누기
  3. 논리적 오른쪽 시프트 (logical right shift)
    1. >>>
    2. 이진수 비트를 오른쪽으로 밀고 최상위 비트에 0 채우기
    3. 2^(이동 숫자)만큼 나누기
public class AssignmentDemo {
	public static void main(String[] args) {
		int value = 1;
		value <<=3;
		System.out.println("값 = " + value);
		value = value>>3;
		System.out.println("값 = " + value);
	}
}