java:StringBuffer和String相互转换的几种用法

public class Demo4_StringBuffer {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Demo1();
		Demo2();
	}

	private static void Demo2() {
		StringBuffer sb1=new StringBuffer("roadtest");
		String s1=new String(sb1);//通过string类的构造方法,传入StringBuffer对象,转换为字符串
		System.out.println(s1);
		
		String s2=sb1.toString();
		System.out.println(s2);//通过StringBuffer类本身的tostring方法,将对象转换为字符串
		
		String s3=sb1.substring(0, sb1.length());
		System.out.println(s3);//通过substring方法,将对象转换为字符串
	}

	private static void Demo1() {
		StringBuffer sb1=new StringBuffer("roadtest");
		System.out.println("通过构造方法将字符串转换为StringBuffer对象:"+sb1);
		
		StringBuffer sb2=new StringBuffer();
		sb2.append("转换字符串为StringBuffer对象");
		System.out.println("通过append方法将字符串转换为StringBuffer对象:"+sb2);
	}

}

 

你可能感兴趣的:(java,java学习之路)