String

1. String s = new String("abc");

在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。

在运行期,根据new创建一个对象,存放到heap中。即将pool中的对象复制一份到heap中,并把heap中的这个对象引用交给s持有。

综上,该语句创建一个或两个对象。 导致在heap中出现内容相同而地址不同的String对象。

 

2. String s1 = "abc";

在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。

 

3. ==是比较地址,equals是比较内容 。

 

4. intern()方法:查找内容相同的字符串,如:

String s2 = "hello";//hello不存在,创建新对象存在string pool中(1) String s2 = new String("hello");//创建新对象存在heap中 s1 == s2;//false 地址不同 s1.equals(s2);//true 内容相同 s2 = s2.intern();//查找与s2内容相同的对象,并赋给s2 s1 == s2;//true 此时s1,s2同指向(1)  

 

5. java中所有的字符串文字都是一个String对象

 

6. String是不可变类,线程安全,不存在任何修改对象的方法

 

7. StringBuffer是可变类,用来修改对象

StringBuffer D = new StringBuffer("ss");//创建两个对象

D.append("test");//在new对象上直接处理,不产生新的对象

 

实例

public class StringChar {
	public static void main(String[] args){
		String s = "hello";//(1)存放在Constant pool里的String pool里
		String s2 = new String("hello");//(2)new出来的对象存放在heap里
		String t = "hello";//(3)因为string pool里已经有了hello,所以t与s指向同一内存地址
		String str = "hello";//(4)同上
		char c[] = {'h','e','l','l','o'};
		
		char ch[] = str.toCharArray();//string转换为char
		
		if(ch == c){
			System.out.println("true");
		}else{
			System.out.println("flase");
		}//false
		
		if(ch.equals(c)){
			System.out.println("true");
		}else{
			System.out.println("flase");
		}//false why???
		
		if(s2 == s){//"=="判断引用是否相同,即是否指向同一内存地址
			System.out.println("true");
		}else{
			System.out.println("flase");
		}//false
		
		if(s2.equals(s)){//equals()判断两个object是否一样,即所有的成员值都相同
			System.out.println("true");
		}else{
			System.out.println("flase");
		}//true
		
		s2 = s2.intern();//intern()找到与s2内容相同的对象,并将其赋给s2
		System.out.println(s == s2);//true 此时s2和s指向同一对象(1)
		System.out.println(t == s2);//true 因为t和s指向同一对象(1),所以此时t和s2指向同一对象(1)
		System.out.println(str == s2);//true 同上
	}

}
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值