System.out.println
System.out.print
toString메소드
문자열, String 인스턴스를 반환하는 문자열
1. package org.example;
2.
3. class Box {
4. private String conts;
5.
6. Box(String cont) {
7. this.conts = cont;
8. }
9.
10. public String toString(){
11. return conts;
12. }
13. }
14.
15. public class str {
16. public static void main(String[] args) {
17. StringBuilder stb = new StringBuilder("12");
18. stb.append(34);
19. System.out.println(stb.toString());
20. System.out.println(stb);
21.
22. Box box = new Box("camera");
23. System.out.println(box.toString());
24. System.out.println(box);
25. }
26. }
1234 // System.out.println(stb.toString());
1234 // System.out.println(stb);
camera // System.out.println(box.toString());
camera // System.out.println(box);
// 19, 20번 째 줄 출력 결과 이유
17. StringBuilder stb = new StringBuilder("12"); // stb = "12"
18. stb.append(34); // stb = 1234로 재정의
19. System.out.println(stb.toString()); // stb는 1234
// -> toString은 왜 붙이는거지?? 생략가능...
17. StringBuilder stb = new StringBuilder("12"); // stb = "12"
18. stb.append(34); // stb에다가 "34"를 append 했으므로 stb가 1234로 재정의
20. System.out.println(stb); // stb 자체가 12에서 1234로 재정의
// 22, 23번 째 줄 출력 결과 이유
22. Box box = new Box("camera"); // Box 인스턴스 생성,
3. class Box {
4. private String conts; // "camera" 라는 문자열 저장
23. System.out.println(box.toString()); // toString 메서드 호출
10. public String toString(){
11. return conts; // toString인스턴스의 참조값을 conts가 반환
따라서 23. System.out.println(box.toString());
// println메소드에는 "camera"라는 String인스턴스의 참조값이 전달되어 "camera"출력
24. System.out.println(box); // Box 인스턴스의 참조값 Box를 인자로 전달
// Box라는 참조변수가 가지고있는 참조값을 그냥 전달 그래도 여전히 "camera" 메소드 전달
내가 정의를 하든 안하든모든 클래스는 toString 메소드를 가지고 있음
f = format의 약자
printf는 문자열을 다양하게 조합할 수 있음
printf 메소드는 첫 번 째 인자로 무조건 문자열이 전달 됨 ( “ “ )
그대로 출력하진 않고 다양하게 조합을 함