Java의 Parameter Passing

개발새발log·2022년 10월 2일
0

Java/Spring

목록 보기
4/6

https://www.baeldung.com/java-pass-by-value-or-pass-by-reference의 핵심 내용을 간추렸습니다.

Pass By Value

When a parameter is pass-by-value, the caller and the callee method operate on two different variables which are copies of each other. Any changes to one variable don't modify the other.

It means that while calling a method, parameters passed to the callee method will be clones of original parameters. Any modification done in callee method will have no effect on the original parameters in caller method.

쉽게 말해, 파라메터로 받은 변수는 복사본이다. 완전히 다른 두 변수이되, 복사본이기 때문에, 한 변수의 값이 바뀌었다고 다른 변수에 영향을 주지 않는다.

Pass By Reference

When a parameter is pass-by-reference, the caller and the callee operate on the same object.

It means that when a variable is pass-by-reference, the unique identifier of the object is sent to the method. Any changes to the parameter’s instance members will result in that change being made to the original value.

Pass By Reference의 경우, 동일한 객체에 대해 작업을 하는 것이다. 즉, 인자로 전달된 변수의 값을 변경하는 건 원래 객체의 값을 변경하는 것과 같다.

Java 예시

✅ 코드는 링크 참고해주세요!

1) Primitive type의 전달

main 함수의 x, y가 modify(x, y) 함수를 호출한 경우, modify의 x1, y1은 본래 x, y의 값을 복사해 저장한다. 별개의 변수이기 때문에 modify에서 x1, y1의 값을 변경한 건 기존의 x, y 변수와 상관없다.

2) Reference Type의 전달 (ex. Object, 배열)

Reference Type 변수의 메모리 할당 방식에 대해 알 필요가 있다.
Reference type 변수의 레퍼런스 값은 스택에 적재되며, 해당 레퍼런스의 실 객체는 힙 영역에 적재된다.

Pass By Value로 레퍼런스 변수 a, b를 복사해서 다른 함수에 전달되면, 그 함수의 인자 a1, b1은 해당 객체들의 레퍼런스를 가지게 된다. Primitive type을 전달할 때와 달리, 실객체의 레퍼런스를 가졌기 때문에 값을 변경할 수 있는 것이다.

결론

Java는 Pass by value를 따른다.

1) Primitive Type의 경우, 파라메터가 pass-by-value로 복사되고,
2) Reference Type의 경우, 레퍼런스가 pass-by-value로 복사된다

profile
⚠️ 주인장의 머릿속을 닮아 두서 없음 주의 ⚠️

0개의 댓글