2014-04-05 2 views
-1

방금 ​​자바 테스트 용지를 받았는데 저를 괴롭혔던 질문이 하나 있습니다.특정 방법에 관한 자바

질문이 있습니다.

다음 프로그램의 출력은 무엇입니까?

public class Swap { 
    public static void swap(int[] a){ 
     int temp = a[1]; 
     a[1] = a[0]; 
     a[0] = temp; 
    } 

    public static void main(String[] args){ 
     int[] x = {5,3}; 
     swap(x); 
     System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]); 
    } 
} 

처음에는 내 생각에 떠오른 생각이 바로 트릭 질문이었습니다. 스왑 메서드의 반환 형식이 void이므로 int [] x 배열에 영향을 미치지 않는다고 생각했습니다. 내 대답은 x [0] : 5 x [1] : 3이었다. 나는 정확한 답을 얻었음이 거의 확실했으며 내가 잘못 표시되었다는 것을 알았을 때 나는 혼란스러워했다. NetBeans에서 실제 코드를 시험해보고 배열의 값이 실제로 바뀌 었음을 알았습니다! 나는 이것이 String의 경우인지 계속 테스트했다. 비슷하지만 다른 코드를 입력했습니다 :

public class Switch { 
    public static void switch(String s){ 
     s = "GOODBYE"; 
    } 

    public static void main(String[] args){ 
     String x = "HELLO"; 
     switch(x); 
     System.out.println(x); 
    } 
} 

출력에 여전히 GOODBYE 대신 HELLO가 인쇄되었습니다. 이제 내 질문은 왜 메서드는 문자열을 변경하지 않지만 배열 내부의 값을 변경합니까?

답변

2

Java에서 - "객체 참조가 값으로 전달됩니다."

public class Swap { 
    public static void swap(int[] a){ // now a = x --> {5,3} 
     int temp = a[1]; 
     a[1] = a[0];  // swapping a[0] and a[1] in this and next step. 
     a[0] = temp; 
// NOW only a[] goes out of scope but since both x and a were pointing to the "same" object {5,3}, the changes made by a will be reflected in x i.e, in the main method. 
    } 

    public static void main(String[] args){ 
     int[] x = {5,3}; // here - x is a reference that points to an array {5,3} 
     swap(x); 
     System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]); 
    } 
} 

그리고,

public class Switch { 
    public static void switch(String s){ // now s=x="Hello" 
     s = "GOODBYE"; //here x="hello" , s ="GOODBYE" i.e, you are changing "s" to point to a different String i.e, "GOODBYE", but "x" still points to "Hello" 
    } 
    public static void main(String[] args){ 
     String x = "HELLO"; 
     switch(x); 
     System.out.println(x); 
    } 
} 
+0

오! 그 말이 이치에 맞았다. 대답 주셔서 감사합니다 ~ 마침내 내 머리 에서이 퍼즐을 얻을 수있었습니다. – user3312742

+0

@ user3312742 - 당신은 환영합니다 :) – TheLostMind

2

를 작성하기 때문에 그냥 다른 문자열에 s 지적한다. 원래 String의 값은 변경되지 않습니다.

반면에 a[0] = something; 또는 a[1] = something;을 쓰는 것은 실제로 a이 참조하는 배열로 엉망이지만 a을 다른 배열로 지정하는 것은 아닙니다.

관련 문제