Java, Call By (Value vs Reference)

murkgom·2022년 1월 18일
0

1. 개념

Call By Value

  • Method의 Parameter 전달시, 을 복사하여 전달

Call By Reference

  • Method의 Parameter 전달시, 참조값을 복사하여 전달

2. In Java

  • 모든 케이스에서 Call By Value 사용

3. Test with code

1) Primitive Type

private void changeInteger(int before, int after) {
    before = after;
}

public void main() {
    int i = 1;
    log.info("before call. i : {}", i);		
    //before call. i : 1
    
    this.changeInteger(i, 4);
    
    log.info("after call. i : {}", i);		
    //after call. i : 1
}
  • method 내부의 값 변화에 기존 값이 영향을 받지 않음
  • Call By Value 확인

2) Reference Type - case 1

private void changeStr(String before, String after) {
    before = after;
}

public void main() {
    String str = "a";
    log.info("before call. str : {}", str);		
    //before call. str : a
    
    this.changeStr(str, "bb");
    
    log.info("after call. str : {}", str);		
    //after call. str : a
}
  • method 내부의 값 변화에 기존 값이 영향을 받지 않음
  • Call By Value 확인

3) Reference Type - case 2

private void changeName(A arg, String name) {
    arg.name = name;
}

public void main() {
    A a = new A();
    a.id = 1;
    a.name = "k2h";
    log.info("before call. a : {}", a.toString());		
    //before call. a : A(id=1, name=k2h)
    
    this.changeName(a, "hhh");
    
    log.info("after call. a : {}", a.toString());		
    //after call. a : A(id=1, name=hhh)
}
  • method 내부의 값 변화에 기존 값이 영향을 받는다...?
  • Call By Reference...? (X)

4. Reference Type의 이해

  • 자바의 객체(=Reference Type)는 실제 값을 보관하는 Heap의 참조 주소값을 가짐
  • method의 Parameter 역시 해당 주소값이 복사, 전달됨

Reference Type case들의 method 내의 상황

case 1

  • before의 주소값이 after의 주소값으로 변경
  • 기존 변수의 값에 영향이 없음

case 2

  • 기존 변수의 참조 주소값이 전달된 상태
  • 참조 주소값을 이용하여 해당 Heap의 값을 변경함
  • 기존 변수가 참조하는 Heap의 값이 바뀌었으므로 기존 변수의 값도 바뀐 것으로 생각

5. 결론

  • 모든 케이스에서 Java의 Method Parameter 전달 방식은 Call By Value

0개의 댓글