본문 바로가기
자바(Java)

자바 중급3 - 스트링버퍼(StringBuffer)

by codeyaki 2022. 1. 14.
반응형

해당 강의를 듣고 정리한 것입니다

https://programmers.co.kr/learn/courses/9

 

자바 중급

평가 5.0 17개의 평가 ★★★★★17 ★★★★0 ★★★0 ★★0 ★0 ds02168 2021.08.20 15:37 Yeonggwang 2021.06.28 01:48 강신우 2021.04.23 10:20 HyeonWoo Jeong 2021.04.08 17:12 이용준 2021.01.26 19:23 리뷰 더보기

programmers.co.kr


스트링 버퍼

: 아무 값도 가지고 있지 않은 StringBuffer객체. 

(String클래스는 불변, StringBuffer는 변하는 클래스)

public class StringBufferExam {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("Hello");
		sb.append(" ");
		sb.append("world");
		
		String str = sb.toString();
		System.out.println(str);		
	}
}

>> Hello world

 

 

체인 메서드 
자기 자신을 리턴하여 계속해 자신의 메서드를 호출하는 방식

StringBuffer가 가지고 있는 메서드들은 대부분 자기 자신, this를 반환함.

public class StringBufferExam {
	public static void main(String[] args) {
		
		StringBuffer sb2 = new StringBuffer();
		StringBuffer sb3 = sb2.append("hello");
		// sb2가 가지고있는 append 메서드는 this가 반환이 됨. 이를 sb3에 저장한것
		// 그러므로 sb2 와 sb3는 똑같음
		// 이를 메서드 체이닝(Method Chaining이라고 부름
		// 메서드 체이닝 :자기자신의 리턴하여 계속하여 자신의 메서드를 호출하는 방식
		if(sb2 == sb3) {
			System.out.println("sb2 == sb3");
		}
	}
}
  • 자기 자신의 메서드를 호출하여 자기 자신의 값을 바꿔나가는 것을 메서드 체이닝이라고 함.
  • StringBuffer클래스는 메서드 체인 방식으로 사용할 수 있도록 만들어져 있다.

체인 메서드의 방식으로 처음에 작성한 코드를 해당 방법으로 한 줄로 생성할 수 있음.

String str2 = new StringBuffer().append("hello").append(" ").append("World").toString();
System.out.print(str2);

>> hello World

 

StringBuffer (Java Platform SE 7 )

Inserts the string into this character sequence. The characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by

docs.oracle.com

 

반응형