Java拾贝第四天——String和匿名对象

发布时间 2023-10-17 12:13:14作者: ocraft

Java拾贝不建议作为0基础学习,都是本人想到什么写什么

复习突然发现String没写
匿名对象
只在堆内存中开辟空间,栈内存中没有对其进行引用的一种对象。(会等待被GC清除)

public class Test4 {
    public static void main(String[] args) {
        new Noname("匿名对象");
    }
}
class Noname{
    String name;

    public Noname(String name) {
        this.name = name;
    }
    public void nameTellYou(){};
}
//方法名采用驼峰命名法,即第一个单词的首字母小写后续的单词首字母大写

String

String作为Java一个特殊的类。有两种实例化方式。(String不是基本数据类型)

    public static void main(String[] args) {
       String str="String不是基本数据类型";
       String s=new String("String不是基本数据类型");
    }

试试比较他们

    public static void main(String[] args) {
        String str = "String不是基本数据类型";
        String s = new String("String不是基本数据类型");
        System.out.println(str == s);
    }
//false

为什么会这样?他们内容不是一样吗?

实际上对于String来使用关系运算符==进行比较的是地址值。(堆内存中的地址值)。

面向对象那里提到过,new关键字其实就是在堆内存中开辟一个新的空间。所以这里的结果是false。

若想要比较String的内容,可以使用String类提供的方法。
public boolean equals(String str)
公开的 返回值是布尔类型 方法名为equals 传参为String

    public static void main(String[] args) {
        String str = "String不是基本数据类型";
        String s = new String("String不是基本数据类型");
        System.out.println(str.equals(s));
    }
//true

String的内容不可变

一个字符串就是一个String的匿名对象(匿名对象仅在堆内存中开辟空间)。

    public static void main(String[] args) {
        System.out.println( "hello".equals("hello") );
    }
//true

基于上述的内容可以发现:

//一个字符串就是一个String的匿名对象
String s="hello";

实际上就是把一个在堆内存中开辟好空间的匿名对象赋值给变量s。

这么做的好处是,如果一个字符串已经被开辟,那么后续再有相同的变量声明它时,就不会再开辟新的内存空间。

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "hello";
        System.out.println(s1 == s2);
        System.out.println(s2 == s3);
    }
/*
true
true
*/

上述栗子说明这3个变量其指向的堆内存空间地址值都是同一个,所以结果是true。

    public static void main(String[] args) {
        String s1 = "hello";
        s1 = s1 + " world!";
        System.out.println(s1);
    }
//这里只是改变变量s1其指向的堆内存空间,原来"hello"后续不再使用会等待GC清除。

这就是String的内容不可变