//pass value type by value (값형식을 값에 의한 전달) – copy of value 전달
static void square1(int x) {
x *= x;
System.out.printf("The value inside square1: %d\n", x);
}
public static void main(String[] args) {
int i = 5;
System.out.println("Before i=" + i);
square1(i);
System.out.println("After i=" + i + "\n\n");
}
//Before i=5
//The value inside square1: 25
//After i=5
//pass reference type by value (참조형식을 값에 의한 전달) – copy of reference 전달
static void square2(IntValue value) {
value.x *= value.x;
System.out.printf("The value inside square2: %d\n", value.x);
}
public static void main(String[] args) {
int i = 5;
IntValue value = new IntValue(i);
System.out.println("Before value.x=" + value.x);
square2(value);
System.out.println("After value.x=" + value.x + "\n\n");
}
//Before value.x=5
//The value inside square2: 25
//After value.x=25
static void changeArray1(int[] arr) {
arr[0]=888; // arr -> myArray이므로 원본 배열의 첫번째 값은 888로 변경
System.out.println("changeArray1 arr=" + Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(",")));
arr = new int[] {-3, -1, -2, -3, -4}; // local 변수로 새롭게 할당하여 지정 그러나 원본 배열 변경 안됨
System.out.println("changeArray1 arr=" + Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(",")));
}
public static void main(String[] args) {
int[] myArray = {1, 4, 5};
System.out.println("Before myArray=" + Arrays.stream(myArray).mapToObj(String::valueOf).collect(Collectors.joining(",")));
changeArray1(myArray);
System.out.println("After changeArray1 myArray=" + Arrays.stream(myArray).mapToObj(String::valueOf).collect(Collectors.joining(",")));
}
//Before myArray=1, 4, 5
//changeArray1 arr=888, 4, 5
//changeArray1 arr=-3, -1, -2, -3, -4
//After myArray=888, 4, 5
static void changeArray2(IntValue[] arr) {
arr[0].x=888; // 원본 배열의 첫번째 값은 888로 변경
System.out.println("changeArray2 arr=" + Arrays.stream(arr).map(Object::toString).collect(Collectors.joining(",")));
arr = new IntValue[] { new IntValue(-3), new IntValue(-1), new IntValue(-2), new IntValue(-3), new IntValue(-4)}; // local 변수로 새롭게 할당하여 지정 그러나 원본 배열 변경 안됨
System.out.println("changeArray2 arr=" + Arrays.stream(arr).map(Object::toString).collect(Collectors.joining(",")));
}
public static void main(String[] args) {
IntValue[] myArray2 = { new IntValue(1), new IntValue(4), new IntValue(5)};
System.out.println("Before myArray2=" + Arrays.stream(myArray2).map(Object::toString).collect(Collectors.joining(",")));
changeArray2(myArray2);
System.out.println("After myArray2=" + Arrays.stream(myArray2).map(Object::toString).collect(Collectors.joining(",")));
}
// Before myArray2=1, 4, 5
// changeArray2 arr=888, 4, 5
// changeArray2 arr=-3, -1, -2, -3, -4
// After myArray2=888,4,5