코딩/Java

Java 4 : 조건문, 반목문, 배열

americanoallday 2025. 2. 5. 17:26

 흐름 파악에 도움이 되는 플로우차트를 그리는 사이트

 

Flowchart Maker & Online Diagram Software

Flowchart Maker and Online Diagram Software draw.io is free online diagram software. You can use it as a flowchart maker, network diagram software, to create UML online, as an ER diagram tool, to design database schema, to build BPMN online, as a circuit d

app.diagrams.net

 

 

조건문(Conditional Statements)

 

1. if 문

조건이 true일 때만 실행되는 기본적인 조건문

public class IfExample {
    public static void main(String[] args) {
        int age = 20;

        if (age >= 18) {
            System.out.println("성인입니다.");
        }
    }
}
성인입니다.

 

2. if-else 문

조건이 true이면 if 블록 실행, false이면 else 블록 실행

public class IfElseExample {
    public static void main(String[] args) {
        int age = 16;

        if (age >= 18) {
            System.out.println("성인입니다.");
        } else {
            System.out.println("미성년자입니다.");
        }
    }
}
미성년자입니다.

 

3. if-else if-else 문

여러 개의 조건을 순차적으로 검사할 때 사용

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

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

 

4. 중첩 if 문 (Nested if)

if 문 안에 또 다른 if 문을 넣어서 더 세부적인 조건 검사 가능

public class NestedIfExample {
    public static void main(String[] args) {
        int age = 20;
        boolean hasID = true;

        if (age >= 18) {
            if (hasID) {
                System.out.println("입장 가능합니다.");
            } else {
                System.out.println("신분증을 가져오세요.");
            }
        } else {
            System.out.println("미성년자는 입장할 수 없습니다.");
        }
    }
}
입장 가능합니다.

 

5. switch

if-else if 문처럼 여러 개의 조건을 검사하는데, 특정 값과 일치하는 경우 실행하는 방식

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            case 1:
                System.out.println("월요일");
                break;
            case 2:
                System.out.println("화요일");
                break;
            case 3:
                System.out.println("수요일");
                break;
            default:
                System.out.println("알 수 없는 요일");
        }
    }
}
수요일
  • break; 를 작성해 주지 않으면 switch 문 끝까지 실행됩니다.

  • default 문은 생략 가능합니다.
  • if 조건문과 비교해보면 if 는 조건식 결과에 true/false 만 가능하고 switch 정수나 문자열 만 가능합니다.
  • 실행 흐름 확인하기
    1. 조건식을 계산한다.
    2. 조건식의 결과와 일치하는 case 문으로 이동한다.
    3. 해당 case 문의 문장들을 수행한다.
    4. break; 를 만나거나 switch 문이 끝나면 switch 문 전체를 빠져나간다.

     

  •  switch 문의 조건식 결과 정수 또는 문자열 이어야 합니다.
  •  case 문의 값은 정수 상수(문자 포함), 문자열 만 가능하며, 중복되지 않아야 합니다.
    1.  

 

반복문(Loop Statements)

1. for

정해진 횟수만큼 반복 실행하는 반복문

for (초기값; 조건; 증감식) {
    // 반복할 코드
}

예제

public class ForExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("반복 횟수: " + i);
        }
    }
}
반복 횟수: 1
반복 횟수: 2
반복 횟수: 3
반복 횟수: 4
반복 횟수: 5

 

2. while

조건이 true인 동안 계속 실행하는 반복문

while (조건) {
    // 조건이 true인 동안 반복 실행할 코드
}

예제

public class WhileExample {
    public static void main(String[] args) {
        int count = 1;

        while (count <= 5) {
            System.out.println("반복 횟수: " + count);
            count++;
        }
    }
}
반복 횟수: 1
반복 횟수: 2
반복 횟수: 3
반복 횟수: 4
반복 횟수: 5

 

3. 중첩 for 문 (Nested for Loop)

public class NestedForExample {
    public static void main(String[] args) {
        for (int i = 2; i <= 9; i++) { // 바깥쪽 for: 단(2~9)
            for (int j = 1; j <= 9; j++) { // 안쪽 for: 곱하는 수(1~9)
                System.out.println(i + " x " + j + " = " + (i * j));
            }
            System.out.println(); // 한 단 출력 후 줄바꿈
        }
    }
}
2 x 1 = 2
2 x 2 = 4
...
9 x 9 = 81

 

4. 향상된 for 문 (Enhanced for Loop)

배열 또는 컬렉션의 요소를 길이만큼 반복적으로 실행하고자 할 때.

기본 for 문과 달리, 인덱스를 직접 다루지 않고 요소를 하나씩 가져옴.

