12_조건문 if와 삼항 연산자

Jiyoon.lee·2023년 11월 18일
0

Java_inflearn

목록 보기
12/25

1. if

  • if는 제어문(control flow statements) 중에 하나이다. 순차적인 흐름 안에서 조건에 따라 제어를 할 필요가 있을 경우 if를 사용한다.

2. if 사용법 1

  • 중괄호 안의 내용을 블록이라고 한다.
if(조건문) {
    조건문이 참일 경우 실행되는 블록
}
  1. 예제1
public class IfExam1 {
    public static void main(String[] args) {
        int a = 5;

        if(a > 4) {
            System.out.println("a는 4보다 큽니다.");
        }
    }
}
  • 실행 결과 :
a는 4보다 큽니다.

4. if 사용법 2

if(조건문) {
    조건문이 참일 경우 실행되는 블록
} else {
    조건문이 거짓일 경우 실행되는 블록
}
  1. 예제2
public class IfExam2 {
    public static void main(String[] args) {
        int a = 3;

        if(a > 4) {
            System.out.println("a는 4보다 큽니다.");
        } else {
            System.out.println("a는 4 이하입니다.");
        }
    }
}
  • 실행 결과 :
a는 4 이하입니다.

6. if 사용법 3

  • else if는 여러 줄 추가될 수 있다.
if(조건문1) {
    조건문1이 참일 경우 실행되는 블록
} else if(조건문2) {
    조건문2이 참일 경우 실행되는 블록
} else {
    조건문1이나 조건문2에 해당되지 않을 경우 실행되는 블록
}

7. 예제3

public class IfExam3 {
    public static void main(String[] args) {
        int score = 70;

        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 70) {
            System.out.println("C");
        } else if (score >= 60) {
            System.out.println("D");
        } else {
            System.out.println("F");
        }
        System.out.println("프로그램 종료");
    }
}
  • 실행 결과 :
C
프로그램 종료

8. if에 중괄호가 없을 경우

  • if 문장에 중괄호 즉, 블록이 없을 경우는 if 문장 다음 문장만 조건에 만족할 경우 실행된다.
  • "hello"는 무조건 출력된다. (들여쓰기를 잘못한 안 좋은 코드의 예)
public class IfExam4 {
    public static void main(String[] args) {
        int a = 4;

        if (a > 5)
            System.out.println("a는 10보다 큽니다.");
            System.out.println("hello");
    }
}
  • 실행 결과 :
hello

9. 삼항 연산자

  • 자바에는 항이 3개인 연산자가 하나 있다. 조건식이 참일 경우 반환값 1이 사용되고, 거짓일 경우 반환값2가 사용된다.
조건식 ? 반환값1 : 반환값2

10. 예제 : 삼항연산자

  • a의 값을 10, 4 등으로 바꿔가면서 실행해보자.
public class IfExam5 {
    public static void main(String[] args) {
        int a = 10;

        int value = (a > 5) ? 20 : 30;

        System.out.println(value);
    }
}

*괄호 안의 조건에 대해 참일 때 앞(20), 거짓일 때 뒤(30)가 출력됨

  • 실행 결과 :
20

0개의 댓글