뭐라도 끄적이는 BLOG

Java 연산자 본문

Java/Java 기본

Java 연산자

Drawhale 2023. 7. 1. 05:58

산술 연산자

산술 연산자는 대수학에서 사용되는 것과 같은 방식으로 수학 식에 사용된다.

Operator Description Example
+ 양쪽 피연산자를 더합니다. A + B
- 양쪽 피연산자를 뺍니다. A - B
* 양쪽 피연산자를 곱합니다. A * B
/ 왼쪽 피연산자를 오른쪽 피연산자로 나눕니다. A / B
% 왼쪽 피연산자를 오른쪽 피연산자로 나눈 나머지를 구합니다. A % B
++ 피연산자의 값을 1 증가 시킵니다. A++
-- 피연산자의 값을 1 감소 시킵니다. A--

Example

public class Test {
   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 25;
      int d = 25;

      System.out.println("a + b = " + (a + b) );
      System.out.println("a - b = " + (a - b) );
      System.out.println("a * b = " + (a * b) );
      System.out.println("b / a = " + (b / a) );
      System.out.println("b % a = " + (b % a) );
      System.out.println("c % a = " + (c % a) );
      System.out.println("a++   = " +  (a++) );
      System.out.println("b--   = " +  (a--) );

      // Check the difference in d++ and ++d
      System.out.println("d++   = " +  (d++) );
      System.out.println("++d   = " +  (++d) );
   }
}

Output

a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
c % a = 5
a++   = 10
b--   = 11
d++   = 25
++d   = 27

비트 연산자

비트 연산자는 피연산자들을 비트 단위로 나누어 연산을 한다.

Operator Description Example
& (bitwise and) 두 피연산자의 같은 자리의 비트가 모두 1이면 해당 자릿수는 1을 반환합니다. (A & B)
| (bitwise or) 두 피연산자의 같은 자리의 비트가 하나 이상이 1이면 해당 자릿수는 1을 반환합니다. (A | B)
^ (bitwise XOR) 두 피연산자의 같은 자리의 비트가 둘중 하나만 1이면 해당 자릿수는 1을 반환합니다. (A ^ B)
~ (bitwise compliment) 각 비트가 1이면 0, 0 이면 1로 치환 됩니다. (~A )
<< (left shift) 오른쪽 피연산자의 값에따라 왼쪽 피연산자의 비트가 왼쪽으로 이동합니다. 이동후 빈자리는 0을 채웁니다. A << 2
>> (right shift) 오른쪽 피연산자의 값에따라 왼쪽 피연산자의 비트가 오른쪽으로 이동합니다. 이동후 빈자리는 마지막 비트의 값으로 채웁니다. A >> 2
>>> (zero fill right shift) 오른쪽 피연산자의 값에따라 왼쪽 피연산자의 비트가 오른쪽으로 이동합니다. 이동후 빈자리는 0을 채웁니다. A >>>2

Example

public class Test {

   public static void main(String args[]) {
      int a = 60;	/* 60 = 0011 1100 */
      int b = 13;	/* 13 = 0000 1101 */
      int c = 0;

      c = a & b;        /* 12 = 0000 1100 */
      System.out.println("a & b = " + c );

      c = a | b;        /* 61 = 0011 1101 */
      System.out.println("a | b = " + c );

      c = a ^ b;        /* 49 = 0011 0001 */
      System.out.println("a ^ b = " + c );

      c = ~a;           /*-61 = 1100 0011 */
      System.out.println("~a = " + c );

      c = a << 2;       /* 240 = 1111 0000 */
      System.out.println("a << 2 = " + c );

      c = a >> 2;       /* 15 = 1111 */
      System.out.println("a >> 2  = " + c );

      c = a >>> 2;      /* 15 = 0000 1111 */
      System.out.println("a >>> 2 = " + c );
   }
}

Output

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2  = 15
a >>> 2 = 15

