본문 바로가기
IT개발/코딩테스트 연습

자바 코딩테스트에서 자주 활용되는 문법과 자료구조

by 시간기억자 2025. 2. 7.
반응형

(chatGPT을 통해 정리된 내용입니다.)

 

1. 기본 문법 및 프로그램 구조

1.1. 자바 프로그램의 기본 구조

  • 클래스와 메인 메소드:
    자바 프로그램은 클래스 안에 작성되며, 실행 진입점은 항상 public static void main(String[] args) 메소드입니다.
public class Main {
    public static void main(String[] args) {
        // 프로그램 시작점
        System.out.println("Hello, World!");
    }
}

 

  • 패키지:
    여러 클래스를 그룹으로 관리하기 위해 패키지를 사용합니다.
package mypackage;

public class MyClass {
    // 클래스 내용
}

 

1.2. 데이터 타입 및 변수 선언

  • 기본형(Primitive Type):
    • int, long, double, boolean, char 등
    • 예시:
int a = 10;
long b = 10000000000L; // 'L' 접미사 필요
double c = 3.14;
boolean flag = true;
char ch = 'A';

 

 

  • 참조형(Reference Type):
    • 객체, 문자열, 배열 등
    • 예시:
String str = "Hello";
int[] arr = new int[5];

 


 

2. 입출력 (I/O)

2.1. Scanner

  • 특징: 사용하기 간편하며, 기본적인 입출력에 적합합니다.
  • 예제:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String s = sc.next();
        // 필요한 입력 처리
        sc.close();
    }
}
  • 주의: 데이터 양이 많을 경우 속도가 느릴 수 있으므로 대용량 입력 시에는 BufferedReader를 사용하는 것이 좋습니다.

 

2.2. BufferedReader & StringTokenizer

  • 특징: 입출력 속도가 빠르며, 많은 데이터를 처리할 때 유용합니다.
  • 예제:
import java.io.*;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        
        int n = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            if (!st.hasMoreTokens()) {
                st = new StringTokenizer(br.readLine());
            }
            arr[i] = Integer.parseInt(st.nextToken());
        }
        // 출력도 BufferedWriter나 StringBuilder를 사용하여 빠르게 처리
    }
}

 

  • 입력예시
5
10 20 30 40 50

 

  • 예상출력
10 20 30 40 50

3. 조건문 및 반복문

3.1. 조건문

  • if-else 문:
    조건에 따라 다른 코드 블록을 실행합니다.
int score = 85;
if (score >= 90) {
    System.out.println("A학점");
} else if (score >= 80) {
    System.out.println("B학점");
} else {
    System.out.println("C학점");
}

예상출력

B학점

 

 

  • switch-case 문:
    하나의 변수에 대해 여러 값 중 하나를 선택할 때 사용합니다.
int day = 3;
switch (day) {
    case 1:
        System.out.println("월요일");
        break;
    case 2:
        System.out.println("화요일");
        break;
    // 생략...
    default:
        System.out.println("해당 없음");
}

예상출력

수요일

 

3.2. 반복문

  • for 문:
    정해진 횟수만큼 반복할 때 사용합니다.
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

예상출력

0 1 2 3 4 5 6 7 8 9

 

  • while 문:
    조건이 참인 동안 반복합니다.
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;
}

예상출력

0 1 2 3 4 5 6 7 8 9

 

  • do-while 문:
    최소 한 번은 실행되어야 할 때 사용합니다.
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 10);

예상출력

0 1 2 3 4 5 6 7 8 9

 

  • 향상된 for 문 (for-each):
    배열이나 컬렉션의 모든 원소를 순회할 때 사용합니다.
int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
    System.out.println(num);
}

예상출력

1 2 3 4 5

 


4. 배열 및 2차원 배열

4.1. 1차원 배열

  • 선언 및 초기화:
public class Main {
    public static void main(String[] args) {
        int[] arr = new int[5];             // 크기 5인 배열
        int[] arr2 = {1, 2, 3, 4, 5};         // 값으로 초기화
        
        // arr2의 값을 출력
        for (int num : arr2) {
            System.out.print(num + " ");
        }
    }
}

예상출력

1 2 3 4 5

 

4.2. 2차원 배열

  • 선언 및 초기화, 순회 예제:
public class Main {
    public static void main(String[] args) {
        int[][] matrix = new int[3][4];       // 3행 4열 배열
        int[][] matrix2 = { {1, 2}, {3, 4}, {5, 6} };
        
        // matrix2의 내용을 출력
        for (int i = 0; i < matrix2.length; i++) {
            for (int j = 0; j < matrix2[i].length; j++) {
                System.out.print(matrix2[i][j] + " ");
            }
            System.out.println();
        }
    }
}

예상출력

1 2 
3 4 
5 6

