(기초)그래서 뭘 배운거야?/Java

JV-93-String / StringBuffer / StringBuilder

Soheny.P 2022. 3. 28. 23:53
728x90
String와 StringBuilder, StringBuffer 이 셋은 출력된 결과만 보기엔 똑같다.
하지만 뜯어보면 다르니까 한 번 뜯어볼라고

 

 

		
		//String
		String str = "hello";
		System.out.println("str = hello : " + str.hashCode());
		str = str + " world";
		System.out.println("str = hello world : " + str.hashCode());

		
		//StringBuilder
		StringBuilder str1 = new StringBuilder();
		str1.append("hello");
		System.out.println("str1 = hello : " + str1.hashCode());
		str1.append(" world");
		System.out.println("str1 = hello world : " + str1.hashCode());
		
		
		//StringBuffer
		StringBuffer str2 = new StringBuffer();
		str2.append("hello");
		System.out.println("str2 = hello : " + str2.hashCode());
		str2.append(" world");
		System.out.println("str2 = hello world : " + str2.hashCode());

 

상단 내용을 출력해보면, String은 hello일 때와 hello world일 때 hash값이 다르다
991~ 에서 179~로 이동.
StringBuilder와 StringBuffer는 append 메소드로 hello뒤에 추가하는 개념이기 때문에
hash값이 고대로 출력된다.

이것이 차이점인데, 이 차이점으로 뭘 어쩐다고?

String은 불변할 값을 사용할 때 주로 사용하기
StringBuffer / StringBuilder는 가변적 값이 할당될 때 사용하기

 

그렇다면, StringBuffer와 StringBuilder는 어떻게 다른건데?

StringBuffer는 동기화를 지원해서 멀티스레드 환경에서도 사용 가능하지만,
StringBuilder는 동기화 미지원이라 싱글스레드 환경에서만 사용 가능하다

그럼 다음 장에서 뭘 정리해볼지 딱 이제 느낌이 온다
프로세스랑 스레드!! 

 

728x90