본문 바로가기
Language/JAVA

[JAVA] 연산자와 연산식 2 // 이항연산자 삼항연산자

by 아이엠제니 2021. 9. 13.

 


 

 

이항 연산자

  • 피연산자가 두 개인 연산자를 말함
  • 산술 연산자, 문자열 연결 연산자, 대입 연산자, 비교 연산자, 논리 연산자, 비트 논리 연산자, 비트 이동 연산자 등

 

 


문자열 연결 연산자(+)

  • 문자열을 서로 결합하는 연산자
  • 피연산자 중 한쪽이 문자열이면, 문자열 연결 연산자로 사용되어 다른 피연산자를 문자열로 변환하고 서로 결합
package thisisjava.chap03.num02;

public class StringConcatExample {
    public static void main(String[] args) {
        String str1 = "JDK" + 6.0; //JDK6.0
        String str2 = str1 + " 특징"; //JDK6.0 특징
        System.out.println(str2);

        String str3 = "JDK" + 3 + 3.0; //JDK33.0
        String str4 = 3 + 3.0 + "JDK"; //6.0JDK
        System.out.println(str3);
        System.out.println(str4);
    }
}

 

 


비교 연산자 ( <,<=,>,>=,==,!= )

  • 비교 연산자는 대소 또는 동등을 비교해서 boolean 타입인 true/false를 산출함
  • 대소 연산자는 boolean 타입을 제외한 기본 타입에 사용할 수 있음
  • 동등 연산자는 모든 타입에 사용될 수 있음
  • 비교 연산자는 흐름 제어문인 조건문(if), 반복문(for, while)에서 주로 이용, 실행 흐름을 제어할 때 사용
package thisisjava.chap03.num02;

public class CompareOperatorExample1 {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 10;
        boolean result1 = (num1 == num2); //true
        boolean result2 = (num1 != num2); //false
        boolean result3 = (num1 <= num2); //true
        System.out.println("result1=" + result1);
        System.out.println("result2=" + result2);
        System.out.println("result3=" + result3);

        char char1 = 'A';
        char char2 = 'B';
        boolean result4 = (char1 < char2); //true
        System.out.println("result4=" + result4);
    }
}

> 피연산자가 char 타입이면 유니코드 값으로 비교 연산 수행

 

package thisisjava.chap03.num02;

public class CompareOperatorExample2 {
    public static void main(String[] args) {
        int v2 = 1;
        double v3 = 1.0;
        System.out.println(v2 == v3);

        double v4 = 0.1;
        float v5 = 0.1f;
        System.out.println(v4 == v5);
        System.out.println((float) v4 == v5);
        System.out.println((int) (v4 * 10) == (int) (v5 * 10));
    }
}

> v4 == v5 false

> 피연산자를 모두 float타입으로 강제 타입 변환한 후 비굔 연산을 하든지, 정수로 변환해서 비교

 

  • String 타입의 문자열을 비교할 때에는 대소 연산자를 사용할 수 없고, 동등 비교 연산자는 사용할 수 있으나
    문자열이 같은지, 다른지를 비교하는 용도로는 사용되지 않음
  • == 연산자는 변수에 저장된 값만 비교
  • 문자열만 비교하고 싶다면 equals() 메소드 사용해야 함
package thisisjava.chap03.num02;

public class StringEqualsExample {
    public static void main(String[] args) {
        String strVar1 = "신민철";
        String strVar2 = "신민철";
        String strVar3 = new String("신민철");

        System.out.println(strVar1 == strVar2);
        System.out.println(strVar1 == strVar3);
        System.out.println();
        System.out.println(strVar1.equals(strVar2));
        System.out.println(strVar2.equals(strVar3));
    }
}

 

 


논리 연산자 (&&, ||, &, |, ^, !)

  • 논리곱(&&), 논리합(||), 배타적 논리합(^), 논리 부정(!) 연산을 수행
  • 논리 연산자의 피연산자는 boolean 타입만 사용할 수 있음

 

  • && / & : AND 논리곱 // 피연산자 모두가 true일 경우에만 연산 결과는 true
  • || / | : OR 논리합 // 피연산자 중 하나만 true이면 연산 결과는 true
  • ^ : XOR 배타적 논리합 // 피연산자가 하나는 true이고 다른 하나가 false일 경우에만 연산 결과는 true
  • ! : NOT 논리부정 // 피연산자의 논리값을 바꿈
