public class TestS
{
public static void test(String str)//这里string str 是定义了一个新的对象?
{
str = "world";
}
public static void main(String[] args)
{
String str = new String("hello");
test(str);
System.out.println(str); //str的值没有改变
}
}
我的理解是str里面是hello的地址,我吧hello的地址传了过去那么str=world后str应该改变为world。但是str还是hello请各位赐教,我这里不是很懂
{
public static void test(String str)//这里string str 是定义了一个新的对象?
{
str = "world";
}
public static void main(String[] args)
{
String str = new String("hello");
test(str);
System.out.println(str); //str的值没有改变
}
}
我的理解是str里面是hello的地址,我吧hello的地址传了过去那么str=world后str应该改变为world。但是str还是hello请各位赐教,我这里不是很懂
你最后输出的是定义在main()中定义的str
你要输出world,就要在test()中写System.out.println(str);
test(str)只是把main()中的str值赋给了test()中的str
str = "world";改变了test()中的str没有改变main()中的str
对于你的第一个程序来说, String str1 = new String("hello");申明定义一个String类型对象str1,
然后你调用了test(str1);这实际上是引用传递那么str1与str指向同一个对象“hello”,接着str = "world";
使str重新指向“wrold”,那么str1还是指向的“hello”,结果当然不会改变啊 恩别处看见的,这个解释比较好理解,不过还是谢谢大家的热心帮助,明天面试ibm希望能有个好结果。谢谢啦
"hello"也是改变不了的,String类是final的
test中的str又重新指向了"world"
main中的str还是指向"hello"
可以把引用类型看作一个C/C++中的指针,它指向的是一个Java对象的内存地址。
但是当函数调用时,JVM会生成第二个引用,并将原始引用的值(对象的内存地址)copy给第二个引用。
函数内部使用的是第二个引用的值,改变的也是第二个引用的值,而原始引用的值一直没有改变。 没有搞清楚值传递的本质是因为大部分人没有搞清楚变量的值与对象的内容之间的区别。
String str = new String("hello");
test(str);
System.out.println(str); //str的值没有改变
——————————————————————
不过顺便说一下,楼主以后最好别这么干,把变量名起的一样,编译时很难分析的
况且增加编程难度
String str = new String("hello");
这里告诉你str的值是hello,就比如说A告诉B,张三有个外号叫三哥。
test(str); 执行了,就比如说C告诉D,张三有个外号叫三少。
那么B和D2个人不相关,他们只知道张三的其中一个外号,并不知道对方的。都只是知道一个外号。
除非放在一起,A,B,D三个人在一起聊天,A说,张三有个外号叫三哥,然后又说不对,应该叫三少来的。
那么B,D开始认为张三的外号叫三哥,后来A纠正了,就认识张三的外号叫三少。
那么你稍微改一下就明白了。
str = test(str);
同时test方法return str就可以了。
PS:Java中传参都应该当作是传值!
给你一个普通类的例子你就明白了:public class TestStr {
public static void main(String[] args) {
A a = new A();
test(a);
System.out.println(a.s);
}
private static void test(A a) {
a.s = "KK";
}
}class A {
String s="cool";
}多看源码和基础知识
用这个来试试加深理解
public class TT { public static void main(String[] args) {
TT tt = new TT(); StringBuffer buf = new StringBuffer("a");
System.out.println(buf.toString());
tt.test(buf);
System.out.println(buf.toString());
tt.test1(buf);
System.out.println(buf.toString());
}
public void test(StringBuffer buf) {
buf = new StringBuffer("b");
}
public void test1(StringBuffer buf) {
buf.append("b");
}
}
更进一步说,方法调用时,传进去的其实是指针的副本。
这个问题我已经研究过了
java都是传的值(基本类型传数值,引用类型传的是内存地址的值) ,java的参数只有传值,没有传引用
string类型的 有点特殊,因为你String str = "a";实际是相当于new String("a");但是当初传的还是地址。还是值。。
你是刚刚 刚刚学吧? public static void test(String str)//这里string str 是定义了一个新的对象?
{
str = "world"; }
public static void main(String[] args)
{
String str_main = new String("hello");
test(str_main);
System.out.println(str_main); //str_main的值没有改变