[JAVA] String <-> Int 문자열 숫자 변환

한별·2023년 3월 24일
0

Java_Study

목록 보기
1/1

String -> Int

Integer.parseInt()

static int parseInt(String s)
java.lang.Integer 클래스의 static 메소드인 parseInt() 메소드는
파라미터로 숫자로 변환할 문자열을 입력받고, 입력받은 문자열을 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
    }
}

valueOf()

static int valueOf(String s)
java.lang.Integer 클래스의 static 메소드이고, 파라미터로 숫자로 변환할 문자열을 입력받습니다.
parseInt() 와 가장 큰 차이점은, valueOf() 메소드는 문자열을 변환하여 Integer Object를 리턴, parseInt() 메소드는 primitive type인 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형으로 받기 위해 .intValue()로 형변환 해준다.
구분을 위해 기재했으나 위와 같은 경우에는 자동으로 형변환이 일어난다.

Int -> String

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);
    }
}

문자열에 int를 이어붙이면 문자열이 출력되는 원리

profile
Just Do it!

0개의 댓글