📢 항에 갯수에 따른 연산자
- 단항 연산자 : 항이 1개
- 이항 연산자 : 항이 2개
- 삼항 연산자 : 항이 3개인 경우
int a = 100;
String strResult = (3 > 1) ? "yes":"no";
System.out.println("strResult = " + strResult); //결과가 참이기 때문에 strResult = yes
📢 대입 및 부호를 이용하는 연산자
- 대입 연산자 : 우측 데이터를 좌측의 변수에 대입 (ex. int i = 0;)
- 부호 연산자 : 부호를 나타내는 연산자(ex. -1)
- 산술 연산자 : 사칙연산(+,-,*,/) 및 나머지(%) 연산
- 증가/감소 연산자 : 값을 1만큼 늘리거나(++), 1만큼 줄임(--) (ex. num++)
- 관계 연산자 : 두 항의 크기를 비교(ex. 1<2)
int num1 = 10;
int num2 = 9;
System.out.println(num1 > num2);
- 논리 연산자 : 논리식에 대한 참/거짓 판단(&&, ||), 결과는 true or false
System.out.println((10>9) && (1 == 0)); //둘 다 참이기 때문에 --> true
System.out.println((10>9) || (1 == 0)); //둘 중에 하나가 참이기 때문에 --> true
- 복합 대입 연산자 : 대입 연산자와 다른 연산자를 조합한 연산 (+=, -=)
int num1 = 10;
int num2 = 5;
num1 += num2; //num1 = num1 + num2;
System.out.println("num1 = " + num1);
📢 비트 연산자
- AND 연산자(&) : 두 개의 비트 값이 모두 1인 경우에만 결과가 1이다.
int num1 = 5;
int num2 = 3;
int result = 0;
result = num1 & num2;
System.out.println("result = " + result); //result = 1
System.out.println(Integer.toBinaryString(num1)); //"101"(이진화)
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(num1))); //"0101"(4자리의 이진화)
- OR 연산자(|) : 두 개의 비트 값 중에 하나라도 1이면 결과가 1이다.
result = num1 | num2;
System.out.println("result = " + result); //result = 7
System.out.println(Integer.toBinaryString(num1)); //101
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(num1))); //0101
- XOR 연산자(^) : 두 개의 비트 값이 같으면 0, 다르면 1 이다.
result = num1 ^ num2;
System.out.println("result = " + result); //result = 6
System.out.println(Integer.toBinaryString(num1)); //101
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(num1))); //0101
- 반전 연산자(~) : 비트 값이 0 -> 1, 1 -> 0 으로 반전
result = ~num1;
System.out.println("result = " + result); //result = -6
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(num1))); //0101
System.out.printf("%s\n", Integer.toBinaryString(result)); //11111111111111111111111111111010
📢 비트 이동 연산자
- << 연산자 : 비트를 왼쪽으로 이동
int numA =3;
result = numA <<1;
System.out.println("result = " + result); //result = 6
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(numA))); //0011
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(result))); //0110
- >> 연산자 : 비트를 오른쪽으로 이동
result = numA >> 1;
System.out.println("result = " + result); //result = 1
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(numA))); //0011
System.out.printf("%04d\n", Integer.parseInt(Integer.toBinaryString(result))); //0001
- >>> 연산자 : 비트를 오른쪽으로 이동(부호 상관 없이 0으로 채움)
numA = -5;
result = numA >>> 1;
System.out.printf("%s\n", Integer.toBinaryString(numA)); //11111111111111111111111111111011
System.out.printf("%s\n", Integer.toBinaryString(result)); //1111111111111111111111111111101
반응형
'Java' 카테고리의 다른 글
[Java] 배열의 의미와 종류 (0) | 2023.08.05 |
---|---|
[Java] 조건문과 반복문 (0) | 2023.08.03 |
[Java] 변수와 자료형 (0) | 2023.08.02 |
댓글