不要再困扰在String与StringBuffer(StringBuilder)的区别上鸟

无论是初学者还是在java这条路上游荡了几年的童鞋都会每每想起String与StringBuffer的区别这个话题!今天再次看见这个话题,该是终结的时候咯!

原文: http://www.iteye.com/topic/142364#422534


看原文后我的总结:

java常量池: http://wenku.baidu.com/view/4a2f961c59eef8c75fbfb348.html

注意为对象在堆中编写的地址变化以及不变化哦
.
1.将textString定义为局部变量

不要再困扰在String与StringBuffer(StringBuilder)的区别上鸟
       
public class testStringStringBuffer {
   public static void stringReplace (String text) {    
   text = text.replace('j' , 'i');  
   System.out.println (text); 
   }    
       
   public static void bufferReplace (StringBuffer text) {    
   text = text.append("C");     
   }    
       
    public static void main (String args[]) {     
    String textString = new String ("java");     
    StringBuffer textBuffer = new StringBuffer ("java");     
        
    stringReplace (textString);     
    bufferReplace (textBuffer);     
        
    System.out.println (textString + textBuffer);     
    }     

}



输出结果:
iava 
javajavaC 


2.将textString定义为全局变量

不要再困扰在String与StringBuffer(StringBuilder)的区别上鸟


/**
 *@source:http://www.iteye.com/topic/142364#422534
 * 
 *@function:
 * 
 * @author [email protected] 2011-6-29
 * 
 */
public class testStringStringBuffer {

	static String textString = null;// 将textString定义为全局变量

	public static void stringReplace(String text) {
		//让textString指向在堆中新产生的对象
		textString = text.replace('j', 'i');
		System.out.println(textString);
	}

	public static void bufferReplace(StringBuffer text) {
		text = text.append("C");
	}

	public static void main(String args[]) {
		textString = new String("java");
		StringBuffer textBuffer = new StringBuffer("java");

		stringReplace(textString);
		bufferReplace(textBuffer);

		System.out.println(textString + textBuffer);
	}

}


输出结果:
iava
iavajavaC


上面这个全局的效果等价于:


package com.cdl.mix;

/**
 *@source:http://www.iteye.com/topic/142364#422534
 * 
 *@function:
 * 
 * @author [email protected] 2011-6-29
 * 
 */
public class testStringStringBuffer {

	//static String textString = null;// 将textString定义为全局变量

//	public static void stringReplace(String text) {
//		//让textString指向在堆中新产生的对象
//		textString = text.replace('j', 'i');
//		System.out.println(textString);
//	}

	public static void bufferReplace(StringBuffer text) {
		text = text.append("C");
	}

	public static void main(String args[]) {
		String textString = new String("java");
		StringBuffer textBuffer = new StringBuffer("java");

		//stringReplace(textString);
		textString=textString.replace('j', 'i');
		System.out.println(textString);
		bufferReplace(textBuffer);

		System.out.println(textString + textBuffer);
	}

}




输出结果:
iava
iavajavaC



区别就是一句话:

String引用改变指向一个新的地址,

StringBuffer引用不变指向自己本身





你可能感兴趣的:(java,C++,c,C#,ITeye)