연산자

dev_314·2022년 9월 28일
0

| 백기선님의 라이브 스터디를 참고하여 작성한 게시물입니다.

산술 연산자

단항 연산자

OperatorDescription
+단항 덧셈, 양수 표현
-단항 뺄셈, 음수 표현
++1 증가
--1 감소
!논리 부정

이항 연산자

OperatorDescription
+덧셈, 스트링 concatenation
-뺄셈
*곱셈
/나눗셈
%나머지

비트 연산자

OperatorDescription
>>오른쪽으로 n비트 밀기
<<왼쪽으로 n비트 밀기
&and
Ior
~flip all bits
^xor
package bit;

public class main {
    public static void main(String[] args) {
        int a = 0b1010;
        int b = 0b1111;
        
        // int는 32bit -> 기본값은 0000_0000_0000_0000_0000_0000_0000_0000
        // bit의 앞의 연속된 0은 생략하는 듯

        System.out.println(Integer.toBinaryString(a >> 2)); // 10
        System.out.println(Integer.toBinaryString(a << 2)); // 101000
        System.out.println(Integer.toBinaryString(a & b)); // 1010
        System.out.println(Integer.toBinaryString(a | b)); // 1111
        System.out.println(Integer.toBinaryString(~a)); // 11111111111111111111111111110101 (32bit)
        System.out.println(Integer.toBinaryString(a ^ b)); // 101
    }
}

관계 연산자

OperatorDescription
>왼쪽이 오른쪽보다 크면 참, 아니면 거짓
<왼쪽이 오른쪽보다 작으면 참, 아니면 거짓
>=왼쪽이 오른쪽보다 크거나 같으면 참, 아니면 거짓
<=왼쪽이 오른쪽보다 작거나 같으면 참, 아니면 거짓
==왼쪽 오른쪽이 같으면 참, 아니면 거짓
!=왼쪽 오른쪽이 다르면 참, 아니면 거짓

논리 연산자

OperatorDescription
&&둘 다 참이어야 참, 하나라도 거짓이면 거짓
II둘 중 하나만 참이여도 참, 둘다 거짓이면 거짓
!참을 거짓, 거짓을 참으로 변경

instanceof

객체의 타입을 확인하는 연산자

package temp;

public class Outer implements MyInterface {

    public Outer() {
    }

    public static void main(String[] args) {

        Outer outer = new Outer();
        System.out.println(outer instanceof Outer); // true
        System.out.println(outer instanceof MyInterface); // true

        Inner inner = new Inner();
        System.out.println(inner instanceof Outer); // true
        System.out.println(inner instanceof MyInterface); // true

        System.out.println(outer instanceof Inner); // false
    }

    @Override
    public void printHi() {
        System.out.println("instanceOf method");
    }

    static class Inner extends Outer {
        public Inner() {
        }

        @Override
        public void printHi() {
            System.out.println("inner method");
        }
    }

}

interface MyInterface {
    void printHi();
}

assignment(=) operator

참고: 대입 연산자

개인적으로는 자주 사용하지 않는 대입 연산자는 가독성을 위해 사용하지 않는 것이 더 좋다고 생각한다.

화살표(->) 연산자

람다식에 사용되는 연산자

(parameter) -> {body}

추후 람다 함수를 다룰 때 집중적으로 살펴보도록 하겠다.

삼항 연산자

int a = 0;
if () {
	a = 1;
} else {
	a = 2;
}

위와 같은 조건문을 삼항 연산자를 통해 다음과 같이 표현할 수 있다.

int a = 조건 ? 1 : 2;

삼항 연산자를 자주 사용하는 편인데,

1. 삼항 연산자가 여러 번 중첩 된 경우
2. 조건이 이해하기 어려운 경우

에는 if-else 구문으로 표현하는 것이 가독성에 더 좋다는 리뷰를 받았다.

또한 삼항 연산자가 성능상 이점이 있는 것도 아니다.

연산자 우선 순위

사진 출처: https://toma0912.tistory.com/66

개발을 하면서 딱히 연산자 우선 순위가 햇갈려 문제가 생긴 적은 없었던 것 같다.

Java 13의 switch 연산자

참고: [Java-22] 자바13 스위치, java13 switch 연산

개선된 switch-case

기존 (Java 12이하)의 Switch-case 문법은 다음과 같다.

// sout == System.out.println()
int a = 3;
switch (a) {
	case 1:
    case 2:
    	sout("a is 1 or 2");
        break;
	case 3:
    	sout("a is 3");
        break;
	defualt:
    	sout("a is bigger than 3");
        break;
}
  1. switch case문은 가독성이 좋지 못하다.
  2. 실수 가능성이 있다 (break 생략 등)

그래서 개인적으로 switch-case를 별로 좋아하지 않는다.

Java 13부터는 개선된 Switch-case를 제공한다.

int a = 4;
switch (a) {
	case 1, 2 -> System.out.println("a is 1 or 2");
	case 3 -> System.out.println("a is 3");
	default -> System.out.println("a is not 1,2,3");
}
  1. multi case label(EX: case 1,2)을 사용할 수 있다.
  2. case문에 람다 함수를 사용할 수 있다.
    그런데 람다 함수와 case: 표기법을 같이 사용할 수 없다.

switch 연산자

switch-case 문 안에서 변수를 초기화 하고 싶다.

int a;
switch(today){
	case "mon" -> a = 1;
    case "tue" -> a = 2;
    ...
    default -> a = 0;
}

Java 13의 Switch 연산자를 통해 개선 가능하다

int a = switch(tody) {
	case "mon" -> 1;
    case "tue" -> 2;
    ...
    default -> a = 0;
}

var와 결합하여 더 유연한 변수 초기화가 가능하다.

var data = switch(today) {
	case "mon" -> 1;
    case "tue" -> "2";
    ...
    default -> a = false;
}

그런데 strong type language의 장점이 사라지므로 좋은 코드는 아닌 것 같다.

profile
블로그 이전했습니다 https://dev314.tistory.com/

0개의 댓글