>>와 >>>의 결과가 같아 같은 연산으로 보이지만 부호가 다르면 결과가 완전히 다르다. >> 연산자는 부호를 유지 시킬수 있지만 >>> 연산자는 0으로 채워버리기 때문에 부호를 전혀 유지할 수 없다.

관계 연산자

Operator Description Example
== (equal to) 두 피연산자의 값이 같은지 확인하고 같은경우 true 다른경우 false를 반환 합니니다. (A == B)
!= (not equal to) 두 피연산자의 값이 같은지 확인하고 같지 않은경우 true 같은경우 false를 반환합니다. (A != B)
> (greater than) 왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 큰지 확인하고 그렇다면 true 아니면 false를 반환합니다. (A > B)
< (less than) 왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 작은지 확인하고 그렇다면 true 아니면 false를 반환합니다. (A < B)
>= (greater than or equal to) 왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 크거나 같은지 확인하고 그렇다면 true 아니면 false를 반환합니다. (A >= B)
<= (less than or equal to) 왼쪽 피연산자의 값이 오른쪽 피연산자의 값보다 작거나 같은지 확인하고 그렇다면 true 아니면 false를 반환합니다. (A <= B)

Example

public class Test {

   public static void main(String args[]) {
      int a = 10;
      int b = 20;

      System.out.println("a == b = " + (a == b) );
      System.out.println("a != b = " + (a != b) );
      System.out.println("a > b = " + (a > b) );
      System.out.println("a < b = " + (a < b) );
      System.out.println("b >= a = " + (b >= a) );
      System.out.println("b <= a = " + (b <= a) );
   }
}

Output

a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

논리 연산자

Operator Description Example
&& (logical and) 두 피연산자가 모두 true이면 true가 반환 됩니다. (A && B)
|| (logical or) 두 피연산자중 하나가 true이면 true가 반환 됩니다. (A || B)
! (logical not) 피연산자가 true이면 false, false이면 true를 반환 합니다. !A

Example

public class Test {

   public static void main(String args[]) {
      boolean a = true;
      boolean b = false;

      System.out.println("a && b = " + (a&&b));
      System.out.println("a || b = " + (a||b) );
      System.out.println("!(a && b) = " + !(a && b));
   }
}

Output

a && b = false
a || b = true
!(a && b) = true

instanceof

instanceof 연산자는 참조변수에만 사용된다. 왼쪽의 변수는 오른쪽의 클래스/인터페이스에 대해 IS-A관계이면 true가 반환 된다.

( Object reference variable ) instanceof  (class/interface type)

Example

public class Test {

   public static void main(String args[]) {

      String name = "James";

      // following will return true since name is type of String
      boolean result = name instanceof String;
      System.out.println( result );
   }
}

Output

true

assignment(=) operator

Operator Description Example
= 단순 할당 연산자로 오른쪽 비연산자의 결과값을 왼쪽 피연산자에게 할당 합니다. C = A + B
+= 오른쪽 피연산자를 왼쪽 피연산자에 더한뒤 왼쪽 피연산자에 할당합니다. C += A
-= 오른쪽 피연산자를 왼쪽 피연산자에 뺀뒤 왼쪽 피연산자에 할당합니다. C -= A
*= 오른쪽 피연산자를 왼쪽 피연산자에 곱한뒤 왼쪽 피연산자에 할당합니다. C *= A
/= 오른쪽 피연산자를 왼쪽 피연산자에 나눈뒤 왼쪽 피연산자에 할당합니다. C /= A
%= 오른쪽 피연산자를 왼쪽 피연산자에 나눈뒤의 나머지를 왼쪽 피연산자에 할당합니다. C %= A
<<= 오른쪽 피연산자의 값에따라 왼쪽 피연산자의 비트가 왼쪽으로 이동한 결과값을 왼쪽 피연산자에 할당합니다. C <<= 2
>>= 오른쪽 피연산자의 값에따라 왼쪽 피연산자의 비트가 오른쪽으로 이동한 결과값을 왼쪽 피연산자에 할당합니다. C >>= 2
&= 두 피연산자의 같은 자리의 비트가 모두 1이면 해당 자릿수는 1을 반환합니다. C &= 2
^= 두 피연산자의 같은 자리의 비트가 둘중 하나만 1이면 해당 자릿수는 1을 반환합니다. C ^= 2
|= 두 피연산자의 같은 자리의 비트가 하나이상 1이면 해당 자릿수는 1을 반환합니다. C |= 2

