JAVA :: String int 형변환

smi·2022년 7월 20일
0

JAVA (자바)

목록 보기
41/62
post-thumbnail

📝 String ➞ int

  • 두 가지 방법
    • Integer.parseInt(): int type을 return
    • Integer.valueOf(): Integer 객체를 return

💡 Integer.parseInt()

▶ 예시

public static void main(String[] args) {        
	String s1 = "1";      
    String s2 = "-2";      
    
    int num1 = Integer.parseInt(s1);  // 1   
    int num2 = Integer.parseInt(s2);  // -2    
}

💡 Integer.valueOf()

▶ 예시

public static void main(String[] args) {        
	String s1 = "1";      
    String s2 = "-2";      
    
    int num1 = Integer.valueOf(s1).intValue();  // 1   
    int num2 = Integer.valueOf(s2).intValue();  // -2  
}

+ Integer Object 타입을 return 하기 때문에 inValue() 메소드로 다시 int 타입으로 변형 * 원래는 자동 형변환이 됨.


📝 int ➞ String

  • 두 가지 방법
    • Integer.toString()
    • String.valueOf()

💡 Integer.toString()

▶ 예시

public static void main(String[] args) {  
    int num1 = 1;   
    int num2 = -2; 
    
	String s1 = Integer.toString(s1);  // "1"  
    String s2 = Integer.toString(s2);  // "-2"
}

💡 String.valueOf()

▶ 예시

public static void main(String[] args) {  
    int num1 = 1;   
    int num2 = -2; 
    
	String s1 = String.valueOf(s1);  // "1"  
    String s2 = String.valueOf(s2);  // "-2"
}
profile
공부한 거 올려요 :)

0개의 댓글