gpt4 book ai didi

java - final String s = "Hello World"是否与 String s = "Hello World"相同?

转载 作者:搜寻专家 更新时间:2023-11-01 01:07:58 25 4
gpt4 key购买 nike

如果一个类被定义为 final 并且我们声明了一个 final 类的实例……这会有什么不同吗?还是 final 在这种情况下是多余的?

final String s = "Hello World" 

一样
String s = "Hello World"

最佳答案

当你在变量上使用 final 时,这意味着它不能被重新赋值。考虑以下示例:

public class FinalExample {
private final String a = "Hello World!"; // cannot be reassigned
private String b = "Goodbye World!"; // can be reassigned

public FinalExample() {
a = b; // ILLEGAL: this field cannot be re-assigned
b = a;
}

public static void main(String[] args) {
new FinalExample();
}
}

如果你尝试运行它,你会在 a=b 上得到一个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The final field FinalExample.a cannot be assigned

at FinalExample.<init>(FinalExample.java:7)
at FinalExample.main(FinalExample.java:12)

现在,我想您想知道在 String 数据类型前面是否有一个 final 是否重要。尽管您可能听说过 String 是不可变的,但您仍然可以将类似 String s = "Hello World!"; 的内容重新分配给另一个字符串值。这种区别是由于您实际上是将 String s 的引用重新分配给新字符串。因此,以下是有效的:

String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output: Goodbye World!

但是你可以使用 final 声明来阻止这种改变:

final String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable s cannot be assigned. It must be blank and not using a compound assignment

如果您想确保没有人可以更改您的String 引用,则final 声明非常有用。您也可以将 final 用于其他数据类型,以防止更改引用

关于java - final String s = "Hello World"是否与 String s = "Hello World"相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24024888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com