본문 바로가기

IT-Consultant

매개변수의 변화 (call by reference)

// [ReferenceParameter.java]
public class ReferenceParameter {
public void increase(int[] n) {
for (int i = 0; i < n.length; i++) {
n[i]++;
System.out.println("n[" + i + "] : " + n[i]);
}
}

public static void main(String[] args) {
int[] ref1 = { 100, 800, 1000 }; // ref.length=3
ReferenceParameter rp = new ReferenceParameter();
rp.increase(ref1);
for (int i = 0; i < ref1.length; i++) {
System.out.println("ref1[" + i + "] : " + ref1[i]);
}
}
}
/*
 * 매개변수 ref1는 stack영역에 저장된 heap영역 접근 주소이며, 실제 데이터는 heap영역에서 변경되므로 결과는 아래와 같다.
 * 
 * 자바 실행 
n[0] : 101 
n[1] : 801 
n[2] : 1001 
ref1[0] : 101 
ref1[1] : 801 
ref1[2] : 1001
 */