Call by Value & Call by Reference
Call by Value 와 Call by Reference에 대해서 알아보자
Last updated
Class CallByValue {
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("swap() 호출 전 : a = " + a + ", b = " + b);
swap(a, b);
System.out.println("swap() 호출 후 : a = " + a + ", b = " + b);
}
}
// 결과값
// swap() 호출 전 : a = 10, b = 20
// swap() 호출 후 : a = 10, b = 20void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int a1 = 10;
int a2 = 20;
swap(&a1, &a2);
cout << "a1: " << a1 << ", a2: " << a2 << endl;
// 결과값
// a1: 20, a2: 10public class CallByReference {
private class Person{
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" + "name='" + name + '\\'' + '}';
}
}
public static void swap(Person x, Person y) {
Person temp = x;
x = y;
y = temp;
}
public static void main(String[] args) {
CallByReference example = new CallByReference();
example.test();
}
private void test() {
Person incheol = new Person("incheol");
Person andrew = new Person("andrew");
System.out.println("swap() 호출 전 : incheol = " + incheol + ", andrew = " + andrew);
swap(incheol, andrew);
System.out.println("swap() 호출 후 : incheol = " + incheol + ", andrew = " + andrew);
}
}
// 결과값
// swap() 호출 전 : incheol = Person{name='incheol'}, andrew = Person{name='andrew'}
// swap() 호출 후 : incheol = Person{name='incheol'}, andrew = Person{name='andrew'}public class CallByReference {
private class Person{
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" + "name='" + name + '\\'' + '}';
}
}
public static void swap(Person x, Person y) {
String temp = x.name;
x.name = y.name;
y.name = temp;
}
public static void main(String[] args) {
CallByReference example = new CallByReference();
example.test();
}
private void test() {
Person incheol = new Person("incheol");
Person andrew = new Person("andrew");
System.out.println("swap() 호출 전 : incheol = " + incheol + ", andrew = " + andrew);
swap(incheol, andrew);
System.out.println("swap() 호출 후 : incheol = " + incheol + ", andrew = " + andrew);
}
}
// 결과값
// swap() 호출 전 : incheol = Person{name='incheol'}, andrew = Person{name='andrew'}
// swap() 호출 후 : incheol = Person{name='andrew'}, andrew = Person{name='incheol'}