본문 바로가기

자바(Java)

자바 Integer.valueOf() vs. (~).parseInt()

Integer 클래스에는 String 타입 argument가 정수인 경우 상응하는 Integer로 변환하는 함수가 존재한다.

Integer.valueOf()는 String으로 표현된 정수를 Integer wrapper로 리턴하며,

Integer.parseInt()는 primitive type인 int로 리턴한다.

 

용도에 따라, 쓰임을 달리할 수 있다.

예컨데 Object argument를 Constructor에서 받는 클래스는 valueOf를 통해 Integer wrapper에 감싼 채 파라미터로 전달함이 옳다.

Primitive type인 int는 Object의 하위 클래스가 아니기 때문에 parseInt()로 리턴된 int는 다시 Integer로 형변환이 필요하기 때문이다.

 

참고로, System.out.println() 등의 메소드에 Integer 클래스를 그대로 포함하더라도 int로 형변환되어 의도한대로 출력된다.