Java/개념

String / int 변환

spring_sunshine 2023. 10. 23. 10:29

Integer.parseInt()

  • String 객체를 기본형 정수(int)로 변환하여 반환한다.
  • String이 유효한 숫자를 포함하고 있지 않으면 NumberFormatException이 발생한다.
String string = "25";
try {
	int number = Integer.parseInt(string); // 음수도 가능
}
catch (NumberFormatException e){
	e.printStackTrace();
}

 

Integer.valueOf()

  • String 객체를 정수 객체(Integer)로 변환하여 반환한다.
  • valueOf() 인자로 String 값을 넣으면, 자동으로 new Integer(Integer.parseInt(string))이 된다.
String string = "25";
try {
	Integer number = Integer.valueOf(string); // new Integer(Integer.parseInt(string));
	int intValue1 = Integer.valueOf(string).intValue(); // int로 변환
}
catch (NumberFormatException e){
	e.printStackTrace();
}

 

String.valueOf()

  • 기본형 타입을 String 객체로 변환하여 반환한다.
  • 인자에 null을 전달하면 문자열 "null"을 리턴한다는 점이 toString()과 다르다.
  • String.valueOf()는 오버로드된 메소드로, int 값을 인자로 전달하면 내부적으로 Integer.toString()을 부른다.
// String 클래스 내부
public static String valueOf(int i) {
    return Integer.toString(i);
}

오버로드 메소드

 

Object.toString()

  • 모든 클래스가 Object 클래스를 상속받기 때문에 오버라이딩해서 사용할 수 있고, 오버라이딩하지 않고 객체에 toString()을 부르면 해당 객체의 클래스이름과 해시코드가 합쳐진 문자열이 반환된다.
  • 올바르게 객체를(iv 값들) 문자열로 바꾸는 역할을 하기 위해 오버라이딩을 하면 된다.
pulbic String toString() {
	return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
public class ExampleClass {
	public String firstName;
	public String lastName;
	public int age;
	
	public ExampleClass(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "first name is: " + this.firstName +
				"\n" + "last name is: " + this.lastName +
				"\n" + "age is: " + this.age;
	}
}

>> 실행결과
first name is: Voyager
last name is: Explorer
age is: 33

 

Integer.toString()

  • 기본형 정수(int) String 객체로 변환하여 반환한다.
  • 인자에 null을 전달하면 NullPointerException이 발생한다.

 

int + ""

  • String을 이어붙이면, String으로 바뀌는 속성을 이용한다.
int intValue1 = 123;
int intValue2 = -123;
 
String str1 = intValue1 + ""; // "123"
String str2 = intValue2 + ""; // "-123"