public class HelloWorld { /**
* @param args
*/
public static void swap(String first, String second) {
String temp;
temp = first;
first = second;
second = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String i = "hello", j = "world";
System.out.print("Hello world!");
System.out.print(i + " " + j);
swap(i, j);
System.out.print(i + " " + j);
}
}为啥程序运行后, 最后一个out.pring应该输出world hello, 可是为什么还是hello world呢? 错在哪里? 请指教, 谢谢
* @param args
*/
public static void swap(String first, String second) {
String temp;
temp = first;
first = second;
second = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String i = "hello", j = "world";
System.out.print("Hello world!");
System.out.print(i + " " + j);
swap(i, j);
System.out.print(i + " " + j);
}
}为啥程序运行后, 最后一个out.pring应该输出world hello, 可是为什么还是hello world呢? 错在哪里? 请指教, 谢谢
在swap中的first,second是另外两个对象,你实际交换的是他们两个,而并不是i和j
因此只交换了first 和 second
public class HelloWorld {/**
* @param args
*/
public static void swap(String [] strArray) {
String temp;
temp = strArray[0];
strArray[0] = strArray[1];
strArray[1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String i = "hello", j = "world";
String strArray[] = new String[2];
strArray[0] = i;
strArray[1] = j;
System.out.println("Hello world!");
System.out.println(i + " " + j);
swap(strArray);
i = strArray[0];
j = strArray[1];
System.out.println(i + " " + j);
}
}