Java 코테용 기본 문법 정리

ejjem·2025년 3월 12일

코딩테스트

목록 보기
11/20

입출력(Input & Output)

표준 입력

Sanner

import java.util.Scanner; // 필수

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a1 = sc.nextInt();  // 정수 입력
        double a2 = sc.nextDouble(); // 실수 입력 
        String a3 = sc.next(); // 공백을 기준으로 한 단어 입력
        String a4 = sc.nextLine(); // 한 줄 입력 받기
        char a5 = sc.next().charAt(0); // 첫 번째 글자만 추출
        sc.close();
    }
}

여러 타입으로 쉽게 입력을 받을 순 있지만 속도가 느려 코테에는 부적합하다고 함.


BufferedReader

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException { // throw IOException을 붙혀야 예외 처리 가능
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String a1 = br.readLine();  // 한 줄 입력받기
		int a2 = Integer.parseInt(br.readLine());  // 정수 변환
        double a3 = Double.parseDouble(br.readLine());  // 실수 변환
        
        // 여러 개의 숫자 입력 
        String[] input = br.readLine().split(" ");  // 공백 기준으로 나누기
        int a4 = Integer.parseInt(input[0]);
        int a5 = Integer.parseInt(input[1]);
    }
}

빠르게 입력을 받을 순 있지만, BufferedReaderreadLine()은 오직 String 타입으로만 입력 받기 때문에, 필요한 형태로 변형해서 사용해야함.


StringTokenizer + BufferedReader

import java.io.*;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String str = br.readLine();
        StringTokenizer st = new StringTokenizer(str);
        StringTokenizer st2 = new StringTokenizer(str, ",");  // 콤마(,)를 구분자로 사용
        StringTokenizer st3 = new StringTokenizer(str, ",:"); // 콤마(,)와 콜론(:) 모두 구분자로 사용

        int a = Interger.parseInt(st.nextToken());
        int b = Interger.parseInt(st.nextToken());
        int b = Interger.parseInt(st.nextToken());
    }
}

BufferedReader를 사용하는 상황에서, 여러 값이 입력 되는 형태이면서 공백으로 구분되는 형태이면 StringTokenizer를 사용하면 좋음. 위 br.readLine().split(" "); 보다 빠름. 구분자를 바꾸려면 추가하면 됨. 여러 개의 형태도 가능.


System.in.read()

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        char ch = (char) System.in.read();  // 한 글자 입력 받기
    }
}

System.in.read()는 한 바이트(1글자)만 읽어들여 한 글자(char) 입력을 받을때 유용.



표준 출력

System.out.print() 계열

System.out.print()

public class Main {
    public static void main(String[] args) {
        System.out.print("Hello");
        System.out.print(" World");
    }
}
Hello World

System.out.print()는 줄 바꿈 없이 출력됨.

System.out.println()

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
        System.out.println("World");
        int a = 10, b = 20;
        System.out.println("a: " + a + ", b: " + b);
    }
}
Hellow
World
a: 10, b: 20

System.out.println()는 출력 후 자동으로 줄 바꿈이 추가됨.

System.out.printf()

public class Main {
    public static void main(String[] args) {
        int a = 10;
        double b = 5.6789;
        
        System.out.printf("정수: %d, 실수: %.2f\n", a, b);
    }
}
정수: 10, 실수: 5.68

System.out.printf는 변수를 원하는 형태로 출력할 때 유용.

서식 문자설명예시
%d정수 출력System.out.printf("%d", 10); // 10
%f실수 출력(기본 6자리)System.out.printf("%f", 3.14); // 3.140000
%.2f소수점 둘째 자리까지 출력 (반올림)System.out.printf("%.2f", 3.14159); // 3.14
%s문자열 출력System.out.printf("%s", "Hello"); // Hello
%c문자 출력System.out.printf("%c", 'A'); // A

StringBuilder

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        
        for (int i = 1; i <= 5; i++) {
            sb.append("숫자: ").append(i).append("\n");  // 문자열 추가
        }
        
        System.out.print(sb.toString());  // 한 번에 출력
    }
}
숫자: 1
숫자: 2
숫자: 3
숫자: 4
숫자: 5

