打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
String 的两种实例化方式

String 的两种实例化方式

隐式实例化:直接赋值

public class Demo {    public static void main(String[] args) {        String s = "hello";        String s2 = "hello";        System.out.println(s == s2);    }}
true

String 一般使用直接赋值的方式创建字符串。此时字符串是一个匿名对象,存放于位于堆的字符串常量池(String Table)中。匿名对象也是对象,就如同对象创建后,对象本身不可以改变,字符串也有不可变的特性,每次都将创建新的字符串。因为不可变,所以字符串可以称为字符串常量。

JVM 中设计字符串常量池是为了减少实例化重复的字符串,以节约新建时间和内存空间。

public class Demo {    public static void main(String[] args) {        String s = "hello";        System.out.println(s);        String s = "world";        System.out.println(s2);    }}
helloworld

显式实例化:使用构造函数

public class Demo {    public static void main(String[] args) {        String s = "hello";        String s2 = new String("hello");        String s3 = new String("hello");        System.out.println(s==s2);        System.out.println(s==s3);        System.out.println(s2==s3);    }}
falsefalsefalse

String 是一个类,可以使用构造函数创建字符串。

intern() 方法

public class Demo {    public static void main(String[] args) {        String s = "hello";        String s2 = new String("hello");        String s3 = new String("hello");        System.out.println(s2 == s2.intern());        System.out.println(s == s3.intern());        System.out.println(s2.intern() == s3.intern());    }}
falsetruetrue

intern() 方法,复制字符串对象到字符串常量池,返回字符串(引用)。native() 方法

具体来说:JVM 会在字符串常量池中去比较是否有「等于(equals)」 此 String 对象的字符串,如果有,返回字符串引用,没有则将此 String 对象包含的字符串放入字符串常量池中,再返回引用

String 被 final 修饰。

  • final 修饰类,类不能被继承
  • 修饰方法,方法不能被重写
  • 修饰字段,字段不能指向其他对象

字符串常量池和运行时常量池的关系

  • 没有关系,运行时常量池存放运行 Class 文件的常量池表。

String 常用方法

转换为字符数组:toCharArray()

String string = "hello";char[] array = string.toCharArray();return new String(array);

获取指定字符

String string = "hello";char c = string.charAt(0) // 'h'

格式化

String.format("%s %s %s", c1.name, c2.name, C.name)

延伸阅读

来源:https://www.icode9.com/content-4-717901.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java常量池理解与总结
Java String类详解(一)
main()方法为啥必须要public static void类型的??java中的静态成员
Java笔试题分类总结
String&StringBuffer笔记
5 个刁钻的 String 面试题!有种就来挑战
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服