기본 타입
int a = 10;
int b = a; // b에 a의 값(10)이 복사됨
b = 20;
System.out.println(a); // 10 (안 변함)
System.out.println(b); // 20
기본 타입은 “값 자체”가 이동
참조 타입
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1;
arr2[0] =99;
System.out.println(arr1[0]); // 99 {같은 배열을 보고 있어서 둘다 바뀜}
System.out.println(arr2[0]); // 99
겉보기에 arr1을 건드리지 않았는데 값이 변하는 이유는 같은 주소값을 공유하는 사이라서 그럼
String
public class StringExample {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true (String Pool 같은 객체 참조)
System.out.println(a == c); // false (new로 만든 다른 객체)
System.out.println(a.equals(c)); // true (값 비교는 동일)
// 불변성 확인
String d = a.concat(" world");
System.out.println(a); // "hello" (변경되지 않음)
System.out.println(d); // "hello world"
}
}
String Pool
StringBuilder
StringBuilder sb = new StringBuilder("hello");
sb.append(" world"); // 같은 객체 안에서 수정
System.out.println(sb); //"hello world"
StringBuffer
StringBuffer sbf = new StringBuffer("hello");
sbf.append(" world"); // 같은 객체 수정(스레드 안전)
System.out.println(sbf); // "hello world"