StringBuilder 인스턴스를 그대로 넣어준 것과 StringBuilder의 toString()함수를 붙여준 것과의 차이점은 무엇인가요?
There's nothing different between line 6 and line 8.
PrintStream.println(Object) calls string.valueOf(Object) which calls the object's toString() method, and that gets printed.
System.out.println(s) and System.out.println(s.toString()) have the same output (unless s is null, in which case the latter throws an exception).
The reason you call s.toString() directly is to get the current "built" value from the StringBuilder as a string so you can pass it on to other code which expects a string. If the code you want to call takes a StringBuilder you could just pass s, but then the called code has the ability to modify your value (they can't with string because it is an immutable data type).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
class Solution {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
for(int i=0; i<5; i++) {
StringBuilder str = new StringBuilder("+++++");
str.setCharAt(i, '#');
System.out.println(str.toString());
}
}
}
|
cs |
'알고리즘 풀이 > SWEA' 카테고리의 다른 글
[SWEA][JAVA] 11592. 크루즈 컨트롤 (0) | 2021.06.14 |
---|---|
[SWEA][JAVA] 2025. N줄덧셈 (0) | 2021.06.14 |
[SWEA][JAVA] 3143. 가장 빠른 문자열 타이핑 (0) | 2021.06.14 |
[SWEA][JAVA] 2029. 몫과 나머지 출력하기 (0) | 2021.06.14 |
[SWEA][JAVA] 2043. 서랍의 비밀번호 (0) | 2021.06.13 |