String 简单使用

package com.direct.str;

public class TestObject {

	/**
	 * @param args
	 */
	/*
	 * 1、object类是根类,里面定义的==和equals的作用相同,都是比较引用地址
	 * 2、而String不可变类,重写了里面的equals方法。
	 * 此时的==是比较引用地址,equals是比较内容
	 * 3、String类中有何String池(Pool),对于可以共享的字符串对象,会出现在池中查找
	 * 是否存在相同的String内容(字符串相同),如果有就直接返回,而不是直接创建一个新的
	 * String对象,减少内存的耗用
	 * 
	 * 
	 * */
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestObject t1 = new TestObject();
		TestObject t2 = new TestObject();
		System.out.println(t1==t2);//false
		System.out.println(t1.equals(t2));//false
		
		String s1 = new String("abc");
		String s2 = new String("abc");
		System.out.println(s1==s2);//false
		System.out.println(s1.equals(s2));//true
		String s3 = "hello";
		String s4 = "hello";
		System.out.println(s3==s4);//true
		System.out.println(s3.equals(s4));//true
		
		

	}

}

  

package com.direct.str;

public class StringBufferDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("我");
		sb.append("要你");
		sb.append("在我身旁");
		System.out.println(sb);
		sb.insert(3, "yue");//插入
		System.out.println(sb);
		String s = "The";
		String s1 = "Star";
		String s3 = s+s1;
		/*
		 * String 在使用上式的两个字符串相加时,速度会比StringBuffer的append()慢。
		 * 但是 String  s = "huis"+"shfiuf"; 速度会非常快,自动为一个字符串
		 * String不可变类,适合简单的字符串传递,不改变内容下的操作。
		 * StringBuffer在缓冲区中进行,适合对字符串中内容经常进行操作
		 * StringBuffer线程安全。
		 * StringBuilder和StringBuffer类功能基本一样,都可以自动增加长度
		 * StringBuider是线程不安全的,适合单线程使用,对附加字符串的需求很频繁
		 */
		

	}

}

  

原文地址:https://www.cnblogs.com/nn369/p/8038125.html