swap함수로 값을 넘기는 경우와 참조값을 넘기는 경우의 차이에 대해 이해 바랍니다.
class Swap {
static void swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
// x,y,temp는 local변수라서 스택에 저장되고
// 메소드의 실행이 끝나면 값이 사라진다.
//즉 main함수에 돌아가기전 모든 변수 값이 사라짐.
//x,y값이 swap함수안에서는 바뀌지만 main으로 돌아가면
//여기있는 변수 x,y, temp는 사라진다.
}
static void swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
// x,y,temp는 local변수라서 스택에 저장되고
// 메소드의 실행이 끝나면 값이 사라진다.
//즉 main함수에 돌아가기전 모든 변수 값이 사라짐.
//x,y값이 swap함수안에서는 바뀌지만 main으로 돌아가면
//여기있는 변수 x,y, temp는 사라진다.
}
public static void main(String[] args) {
int x = 10;
int y = 20;
int x = 10;
int y = 20;
Swap.swap(x, y); //x, y 값자체 10,20을 넘긴다.
//swap함수의 실행이 끝나고 아래 출력하는 변수는 main함수에서
//정의한 local변수(스택에저장)x, y이므로 swap의 x, y와는 관련이 없다.
System.out.println("x.. " + x); //10
System.out.println("y.. " + y); //20
}
}
//정의한 local변수(스택에저장)x, y이므로 swap의 x, y와는 관련이 없다.
System.out.println("x.. " + x); //10
System.out.println("y.. " + y); //20
}
}
class Swap {
int x, y;
static void swap(Swap s) {
int temp;
temp = s.x;
s.x = s.y;
s.y = temp;
}
int x, y;
static void swap(Swap s) {
int temp;
temp = s.x;
s.x = s.y;
s.y = temp;
}
public static void main(String[] args) {
Swap s = new Swap();
s.x=10; s.y=20;
System.out.println("<<<<< before >>>>>>");
System.out.println("s.x.. " + s.x);
System.out.println("s.y.. " + s.y);
Swap.swap(s); //참조를 넘기므로 돌아오면 값이 바뀌어있다.
System.out.println("<<<<< after >>>>>>");
System.out.println("s.x.. " + s.x); //20
System.out.println("s.y.. " + s.y); //10
}
}
Swap s = new Swap();
s.x=10; s.y=20;
System.out.println("<<<<< before >>>>>>");
System.out.println("s.x.. " + s.x);
System.out.println("s.y.. " + s.y);
Swap.swap(s); //참조를 넘기므로 돌아오면 값이 바뀌어있다.
System.out.println("<<<<< after >>>>>>");
System.out.println("s.x.. " + s.x); //20
System.out.println("s.y.. " + s.y); //10
}
}
오라클자바커뮤니티 실무 개발자 과정 - 개인80%환급
댓글 없음:
댓글 쓰기