본문 바로가기
JAVA

[Java] 📚 문자열 형변환 Object to String : Casting, valueOf, toString

by ro117youshin 2023. 3. 5.
728x90


valueOf(Object obj)

  • Returns the string representation of the Object argument. (Java docs)
    : 파라미터에 들어가는 Object (int, double ...)를 String 문자열 표현으로 바꿔서 반환한다.
  • if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned. (Java docs)
    : 파라미터가 null 이라면, String 문자열로 "null"이 반환되며, null 이 아니라면 toString() 함수값을 반환한다.

Object.toString()

  • In general, the toString method returns a string that "textually represents" this object. (Java docs)
    : 일반적으로, toString 메소드는 이 object를 "텍스트로 표현하는" String 문자열을 반환한다. 
  • The result should be a concise but informative representation that is easy for a person to read. (Java docs)
  • It is recommended that all subclasses override this method. (Java docs)
  • Returns : a string representation of the object. (Java docs)
    : 결과는 사람들이 읽기 쉬운 유의미하지만 간결한 표현이여야 한다. 모든 subclass들이 이 메소드를 오버라이드 하는 것이 좋다. 

Casting VS valueOf VS toString 차이점

String.valueOf() 

  • 파라미터가 null이면 문자열 null을 만들어서 담는다.
  • 어떠한 값을 넣어도 모두 String 문자열로 변환할 수 있다.

ex) 

String str;
str = String.valueOf(new Integer(117));	// str은 문자열 "117"가 된다.
str = String.valueOf("livebyfaith");	// str은 문자열 "livebyfaith"가 된다.

Object nullValue = null;
str = String.valueOf(nullValue);	// 문자열 "null"이 된다.

Casting

  • 대상이 null이면 NullPointerException 발생.
  • Object 값이 String이 아니면 ClassCastException 발생.
  • Object가 String 타입을 필요로 한다는 것을 의미, 따라서 Object가 실제로 String 문자열이여야 변환된다. 

ex)

int value = 117;
String str = value + ""; // str은 문자열 "117"이 된다. (int to String)
// 덧셈 연산자는 두 개의 피연산자 중 어느 한 쪽이라도 String 이면 결과는 String.
// Object to String
Object reallyString = "livebyfaith";
String str = (String) reallyString;	// str은 문자열 "livebyfaith"가 된다.

Object notString = new Integer(117);
String str = (String) notString;	// ClassCastException 발생.
// Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap') at fortest.testObjectToString.main(testObjectToString.java:12)

Object nullValue = null;
String str = (String) nullValue;	// str은 문자열 "null"이 된다.

Obj.toString()

  • 당연하게 함수를 사용하는 만큼 대상 값이 null이면 NullPointerException 발생.
  • Object에 담긴 값이 String이 아니라도 출력.
  • Object(Wrapper Class [Integer, Double, Character ...])의 데이터를 String 문자열로 바꿔준다.
  • toString()은 메소드이므로 기본 자료형(Primitive Type)은 사용할 수 없다.

ex)

int number = 117;
String str = number.toString();	// 에러: Cannot invoke toString() on the primitive type int
String str = (new Integer(117)).toString();	// str은 문자열 "117"이 된다.

 

+ 차이점은 null 값에 따른 NullPointerException의 발생 유무이다.

ex)

String str = null;
System.out.println((String) str));			// 'null' text return
System.out.println(String.valueOf(str));		// 'null' text return
System.out.println(str.toString());			// NullPointerException

 

Reference

댓글