반복문에서 print()를 여러 번 사용하면 출력 속도가 느려지므로, StringBuilder를 이용해 문자열을 미리 저장한 후 한 번에 출력하면 효율적.
append()를 사용하면 새로운 문자열을 생성하지 않고 기존 문자열에 추가 가능.


배열 출력

Arrays.toString()

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(arr));
    }
}
[1, 2, 3, 4, 5]

배열을 문자열 형태로 출력.

Arrays.deepToString()

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = {{1, 2, 3}, {4, 5, 6}};
        System.out.println(Arrays.deepToString(arr));
    }
}
[[1, 2, 3], [4, 5, 6]]

2차원 배열을 보기 좋게 출력.



조건문

if-else

public class Main {
    public static void main(String[] args) {
        int num = 10;

        if (num > 0) {
            System.out.println("양수입니다.");
        } else if (num < 0) {
            System.out.println("음수입니다.");
        } else {
            System.out.println("0입니다.");
        }
    }
}

&& (AND), || (OR), ! (NOT) 와 함께 사용할 수 있음.

3항 연산자

public class Main {
    public static void main(String[] args) {
        int num = 5;
        String result = (num % 2 == 0) ? "짝수" : "홀수";
        System.out.println(result);
    }
}

(조건) ? 참일 때 값 : 거짓일 때 값


switch-case

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

        switch (day) {
            case 1:
                System.out.println("월요일");
                break;
            case 2:
                System.out.println("화요일");
                break;
            case 3:
                System.out.println("수요일");
                break;
            default:
                System.out.println("기타 요일");
        }
    }
}
  • switch (변수) → 비교할 변수.
  • case 값: → 변수와 값이 일치하면 해당 코드 실행.
  • break; → 실행 후 빠져나오기 (없으면 다음 case도 실행됨).
  • default: → 모든 case가 일치하지 않을 때 실행.

이 때 break가 없으면 case 이후 모든 코드가 실행됨.



반복문

for문

for (초기값; 조건식; 증감식) {
    // 반복 실행할 코드
}
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("반복 횟수: " + i);
        }
    }
}
반복 횟수: 1
반복 횟수: 2
반복 횟수: 3
반복 횟수: 4
반복 횟수: 5

for-each 문

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

        for (int num : numbers) {
            System.out.println("숫자: " + num);
        }
    }
}

for (자료형 변수명 : 배열/리스트) 형식
배열이나 리스트의 모든 요소를 반복할 때 유용.


while문

while (조건식) {
    // 반복 실행할 코드
}
public class Main {
    public static void main(String[] args) {
        int count = 1;

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

do-while 문

do {
    // 실행할 코드
} while (조건식);
public class Main {
    public static void main(String[] args) {
        int num = 5;

        do {
            System.out.println("현재 숫자: " + num);
            num--;
        } while (num > 0);
    }
}
현재 숫자: 5
현재 숫자: 4
현재 숫자: 3
현재 숫자: 2
현재 숫자: 1

do 블록이 먼저 실행되고, while에서 조건을 검사함. 때문에 일단 한 번 실행한 후에 조건을 검사하는 반복문.
즉, 조건과 상관없이 최소 1번은 실행됨.



배열(Array)

배열은 같은 타입의 데이터를 연속적으로 저장하는 자료구조.
한 번 선언하면 크기가 고정되므로, 추가/삭제가 불가능.

배열 선언 & 초기화

public class Main {
    public static void main(String[] args) {
        int[] arr1 = new int[5];  // 크기 5짜리 정수 배열 (기본값: 0)
        arr1 = new int[]{1, 2, 3, 4, 5};  // 배열을 새로운 값으로 초기화
        
        int[] arr2 = {1, 2, 3, 4, 5};  // 배열 선언과 동시에 초기화
    }
}

배열 값 변경 & 순회

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

        arr[2] = 100;  // 세 번째 요소 변경

        for (int i = 0; i < arr.length; i++) {  
            System.out.println("arr[" + i + "] = " + arr[i]);
        }
    }
}

배열을 for-each 문으로 순회

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};

        for (int num : arr) {  
            System.out.println(num);
        }
    }
}

2차원 배열 선언 & 초기화

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

        System.out.println("matrix[1][2]: " + matrix[1][2]);  // 두 번째 행, 세 번째 열
    }
}

2차원 배열 순회

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

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}


profile
개발자 지망생

0개의 댓글