Dev Lang/JAVA

[JAVA] 자바의 기본형과 참조형의 값 공유 특성

개발자 성현 2024. 12. 28. 14:29

학습 키워드

  • 기본형(Primitive Type)
  • 참조형(Reference Type)
  • 값 복사(Pass by Value)
  • 참조 복사(Pass by Reference)

학습 정리

1. 기본형(Primitive Type)

기본형은 실제 값을 복사하여 전달. 복사본은 원본과 독립적으로 동작하며 서로 영향을 주지 않음.

public class PrimitiveExample {
    public static void main(String[] args) {
        int x = 10;
        int y = x;  // x의 값 복사

        x = 20;     // x값 변경
        System.out.println("x: " + x);  // 출력: 20
        System.out.println("y: " + y);  // 출력: 10
    }
}

2. 참조형(Reference Type)

참조형은 객체의 주소를 복사하여 전달. 여러 참조 변수가 동일한 객체를 가리킬 수 있어 한 변수에서의 변경이 다른 변수에도 영향을 미침.

public class ReferenceExample {
    public static void main(String[] args) {
        class Person {
            String name;
            Person(String name) { this.name = name; }
        }

        Person p1 = new Person("Kim");
        Person p2 = p1;  // p1의 참조 복사

        p1.name = "Lee";  // p1의 객체 변경
        System.out.println("p1.name: " + p1.name);  // 출력: Lee
        System.out.println("p2.name: " + p2.name);  // 출력: Lee
    }
}

3. 메서드 호출 시의 차이

public class MethodCallExample {
    static void modifyPrimitive(int x) {
        x = 20;  // 지역변수 변경
    }

    static void modifyReference(Person p) {
        p.name = "Park";  // 객체의 속성 변경
    }

    public static void main(String[] args) {
        int num = 10;
        modifyPrimitive(num);
        System.out.println(num);  // 출력: 10 (변경 없음)

        Person person = new Person("Kim");
        modifyReference(person);
        System.out.println(person.name);  // 출력: Park (변경됨)
    }
}

이러한 특성 때문에 참조형을 사용할 때는 객체의 공유와 변경에 주의가 필요하며, 필요한 경우 객체를 복제하여 사용해야 함.