public class EnhancedForExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        for (int num : numbers) {
            System.out.println("값: " + num);
        }
    }
}
값: 10
값: 20
값: 30
값: 40
값: 50

 

5. do-while

do-while은 조건을 확인하기 전에 실행되기 때문에, 적어도 한 번은 반드시 실행 됨.

do {
    // 실행할 코드 (최소 1번 실행됨)
} while (조건);

 

 

반복문 제어 : break, continue

break : for, while, switch 문을 강제로 종료. 자신이 포함된 하나의 반복문을 벗어남.

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break; // i가 5가 되면 반복문 종료
            }
            System.out.println("반복 횟수: " + i);
        }
    }
}
반복 횟수: 1
반복 횟수: 2
반복 횟수: 3
반복 횟수: 4

 

continue : 반복문 내에서 현재 반복을 건너뛰고 다음 반복으로 이동

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // i가 3이면 건너뛰고 다음 반복 실행
            }
            System.out.println("반복 횟수: " + i);
        }
    }
}
반복 횟수: 1
반복 횟수: 2
반복 횟수: 4
반복 횟수: 5

 

 

Math.random() 메서드

0과 1 사이의 랜덤한 실수(double)값 반환.

 

1부터 10까지의 난수 (정수)

int randomInt = (int) (Math.random() * 10) + 1;
System.out.println(randomInt); // 1 ~ 10 사이의 랜덤 정수

특정 범위의 난수 (예: 5 ~ 15)

int min = 5, max = 15;
int randomInt = (int) (Math.random() * (max - min + 1)) + min;
System.out.println(randomInt); // 5 ~ 15 사이의 랜덤 정수

* 간단한 난수는 Math.random(), 더 다양한 기능이 필요하면 Random 클래스를 사용

 

배열(Array)

“같은 타입”의 데이터를 “연속된 메모리 공간”에 저장하는 자료구조

 같은 타입의 데이터만 저장 가능 (int[], double[], String[] 등)

 인덱스(Index)를 사용하여 요소(Element) 접근 (0부터 시작)

 크기가 고정됨 (생성 시 크기를 지정해야 함)

더보기
배열의 크기를 바꿀 수 없는 이유?
  • new int[5];로 배열을 생성하면 int 가 4byte 이기 때문에 총 20byte 를 저장하기 위한 연속적인 메모리 공간을 찾습니다.
  • 연속적인 공간을 찾아서 주소를 배정합니다.
  • 배정이 끝난 후 크기를 5가 아닌 10으로 늘려야 한다고 가정해 봤을 때 배정받은 주소 뒤에 20byte 를 추가적으로 배정해야 하는데 뒤에 연속적인 메모리 공간이 존재한다는 보장이 없습니다.
  • 따라서 크기를 바꿀 수 없습니다.

배열의 크기가 부족할 때의 방법

  • 필요한 만큼의 크기의 배열을 새롭게 만듭니다.

  • 새로 만든 배열에 기존 배열의 값을 복사해서 저장합니다.

 

배열 선언 & 생성 방법:

데이터타입[] 배열이름 = new 데이터타입[배열크기];
OR
데이터타입 변수이름[] = new 데이터타입[배열크기];

 

배열 선언 & 값 바로 초기화

데이터타입[] 배열이름 = {값1, 값2, 값3, ...};

 

int[] num = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9};

* new int[]  생략 가능

 

2차원 배열

[행][열] 형식

데이터타입[][] 배열이름 = new 데이터타입[행][열];

예제

public class MultiDimensionalArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        System.out.println(matrix[1][2]); // 6
    }
}

 

String 배열

여러 개의 문자열을 저장하는 배열

 

String 배열 선언 & 초기화

public class StringArrayExample {
    public static void main(String[] args) {
        // 방법 1: 크기 지정 후 값 할당
        String[] fruits = new String[3];
        fruits[0] = "Apple";
        fruits[1] = "Banana";
        fruits[2] = "Cherry";

        // 방법 2: 선언과 동시에 초기화
        String[] colors = {"Red", "Green", "Blue"};

        System.out.println(fruits[1]); // Banana
        System.out.println(colors[2]); // Blue
    }
}
public class StringExample {
    public static void main(String[] args) {
        // 문자열 리터럴 방식 (문자열 풀에 저장됨)
        String str1 = "Hello";

        // new 키워드 사용 (Heap 메모리에 새 객체 생성)
        String str2 = new String("Hello");

        System.out.println(str1); // Hello
        System.out.println(str2); // Hello
    }
}

 

String 클래스

문자열을 다루는 Java의 내장 클래스

