WEB/Back-end

Wrapper, Math, DecimalFormat, 정규표현식Pattern, getClass (Java)

최새벽 2024. 7. 18. 20:08

wrapper 클래스

  • 기본 자료형을 클래스로 만들어 놓은 것
  • 포장하고 있는 기본 타입의 값을 변경할 수는 없고, 객체를 생성하는 목적으로 사용
  • Boxing: wrapper 객체로 만드는 과정
  • Unboxing: wrapper 객체에서 기본 타입 값을 얻어내는 과정
Integer obj = 100; // auto boxing
int value = obj; // unboxing

int value = obj + 50; // unboxing 후 연산 
  • parse+기본타입 : 문자열을 기본 타입으로 변환할 때 사용
  • String.valueOf(기본타입) : 기본타입을 문자열로 변환할 때 사용
    • 3 + "" : 빈 문자열 더해줘도 문자열 변환 가능
  • 포장 객체는 번지로 비교를 하기 때문에 ==, !=로 내용 비교 불가능

Math 클래스

  • 자바에서 계산하는 것보다 DB에서 처리하는 게 빠르므로 실제 개발에서는 거의 사용 안 함
  • Math.abs(숫자) : 절대값
  • Math.ceil(숫자) : 올림값
  • Math.floor(숫자) : 버림
  • Math.max(숫자1, 숫자2) : 최대
  • Math.min(숫자1, 숫자2) : 최소
  • Math.random() : 난수 생성
  • Math.round(숫자): 반올림, 메서드 자체에서 자릿수 지정 불가능
  • 랜덤은 Random이라는 클래스가 존재함

형식 클래스

  • DecimalFormat 클래스
  • #,###
int price = 187000;
double dPrice = 187000.1;

DecimalFormat df = new DecimalFormat("#,###.00");

String strPrice = df.format(price);
String dStrPrice = df.format(dPrice);

System.out.println(strPrice); // 출력: 187,000.00
System.out.println(dStrPrice); //출력: 187,000.10

정규 표현식 Pattern 클래스로 검증

public static void main(String[] args) {
    // 소문자 b + 알파벳 소문자 0개 이상
    // compile: 실행하기 위해서 미리 준비시키는 작업이라는 의미로 사용
    // 미리 compile하고 문자열로만 비교하면 수행 속도가 빨라짐
    Pattern p = Pattern.compile("b[a-z]*");
    Matcher m;

    m = p.matcher("c");
    System.out.println(m.matches());

    String[] str = { "bat", "cat", "bed", "blue" };
    for (String string : str) {
        m = p.matcher(string);
        System.out.println(m.matches());
    }
}
  • 출력
false
true
false
true
true

객체로부터 메타정보 얻어내기

Class clazz = 객체참조변수.getClass();