String参数传递

 1 public class ch01 {
 2     String str = "lisi";
 3     public static void change(String str){
 4         System.out.println(str);
 5     }
 6     
 7     public static void main(String[] args) {
 8         ch01 c = new ch01();
 9         String str01 = "zhangsan";
10         change(str01);
11         System.out.println(c.str);
12     }
13 }

输出结果为:

zhangsan
lisi

分析:因为String是个特殊的final类,所以每次对String的更改都会重新创建内存地址并存储(也可能是在字符串常量池中创建内存地址并存入对应的字符串内容),但是因为这里String是作为参数传递的,在方法体内会产生新的字符串而不会对方法体外的字符串产生影响。

另外

 1 public class Example {
 2     String str = new String("good");
 3     char[] ch = { 'a', 'b', 'c' };
 4  
 5     public static void main(String args[]) {
 6         Example ex = new Example();
 7         ex.change(ex.str, ex.ch);
 8         System.out.print(ex.str + " and ");
 9         System.out.print(ex.ch);
10     }
11  
12    public static void change(String str, char ch[])      
13    {
14         str = "test ok";
15         ch[0] = 'g';
16     }
17 }

此段代码的输出结果是:

good and gbc


 1 public class Example{
 2     String str=new String("hello");
 3     char[]ch={'a','b'};
 4     public static void main(String args[]){
 5         Example ex=new Example();
 6         ex.change(ex.str,ex.ch);
 7         System.out.print(ex.str+" and ");
 8         System.out.print(ex.ch);
 9     }
10     public void change(String str,char ch[]){
11         str="test ok";
12         ch[0]='c';
13     }
14 }

此段代码的输出结果为

hello and cb
原文地址:https://www.cnblogs.com/XuGuobao/p/7203390.html