이번 포스팅은 Java라는 언어가 call by value인지 call by reference인지 확인해 시간을 가지려고 합니다.
공부를 하다가도 계속 헷갈려서 이번에 정리를 하려고 합니다.
call by value는 값을 호출하는 것을 의미하고,
call by reference는 메모리 주소값을 호출하는 것을 의미합니다.
결론부터, 말씀드리자면, Java는 call by Value
입니다.
위에서 언급한대로 call by value는 인자에 저장되어 있는 값을 호출하는 것 입니다.
public int increase(int a){
return ++a;
}
public static void main(String[] args){
int a = 1;
a = increase(a);
System.out.println(a); // 2
}
public void increase(int a){
++a;
}
public static void main(String[] args){
int a = 1;
increase(a);
System.out.println(a); // 1
}
정리하면, Java는 call by value이고, 기본형 타입은 값 자체를 가지고 있기 때문에 변수에 값 자체를 복사해서 호출하는 형식입니다.
call by reference 메모리 주소값을 호출합니다.
다시 한번 말하지만, Java는 call by Value입니다.
그래서 call by value를 합니다. 어떤 것을?? 메모리 주소값을!!!!
call by value로 참조 변수를 호출하는 것은 메모리 주소를 복사해서 가지고 오는 것입니다.
public class Test {
int size;
}
---------------------------------------------------------
public class Main {
private static void increase(Test test) {
test.size = 2;
}
public static void main(String[] args) {
Test test = new Test();
test.size = 1;
System.out.println(test.size); // 1 출력
increase(test);
System.out.println(test.size); // 2 출력
}
}
메모리 주소값이 같으니까요!
참조 변수를 call by value하는 것은 해당 레퍼런스의 메모리 주소값을 복사하는 것이고
, call by reference는 메모리 주소값 자체 즉, 원본을 가지고 오는 것 입니다.
public class Test {
int size;
}
---------------------------------------------------------
public class Main {
private static void increase(Test test) {
test = new Test();
test.size = 3;
}
public static void main(String[] args) {
Test test = new Test();
test.size = 1;
System.out.println(test.size); // 1 출력
increase(test);
System.out.println(test.size); // 1 출력
}
}
왜 이런 결과가 생길까요?? call by value이기 때문입니다.
test의 복사본에 새로운 객체가 할당되면서 원본 test 객체와의 관련이 없어진 것입니다.
reference