ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

String 的两种实例化方式

2020-07-01 14:02:58  阅读:476  来源: 互联网

标签:两种 String s2 System println 实例 字符串 hello


String 的两种实例化方式

隐式实例化:直接赋值

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

image

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);
    }
}
hello
world

image

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

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);
    }
}
false
false
false

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

image

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());
    }
}
false
true
true

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)

延伸阅读

标签:两种,String,s2,System,println,实例,字符串,hello
来源: https://www.cnblogs.com/deppwang/p/13218907.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有