String类型作为方法的形参


代码:

public class TestString {
	
	String str = new String("good");
	char [] ch = {'a','b','c'};


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestString ex = new TestString();
		 ex.change(ex.str,ex.ch);
		System.out.println(ex.str+"and");
		System.out.println(ex.ch);

	}
	
	public  void change(String str2, char[] ch2) {
		System.out.println("交换前:" + str2);
		//result is the same
		//str2 = new String("test ok");		 
		str2 = "test ok";
		System.out.println("交换后:" + str2);
		ch[0] = 'g';
		
	}


}

输出结果:

交换前:good
交换后:test ok
goodand
gbc

分析:因为String类是一个不可变类型,从变量被声明时,内存大小已经固定了,如果要改变它的值,会重新开辟新的内存存储,所以输出的str还是初始化的那个,即String类型作为方法的形参并不会改变字符串内容。

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM