Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- Thread
- Java데이터 타입
- 시스템 환경 변수 편집
- 인텔리제이 한글 깨짐 해결법
- break문
- java변수
- for문
- 포함관계
- 메서드 오버로딩
- 집합관계
- function
- this예약어
- multi-threading
- continue문
- 상수
- 자바 멀티스레딩
- IntelliJ IDEA
- 연관관계
- JAVA기초
- 생성자
- While
- JAVA객체지향
- Java
- OPP개념
- 반복문
- 메서드
- 접근제어지시자
- 형 변환
- 인텔리제이 기초 설정
- 컴파일
Archives
- Today
- Total
최원종의 개발 블로그
String, StringBuffer 본문
String 클래스
String 클래스는 자바에서 문자열을 표현하는 데 사용.
String은 불변 객체로, 한 번 생성된 문자열은 변경할 수 없다.
String 선언 방식
String 객체는 두 가지 방식으로 생성할 수 있다.
- 리터럴 방식: String str1 = "Hello"; (문자열 리터럴은 String Constant Pool에 저장되어 재사용됩니다.)
- new 연산자 사용: String str2 = new String("Hello"); (힙 메모리에 새로운 객체를 생성하며, String Constant Pool과는 별개로 동작한다
String Constant Pool
String Constant Pool은 JVM의 힙 메모리 내에 존재하는 특별한 영역으로, 문자열 리터럴을 저장하고 재사용하여 메모리 효율성을 높입니다.
동일한 문자열 리터럴은 String Constant Pool에서 하나의 객체만 생성되고, 모든 변수가 이를 참조한다.

코드
package com.tenco._string;
public class StringTest1 {
public static void main(String[] args) {
// 스트링 클래스는 불변이다.
String str1 = new String("Hello");
String str2 = new String("Hello");
String str3 = new String(" World");
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(str1.concat(str3));
String str4 = str1.concat(str3);
System.out.println(str1.hashCode());
// 원래 객체 주소가 생성 되어 있고 내부 변수 값이 변경이 된다면
// String 클래스는 수정이 되지 않고 불변이다.
// 즉, 수정이 된다면 새로운 String 객체를 만드는 동작으로 실행이 된다.
String str5 = new String("안녕");
System.out.println("고유 주소 확인 : " + System.identityHashCode(str5));
str5.concat("반가워");
System.out.println("고유 주소 확인 : " + System.identityHashCode(str5));
} // end of main
}
String 클래스의 불변성으로 인해 문자열을 자주 변경할 때 메모리 낭비가 발생한다면, 이를 해결하기 위해 StringBuffer 또는 StringBuilder를 사용할 수 있다.
StringBuffer vs StringBuilder
StringBuffer
- 내부적으로 가변적인 char [] 배열을 사용하여 문자열을 변경.
- 동기화(synchronization)를 지원하므로 멀티스레드 환경에서 안전.
- 멀티스레드 환경에서 사용 권장.(백엔드 서버)
StringBuilder
- StringBuffer와 동일한 기능이지만 동기화를 지원하지 않음.
- 동기화 오버헤드가 없으므로 단일 스레드 환경에서 더 빠름
- 단일 스레드 프로그램에서 사용 권장
package com.tenco._string;
public class StringBufferTest1 {
public static void main(String[] args) {
String str1 = "HELLO";
String str2 = new String("WORLD");
StringBuffer buffer1 = new StringBuffer(str1);
System.out.println("수정 전 : " + System.identityHashCode(buffer1));
System.out.println(buffer1);
// 주소값 : 189568618
// buffer1 에 접근해서 안에 상태값을 수정 (문자열 수정)
buffer1.append(str2);
System.out.println(buffer1);
System.out.println("수정 후 : " + System.identityHashCode(buffer1));
} // end of mai n
}
'Java > JAVA 유용한 클래스' 카테고리의 다른 글
| Inner class(중첩 클래스) (0) | 2026.03.12 |
|---|---|
| Thread (0) | 2026.03.10 |
| Exception(예외처리) (0) | 2026.03.10 |
| Object 클래스의 메서드 활용 (0) | 2026.03.09 |
| Object 클래스란? (0) | 2026.03.09 |
