结果为什么会不同???
程序1:
public class X {
public static void modify(String s) {
s += ",world!";
} public static void main(String[] args) {
String s = new String("Hello");
modify(s);
System.out.println(s);
}}程序2:
class Letter {
String c;
}public class PassObject {
static void f(Letter y) {
y.c += ",world!";
} public static void main(String[] args) {
Letter x = new Letter();
x.c = "hello";
f(x);
System.out.println(x.c);
}
}String类
程序1:
public class X {
public static void modify(String s) {
s += ",world!";
} public static void main(String[] args) {
String s = new String("Hello");
modify(s);
System.out.println(s);
}}程序2:
class Letter {
String c;
}public class PassObject {
static void f(Letter y) {
y.c += ",world!";
} public static void main(String[] args) {
Letter x = new Letter();
x.c = "hello";
f(x);
System.out.println(x.c);
}
}String类
解决方案 »
- JAVA SWING的界面问题,运行时如何在界面添加一个新按钮?
- java线程 从非常简单的说起谢谢 给点列子啊
- static与final修饰的对象所存储的地址值都不变吗?
- 请教如何分割时间段的问题
- 关于ResultSet的矛盾 1、2、3……
- 各位大虾,在哪能够下载java做的免费的源代码??
- 怎样在swt的Tree中实现拖拽功能(特别是可以拖拽子树)
- 怎么AppletContext的showDocument()方法没有结果
- jCreator LE v3.10 版本的,为什么不能自动显示方法
- 谁有向需要登录的网站上传cookie的成功案例,能否贴出源代码,谢谢!!!!
- struts的action返回值问题
- jsp页面引入外部css文件怎么弄都不起效果!!!各位大神来看看吧!!!
这个语句创建了一个新的String对象并赋值给s,所以原对象的内容不会被改变。
s += ",world!";
}这个s 是 main函数里面String s 的一个拷贝。
拷贝的内容是一个内存地址。s+=",world";
此时,产生了一个新的字符串 Hello world
s 指向的地址不再是 原来地址了。
public static void modify(String s1) {//这里接受引用,注意这个s和main方法中的s不是同一个
s += ",world!";//这个等同于s = s+",world!" s+",world!"这句新建了一个字符串对象,并将地址给了s
System.out.println(s);//我们可以在这里加个输出看看是什么 这里应该是hello,world1
} public static void main(String[] args) {
String s = new String("Hello");//这里将new出来的字符串的地址给了s变量
modify(s);//调用方法传引用
System.out.println(s);
}}
程序二:分析方法类似一但是要注意此时class Letter 有一个地址里面存的是String c的地址,方法的f(letter l)传递的是 Letter x = new Letter();地址的复制,这个地址有存有String c的地址,所以当字符串改变时,l的地址不变变得只是c的地址,
class Letter {
String c;
}public class PassObject {
static void f(Letter y) {
y.c += ",world!";
} public static void main(String[] args) {
Letter x = new Letter();
x.c = "hello";
f(x);\\x-->c地址1-->内容:hello
\\x-->c地址2-->内容:hello,world
\\x的地址不变,变得只是x中字符串的地址
System.out.println(x.c);
}
}
楼上说的不错,java参数传递是传值的,第一个是地址的改变(字符串赋值可以认为是new,但绝不是new),第二个是地址所指向的内容的改变,x,y地址相同,任何一个对内容的修改都会反映到另一个中。
public class X {
public static void modify(StringBuffer s) {
s =s.append(",world!");
} public static void main(String[] args) {
StringBuffer s = new StringBuffer("Hello");
modify(s);
System.out.println(s);
}}