[JAVA] String to int, int to String 형변환하기

SUN·2024년 1월 3일
0

JAVA

목록 보기
5/5

✏️ String to int 형변환하기(문자열을 숫자로)

1. Integer.parseInt()

기본 자료형인 int를 리턴

class stringToInt {
  public static void main(String[] args) {
   	String str = 123;
    
    int num = Integer.parseInt(str);
    
    System.out.println(num); // 결과 : 123
  }
}

2. Integer.valueOf()

객체인 Integer Object를 리턴

class stringToInt {
  public static void main(String[] args) {
    String str = 123;
    
    int num = Integer.valueOf(str);
    
    System.out.println(num); // 결과 : 123
  }
}

📍 기본 int 가 필요하면 parseInt()를 Integer 래퍼 객체가 필요하면 valueOf()를 사용하면 된다.



✏️ int to String 형변환하기(숫자를 문자열로)

1. Integer.toString()

class intToString {
  public static void main(String[] args) {
    int num = 123;
    
    String str = Integer.toString(num);
    
    System.out.println(str); // 결과 : 123
  }
}

2. String.valueOf() : 내부적으로는 Integer.toString을 사용

class intToString {
  public static void main(String[] args) {
    int num = 123;
    
    String str = Integer.valueOf(num);
    
    System.out.println(str); // 결과 : 123
  }
}

3. int + ""

class intToString {
  public static void main(String[] args) {
    int num = 123;
    
    String str = num + "";
    
    System.out.println(str); // 결과 : 123
  }
}

[출처]
https://hianna.tistory.com/524
https://blog.naver.com/sthwin/221000179980

profile
끄적끄적 코딩공부

0개의 댓글