Java/[국비] JAVA

[국비][JAVA] 불변 객체 String 알아보기

줌인. 2024. 6. 3. 20:24

▶ 참고 사이트

https://docs.oracle.com/en%2Fjava%2Fjavase%2F17%2Fdocs%2Fapi%2F%2F/java.base/java/lang/String.html

 

String (Java SE 17 & JDK 17)

All Implemented Interfaces: Serializable, CharSequence, Comparable , Constable, ConstantDesc The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constan

docs.oracle.com

 

[예제 코드1]

public class StringImmutable1 {
    public static void main(String[] args) {
        String str = "hello";
        str.concat(" java"); //참조 변수임에도 불구하고 합쳐지지 않은 것을 확인 가능
        System.out.println("str = " + str);
    }
}

class StringImmutable2 {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = str1.concat(" java"); //변경이 필요한 경우 기존값 변경없이, 새로운 결과 반환
        System.out.println("str1 = " + str1);
        System.out.println("str2 = " + str2);
    }
}

 

[예제 코드 2]

public class ImmutableMain {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = s1.concat(" java");
        System.out.println(s3);
    }
}

 

 

[불변 설계 이유 도식화]

- 하기 그림처럼 s1과 s2는 같은 주소를 참조하고 있음

- 이 상태에서 s1의 값만 변경한다고 할 경우(불변이 아닐경우) s2안의 값까지 변경이 됨

- 따라서 초기상태의 "hello"의 값을 찾을 수 없는 문제가 발생

- 이같은 사이드 이펙트 문제를 발생하기 위해 불변으로 설계됨

- 따라서 값을 반환하여 새로운 String 타입으로 저장

 


▶ StringBuilder : mutable 객체

https://docs.oracle.com/en%2Fjava%2Fjavase%2F17%2Fdocs%2Fapi%2F%2F/java.base/java/lang/StringBuilder.html

 

StringBuilder (Java SE 17 & JDK 17)

All Implemented Interfaces: Serializable, Appendable, CharSequence, Comparable A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in

docs.oracle.com

※ `StringBuilder` 클래스가 `final`로 선언된 이유는 이 클래스를 상속하여 변경할 수 없도록 하기 위함

⇒ `StringBuilder`는 mutable 객체로, 내부 상태를 변경할 수 있지만, 클래스 자체를 불변으로 만들면 상속을 통해서 내부         동작을 변경할 위험을 방지할 수 있음을 주의

 

728x90