call by value? call by reference?

2022. 8. 22. 23:53BackEnd(Java)/Java

✅ 자바의 메서드 매개변수 전달 방식에 대해서 알아보자

 

자바를 공부하던 도중에 자바에서 메서드 매개변수 전달 방식에 대해서 궁금하게 되었다.

 

자바는 call by value인가 아니면 call by reference인가?

 

먼저 call by value에 대해서 부터 알아보자!

위키피디아 정의에 따르면

 

Call-by-value

In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by copying the value into a new memory region). If the function or procedure is able to assign values to its parameters, only its local copy is assigned — that is, anything passed into a function call is unchanged in the caller's scope when the function returns.

 

번역하자면 call-by-value 메커니즘은 함수로 인자를 전달할 때 전달될 변수의 값을 복사(copy)하여 함수의 인자로 전달함

또한 복사된 값은 함수 내에서 지역적으로 사용되는 local value라는 특징을 가진다.

 

그리고 caller(호출자)는 실인자의 복사 값을 넘겨주었으므로, callee(피호 출자)는 가인자에 어떠한 작업을 하더라도 실 인자는 변하지 않는다.

 

 

Call-by-reference

In call-by-reference evaluation(also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.

 

번역하자면 call-by-reference 참조에 의한 호출(혹은 참조에 의한 전달) 메커니즘은 함수는 값의 복사본이 아닌 인수로 사용된 변수에 대한 암 시작 참조를 전달받으며, 일반적으로 함수가 인수로 사용된 변수를 수정 가능함을 의미한다.

 

두 개념에 대한 정의는 대략적으로 파악이 되지만 쉽게 이야기하자면

call-by-value는 변수에 담긴 값, 즉 메모리에 있는 값을 함수의 파라미터로 전달하는 방식을 의미하며

call-by-reference는 변수에 담긴 값이 아닌, 값을 담고 있는 메모리의 주소 값(래퍼런스)을 전달하는 방식을 의미한다.

 

그렇다면 다시 원점으로 돌아와서 JAVA는 call by value 일까 call by reference 일까?

java는 call by value 방식으로 함수의 매개변수를 전달한다.

 

 

예시를 통해 자세히 알고 싶으면 여기 참조

http://mussebio.blogspot.com/2012/05/java-call-by-valuereference.html

 

결론

자바는 함수에 인자 값을 넘길 때 call-by-value를 하는데 기본자료형에 해당하는 변수를 인자 값으로 넘길 때는 값을 넘기고,참조형 변수를 넘길때는 레퍼런스를 넘기는 것처럼 보이지만

레퍼런스 타입의 경우 그 변수가 가지는 값이 주소 값이 되므로 call by value에 의해 파라미터를 넘기는 방식이 된다.

그래서 value값은 객체에 대한 포인터 또는 원시적인(primitive) 타입이다!

 


 참고 자료

 

 

반응형

'BackEnd(Java) > Java' 카테고리의 다른 글

CompletableFuture  (0) 2022.11.22
추상클래스 vs 인터페이스  (0) 2022.09.01
java Stream 참고 사이트  (0) 2022.08.21
valueOf, parseInt 비교  (0) 2022.04.07
JAVA Optional 잘쓰기  (0) 2022.04.04