Skip to content

Commit 38ff5ef

Browse files
committed
add: String 타입 캐스팅과 String.valueOf() 차이
1 parent 79bbe44 commit 38ff5ef

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

documents/.vuepress/const.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ exports.JavaList = [
3535
"Java/Object.md",
3636
"Java/Primitive-type과-Reference-Type.md",
3737
"Java/자바에서-클래스-정보-알아내는-법.md",
38+
"Java/String-타입-캐스팅과-String.valueOf()-차이.md",
3839
];
3940

4041
exports.OperatingSystemList = [
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# String 타입 캐스팅과 String.valueOf() 차이
2+
* 두 방식 모두 String 타입으로 타입으로 변환하는 것은 같지만, 동작 방식과 예외 처리에서 차이가 있음
3+
4+
## String 타입 캐스팅
5+
```java
6+
Object intValue = 10;
7+
String str1 = (String) intValue; // ClassCastException
8+
9+
Object nullValue = null;
10+
String str2 = (String) nullValue; // null
11+
str2.concat("maeilmail"); // NullPointerException
12+
```
13+
* value가 String 타입이 아니면 ClassCastException 발생
14+
* value가 null인 경우 null을 반환하기 때문에 사용 시 NPE가 발생할 수 있음
15+
16+
## String.valueOf()
17+
```java
18+
Object intValue = 10;
19+
String str1 = String.valueOf(intValue); // "10"
20+
21+
Object nullValue = null;
22+
String str2 = String.valueOf(nullValue); // "null"
23+
str2.concat("maeilmail"); // "nullmaeilmail"
24+
```
25+
* value가 String 타입이 아니면 value.toString() 호출 후 String으로 변환
26+
* value가 null인 경우 "null" 문자열을 반환

0 commit comments

Comments
 (0)