Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

햄발

String, StringBuffer 클래스 본문

Java

String, StringBuffer 클래스

햄발자 2024. 4. 29. 17:15

 

 

String 클래스

 

String 을 선언하는 방법 

 String str1 = "Hello";
 String str2 = new String("Hello");
 String str3 = new String("Hello");

 

  • 힙 메모리에 인스턴스로 생성되는 경우와 상수 풀(constant pool) 에 있는 주소를 참조하는 두 가지 방법이있다.
  • 힙 메모리는 생성될때마다 다른 주소 값을 가지지만, 상수 풀의 문자열은 모두 같은 주소 값을 가진다.

 

String Constant Pool

 

 

예시

package useful;

public class StringTest {
	
	public static void main(String[] args) {
		
		String str1 = new String("abc");
		String str2 = new String("abc");
		
		System.out.println(str1 == str2);
		
		String str3 = "abc";
		String str4 = "abc"; // 불변 
		
		// 상수 풀에 올라간 String 값은 
		// 먼저 존재하는지 확인 부터 한다. 
		
		// 완전 똑같은 문자열 abc가 존재 한다면 
		// 새로 생성하지 않고 다시 재사용 한다. 
		
		System.out.println(str3 == str4);
		
		//  == 객체의 주소값을 비교하는 것 (참조 타입) 
		//  equals는 문자열 값을 비교 하는 것
		// 결론적으로 문자열 비교는 논리적인 판단으로 
		// 같은지 다른지 true, false 값을 반환 한다. 
		
		System.out.println(str1 == str4); // false 
		System.out.println( str1.equals(str4) ); // true 
		
		
	} // end of main 
	
} // end of calss

 

리터럴 방식으로 한번 생성된 String은 불변(immutable)

String을 연결하면 기존의 String에 연결되는 것이 아닌 새로운 문자열이 생성됨

 

package useful;

public class StringTest2 {
	
	public static void main(String[] args) {
		
		
		String str3 = "abc";
		String str4 = "abc";
		
		System.out.println( System.identityHashCode(str3)  );
		System.out.println( System.identityHashCode(str4)  );
		
		str3 =  str3 + " : def ";
		System.out.println( System.identityHashCode(str3)  );
	
				
	} // end of main 
	
} // end of calss

 

 

 

 


 

 

StringBuffer 클래스

대체 방법으로는 StringBuilder, StringBuffer 활용할 수 있다.

 

 

예시

package useful;

public class StringBufferTest {
	
	// 코드의 시작점 - (메인 작업자) 
	public static void main(String[] args) {
	
		String str1 = new String("Hello");
		String str2 = new String("World");
		
		StringBuffer bufferStr = new StringBuffer("Hello");
		System.out.println(bufferStr); 
		// 1. 
		System.out.println( System.identityHashCode(bufferStr)); // 원시 주소 값
		
		bufferStr.append(str2);
		
		System.out.println(bufferStr);
		// 2.
		System.out.println( System.identityHashCode(bufferStr) );
		
		// 1 번 결과와 2번 결과에 주소값이 같다라는 의미는 
		// 새로운 메모리를 할당 한 것이 아닌 변경한 것이다.  
		
		// 활용 
		String newStr = bufferStr.toString(); // toString 호출시 타입 -> String  
		
		
	} // end of main
	
} // end of class

 

 

  • 내부적으로 가변적인 char[] 를 멤버 변수로 가진다.
  • 문자열을 여러번 연결하거나 변경할 때 사용하면 유용하다.
  • 새로운 인스턴스를 생성하지 않고 char[] 를 변경한다.
  • StringBuffer는 멀티 쓰레드 프로그래밍에서 동기화(synchronization)을 보장한다.
  • 단인 쓰레드 프로그램에서는 StringBuilder 사용을 권장한다.
  • toString() 메서드로 String반환한다.

 

text block ( java 13 )

  • 문자열을 """ """ 사이에 이어서 만들 수 있다.
  • html, json 문자열을 만드는데 유용하게 사용할 수 있다.

예시

package useful;

public class StringTextBlock {

	public static void main(String[] args) {
		// """ 찍고 한줄 내리기
		String strBlock = """
				This
				is
				text
				block
				test.""";

		String jsonText = """
				{
				  "userId": 1,
				  "id": 1,
				  "title": "delectus aut autem",
				  "completed": false
				}
				""";


		String htmlText = """
				<!doctype html>
				<html dir="ltr" lang="ko"
				    chrome-refresh-2023>
				  <head>
				    <meta charset="utf-8">
				    <title>새 탭</title>
				    <style>
				      body {
				        background: #FFFFFF;
				        margin: 0;
				      }

				      #backgroundImage {
				        border: none;
				        height: 100%;
				        pointer-events: none;
				        position: fixed;
				        top: 0;
				        visibility: hidden;
				        width: 100%;
				      }

				      [show-background-image] #backgroundImage {
				        visibility: visible;
				      }
				    </style>
				  </head>
				  <body>
				    <iframe id="backgroundImage" src=""></iframe>
				    <ntp-app></ntp-app>
				    <script type="module" src="new_tab_page.js"></script>
				    <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
				    <link rel="stylesheet" href="chrome://theme/colors.css?sets=ui,chrome">
				    <link rel="stylesheet" href="shared_vars.css">
				  </body>
				</html>
								""";


	}

}

 

 

'Java' 카테고리의 다른 글

Swing - 3  (0) 2024.04.29
Exception (예외처리)  (0) 2024.04.29
Object 클래스  (0) 2024.04.29
★ 인터페이스(interface) ★  (1) 2024.04.25
추상 클래스(abstract class)  (1) 2024.04.25