1. Call By Value(값에 의한 호출)
- 값에 의한 호출은 파라미터로 넘어온 값이 실제 값이 아니라 실제 값으로 복사한 값으로 넘어오는 경우이다.
- 만약 파라미터의 데이터 타입이 기본형 데이터 타입일 경우에는 값에 의한 호출이 발생한다.
public class CallBy {
public static void main(String[] args) {
// 값에 의한 호출
int num = 3;
System.out.println(num); // 3 출력
callByValue(num); // 4 출력
System.out.println(num); // 3 출력
}
public static void callByValue(int num) {
num++;
System.out.println(num);
}
}
3
4
3
2. Call By Reference(참조에 의한 호출)
- 참조에 의한 호출은 파라미터로 넘어온 값이 실제 주소 값으로 넘어오는 경우이다.
- 만약 파라미터의 데이터 타입이 참조형 데이터 타입일 경우에는 참조에 의한 호출이 발생한다.
public class CallBy {
public static void main(String[] args) {
// 참조에 의한 호출
int[] array = new int[3];
System.out.println(array[0]); // 0 출력
callByReference(array); // 30 출력
System.out.println(array[0]); // 30 출력
}
public static void callByReference(int[] arr) {
arr[0] = 30;
System.out.println(arr[0]);
}
}
0
30
30
- 단, 참조에 의한 호출을 사용할 때 파라미터로 들어간 참조형 데이터 타입의 변수에 새로운 주소 값이 부여되면 실제 값이 변경되지 않는다는 점을 주의해야 한다.
public class CallBy {
public static void main(String[] args) {
int[] array = new int[3];
System.out.println(array.length); // 3 출력
increaseLength(array); // 5 출력
System.out.println(array.length); // 3 출력
}
public static void increaseLength(int[] arr) {
arr = new int[5];
System.out.println(arr.length);
}
}
3
5
3
- 그러나 새로운 주소를 리턴해서 실제 값에 덮어씌워준다면 결과는 다음과 같이 달라진다.
public class CallBy {
public static void main(String[] args) {
int[] array = new int[3];
System.out.println(array.length); // 3 출력
array = increaseLength(array); // 5 출력
System.out.println(array.length); // 5 출력
}
public static int[] increaseLength(int[] arr) {
arr = new int[5];
System.out.println(arr.length);
return arr;
}
}
3
5
5
'~2023.02 > 외부교육' 카테고리의 다른 글
[JAVA] 콜렉션(Collection) (0) | 2022.03.19 |
---|---|
[JAVA] 객체(Object) & 캡슐화(Encapsulation) (0) | 2022.03.19 |
[JAVA] 배열의 동적 할당(Dynamic Allocation) (0) | 2022.03.16 |
[JAVA] 메서드(Method) (0) | 2022.03.12 |
1주차(22.03.02~03.04) (0) | 2022.03.05 |