컴퓨터프로그래밍및실습 (2022년)/0908

From DISLab
Revision as of 23:55, 19 July 2022 by Swpark (talk | contribs)
Jump to navigation Jump to search

연산자

연산자와 연산식

연산자 종류 연산자 피연산자 수 산출값 기능 설명
산술 +, -, *, /, % 이항 숫자 사칙연산 및 나머지 연산 2 + 3
부호 +, - 단항 숫자 음수와 양수의 부호 -2
문자열 + 이항 문자열 두 문자열을 연결 "abc" + "def"
대입 =, +=, -=, *=, /=, %=, &=
^=, !=, <<=, >>=, >>>=
이항 다양 우변의 값을 좌변의 변수에 대입 i += 3
증감 ++, -- 단항 숫자 1만큼 증가/감소 i++
비교 ==, !=, >, <, >=, <=
instanceof
이항 boolean 값의 비교 i > j
논리 !, &, |, &&, || 단항
이항
boolean 논리적 NOT, AND, OR 연산 !(a < 3), (a < 3) && (a > 1)
조건 (조건식) ? A : B 삼항 다양 조건식에 따라 A 또는 B 중 하나를 선택 a = (x > y) ? x : y
비트 ~, &, |, ^ 단항
이항
숫자
boolean
비트 NOT, AND, OR, XOR 연산 ~a, a & b
쉬프트 >>, <<, >>> 이항 숫자 비트를 좌측/우측으로 밀어서 이동 a >> 3

연산의 방향과 우선순위

x > 0 && y < 0 // 어떤 순으로 연산될 것인가?

v1 = 100 * 2 / 3 % 5; // v1 = (((100 * 2) / 3) % 5)

a = b = c = 5; // (a = (b = (c = 5)));
  • 연산자 우선순위
연산자 연산 방향 우선 순위
++, --, +, -, ~, ! 높음
*, /, %
+, -
<<, >>, >>>
<, >, <=, >=, instanceof
==, !=
&
^
|
&&
||
? :
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= 낮음

int var1 = 1;
int var2 = 3;
int var3 = 2;
int result = var1 + var2 * var3;

int result = (var1 + var2) * var3;

단항 연산자

부호 연산자

int i1 = +100;  // 부호 + (양수)
int i2 = -100;  // 부호 - (음수)
double d1 = +3.14;

int x = -100;
int result1 = -x; // OK

short s1 = 100;
short s2 = -s1; // 오류. 정수 연산은 int로 바뀌기 때문
int i3 = -s1; // OK

증감 연산자(++, --)

++i;
i++;

--i;
i--;

//------------------
int x = 10;
int z;

z = ++x;

// 위 코드는 아래와 동일
x = x + 1;
z = x;

//-------------------
int x = 10;
int z;

z = x++;

// 위 코드는 아래와 동일
z = x;
x = x + 1;

//------------------
int x = 10;
int z;

z = --x;

// 위 코드는 아래와 동일
x = x - 1;
z = x;

//-------------------
int x = 10;
int z;

z = x--;

// 위 코드는 아래와 동일
z = x;
x = x - 1;

논리 부정 연산자 !

boolean play = true;

play = !play;

비트 반전 연산자 ~

byte v1 = 10; // 00001010
byte v2 = ~v1; // 오류. 정수 종류의 연산은 자동으로 int로 변환됨

int i2 = ~v1; // OK. 11111111 11111111 11111111 11110101

int i3 = ~v1 + 1; // -10 (2의 보수)

System.out.println( Integer.toBinaryString(i3) );

이항 연산잔

산술 연산자

byte byte1 = 1;
byte byte2 = 1;
byte byte3 = byte1 + byte2; // 오류. 정수 타입의 산술 연산은 32비트인 int로 형변환됨

int result1 = byte1 + byte2; // OK

int int1 = 10;
int int2 = 4;
int result2 = int1 / int2;  // 2
double result3 = int1 / int2; // 2.0

double result4 = (double) int1 / int2; // 2.5

char c1 = 'A' + 1; // OK 'B'
char c2 = 'A';
char c3 = c2 + 1; // 컴파일 에러. c2가 int로 형변환됨
오버플로우
int x = 1000000;
int y = 1000000;

int z = x * y; // z에는 오버플로우되어 -727379968와 같이 알 수 없는 값이 저장됨

//-------------

long x = 1000000;
long y = 1000000;

