[SWEA][JAVA] 2027. 대각선 출력하기
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 |