[Java] int <> String 변환

jhkim·2023년 12월 25일

글 작성 목적

  • 문제를 풀다보면, 자료형을 변환해야하는 일이 자주 발생한다. 특히 문자를 숫자형으로 변환하는 일들이 자주 발생하는데 이를 미리 정리하여 추후 헷갈리는 일이 없도록 할 예정이다.

String -> int

Integer.parseInt

  • 해당 함수를 사용할 경우 문자열을 기본 정수 (int)로 변환해준다.

  • parseInt(string, radix);

Parameter

  • string: 숫자로 변환하고 싶은 문자열
  • radix: string 문자열을 읽을 진법
public class StringToInt {    
	public static void main(String[] args) {        
		String str1 = "123";        
		String str2 = "0xF";         
    
		int intValue1 = Integer.parseInt(str1);        
		int intValue2 = Integer.parseInt(str2, 16); 	
    
    	System.out.println(intValue1); // 123
    	System.out.println(intValue2); // 15
    }
}
  • 예시1. "123"이라는 String을 10진법 Int로 읽어온다.
  • 예시2. "0xF"라는 String을 16진법으로 생각하여 10진법 Int로 변환한다.

(참고) Integer.valueOf()

  • 해당 함수를 사용할 경우 문자열을 정수 객체 (Integer Object)로 변환한다. 즉, int가 아닌 Integer가 필요할 때 사용하면 된다. 이는 Integer(Integer.parseInt(s))와 동일한 결과값을 출력할 것이다.

int -> String

Integer.toString(), String.valueOf()

  • Integer 클래스 혹은 String 클래스 내에 있는 기능을 사용하여 숫자를 문자로 변환할 수 있다.
public class IntToString {
	public static void main(String[] args) {
    	int intValue1 = 1234;
    	int intValue2 = 1234;
    
    	String str1 = Integer.toString(intValue1);
    	String str2 = String.valueOf(intValue2);
    
    	System.out.println(str1); // 1234
    	System.out.println(str2); // 1234
    }
}
profile
다시 시작합니다 :)

0개의 댓글