자바 기준으로 작성되었습니다.



String Constant Pool이란?

    1. String str1 = "TeamNova";

    2. String str2 = new String("TeamNova");



어떤차이일까? 

1번은 String Constant Pool* 을 참조한다.

2번은 새로운 객체를 생성하여 문자열을 담는다.

String Constant Pool이라는 객체가 만들어져 있고 이곳에 있는 문자조각*을 재사용한다.

-> 마치 방하나에 LEGO조각(?)이 엄청나게 많아서 이걸로 여러가지 형태를 만들수 있다고 상상해 보자.

-> 매번 새로운 LEGO를 살필요가 없을 것이다. ( 진지하게 따지지 말긔 )


문자열을 생성할때마다 새로운 객체를 매번 생성하면 메모리를 비효율적으로 사용하므로 낭비이다.

하지만 이미 만들어진 문자를 재사용 한다면? 새로 객체를 생성하지 않아도 된다. 따라서 메모리를 효율적으로 사용할 수 있다.

필자는 이것이 String Constant Pool ...이라고 이해했다.

아래는 직접 코드로 테스트한 결과이다.

public class test1 {
	
	public static void main(String[] args) {
		
	   	String str1 = "TeamNova";
        String str2 = "TeamNova";
        String str3 = new String("TeamNova");
        String str4 = new String("TeamNova");
        //str1과 str2 비교 ( 둘다 String Constant Pool에 위치함 )
        System.out.println("str1 == str2 :"+(str1==str2));
        //str1과 str3 비교 ( 각각 String Constant Pool, Java Heap 영역에 위치함 )
        System.out.println("str1 == str3 :"+(str1==str3));
        //str3과 str4 비교 ( 각각 Java Heap 영역에 위치함 ( 각각 객체 생성 ) )
        System.out.println("str3 == str4 :"+(str3==str4));
        
       /*
        * 결과 정리
        * 
        * Heap 영역으로 배정되면 각각 메모리 영역이 따로 배정됨 ( 방으로 예를 들면 각각 새로운 방 생성 )
        * 따라서 메모리 주소가 다름.
        * 
        * String Pool은 문자열을 담당하는 방을 하나 만들어 둠.
        * 그곳에 문자들을 모두 모아 두어서 메모리 주소가 같음.
        * 
        * ※ 중요 : String Constant Pool은 Heap 영역에 존재한다.
        *        이곳에 있는 문자열을 재사용한다. 리터널하게...
        *        따라서 새로운 객체를 생성하지 않아 메모리 효율이 좋다.
        * */
	}
}


※ 위 코드에서 처럼...

str1과 str2는 같은 객체이다.  

str3과 str4는 다른 객체이다. 


따라서 총 3개의 객체가 만들어 졌다.



PS. 자바에서 객체의 메모리주소를 알아내는 ( 포인터 ) 방법을 아시는 분은 댓글 남겨주시면 감사합니다...!

잘못 기술된 부분 있다면 메일(inma06@naver.com) or 댓글 남겨주세요

'컴퓨터 프로그래밍 > JAVA' 카테고리의 다른 글

[연습]게임 - 무기강화  (2) 2018.10.03

import java.lang.System;
import java.util.Random;
import java.util.Scanner;

public class MainApp {
	

	private Scanner scanner;


	public static void main(String[] args) {
	MainApp my1 = new MainApp();
	my1.userCmd();		
	}
	
	public void userCmd() {
		MainApp my1 = new MainApp();
		scanner = new Scanner(System.in);		
		System.out.println("강화 하시려면 1을 입력하세요.");
		int userInput = scanner .nextInt();				
		if(userInput == 1) my1.get_enchan();
		else{
			System.out.println("강화를 취소합니다.");			
		}		
	}	
	
		
		public void get_enchan() {
			MainApp my1 = new MainApp();
			Random random = new Random();			
			System.out.println("강화를 시작합니다.");
			Boolean [] enchant = new Boolean[3];  
			for(int i=0; i<enchant.length; i++) { 
				enchant[i] = random.nextBoolean();
				
				if(enchant[i]) {
					System.out.println("★★★★★★★★★★");				
				}
				else System.out.println("○○○○○○○○○○○○");
			}

			if(enchant[0]) {
				if(enchant[1]) {
					if(enchant[2]) {
						System.out.println("인챈트를 성공하였습니다.");
					}	else {
						System.out.println("인챈트가 실패하였습니다."); my1.userCmd();
					}
				}	else {
					System.out.println("인챈트가 실패하였습니다."); my1.userCmd();
				}
			}			
			else if(enchant[0] == false) {
				if(enchant[1] == false) {
					if(enchant[2] == false) {
						System.out.println("인챈트를 성공하였습니다.");
					}	else {
						System.out.println("인챈트가 실패하였습니다."); my1.userCmd();
					}
				}	else {
					System.out.println("인챈트가 실패하였습니다."); my1.userCmd();
				}
				
			}	else {
				System.out.println("인챈트가 실패하였습니다."); my1.userCmd();
				
			}
		}
}	




+ Recent posts