5. 컬렉션 프레임워크 (Java Collections Framework)

5.1. List

  • ArrayList:
    동적 배열로, 요소의 추가 및 삭제가 용이합니다.
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(20);
        System.out.println(list.get(0));  // 첫 번째 요소 출력
    }
}

예상출력

10

 

  • LinkedList:
    이중 연결 리스트로, 삽입 및 삭제가 빈번한 경우에 유리합니다.
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("apple");
        linkedList.add("banana");
        System.out.println(linkedList);
    }
}

예상출력

[apple, banana]

 

5.2. Set

  • HashSet:
    중복된 요소를 허용하지 않으며, 순서는 보장하지 않습니다.
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(1); // 중복 추가 시도
        System.out.println(set.size());
    }
}

예상출력

2

 

  • TreeSet :
    정렬된 순서를 유지하며, 중복된 요소를 허용하지 않습니다.
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(5);
        treeSet.add(2);
        treeSet.add(8);
        System.out.println(treeSet);
    }
}

예상출력

[2, 5, 8]

 

 

  • LinkedHashSet:
import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        LinkedHashSet<String> lhs = new LinkedHashSet<>();
        lhs.add("banana");
        lhs.add("apple");
        lhs.add("cherry");
        System.out.println(lhs);
    }
}

예상출력

[banana, apple, cherry]

 

 

5.3. Map

  • HashMap:
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 2);
        System.out.println(map.get("apple"));
    }
}

예상출력

3

 

  • TreeMap:
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("apple", 3);
        treeMap.put("banana", 2);
        System.out.println(treeMap);
    }
}

예상출력

{apple=3, banana=2}

 

5.4. Queue

  • LinkedList를 이용한 Queue:
import java.util.Queue;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(10);
        queue.add(20);
        System.out.println(queue.poll());  // 10을 제거 후 반환
    }
}

예상출력

10

 

  • PriorityQueue:
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(2);
        pq.add(8);
        System.out.println(pq.poll());  // 최소값인 2 반환
    }
}

예상출력

2

 


 

6. 정렬 (Sorting)

6.1. Arrays.sort()와 Collections.sort()

  • 배열 정렬:
import java.util.Arrays;

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

예상출력

[1, 2, 3, 5, 8]

 

  • 리스트 정렬:
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3));
        Collections.sort(list);  // 오름차순 정렬
        System.out.println(list);
    }
}

예상출력

[1, 2, 3, 5, 8]

 

6.2. 사용자 정의 정렬 (Comparator, 람다식)

  • Comparator 사용:
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {5, 2, 8, 1, 3};
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return b - a;  // 내림차순 정렬
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

예상출력

[8, 5, 3, 2, 1]

 

 

  • 람다식 사용 (자바 8 이상):
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {5, 2, 8, 1, 3};
        Arrays.sort(arr, (a, b) -> b - a);  // 내림차순 정렬
        System.out.println(Arrays.toString(arr));
    }
}

예상출력

[8, 5, 3, 2, 1]

7. 람다식 및 스트림 (Java 8 기능)

7.1. 람다식

  • 예제 (Runnable 인터페이스 구현):
public class Main {
    public static void main(String[] args) {
        Runnable r = () -> System.out.println("람다식 실행");
        new Thread(r).start();
    }
}

예상출력

람다식 실행

 

7.2. 스트림(Stream) API

  • 예제:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        // 3보다 큰 수들만 필터링
        List<Integer> filtered = list.stream()
                                     .filter(x -> x > 3)
                                     .collect(Collectors.toList());
        System.out.println(filtered);
    }
}

예상출력

[4, 5]

8. 기타 유용한 기능 및 팁

8.1. String, StringBuilder, StringBuffer

  • StringBuilder 예제:
public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            sb.append(i).append(" ");
        }
        System.out.println(sb.toString());
    }
}

예상출력

0 1 2 3 4 5 6 7 8 9

 

 

8.2. Math 클래스

  • 예제:
public class Main {
    public static void main(String[] args) {
        int maxVal = Math.max(10, 20);
        double sqrtVal = Math.sqrt(16);
        System.out.println("max: " + maxVal);
        System.out.println("sqrt: " + sqrtVal);
    }
}

예상출력

max: 20
sqrt: 4.0

 

8.3. 예외 처리 (Exception Handling)

  • try-catch-finally 예제:
public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // 예외 발생
        } catch (Exception e) {
            System.out.println("예외 발생: " + e.getMessage());
        } finally {
            System.out.println("항상 실행됨");
        }
    }
}

예상출력

예외 발생: / by zero
항상 실행됨

 

8.4. static 키워드

  • static 메소드 예제:
public class Util {
    public static int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int result = Util.add(3, 5);
        System.out.println(result);
    }
}

예상출력

8

 

 

 

반응형

댓글