국비

[ 21일차 103~118 ] 수업 정리 - 자바

코딩하는냥이 2025. 5. 14. 15:01
반응형

✅ 오전 수업

📌 SmartPhone 클래스와 toString()

public class SmartPhone {
    private String company, os;

    public SmartPhone(String company, String os) {
        this.company = company;
        this.os = os;
    }

    public String toString() {
        return company + ", " + os;
    }
}
  • toString() 메서드를 오버라이드해 객체 출력 시 유의미한 정보를 출력하도록 함.

📌 예외 처리 기본 구조

  • NullPointerException 예제와 try-catch 블록 사용법
  • Class.forName()을 통한 ClassNotFoundException 처리
  • 다중 catch 사용법 (e.g. ArrayIndexOutOfBoundsException, NumberFormatException)
try {
    int value = Integer.parseInt(arrays[i]);
} catch (ArrayIndexOutOfBoundsException e) {
    // 배열 인덱스 초과 처리
} catch (NumberFormatException e) {
    // 숫자 형식 아님 처리
}

📌 throws를 통한 예외 위임

public static void findClass(String str) throws ClassNotFoundException {
    Class.forName(str);
}

📌 사용자 정의 예외 처리 (InsufficientResourcesException)

public void withdraw(int money) throws InsufficientResourcesException {
    if (balance < money)
        throw new InsufficientResourcesException("잔고 부족");
}

📌 equals()와 hashCode() 오버라이딩

Member 클래스

  • equals()만 오버라이드

Student 클래스

  • equals()와 hashCode() 모두 오버라이드
  • HashSet에서 객체 중복 여부 판단 테스트

✅ 오후 수업

📌 toString(), System.err

System.err.println("[Error]");
System.err.println(e.getMessage());
  • 표준 오류 출력 스트림 사용 예제

📌 System.in.read(), System.nanoTime(), System.getProperty()

  • 키보드 입력을 직접 읽는 방법
  • 프로그램 수행 시간 측정
  • 시스템 정보 출력 (운영체제, 사용자 홈 디렉토리 등)

📌 StringBuilder

String data = new StringBuilder()
    .append("DEF")
    .insert(0, "ABC")
    .delete(3, 4)
    .toString();
  • 문자열의 효율적 조작

📌 Math, Random, Arrays.sort(), Arrays.equals()

  • 로또 번호 추첨 구현
  • Math.ceil(), Math.floor(), Math.round() 등 활용

📌 Date, SimpleDateFormat, LocalDateTime, DateTimeFormatter

  • 날짜 및 시간 포맷 지정 출력
  • 시간 연산 (plusYears, minusMonths, ChronoUnit)

📌 DecimalFormat 숫자 포맷 지정

DecimalFormat df = new DecimalFormat("#,###.0000");
System.out.println(df.format(1234567.89));

📌 정규 표현식

String regExp = "(02|010)-\\d{3,4}-\\d{4}";
boolean result = Pattern.matches(regExp, "010-1234-5678");
  • 전화번호 및 이메일 형식 검사

📌 Class, Field, Constructor, Method를 이용한 리플렉션

Class clazz = Car.class;
Constructor[] constructors = clazz.getDeclaredConstructors();
Field[] fields = clazz.getDeclaredFields();
Method[] methods = clazz.getDeclaredMethods();
  • 클래스 내부 정보 동적으로 분석하는 기능

📌 요약 표

개념 주요 내용 요약
예외 처리 try-catch, throws, 다중 catch 활용
사용자 정의 예외 직접 예외 클래스 정의 후 throw 사용
equals/hashCode 객체 동등 비교 및 중복 저장 제어 (HashSet)
System 클래스 System.in, System.err, System.nanoTime, getProperty() 등 다양한 기능 사용
문자열 처리 StringBuilder, DecimalFormat, 정규표현식
날짜와 시간 Date, SimpleDateFormat, LocalDateTime, DateTimeFormatter 활용
리플렉션(Reflection) 클래스 정보 동적 분석: 생성자, 필드, 메소드 확인

💡 핵심 정리

  • 예외는 try-catch로 처리하고, 필요 시 throws로 위임 가능
  • 객체 비교에는 equals()와 hashCode()를 오버라이드해야 정확한 동등성 비교 가능
  • 날짜 및 시간 관련 클래스는 java.time, java.text 패키지를 적절히 활용
  • 리플렉션은 클래스의 구성요소를 런타임에 확인할 수 있는 고급 기능