long z = x * y; // OK
정확한 계산은 정수 사용
int apple = 1;
double priceUnit = 0.1;
int number = 7;

double result = apple - number * priceUnit; // 0.3이 되어야 할 것 같지만 아님. 왜?

System.out.println(result); // 0.29999999999999993
NaN과 Infinity 연산
5 / 0  ArithmeticException 예외 발생
5 % 0  ArithmeticException 예외 발생

5 / 0.0  Infinity
5 % 0.0  NaN

double val = Double.valueOf("NaN"); // NaN 입력

if (Double.isNaN(val)) { // NaN인지 검사
    System.out.println("OOPS");
}

문자열 연결 연산자 (+)

String str1 = "JDK" + 6.0; // "JDK6.0"
String str2 = str1 + " 특징"; // "JDK6.0 특징"

String str3 = "JDK" + 3 + 3.0; // ("JDK" + 3) + 3.0 → ("JDK" + "3") + 3.0 → "JDK3" + "3.0" → "JDK33.0"
String str4 = 3 + 3.0 + "JDK"; // (3 + 3.0) + "JDK" → (3.0 + 3.0) + "JDK" → "6.0" + "JDK" → "6.0JDK"

비교 연산자

int num1 = 10;
int num2 = 10;

boolean result1 = num1 == num2;
boolean result2 = (num1 != num2);
boolean result3 = (num1 <= num2);

char char1 = 'A';
char char2 = 'B';

boolean result4 = (char1 < char2);

//------------------

'A' == 65  true
3 == 3.0  true
0.1 == 0.1f  false // 2진수로 변환하기 때문에 정확한 0.1 표현이 안됨. 
                     // 0.1을 2진수로 바꾸었다가 10진수로 변환하면 0.10000000149011612와 같이 표현됨

//------------------

String strVar1 = "신용권";
String strVal2 = "신용권";
String strVal3 = new String("신용권");

strVal1 == strVal2  true
strVar2 == strVal3  false

strVal1.equals(strVal2)  true
strVal2.equals(strVal3)  true // 내용으로 비교하기 때문

논리 연산자

구분 연산식 설명
AND && 모두 참일 때만 참
OR || 모두 거짓일 때만 거짓
XOR ^ 배타적 논리합. 하나는 true, 다른 하나는 false 일 때만 true
NOT ! 피연산자의 논리값을 바꿈

int charCode = 'A';

if (charCode >= 'A' && charCode <= 'Z') {
    System.out.println("대문자입니다");
}

비트 연산자

비트 논리 연산자
byte num1 = 45;
byte num2 = 25;

byte result1 = num1 & num2;
byte result2 = num1 | num2;
byte result3 = num1 ^ num2;
byte result4 = ~num1;
변수 십진수 연산
num1 00101101 45
num2 00011001 25
result1 00001001 9 num1 & num2
result2 00111101 61 num1 | num2
result3 00110100 52 num1 ^ num2
result4 11010010 -46 ~num1

비트 이동 연산자
int result1 = 1 << 3;
int result2 = -8 >> 3;
int result3 = -8 >>> 3;
변수 연산 이진값 비고
1 00000000 00000000 0000000 00000001
result1 8 1 << 3 00000000 00000000 0000000 00001000 23
-8 11111111 11111111 1111111 11111000
resutl2 -1 -8 >> 3 11111111 11111111 1111111 11111111
result3 536870911 -8 >>> 3 00011111 11111111 1111111 11111111

대입 연산자

  • 예제 코드
public class AssignmentOperatorExample {
    public static void main(String[] args) {
        int result = 0;

        result += 10; // result = result + 10;
        System.out.println(result);

        result -= 5; // result = result - 10;
        System.out.println(result);

        result *= 3; // result = result * 3;
        System.out.println(result);

        result /= 5; // result = result / 5;
        System.out.println(result);

        result %= 3;
        System.out.println(result);
    }
  • 실행 결과
10
5
15
3
0
  • 유용한 경우
int result *= x + y * z; // result = result * (x + y * z);

삼항 연산자

int score = 95;

char grade = (score > 90) ? 'A' : 'B';

// 아래와 동일한 의미의 코드이다.

int score = 95

char grade;
if (score > 90)
    grade = 'A';
else
    grade = 'B';

조건문

if 문


if-else 문


if-else if-else 문


중첩 if 문


switch 문


반복문

for 문

while 문

do-while 문

break 문

continue 문