//리턴값이 없어도 값을 공유하는 방법
//리턴값이 없어도 heap memory를 공유하여 값을 저장하게 된다면
//메소드가
//Call by Reference(참조에 의한 호출)
public class Exam_01 {
public static void func() {}
public static void func1(int num){}
public static void func2(int[] arr) {}
public static void method(int[] arr) {
arr[2]=100;
//index=offset=기준에서부터 얼마만큼 떨어져있는가
//arr이 1000번지를 기억하고 있다고 가정했을때 arr[0]이 1000번지, arr[1]이 1004번지
//arr[2]=100 이란건 heap memory에 1008번지에 100을 넣으라는 의미
}
public static int test(int a) {
a=50;
return a; // return하지 않으면 매개변수 a는 지역변수이므로 이 method가 끝나면 사라짐. 그러므로 Call by value에서 값을 전달하고 싶다면 return을 해줘야함.
}
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4,5};
method(arr); //배열참조변수arr을 넘겼다 = heap memory에 있는 배열의 주소값을 넘겼다
System.out.println(arr[2]);
//메서드를 이름만 가지고 호출했다
func(); // call by name - call하면서 인자값을 안보내면
func1(100); // call by value - 기본자료형 데이터를 보내면서 메서드를 call했을때
func2(new int[] {1,2,3}); // call by reference - 기본자료형이 아닌 데이터를 보내면서 메서드를 call했을때
//call by name과 call by value 는 인자값과 return이 있어야지만 값을 공유할 수 있지만
//call by reference는 주소값을 전달하기 때문에 두개의 메소드가 하나의 값을 통제가능(return없이도 값을 공유할수 있다)
int a=10;
test(a);
System.out.println(a);
}
}
Comment