본문 바로가기
Language/Java

[Java] 문자열을 숫자로 변환 / Integer.parseInt(), Interger.valueOf()

by 키튼햄 2023. 11. 4.

문자열(String)을 숫자(Integer)로 변환하는 방법은 크게 두 가지가 있다.

1. Integer.parseInt()

2. Integer.valueOf()

 

parseInt() 메소드와 valueOf() 메소드는 모두 java.lang.Integer클래스의 static 메소드이다.

 

1. Integer.parseInt()

파라미터의 문자열(String)을 기본형 정수(primitive type int)로 반환하는 메소드이다.

문자열이 유효한 숫자를 포함하지 않으면 NumberFormatException이 발생한다.

 

public class StringToInt{
    public static void main(String[] args){
        String str1 = "12345";
        String str2 = "-12345";
        
        int num1 = Integer.parseInt(str1);
        int num2 = Integer.parseInt(str2);
        
        System.out.println(num1);
        System.out.println(num2);
    }
}

//출력
12345
-12345

 

 

 

 

2. Interger.valueOf()

파라미터의 문자열(String)을 정수 객체(Integer Object)로 반환하는 메소드이다.

Integer.valueOf()는  new Integer(Integer.paseInt(str))과 동일하다고 볼 수 있다.

 

public class StringToInt{
    public static void main(String[] args){
        String str1 = "12345";
        String str2 = "-12345";
        
        int num1 = Integer.valueOf(str1);
        int num2 = Integer.valueOf(str2);
        
        System.out.println(num1);
        System.out.println(num2);
    }
}

//출력
12345
-12345