💡 학습 목표
|
1. String 클래스의 대해 알아 보자.
String 선언하는 두가지 방법
String str1 = "Hello";
String str2 = new String("Hello");
String str3 = new String("Hello");
- 힙 메모리에 인스턴스로 생성되는 경우와 상수 풀(constant pool)에 있는 주소를 참조하는 두 가지 방법
- 힙 메모리는 생성될때마다 다른 주소 값을 가지지만, 상수 풀의 문자열은 모두 같은 주소 값을 가짐
String Constant Pool 이란
시나리오 코드1
package basic.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 class
- 리터럴 방식으로 한번 생성된 String은 불변(immutable)
- String을 연결하면 기존의 String에 연결되는 것이 아닌 새로운 문자열이 생성됨
2. StringBuffer 클래스에 대해서 알아 보자.
String 클래스의 잦은 변화가 있을 때 메모리 낭비를 발생할 수 있다는 개념을 알았다면 대체 방법에 대해서 살펴 보자.
대체 방법으로는 StringBuilder, StringBuffer 활용할 수 있는데 StringBuffer는 멀티 쓰레드 프로그래밍에서(백엔드서버) 동기화(synchronization)을 보장하기 때문에 StringBuffer 만 알아 보도록 하자.
시나리오 코드 2
1.
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
2. 활용 다른 방법
더보기
package basic.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 = (String.valueOf(bufferStr));
System.out.println("-------------");
System.out.println(System.identityHashCode(newStr));
} // end of main
} // end of class
- 내부적으로 가변적인 char[]를 멤버 변수로 가짐
- 문자열을 여러번 연결하거나 변경할 때 사용하면 유용함
- 새로운 인스턴스를 생성하지 않고 char[] 를 변경함
- StringBuffer는 멀티 쓰레드 프로그래밍에서 동기화(synchronization)을 보장
- 단인 쓰레드 프로그램에서는 StringBuilder 사용을 권장
- toString() 메서드로 String반환
3. text block ( java 13 ) 사용 해보기
- 문자열을 """ """ 사이에 이어서 만들 수 있음
- html, json 문자열을 만드는데 유용하게 사용할 수 있음
package basic.useful;
public class StringTextBlock {
public static void main(String[] args) {
// """ 찍고 한줄 내리기
String strBlock = """
This is a Text Bloc
""";
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: #3C3C3C;
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>
""";
// html, json 문자열을 만드는데 유용하게 사용할 수 있음
// 지식 json이라는 녀석은 Javascript Object Notation으로 규칙으로 형성된 문자열을 json이라 한다.
} // end of main
} // end of class
'Java > JAVA 3 - 유용한 클래스' 카테고리의 다른 글
Thread에 wait와 notify(프로듀서-컨슈머패턴) - 6 (0) | 2024.05.21 |
---|---|
자바 multi-threading 이란 - 5 (0) | 2024.05.01 |
자바 Tread - 4 (0) | 2024.05.01 |
JAVA 3 - Exception(예외처리) (0) | 2024.04.29 |
JAVA 3 - Object 클래스 (0) | 2024.04.25 |