응용 프로그램이 실행되면, JVM은 프로그래밍을 수행하는데 필요한 메모리를 할당받는다. 그 이후 메모리에 영역을 나누어 관리한다.
메모리 구조는 다음과 같다.
기본형 매개변수를 사용하여 메서드에 넘기면, 메서드는 해당 매개변수를 수정해도, 원래 값에는 변화가 없다.
하지만 참조형 매개변수를 사용하면, 변화한다. 이유는 참조형 매개변수는 '주소'값을 넘기기 때문이다.
이것이 call by reference 이다.
다음은 call by value 설명을 위한 예제 코드이다.
출처 : 자바의 정석(남궁성)
class Data {
int x;
}
class PrimitiveParamEx {
public static void main(String[] args) {
Data d = new Data();
d.x = 10;
System.out.println("main() : x = " + d.x);
change(d.x);
System.out.println("After change(d.x)");
System.out.println("main() : x = " + d.x);
}
static void change(int x) {
x = 1000;
System.out.println("change() : x = " + x);
}
}
간단히 소개된 책 내용을 좀더 상세히 이해하며 그림을 작성해보았다.
JVM의 모든 내용이 다 드러나게 말이다.
new Data()
Data d = new Data()
d.x = 10
다음은 call by reference 이다.
class Data {
int x;
}
class ReferenceParamEx {
public static void main(String[] ar
gs) {
Data d = new Data();
d.x = 10;
System.out.println("main() : x = " + d.x);
change(d);
System.out.println("After change(d)");
System.out.println("main() : x = " + d.x);
}
static void change(Data d) {
d.x = 1000;
System.out.println("change() : x = " + d.x);
}
}
아까랑 달라진점은, change 함수내에서 직접 Heap영역에 존재하는 인스턴스의 주소값을 복사한 것 밖에 없다.
이렇게 주소값을 복사하면 데이터값을 저장하고 있는 Heap 영역에 접근할 수 있으므로, 값을 메서드를 통해 변경할 수 있다.
https://velog.io/@goat_hoon/자바의-정석-6.-객체지향언어
제가 쓴 글에서 따로 발췌해온 포스트입니다.