티스토리 뷰

반응형

valueOf (Object obj)

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

 

Object.toString()

  • In general, the toString method returns a string that "textually represents" this object. (Java docs)
  • 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)
  • 일반적으로, toString 메소드는 이 object를 "텍스트로 표현하는" String 문자열을 반환한다.
  • 결과는 사람들이 읽기 쉬운 유의미하지만 간결한 표현이여야 한다. 모든 subclass들이 이 메소드를 오버라이드하는 것이 좋다.

 

 

Casting / toString / valueOf 의 차이점

Casting

  • Object가 String 타입을 필요로 한다는 것을 의미한다.
  • 따라서 Object가 실제로 String 문자열이여야 변환된다.
  • ex)
    • int value = 432;
    • String str = value + ""; -> str은 문자열 "432"가 된다. (int -> String 으로 변환하는 방법 중 하나)
      • why?) 덧셈 연산자는 두 개의 피연산자 중 어느 한 쪽이라도 String이라면 결과는 String이다.
    • Object reallyAString = "foo";
    • String str = (String) reallyAString; -> str은 문자열 "foo"가 된다.
    • Object notAString = new Integer(42);
    • String str = (String) notAString; -> ClassCastException 발생시킨다.
    • Object nullValue = null;
    • String str = (String) nullValue; -> str은 문자열 "null"이 된다.

Obj.toString()

  • Object (Wrapper Class[Integer, Character, Double ...]) 의 데이터를 String 문자열로 바꿔준다.
  • toString() 은 메소드이므로 기본 자료형 (Primitive Type) 은 사용할 수 없다.
  • ex)
    • int primitype = 3;
    • String str = primitype.toString() -> 기본 자료형은 메소드를 사용할 수 없으므로 에러가 발생한다.
    • String str = (new Integer(42)).toString() -> str은 문자열 "42"가 된다.
    • Object nullValue = null;
    • String str = nullValue.toString() -> NullPointerException 발생시킨다.

String.valueOf()

  • 어떠한 값을 넣어도 모두 String 문자열로 변환할 수 있다.
  • ex)
    • String str;
    • str = String.valueOf(new Integer(42)); -> str은 문자열 "42"가 된다.
    • str = String.valueOf("foo"); -> str은 문자열 "foo"가 된다.
    • Object nullValue = null;
    • str = String.valueOf(nullValue); -> 위에서 언급한 것과 같이 문자열 "null"가 된다.

Casting / valueOf() 성능 비교

  • case 1:
    • 1. strTest1 = "" + 432;
    • 2. strTest2 = String.valueOf(432); (O)
    • 1번의 경우, 빈 문자열에 다른 타입 데이터를 덧셈 연산자 (+) 로 연결할 시 효율성이 떨어진다고 한다.
    • 왜냐하면 빈 문자열에 String을 +로 연산하면 컴파일러에서 데이터 판단 작업이 발생 하기 때문이라고 한다.
  • case 2:
    • 1. strTest = "0" + 432; (O)
    • 2. strTest = "0" + String.valueOf(432);
    • 해당 사례의 경우, "0" 자체는 빈 String 문자열이 아니기 때문에 이후에 + 로 연결되는 데이터는 String으로 인식한다.
    • 따라서, 불필요하게 String.valueOf() 메소드를 쓸 필요가 없다고 한다.

 

Reference

반응형

'Programming Language > JAVA' 카테고리의 다른 글

equals() & hashcode()  (0) 2019.11.29
StringTokenizer  (0) 2019.09.06
String, StringBuilder, StringBuffer  (0) 2019.09.02
HashTable, HashMap, ConcurrentHashMap  (0) 2019.09.01
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함