메서드 설명 예제
length() 문자열 길이 반환 "Hello".length(); → 5
charAt(index) 특정 위치 문자 반환 "Java".charAt(1); → 'a'
toUpperCase() 대문자로 변환 "hello".toUpperCase(); → "HELLO"
toLowerCase() 소문자로 변환 "HELLO".toLowerCase(); → "hello"
substring(start, end) 부분 문자열 추출 "Hello".substring(1, 4); → "ell"
indexOf("문자열") 특정 문자열 위치 반환 "Hello".indexOf("l"); → 2
replace("A", "B") 문자열 바꾸기 "Java".replace("J", "K"); → "Kava"
trim() 앞뒤 공백 제거 " Hello ".trim(); → "Hello"
split("구분자") 문자열 나누기 (배열 반환) "a,b,c".split(","); → ["a", "b", "c"]
equals() 문자열 비교 str1.equals(str3)
toString() 1차원 배열이나 객체를 문자열로 변환 str.toString()
repeat(num) num만큼 문자열 반복 "*".repeat(4); ****
public class StringMethods {
    public static void main(String[] args) {
        String text = " Java Programming ";

        System.out.println("길이: " + text.length()); // 18
        System.out.println("대문자 변환: " + text.toUpperCase()); // " JAVA PROGRAMMING "
        System.out.println("소문자 변환: " + text.toLowerCase()); // " java programming "
        System.out.println("공백 제거: " + text.trim()); // "Java Programming"
        System.out.println("부분 문자열: " + text.substring(1, 5)); // "Java"
        System.out.println("문자 위치: " + text.indexOf("P")); // 6
    }
}

 

toString(), deepToString()

import java.util.Arrays;

public class ToStringExample {
    public static void main(String[] args) {
        int[] oneDArray = {1, 2, 3};
        int[][] twoDArray = {{1, 2, 3}, {4, 5, 6}};

        System.out.println("1D 배열 (toString): " + Arrays.toString(oneDArray));
        System.out.println("2D 배열 (toString): " + Arrays.toString(twoDArray));
        System.out.println("2D 배열 (deepToString): " + Arrays.deepToString(twoDArray));
    }
}
1D 배열 (toString): [1, 2, 3]
2D 배열 (toString): [[I@5acf9800, [I@4617c264]  <-- (메모리 주소 출력)
2D 배열 (deepToString): [[1, 2, 3], [4, 5, 6]]

 

 

Array Class

메서드 설명 예제
equals() 1차원 배열 요소 비교 가능 str1.equals(str3)
deepEquals() 2차원 배열 요소 비교 가능 Arrays.deepEquals(arr2D_1, arr2D_2)
deepToString() 2차원 배열을 문자열로 변환 Arrays.deepToString(arr2D)
copyOf() 배열 복사 Arrays.copyOf(원본배열, 새로운 길이);
copyOfRange() 배열 일부 복사 Arrays.copyOfRange(원본배열, 시작인덱스, 끝인덱스);
sort() 배열을 오름차순으로 정렬하는 메서드 Arrays.sort(배열);

 

equals(), deepEquals()

import java.util.Arrays;

public class EqualsExample {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = {1, 2, 3};
        int[][] deepArr1 = {{1, 2}, {3, 4}};
        int[][] deepArr2 = {{1, 2}, {3, 4}};

        System.out.println("1D 배열 비교 (equals): " + Arrays.equals(arr1, arr2)); // true
        System.out.println("2D 배열 비교 (equals): " + Arrays.equals(deepArr1, deepArr2)); // false (주소 비교)
        System.out.println("2D 배열 비교 (deepEquals): " + Arrays.deepEquals(deepArr1, deepArr2)); // true
    }
}
1D 배열 비교 (equals): true
2D 배열 비교 (equals): false
2D 배열 비교 (deepEquals): true

 

copyOf()

Arrays.copyOf(원본배열, 새로운 길이);
import java.util.Arrays;

public class CopyOfExample {
    public static void main(String[] args) {
        int[] original = {1, 2, 3, 4, 5};
        int[] copied = Arrays.copyOf(original, 3); // 원본 배열의 앞 3개 요소 복사

        System.out.println(Arrays.toString(copied)); // [1, 2, 3]
    }
}

 

copyOfRange()

Arrays.copyOfRange(원본배열, 시작인덱스, 끝인덱스);
import java.util.Arrays;

public class CopyOfRangeExample {
    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40, 50};
        int[] copied = Arrays.copyOfRange(original, 1, 4); // index 1~3까지 복사

        System.out.println(Arrays.toString(copied)); // [20, 30, 40]
    }
}

 

sort()

Arrays.sort(배열);
import java.util.Arrays;

public class SortExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1, 2};
        Arrays.sort(numbers); // 오름차순 정렬

        System.out.println(Arrays.toString(numbers)); // [1, 2, 3, 5, 8]
    }
}