h-i-s-t-o-r-y

[Java] 연산자 본문

Java

[Java] 연산자

H' 2021. 7. 12. 20:17

▷ 연산자의 정의

연산자 (operator) : 연산을 수행하는 기호
피연산자 (operand) : 연산자의 작업대상 (변수, 상수, 리터럴, 수식

▷ 연산자의 [기능별] 분류

> 산술연산자

//  +  -  *  /  %  <<  >>
System.out.println(3 + 5);
int x=3, y=5;
System.out.println(x - y);

System.out.println(3 * 5);   // 15
System.out.println(3 / 5);   // 0      int/int : 결과는 몫이 나옴
System.out.println(3.0/5.0); // 0.6    double/double : 나눈값이 제대로 나옴
System.out.println(3 % 5);   // 3      % : 나머지 연산자
// The operator + is undefined for the argument type(s) int, boolean
// int 타입과 boolean 타입은 산술연산자로 연산할 수 없다.
System.out.println(3 + true);
// 0으로 연산하는 경우 주의 !
System.out.println(3 / 0);  // 정수/0 산술오류
System.out.println(3.14 / 0);  // 실수/0 Infinity

System.out.println(3 % 0);  // 정수%0 산술오류
System.out.println(3.14 % 0);  // 실수%0 NaN (Not a Number)
// 나머지 연산자는 %(음수) 연산도 가능하다.
System.out.println(-10 % 8);
System.out.println(10 % -8);
System.out.println(-10 % -8);
// 하지만 부호 무시되므로, |음수|로 나눈 나머지와 같다.

// 연산 ?
// 피연산자의 부호를 모두 무시하고, 결과를 구한 후 왼쪽 피연산자의 부호를 붙인다.

> 비트연산자

int dec = 1234;
int hex = 0xABCD;
int mask = 0xF;

System.out.printf("hex=%X%n", hex);
System.out.printf("%X%n", hex & mask);

// int 32비트                                A      B          C     D
// hex ->  00000000 00000000 10101011 11001101
// mask -> 00000000 00000000 00000000 00001111

hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
//                        00000000 00000000 10101011 1100

hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
//                             00000000 00000000 10101011

hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
//                     00000000 00000000 1010

// hex 변수의 뒤에서부터 13    번째 비트값? 0/1
System.out.println((hex >> 12) & 0x1);

 


> 비교연산자

//   >   <   >=   <=   ==   !=
System.out.println(4 > 5);   // false
System.out.println(4 < 5);   // true
System.out.println(4 >= 5);  // false
System.out.println(4 <= 5);  // true
System.out.println(4 == 5);  // false      **주의 ==
System.out.println(4 != 5);  // true       **주의 !=
// The left-hand side of an assignment must be a variable
// 할당의 왼쪽은 변수라야 한다.
System.out.println(4 = 5);

> 논리연산자

- 일반 논리 연산자

// 1) 일반 논리 AND 연산자 - && (논리곱)
System.out.println(3 > 5   &&   5 > 4);  // false
// 둘다 참일 때 참인 연산자​
// 2) 일반 논리 OR 연산자 - || (논리합)
System.out.println(3 > 5   ||   5 > 4);  // true
// 하나라도 참이면 참인 연산자
// 3) 부정 (NOT) 연산자     -  !
// (주의) ' =! ' 는 '부정하고 난 다음 그것을 대입하겠다' 는 의미
System.out.println( !true);   // false
System.out.println( !false);  // true
// The operator ! is undefined for the argument type(s) int
// 연산자 우선순위 이해 -    !(높음)    >(낮음)
System.out.println( !3>5);    // Error
System.out.println( !(3>5));  // true
1. x는 10보다 크고, 20보다 작다
      x>10     &&      x<20

2. i는 2의 배수 또는 3의 배수 이다.
    i%2==0     ||     i%3==0

3. i는 2의 배수 또는
   3의 배수지만 6의 배수는 아니다.
      i%2==0   ||   ( i%3==0    &&   i%6!=0 )
 (연산자 우선순위 && > || 라서 괄호는 없어도 됨)

4. 문자 ch는 숫자('0'~'9')이다.
    ch>=48   &&   ch<=57
    ch>='0'  &&   ch<='9'

- 비트 논리 연산자

// 1) 비트 논리 AND 연산자 - &
System.out.println(10 & 3);  // 2
0000 1010 & 0000 0011 -> 0000 0010
// 비트 값을 가지고 논리곱함
// 2) 비트 논리 OR 연산자 - |
System.out.println(10 | 3);  // 11
0000 1010 | 0000 0011 -> 0000 1011
// 비트 값을 가지고 논리합함
// 3) 비트 부정 연산자 - ~ (틸드 연산자)
System.out.println( ~10);  // -11
~ 0000 1010  ->  1111 0101  ->  -11
// 4) XOR 연산자 - ^
// eXclusive OR - 배타적인, 서로 달라야 참
System.out.println(10 ^ 3);  //9
0000 1010 ^ 0000 0011 -> 0000 1001

> 효율적인 연산 (short circuit evaluation) 의 의미

앞에 것이 참이면 뒤에는 그냥 연산/처리안함
어차피 참이니까~ 기억공간도 할당안함!

> 대입 연산자

- 식과 대입연산자

식 ? expression
- 연산자와 피연산자를 조합하여 계산하고자 하는 바를 표현한 것
식의 평가 ? evaluation
- 식의 계산 결과를 얻는 것
조건식
- 참/거짓으로 + 연산자, 피연산자를 조합한 것
대입연산자 '='
- 변수와 같은 저장공간에 결과를 저장하는 연산자

> 삼항연산자 (=조건연산자)

조건식 ? 항2 : 항3
조건식이 참일 경우 항2, 거짓일 경우 항3을 수행한다.
int x = 100;
int y = x>50? 10: 20;   //조건이 참
System.out.println(y);  //10
// (문제) 삼항연산자
// 두 정수를 입력받아서 큰수, 작은수를 출력하세요

System.out.print("> 두 정수를 입력하세요 ? ");
Scanner scanner = new Scanner(System.in);

int a;
int b;

String value = scanner.next();
String [] values = value.split(",");
a = Integer.parseInt(values[0]);
b = Integer.parseInt(values[1]);

int large = a>b? a: b;
int small = a<b? a: b;

System.out.printf("> 큰 값:%d\\n> 작은 값:%d", large, small);

// java.lang.Math 클래스
Math.max(a, b);
Math.min(a, b);
// p.131 예제 3-32 삼항연산자 중첩
int x, y, z;
int absX, absY, absZ;
char signX, signY, signZ;

x = 10;
y = -5;
z = 0;

// 절대값 구하기
absX = x >= 0 ? x : -x;
absY = y >= 0 ? y : -y;
absZ = z >= 0 ? z : -z;

// 부호 구하기
signX = x > 0 ? '+' : ( x==0 ? ' ' : '-');
signY = y > 0 ? '+' : ( y==0 ? ' ' : '-');
signZ = z > 0 ? '+' : ( z==0 ? ' ' : '-');

System.out.printf("x=%c%d%n", signX, absX);
System.out.printf("y=%c%d%n", signY, absY);
System.out.printf("z=%c%d%n", signZ, absZ);
// (문제) 삼항연산자 중첩
// 세 정수 a,b,c를 입력해서 가장큰수, 가장작은수 구해서 출력하세요
int a, b, c;

System.out.print("> 세 정수를 입력하세요 ? ");

Scanner scanner = new Scanner(System.in);

a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();

int max = a>b? (a>c? a: c): (b>c? b: c);
int min = a>b? (b>c? c: b): (a>c? c: a);

System.out.printf("가장 큰 수:%d 가장 작은 수:%d", max, min);

> 단항연산자

//  ++  --  +  -  ~  ! (type)
System.out.println( +5);
System.out.println( -5);
// 어떤 기억공간의 값을 1 증가하는 방법 (4가지)
int x = 10;
x = x + 1;
x += 1;   // += 복합대입연산자
x++;            // 후위형 증감연산자
++x;            // 전위형 증감연산자

// 어떤 기억공간의 값을 1 감소
x = x - 1;
x -= 1;
x--;
--x;

- 복합 대입연산자

x = x * 10;
x *= 10;

x = x / 10;
x /= 10;

- 증감연산자 (+전위형과 후위형의 차이점)

int x = 10;

// 단독으로 사용될 때는 동일값
x++;
++x;

int y = ++x;  // y에 대입하기 전에 x값 증가시킴
int y = x++;  // y에 대입하고난 후에 x값 증가시킴
System.out.printf("x=%d, y=%d\n", x, y);

▷ 연산자의 우선순위

산술 > 비교 > 논리 > 대입 (대입은 제일 마지막에 수행된다.)
단항 > 이항 > 삼항
단항, 대입연산자를 제외한 모든 연산의 진행방향은 왼쪽에서 오른쪽 이다.

 

 

Comments