[Java] 문자열 숫자 변환

인철·2024년 2월 26일
0

Java

목록 보기
51/52
post-thumbnail

String >>> Int (문자열 > 숫자)

Java.lang.Integer 클래스의 parseInt(), valueOf() 메서드 사용 가능

Integer.parseInt(String s)

파라미터로 숫자로 변환할 문자열을 입력받고, 입력받은 문자열을 Integer로 변환한 int값을 반환

public class StringToInt {    
	public static void main(String[] args) {        
    String str1 = "123";
    String str2 = "-123";
    int intValue1 = Integer.parseInt(str1);
    int intValue2 = Integer.parseInt(str2);
    System.out.println(intValue1); // 123
    System.out.println(intValue2); // -123    
    	}
    }

Integer.valueOf()

parseInt()와 차이점은 문자열을 변환하여 Integer Object를 리턴한다.
parseInt()는 int를 리턴한다.

public class StringToInt {    
	public static void main(String[] args) {        
    String str1 = "123";
    String str2 = "-123";
    int intValue1 = Integer.valueOf(str1).intValue();
    int intValue2 = Integer.valueOf(str2).intValue();
    System.out.println(intValue1); // 123
    System.out.println(intValue2); // -123    
    	}
    }

int >> String (숫자 > 문자열)

Integer.toString(), String.valueOf(), int + "" 방법이 있다.

Integer.toString()

public class IntToString {
	public static void main(String[] args) {
		int intValue1 = 123;
		int intValue2 = -123;
		String str1 = Integer.toString(intValue1);
		String str2 = Integer.toString(intValue2);
		System.out.println(str1);
		System.out.println(str2);
		}
    }

String.valueOf()

public class IntToString {
	public static void main(String[] args) {
		int intValue1 = 123;
		int intValue2 = -123;
		String str1 = String.valueOf(intValue1);
		String str2 = String.valueOf(intValue2);
		System.out.println(str1);
		System.out.println(str2);
		}
    }

int + ""

public class IntToString {
	public static void main(String[] args) {
		int intValue1 = 123;
		int intValue2 = -123;
		String str1 = intValue1 + "";
		String str2 = intValue2 + "";
		System.out.println(str1);
		System.out.println(str2);
		}
    }
profile
같은글이있어도양해부탁드려요(킁킁)

0개의 댓글