자바 스터디

연산자

내일도무사히 2021. 1. 6. 17:20

백기선님의 Java 스터디를 진행하며 찾아본 내용입니다.

 

 

목표

자바가 제공하는 다양한 연산자를 학습하시오

 

 

학습할 것

  • 산술 연산자
  • 비트 연산자
  • 관계 연산자
  • 논리 연산자
  • instanceof
  • assignment(=) operator
  • 화살표(->) 연산자
  • 3항 연산자
  • 연산자 우선 순위
  • (optional) Java 13. switch 연산자

산술 연산자

일반적인 수학 연산을 위해 사용되어지는 연산자

+, -, *, /, %, ++, --

 

 

 

비트연산자

정수 또는 긴 정수 비트로 이진 논리 연산을 수행하는데 사용되어지는 연산자
Operator Description
& AND Operator
~ NOT Operator
| OR Operator
~ NOT Operator
<< Zero-fill left shift
>> Signed right shift
>>> Zero-fill right shift

 

 

 

관계 연산자

두개의 값을 비교하는데에 사용되어지는 연산자
Operator Name
== Equal to
!= Not Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

 

 

 

논리 연산자

두 개의 값 간의 논리 연산을 수행하는 연산자
Operator Name
&& Logical and
|| Logical or
! Logical not

 

 

instanceof

객체가 지정된 유형의 인스턴스(class or subclass of interface)인지 테스트하는데 사용되어지는 메소드

return 값은 boolean 값

1
2
3
4
5
6
class Simple1 {
  public static void main(String args[]) {
    Simple1 s = new Simple1();
    System.out.println(s insanceof Simeple1); // true 
  }
}
cs

 

 

assignment(=) operator

변수에 값을 할당하는데 사용되어지는 연산자
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x^3
>>= x >>= 3 x = x>>3
<<= x <<= 3 x = x<<3

 

 

 

Arrow token

자바8에서 소개된 람다 표현식에서 사용되어지는 연산자

다음과 같이 사용되어진다

 

1
2
3
4
5
6
Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Run method");
            }
};
cs

위의 코드는 아래의 코드와 같다

1
Runnable r = () -> System.out.println("Run method");
cs

 

 

 

 

3항 연산자

if-then-else 문에 대한 축약 형으로 볼 수 있다.

 

1
2
// someCondition이 true면 value1의 값을 result에 할당하고 그렇지 않으면 value2의 값을 결과에 할당한다
result = someCondition ? value1 : value2;
cs

 

 

 

연산자 우선 순위

Operators Precedence
postfix expr++, expr--
unary ++expr, --expr, +expr, -expr, ~, !
multiplicative *, /, %
additive +, -
shift <<, >>, >>>
relational <, >, <=, >=, instanceof
equality ==, !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=

 

 

(optional) Java 13. switch 연산

 자바 13에서 소개된 switch 구문은 yield가 기존의 break를 대체한다.

 새로운 switch 구문은 다음 형식을 따른다

 

1
case label_1, label_2, ..., label_n -> expression;|throw-statement;|block 
cs

 

 

자바 런타임이 화살표 왼쪽에 있는 label과 매치하는 것이 있다면 우측의 코드를 실행해주며, 기존의 switch문과 같이 break가 없다고해서 다음 case로 넘어가지 않게 된다. 

 

 

코드로 보자면 기존의 switch 구문은 다음과 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public enum Day { SUNDAY, MONDAY, TUESDAY,
    WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
 
// ...
 
    int numLetters = 0;
    Day day = Day.WEDNESDAY;
    switch (day) {
        case MONDAY:
        case FRIDAY:
        case SUNDAY:
            numLetters = 6;
            break;
        case TUESDAY:
            numLetters = 7;
            break;
        case THURSDAY:
        case SATURDAY:
            numLetters = 8;
            break;
        case WEDNESDAY:
            numLetters = 9;
            break;
        default:
            throw new IllegalStateException("Invalid day: " + day);
    }
    System.out.println(numLetters);
cs

 

위의 코드는 Java13 swtich 코드로 구현한 다음의 코드와 같다

 

1
2
3
4
5
6
7
8
9
10
    int numLetters = 0;
    Day day = Day.WEDNESDAY;
    switch (day) {
        case MONDAY, FRIDAY, SUNDAY -> numLetters = 6;
        case TUESDAY                -> numLetters = 7;
        case THURSDAY, SATURDAY     -> numLetters = 8;
        case WEDNESDAY              -> numLetters = 9;
        default -> throw new IllegalStateException("Invalid day: " + day);
    };
    System.out.println(numLetters);
cs

 

또한 화살표(->) 대신 콜론(:)을 이용해 다음과 같이 표현할 수 도 있다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    Day day = Day.WEDNESDAY;
    int numLetters = switch (day) {
        case MONDAY:
        case FRIDAY:
        case SUNDAY:
            System.out.println(6);
            yield 6;
        case TUESDAY:
            System.out.println(7);
            yield 7;
        case THURSDAY:
        case SATURDAY:
            System.out.println(8);
            yield 8;
        case WEDNESDAY:
            System.out.println(9);
            yield 9;
        default:
            throw new IllegalStateException("Invalid day: " + day);
    };
    System.out.println(numLetters);
cs

 

yield구문은 리턴과 같은 기능을 수행하는데

 

Java SE 13에서 부터는 break문 대신 yield구문을 이용해 break의 역할을 수행해야한다

 

또한 switch구문을 사용할 때 콜론(:)이 아닌 화살표(->)를 사용하는 것이 권장되어진다.

 

 

 

 

 

 

References

www.w3schools.com/java/java_operators.asp

 

Java Operators

Java Operators Java Operators Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Although the + operator is often used to add together two values, like in the example ab

www.w3schools.com

stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java

 

What does the arrow operator, '->', do in Java?

While hunting through some code I came across the arrow operator, what exactly does it do? I thought Java did not have an arrow operator. return (Collection) CollectionUtils.select(list...

stackoverflow.com

docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

 

Equality, Relational, and Conditional Operators (The Java™ Tutorials > Learning the Java Language > Langu

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

 

Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com