字符串相关的类:String

1.String的特性

String类:代表字符串。Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。

  1. String是一个final类,代表不可变的字符序列。
  2. 字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改。
  3. String对象的字符内容是存储在一个字符数组value[]中的。
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0

2.String对象的创建

String str = "hello";
//本质上this.value = new char[0];
String s1 = new String(); 
//this.value = original.value;
String s2 = new String(String original); 
//this.value = Arrays.copyOf(value, value.length);
String s3 = new String(char[] a); 
String s4 = new String(char[] a,int startIndex,int count);

String对象的创建

3.字符串对象是如何存储的

在这里插入图片描述

4.String使用陷阱

  • String s1 = “a”;
    说明:在字符串常量池中创建了一个字面量为"a"的字符串。
  • s1 = s1 + “b”;
    说明:实际上原来的“a”字符串对象已经丢弃了,现在在堆空间中产生了一个字符串。
  • s1+“b”(也就是"ab")。
  • 如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。如果这样的操作放到循环中,会极大影响程序的性能。
  • String s2 = “ab”;
    说明:直接在字符串常量池中创建一个字面量为"ab"的字符串。
  • String s3 = “a” + “b”;
    说明:s3指向字符串常量池中已经创建的"ab"的字符串。
  • String s4 = s1.intern();
    说明:堆空间的s1对象在调用intern()之后,会将常量池中已经存在的"ab"字符串赋值给s4。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值