package thisisjava.chap03.num02;

public class LogicalOperatorExample {
    public static void main(String[] args) {
        int charCode = 'A';
        if ((charCode >= 65) & (charCode <= 90)) {
            System.out.println("대문자 이군요");
        }
        if ((charCode >= 97) && (charCode <= 122)) {
            System.out.println("소문자 이군요");
        }
        if (!(charCode < 48) && !(charCode > 5)) {
            System.out.println("0~9 숫자 이군요");
        }
        int value = 6;

        if ((value % 2 == 0) | (value % 3 == 0)) {
            System.out.println("2 또는 3의 배수이군요");
        }
        if ((value % 2 == 0) || (value % 3 == 0)) {
            System.out.println("2 또는 3의 배수이군요");
        }
    }
}

 

 


비트 연산자 (&, |, ^, ~, <<, >>, >>>)

  • 비트 연산자는 데이터를 비트 단위로 연산함
  • 즉 0과 1이 피연산자가 됨
  • 0과 1로 표현이 가능한 정수 타입만 비트 연산을 할 수 있음
  • &, |, ^, ~
    피연산자가 boolean 타입일 경우에는 일반 논리 연산자
    피연산자가 정수 타입일 경우에는 비트 논리 연산자로 사용

 

  • AND 논리곱 : 두 비트 모두 1일 경우에만 연산 결과가 1
  • OR 논리합: 두 비트 중 하나만 1이면 연산 결과는 1
  • XOR 배타적 논리합: 두 비트 중 하나는 1이고 다른 하나가 0일 경우 연산 결과는 1
  • NOT 논리 부정: 보수

 

package thisisjava.chap03.num02;

public class BiteLogicExample {
    public static void main(String[] args) {
        System.out.println("45 & 25 = " + (45 & 25));
        System.out.println("45 | 25 = " + (45 | 25));
        System.out.println("45 ^ 25 = " + (45 ^ 25));
        System.out.println("~45 = " + (~45));
    }
}

 

 


비트 이동 연산자 (<<, >>, >>>)

  • a << b : 정수 a의 각 비트를 b만큼 왼쪽으로 이동(빈자리는 0으로 채워짐)
  • a >> b : 정수 a의 각 비트를 b만큼 오른쪽으로 이동(빈자리는 정수 a의 최상위 부호 비트(MSB)와 같은 값으로 채워짐
  • a >>> b : 정수 a의 각 비트를 b만큼 오른쪽으로 이동(빈자리는 0으로 채워짐)

 

package thisisjava.chap03.num02;

public class BitShiftExample {
    public static void main(String[] args) {
        System.out.println("1 << 3 = " + (1 << 3));
        System.out.println("=8 >> 3 = " + (-8 >> 3));
        System.out.println("-8 >>> 3 = " + (-8 >>> 3));
    }
}

 

 


대입 연산자(=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=)

  • 대입 연산자는 오른쪽 피연산자의 값을 좌측 피연산자인 변수에 저장
package thisisjava.chap03.num02;

public class AssignmentOperatorExample {
    public static void main(String[] args) {
        int result = 0;
        result += 10;
        System.out.println("result=" + result);
        result = 5;
        System.out.println("result=" + result);
        result *= 3;
        System.out.println("result=" + result);
        result /= 5;
        System.out.println("result=" + result);
        result %= 3;
        System.out.println("result=" + result);
    }
}

 

 


삼항 연산자

  • 세 개의 피연산자를 필요로 하는 연산자를 말함
조건식 ? 값 또는 연산식 : 값 또는 연삭식
(피연산자1) (피연산자2)     (피연산자3)
                  true
                                      false

 

package thisisjava.chap03.num02;

public class ConditionalOperationExample {
    public static void main(String[] args) {
        int score = 85;
        char grade = (score > 90) ? 'A' : ((score > 80) ? 'B' : 'C');
        System.out.println(score + "점은" + grade + "등급입니다");
    }
}

 

 

 

'이것이 자바다' 공부 기록
300x250