toString() 메서드는 Object 클래스의 핵심 메서드 중 하나로, 객체의 문자열 또는 텍스트 형태의 표현을 반환하는 데 사용됩니다. Object 클래스의 toString() 메서드를 그대로 호출하면 지정된 객체의 클래스 이름 뒤에 '@' 기호와 해당 객체의 해시코드(hashcode)가 붙은 형태의 문자열이 반환됩니다(예: java.lang.String;@36f72f09).
흥미롭게도 toString() 메서드는 숫자의 문자열 표현을 얻는 데에도 활용할 수 있습니다. 서로 다른 변수에 담긴 여러 숫자를 하나의 문자열로 조합해야 하는 경우, 각 숫자를 문자열로 변환한 뒤 이어 붙여 통합된 문자열이나 원하는 형식으로 포맷된 문자열을 손쉽게 만들 수 있습니다.
문법(Syntax)
public String toString()
예제(Example)
아래 예제에서는 기본형(primitive type)과 래퍼 클래스(wrapper class)인 int/Integer, float/Float, double/Double 값을 각각 toString() 메서드를 통해 문자열로 변환하는 과정을 보여줍니다.
public class ToStringMethodTest {
public static void main(String args[]) {
int num1 = 50;
Integer num2 = 75;
float flt1 = 50.75f;
Float flt2 = 80.55f;
double dbl1 = 3256522.44d;
Double dbl2 = new Double(565856585d);
// toString() 메서드로 숫자를 문자열 형식으로 변환
String str_int1 = Integer.toString(num1);
String str_int2 = num2.toString();
String str_flt1 = Float.toString(flt1);
String str_flt2 = flt2.toString();
String str_dbl1 = Double.toString(dbl1);
String str_dbl2 = dbl2.toString();
System.out.println("int to string = " + str_int1);
System.out.println("Integer to string = " + str_int2);
System.out.println("float to string = " + str_flt1);
System.out.println("Float to string = " + str_flt2);
System.out.println("double to string = " + str_dbl1);
System.out.println("Double to string = " + str_dbl2);
}
}실행 결과(Output)
int to string = 50 Integer to string = 75 float to string = 50.75 Float to string = 80.55 double to string = 3256522.44 Double to string = 5.65856585E8
참고 사항
기본형(int, float, double 등)은 각 래퍼 클래스의 정적 메서드인 Integer.toString(), Float.toString(), Double.toString()을 사용해 변환하고, 래퍼 객체(Integer, Float, Double)는 인스턴스 메서드인 toString()을 직접 호출하면 됩니다.
또한 큰 double 값이 과학적 표기법(예: 5.65856585E8)으로 출력되는 점에 유의하세요. 일반적인 십진수 형태가 필요하다면 String.format()이나 DecimalFormat을 함께 사용하는 것이 좋습니다.