Example

public class Test {

   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 0;

      c = a + b;
      System.out.println("c = a + b = " + c );

      c += a ;
      System.out.println("c += a  = " + c );

      c -= a ;
      System.out.println("c -= a = " + c );

      c *= a ;
      System.out.println("c *= a = " + c );

      a = 10;
      c = 15;
      c /= a ;
      System.out.println("c /= a = " + c );

      a = 10;
      c = 15;
      c %= a ;
      System.out.println("c %= a  = " + c );

      c <<= 2 ;
      System.out.println("c <<= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c >>= 2 ;
      System.out.println("c >>= 2 = " + c );

      c &= a ;
      System.out.println("c &= a  = " + c );

      c ^= a ;
      System.out.println("c ^= a   = " + c );

      c |= a ;
      System.out.println("c |= a   = " + c );
   }
}

Output

c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10

화살표(->) 연산자

java 8부터 추가된 람다식에 사용되는 연산자이다. 람다는 다른장에서 더 자세히 다룬다.

 

3항 연산자

variable x = (expression) ? value if true : value if false

3항 연산자는 3개의 피연산자로 이루어져 있다. expression의 값이 true일때 :을 기준으로 왼쪽 false일때 오른쪽의 값이 변수 x에 할당된다.

Example

public class Test {

   public static void main(String args[]) {
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}

Output

Value of b is : 30
Value of b is : 20

연산자 우선 순위

일반적인 수학의 연산자 처럼 위에서 소개한 연산자 모두 우선순위가 있다. 하지만 이 모든 것을 숙지할 필요없이 적절히 괄호를 사용해주면 사용하는 사람도 코드를 읽는 사람도 편리하다.

Category Operator Associativity
Postfix expression++ expression-- Left to right
Unary ++expression –-expression +expression –expression ~ ! Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left

(optional) Java 12. switch 연산자

조건문으로 사용하던 switch문이 switch식의 형태로 사용할 수 있다. ( statements -> expressions )

static void howMany(int k) {
    switch (k) {
        case 1  -> System.out.println("one");
        case 2  -> System.out.println("two");
        default -> System.out.println("many");
    }
}

switch가 expression으로 사용될 수 있다.

static void howMany(int k) {
    System.out.println(
        switch (k) {
            case  1 -> "one"
            case  2 -> "two"
            default -> "many"
        }
    );
}

다음과 같이 변수 할당을 할 수 있다.

T result = switch (arg) {
    case L1 -> e1;
    case L2 -> e2;
    default -> e3;
};

그리고 switch식에 사용하는 yield 키워드가 추가 되었다.

int result = switch (s) {
    case "Foo": 
        yield 1;
    case "Bar":
        yield 2;
    default:
        System.out.println("Neither Foo nor Bar, hmmm...");
        yield 0;
};

yield 키워드로이전의 switch문과 새로 나온 switch식을 명확하게 구분할 수 있다.


※ 참고 자료

www.tutorialspoint.com/java/java_basic_operators.htm

docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

openjdk.java.net/jeps/354

반응형

'Java > Java 기본' 카테고리의 다른 글

Java Class  (0) 2023.07.01
Java 제어문  (0) 2023.07.01
Java Variables와 Data Types  (0) 2023.06.30
Garbage Collector의 종류 (Serial, Parallel, CMS, G1, Z)  (0) 2023.06.29
JVM 구성 요소  (0) 2023.06.29