차이점
String.valueOf 같은 경우 해당 값이 null 일때는 String 형 "null"반환
toString 같은 경우 NullPointException 발생
왜?
String.valueOf 같은 경우에는 아래와 같이 해당 객체가 null 경우에 대한 조건문이 있지만,
toString은 존재하지 않는다.
String.valueOf 구현체
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
toString 구현체
/**
* Returns a {@code String} object representing this
* {@code Integer}'s value. The value is converted to signed
* decimal representation and returned as a string, exactly as if
* the integer value were given as an argument to the {@link
* java.lang.Integer#toString(int)} method.
*
* @return a string representation of the value of this object in
* base 10.
*/
public String toString() {
return toString(value);
}
Example
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Map<String, Integer> testList = new HashMap<String, Integer>();
testList.put("A", 100);
// valueof = "null"
String valueOf = String.valueOf(testList.get("B"));
System.out.println(valueOf);
try {
// NPE 발생
String toString = (testList.get("B")).toString();
System.out.println(toString);
} catch (NullPointerException e) {
System.out.println("NPE 발생");
}
}
}'language > Java' 카테고리의 다른 글
| [Java] BigInteger (0) | 2022.06.09 |
|---|