String和StringBuffer类型数据进行参数传递问题

1.String和StringBuffer做为形参传递

通常参数传递有两种:

                基本类型:不会影响实际参数的值

                引用类型:会影响实际参数的值

而String和StringBuffer作为引用类型是否是上面的一样的呢?首先看一下下面的例子

package xfcy_01;
/**
 * 案例: String和StringBuffer做为形参传递
 * 形式参数:
 * 		基本类型:不会影响实际参数的值
 * 		引用类型:会影响实际参数的值
 * 注意:String类型数据应该按照基本数据处理
 * @author 晓风残月
 *
 */
public class StringBufferDemo04 {
	public static void main(String[] args) {
		//1.String类型
		String str1="hello";
		String str2="world";
		System.out.println(str1+"----------------"+str2);
		change(str1,str2);
		System.out.println(str1+"----------------"+str2);
		
		//2.StringBuffer类型
		StringBuffer sb1=new StringBuffer("hello");
		StringBuffer sb2=new StringBuffer("world");
		System.out.println(sb1+"-----------------"+sb2);
		change2(sb1,sb2);
		System.out.println(sb1+"-----------------"+sb2);
	}

	private static void change2(StringBuffer sb1, StringBuffer sb2) {
		sb1=sb2;
		sb2=sb1.append(sb2);
	}

	public static void change(String str1, String str2) {
		str1=str2;
		str2=str1+str2;
	}
}

得到的结果为:

String和StringBuffer类型数据进行参数传递问题_第1张图片

讲解过分析如下:

String和StringBuffer类型数据进行参数传递问题_第2张图片

但若为StringBuffer类型的数据

String和StringBuffer类型数据进行参数传递问题_第3张图片

2.总结

       在引用类型中应该注意String类型的数据是一种特殊情况,不会因为形参改变从而改变实参


你可能感兴趣的:(Java)