String a= "" 与 String a = new String()区别

本文深入探讨Java中String对象的实例化方式及其在内存中的存储特性,包括直接赋值与new关键字的区别,以及它们如何影响对象的内存位置。通过理解字符串常量池与堆内存中的对象创建,读者将能更好地掌握Java内存管理和性能优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String a = “a”;

String b = “a”;

String c = “c”;

区别:

1、’直接定义的String “a”'c’是储存在 常量存储区中的字符串常量池中;new String(“a”)是存储在中;

2、常量池中相同的字符串只会有一个,但是new String(),每new一个对象就会在堆中新建一个对象,不管这个值是否相同;

String a = “a” String b = “a” a b都指向字符串常量池中的“a”,所以 a==b 为 true;

String a = new String(“a”) String b = new String(“a”);是会在堆中创建两个对象new String() “a”是常量池中的”a”,这两个对象的值都为 a,所以a==b 返回false;a.equals(b)返回true;

3、

String a = “a”在编译阶段就会在内存中创建;

String a = new String(“a”);是在运行时才会在堆中创建对象

参考:

http://www.cnblogs.com/luckyliu/archive/2012/04/05/2433657.html

http://blog.sina.com.cn/s/blog_5edcfe6a0100d7u2.html

区别具体体现在于值相等内存地址是否相同 ==判断地址 .equals判断值(String重写了equals,equals本身也是判断地址)
同时往map里放值 例如往HashMap放值 值相等时只能放一个 不能放下两个
参考:
https://www.cnblogs.com/aspirant/p/9193112.html

a instanceof b a是否是b的实例 是返回true
例如

“sss“ instanceof  String //true;
String s = null;
s instanceof String  //false


System.out.println(new Image() instanceof String); //compile time error
System.out.println(new Image() instanceof Exception); //compile time error
System.out.println(new Image() instanceof Object); //compilation and output true
System.out.println(new Image() instanceof List); //compilation and output false
System.out.println(new Image() instanceof List<?>); //compilation and output false
System.out.println(new Image() instanceof List<String>); //compile time error
System.out.println(new Image() instanceof List<Image>); //compile time error
System.out.println(new Image() instanceof List); //compile time error
System.out.println(new String() instanceof List<?>); //compile time error
System.out.println(null instanceof Object); //compilation and output false  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值