복제
ex 1)
public class ReferenceDemo1 {
public static void runValue(){
int a = 1;
int b = a;
b = 2;
System.out.println("runValue, "+a);
// 실행 결과 : runValue, 1
}
public static void main(String[] args) {
runValue();
}
}

복제 : a의값을 b라는 박스에 넣는다
참조 (reference)
ex 1)
class A{
public int id;
A(int id){
this.id = id;
}
}
public class ReferenceDemo1 {
public static void runValue(){ // 복제
int a = 1;
int b = a;
b = 2;
System.out.println("runValue, "+a);
}
public static void runReference(){ // 참조
A a = new A(1);
A b = a; // b도 A인스턴스를 가져서 참조가 가능
b.id = 2;
System.out.println("runReference, "+a.id);
}
public static void main(String[] args) {
runValue();
runReference();
}
}
실행 결과
runValue, 1
runReference, 2
변수 b에 담긴 인스턴스의 id 값을 2로 변경했을 뿐인데 a.id의 값도 2가 된 것이다.
변수 b와 변수 a에 담긴 인스턴스가 서로 같다는 것을 의미
b.id = 2;
System.out.println("runReference, "+a.id);
참조 와 복제 비교
비유하자면 복제는 파일을 복사하는 것이고 참조는 심볼릭 링크(symbolic link) 혹은 바로가기(윈도우)를 만드는 것과 비슷하다
바로가기를 하면 바로 바뀌는 이유 : 원본 파일에 대한 주소 값이 담겨 있다.+
두 개의 구문의 차이점
int a = 1;
A a = new A(1);
전자는 데이터형이 int이고 후자는 A이다
자바에서는 기본 데이터형을 제외한 모든 데이터 타입은 참조 데이터형(참조 자료형)이라고 부른다. 기본 데이터형은 위와 같이 복제 되지만 참조 데이터형은 참조된다.
변수에 담겨있는 데이터가 기본형이면 그 안에는 실제 데이터가 들어있고, 기본형이 아니면 변수 안에는
데이터에 대한 참조 방법이 들어있다

참조 데이터 형과 매개 변수
public class ReferenceParameterDemo {
static void _value(int b){
b = 2;
}
public static void runValue(){
int a = 1; // 기본 데이터 타입
_value(a);
System.out.println("runValue, "+a);
}
static void _reference1(A b){
b = new A(2);
}
public static void runReference1(){
A a = new A(1);
_reference1(a);
System.out.println("runReference1, "+a.id);
}
static void _reference2(A b){
b.id = 2;
}
public static void runReference2(){
A a = new A(1);
_reference2(a);
System.out.println("runReference2, "+a.id);
}
public static void main(String[] args) {
runValue(); // runValue, 1
runReference1(); // runReference1, 1
runReference2(); // runReference2, 2
}
}
실행 결과
runValue, 1
runReference1, 1
runReference2, 2
_value의 매개변수로 기본 데이터형(int)를 전달
runValue();
_reference1의 매개변수로 참조 데이터 타입
메소드 _reference1 안에서 매개변수 b의 값을 다른 객체로 변경하고 있다. 이것은 지역변수인 b의 데이터를 교체한 것일 뿐이기 때문에 runReference1의 결과에는 영향을 미치지 않는다.
runReference1(); // b = new A(2)
메소드의 변수에 영향
매개변수 b의 인스턴스 변수 id 값을 2로 변경하고 있다. 이러한 맥락에서 _reference2의 변수 b는 runReference2의 변수 a와 참조 관계로 연결되어 있는 것이기 때문에 a와 b는 모두 같은 객체를 참조하고 있는 변수다.
runReference2(); // b.id = 2