본문 바로가기

Java

String Class의 특징

String class는 문자열을 다루기 위한 class로 불편클래스(immutable class)이다. String class는  문자열을 변경할 경우 인스턴스 내의 문자열이 변경되는 것이 아니라 새로운 객체가 생성된다. 그래서 문자열의 수정이나 결합이 많이 일어나는 경우 StringBuffer클래스를 이용하는 것이 바람직하다.

 

 

ex. String a = new String("abc");

      String b = new String("def");

      a = a + b;  //   a = new String(a+b);

 

String a = "abc"; 와 같은 문자열 리터럴로 String을 선언하면 문자열 리터럴은 프로그램 실행 시 자동으로 constant pool에 저장된다.  그리고 해당 문자열("abc") 리터럴을 참조하는 참조변수가 더 있을 경우 모두 같은 주소를 가리키게 된다. (재사용)

  

 

길이가 0인 배열

자바에서는 길이가 0인 배열을 생성 가능하다. (ex. char[] a = new char[0]; )

위와 같이 길이가 0인 배열을 생성 하면 생성된 객체는 길이 정보를 가지고 있기 때문에 메모리 size가 0은 아니다.

 

 

초기화

String class를 초기화 할 경우 null로 초기화를 하는 것보단 ""으로 초기화를 하여 nullpointerexception을 예방하는 것이 바람직하다.

ex. String str = "";    char c = ' '; ( char형은 공백으로 초기화 )

 

public class Test {

    public static void main(String[] args) {
    	System.out.println("int 배열은 서로 다른 곳을 가리깉다. ");
    	int[] a = {1, 2, 3};  
    	int[] b = {1, 2, 3};
    	System.out.println(System.identityHashCode(a));
    	System.out.println(System.identityHashCode(b));
    	
    	System.out.println();
    	System.out.println("길이가 0인 배열");
    	
    	char[] c = new char[0]; 
    	char[] d = new char[0]; 
    	System.out.println(System.identityHashCode(c));
    	System.out.println(System.identityHashCode(d));
    	
    	System.out.println();
    	System.out.println("문자열 초기화");
    	
    	String str = new String(""); // heap에 String class 생성 내부의 char[]은 길이를 0으로 가진다.
    	String str2 = new String("");
    	String str3 = ""; // constant pool에 저장 
    	String str4 = ""; // str3와 같은 곳을 가리킨다.
    	System.out.println(System.identityHashCode(str));
    	System.out.println(System.identityHashCode(str2));
    	System.out.println(System.identityHashCode(str3));
    	System.out.println(System.identityHashCode(str4));
    }

}