public class Example {
String str =new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str + " and " + ex.ch);
}
public void change(String str, char ch[]){
str = "test ok";
System.out.println("str:" + str);
ch[0] = 'g';
}
}原本题目是这样的,结果是
str:test ok
good and
gbc
这里我看网友解答都感觉有点抽象,不是很理解,什么按值传的,按地址传的,数组我知道是按地址,但是字符串这个请网友能不能详细解释一下啊?我把题目改了一下,答案又变成另外样子,我又糊涂了
public class Example {
String str =new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str + " and ");
System.out.println(ex.ch);
}
public void change(String str, char ch[]){
this.str = "test ok";
System.out.println("str:" + str);
ch[0] = 'g';
}
}
怎么在方法里加了个this之后,方法内打印出的就不是test ok 了,
希望好心人帮忙解答一下,最好画个图给看看
String str =new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str + " and " + ex.ch);
}
public void change(String str, char ch[]){
str = "test ok";
System.out.println("str:" + str);
ch[0] = 'g';
}
}原本题目是这样的,结果是
str:test ok
good and
gbc
这里我看网友解答都感觉有点抽象,不是很理解,什么按值传的,按地址传的,数组我知道是按地址,但是字符串这个请网友能不能详细解释一下啊?我把题目改了一下,答案又变成另外样子,我又糊涂了
public class Example {
String str =new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str + " and ");
System.out.println(ex.ch);
}
public void change(String str, char ch[]){
this.str = "test ok";
System.out.println("str:" + str);
ch[0] = 'g';
}
}
怎么在方法里加了个this之后,方法内打印出的就不是test ok 了,
希望好心人帮忙解答一下,最好画个图给看看
public void change(String str, char ch[]){
this.str = "test ok";
System.out.println("str:" + str);
ch[0] = 'g';
}首先,这里楼主要分清楚,形参str和类属性str。
在函数参数上的str是形参,而加上this后就变成了类属性Example.str了。
而后面,楼主print的是形参str,所以加上this后,形参str就没有赋值了,所以不会输出"test ok"
怪不得每次set方法,前面都是this.什么的
怪不得每次set方法,前面都是this.什么的
public void change(String str, char ch[]){}在这个范围作用域内str的值为:"test ok";如果你还不了解的话,在方法第一行打印System.out.println(str);你看到的值是good,str = "test ok";
赋值后才是:"test ok";
此值的作用范围在change方法之内。不会改变,成员变量,因为String str =new String("good");
成员变量str存放在堆中,而String str = "test ok";只存在栈中。
其实他在栈中创建了一个新的对象,存放test ok