• JAVA 中关于String的特性


    一、初始化String的两种方式

    String str1 = "hello";
    String str2 = new String("hello");

    第一种方式本质上是声明了一个String的匿名对象,然后str1指向该对象。该匿名对象保存在对象池中。

    第二种方式分为两步:

    1) 声明一个"hello"的String对象

    2) new 关键字申请新的内存,将该内存分配String对象,并将值"hello"分配给该对象。步骤1中的对象废弃,等待GC回收。

    开发中推荐使用方式1。

    二、两种比较String的方式

    通过“==” 或者String的equals方法可以比较两个String,但它们之间有本质区别。"=="比较的是两个对象的地址,而equals方法比较的是两个对象的内容。

    public class TestJava
    {
        public static void main(String[] args)
        {
            String str1 = "hello";
            String str2 = new String("hello"); 
    
            System.out.println(str1 == str2);//false 
            System.out.println(str1.equals(str2));//true
        }
    }

    三、String的不可改变性

    String对象一旦声明那么它的内容就不可改变。

    public class TestJava
    {
        public static void main(String[] args)
        {
            String str1 = "hello";
            String str2 = "hello"; 
    
            System.out.println(str1 == str2);//true
            System.out.println(str1.equals(str2));//true
    
            str2 += " world";
            System.out.println(str1 == str2);//false
            System.out.println(str1.equals(str2));//false
        }
    }

    一开始str1和str2指向同一个对象。然后对str2做+=操作,实际上是str2指向了生成的一个新的"hello world"字符串,所以str2指向的地址和内容都已经改变。而在这之前str2指向的字符串没有发生任何改变。

  • 相关阅读:
    ASP.Net Core -- Logging
    ASP.Net Core -- 文件上传
    ASP.Net Core -- 依赖注入
    ASP.Net Core -- 领域模型与数据库架构保持同步
    Entity Framework Core -- 种子数据
    ASP.Net Core -- Environment TagHelper
    ASP.Net Core -- 为什么要使用TagHelper?
    dotnet ef 无法执行,因为找不到指定的命令或文件
    ASP.Net Core 3.x -- 中间件流程与路由体系
    ASP.Net Core -- View Components
  • 原文地址:https://www.cnblogs.com/kuillldan/p/5570675.html
Copyright © 2020-2023  润新知