Java - 创建字符串的方式

  1. 提取字符数组array中的一部分创建一个字符串对象。参数offst表示开始截取字符的位置,length表示截取字符的长度
    String a = new String(array,int offset,int length)
  2. 用一个字符数组创建一个字符串对象
  3. 引用字符串常量赋值给一个字符串变量
public class TextAboutBook {
    
    
    public static void main(String[] args) {
    
    
        char[] array = {
    
    't','h','f'};
        String a = new String(array,0,3);//方式1
        String b = new String(array);//方式2
        String c = "thf";//方式3
        String d = "thf";
        System.out.println(a);//thf
        System.out.println(b);//thf
        System.out.println(c);//thf
        System.out.println(d);//thf
        System.out.println(c == d);//true c和d的内存地址都指向了 'thf'
        System.out.println(a == b);//false a和b开辟了不同的空间,内存地址不同
        System.out.println(a.equals(c));//true a和c的内容相同
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41017444/article/details/113357790
今日推荐