728x90

 

Integer.valueOf(String)

  • 반환 타입: Integer 객체
  • 설명: Integer.valueOf(String)는 문자열을 Integer 객체로 변환합니다. 이 메서드는 내부적으로 Integer 객체를 생성하거나, 이미 생성된 객체를 캐싱하여 반환할 수 있습니다. 따라서 이 메서드는 Integer 객체를 반환하기 때문에 자동 박싱(autoboxing)이 발생합니다.
  • 캐싱: Integer.valueOf(int)는 -128부터 127까지의 값을 캐싱합니다. 이 범위 내의 값들은 동일한 객체를 재사용합니다.
Integer intValue = Integer.valueOf("123");

 

Integer.parseInt(String)

  • 반환 타입: 기본 타입 int
  • 설명: Integer.parseInt(String)는 문자열을 기본 타입 int로 변환합니다. 이 메서드는 문자열을 숫자로 파싱하여 직접 int 타입으로 반환하기 때문에, 객체 생성이나 캐싱과 관련이 없습니다.
int intValue = Integer.parseInt("123");
 

 

요약

  • Integer.valueOf(String)는 Integer 객체를 반환하고, 캐싱 메커니즘을 사용할 수 있습니다. 반환 타입은 객체(Integer)입니다.
  • Integer.parseInt(String)는 기본 타입 int를 반환하며, 캐싱 메커니즘이 없습니다. 반환 타입은 기본 타입(int)입니다.

 

사용 예시

public class Main {
    public static void main(String[] args) {
        String str = "123";
        
        // Integer.valueOf(String) 사용
        Integer integerValue = Integer.valueOf(str);
        System.out.println("Integer.valueOf: " + integerValue); // Integer 객체 반환

        // Integer.parseInt(String) 사용
        int intValue = Integer.parseInt(str);
        System.out.println("Integer.parseInt: " + intValue); // 기본 타입 int 반환
    }
}

 

결론

  • Integer.valueOf(String)는 Integer 객체를 반환하고, 캐싱 메커니즘을 통해 메모리 효율성을 향상시킬 수 있습니다.
  • Integer.parseInt(String)는 기본 타입 int를 반환하며, 메모리 효율성 측면에서 조금 더 가볍습니다.

두 메서드 모두 문자열을 정수로 변환하는 데 유용하지만, 반환 타입과 내부 동작 방식의 차이로 인해 특정 상황에서 더 적합한 메서드를 선택할 수 있습니다.

+ Recent posts