포스트

JAVA (3) - 연산자와 제어문

JAVA (3) - 연산자와 제어문

1. 연산자 (Operators)

Java의 연산자는 피연산자의 개수 및 역할에 따라 여러 종류로 나뉜다.

1.1 산술 및 단항 연산자

  • 산술 연산자: +, -, *, /, % (덧셈, 뺄셈, 곱셈, 나눗셈, 나머지)
  • 증감 연산자: ++, -- (변수의 값을 1 증가 또는 감소)
  • 전위 연산자(++a): 값을 먼저 증가시킨 뒤 연산 진행
  • 후위 연산자(a++): 연산을 진행한 뒤 값을 증가
1
2
3
4
5
6
7
8
9
10
int a = 10;
int b = 3;

System.out.println(a / b); // 3 (정수 나눗셈은 소수점 버림)
System.out.println(a % b); // 1

int c = 5;
System.out.println(++c); // 6
System.out.println(c++); // 6 (출력 후 c는 7이 됨)

1.2 비교 및 논리 연산자

  • 비교 연산자: ==, !=, >, <, >=, <= (참/거짓인 boolean 타입 반환)
  • 논리 연산자: && (AND), || (OR), ! (NOT)
  • Short-Circuit Evaluation: && 연산에서 앞 조건이 false이면 뒤 조건은 평가하지 않는다.
1
2
3
4
5
6
7
8
9
boolean isAdult = true;
boolean hasId = false;

if (isAdult && hasId) {
    System.out.println("입장 가능");
} else {
    System.out.println("입장 불가능");
}

1.3 대입 및 삼항 연산자

  • 복합 대입 연산자: +=, -=, *=, /=, %=
  • 삼항 연산자: 조건식 ? 참일_때_값 : 거짓일_때_값
1
2
3
4
int score = 85;
String result = (score >= 80) ? "합격" : "불합격";
System.out.println(result); // 합격


2. 조건문 (Conditional Statements)

2.1 if-else 문

가장 기본적인 조건문으로, 조건식의 참/거짓 여부에 따라 실행할 블록을 결정한다.

1
2
3
4
5
6
7
8
9
10
int score = 75;

if (score >= 90) {
    System.out.println("A 학점");
} else if (score >= 80) {
    System.out.println("B 학점");
} else {
    System.out.println("C 학점");
}

2.2 switch 문

특정 변수의 값에 따라 다중 분기를 처리할 때 사용한다. Java 12 이상부터는 화살표 표기법(->)을 사용하는 향상된 switch 문(Switch Expressions)을 지원한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 기존 switch 문
int day = 2;
switch (day) {
    case 1:
        System.out.println("월요일");
        break;
    case 2:
        System.out.println("화요일"); // 실행
        break;
    default:
        System.out.println("주말");
}

// Java 12+ Switch Expression
String dayName = switch (day) {
    case 1 -> "월요일";
    case 2 -> "화요일";
    default -> "주말";
};


3. 반복문 (Loop Statements)

3.1 for 문 및 Enhanced for 문

반복 횟수가 정해져 있을 때 주로 사용한다.

1
2
3
4
5
6
7
8
9
10
11
// 일반 for 문
for (int i = 0; i < 5; i++) {
    System.out.println("i: " + i);
}

// 향상된 for 문 (Enhanced for)
int[] numbers = {10, 20, 30};
for (int num : numbers) {
    System.out.println(num);
}

3.2 while 및 do-while 문

조건이 참인 동안 계속 반복한다. do-while 문은 조건 검사 전에 무조건 최초 1회 실행을 보장한다.

1
2
3
4
5
6
7
8
9
10
11
int count = 0;
while (count < 3) {
    System.out.println("count: " + count);
    count++;
}

int num = 5;
do {
    System.out.println("최초 1회 실행 보장");
} while (num < 0);


4. 기타 제어 키워드

  • break: 진행 중인 반복문이나 switch 문을 즉시 탈출한다.
  • continue: 반복문의 나머지 코드를 실행하지 않고 다음 반복으로 건너뛴다.
1
2
3
4
5
6
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue; // 3일 때 출력을 건너뜀
    if (i == 5) break;    // 5일 때 루프 탈출
    System.out.print(i + " "); // 출력 결과: 1 2 4
}

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.