java 字符串和最终

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/874978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:10:56  来源:igfitidea点击:

String and Final

javastringvariablesfinal

提问by Pahari Chora

What is difference between in the following statements

以下陈述有什么区别

String name = "Tiger";

final String name ="Tiger";

Although the Stringclass is finalclass, why do we need to create a String "CONSTANT" variable as final?

String类虽然是final类,为什么还要创建一个String“CONSTANT”变量作为final呢?

回答by Ayman Hourieh

finalin this context means that the variable namecan only be assigned once. Assigning a different Stringobject to it again results in a compile error.

final在这种情况下意味着变量name只能分配一次。String再次为其分配不同的对象会导致编译错误。

I think the source of the confusion here is that the finalkeyword can be used in several different contexts:

我认为这里混淆的根源在于final关键字可以在几种不同的上下文中使用:

  • final class: The class cannot be subclassed.
  • final method: The method cannot be overridden.
  • final variable: The variable can only be assigned once.
  • final 类:该类不能被子类化。
  • final 方法:该方法不能被覆盖。
  • final 变量:变量只能赋值一次。

See the Wikipedia article on final in Javafor examples on each case.

有关每种情况的示例,请参阅 Wikipedia 上有关Java 中 final 的文章。

回答by Steve Jessop

"final" means different things in the two cases.

“最终”在这两种情况下意味着不同的东西。

The java.lang.String class is final. This means you can't inherit from it.

java.lang.String 类是最终的。这意味着你不能继承它。

The variable "name" is final, meaning that you can't change it to point to a different instance of String. So a non-final String variable isn't a constant, because you could read it at two different times and get different values.

变量“name”是最终的,这意味着您不能将其更改为指向不同的 String 实例。因此,非最终 String 变量不是常量,因为您可以在两个不同的时间读取它并获得不同的值。

As it happens, Java string objects are also immutable. This means that you cannot modify the value which a particular String object represents. Compare this with an array - you can replace the first element of an array object with a different object, but you can't replace the first character of a String object with a different char. This is why String.replace() returns a new string - it can't modify the old one.

碰巧的是,Java 字符串对象也是不可变的。这意味着您不能修改特定 String 对象表示的值。将此与数组进行比较 - 您可以用不同的对象替换数组对象的第一个元素,但不能用不同的字符替换 String 对象的第一个字符。这就是 String.replace() 返回一个新字符串的原因——它不能修改旧字符串。

One reason that String is final is to prevent an instance of a subclass of String, which implements mutable behaviour, being passed in place of a String.

String 是 final 的一个原因是为了防止 String 的子类的实例被传递,它实现了可变行为,代替 String 传递。

But whether you can modify a particular object, and whether you can assign a different object to a variable, are completely different concepts. One is a property of String objects, and the other is a property of String variables, which are references to String objects.

但是是否可以修改特定的对象,以及是否可以将不同的对象分配给变量,是完全不同的概念。一个是String对象的属性,另一个是String变量的属性,是String对象的引用。

回答by pgras

Have a look at The final word on the final keyword.

看看关于 final 关键字的最终词

String name = "scott";
name = "tiger"; // OK

final String gender = "male";
gender = "female"; // won't compile you cannot reassign gender cause it's final

回答by Neil Coffey

Remember that Java final keywordserves two purposes in this case:

请记住,在这种情况下,Java final 关键字有两个用途:

  • it means the reference cannot be set to another String-- i.e. you cannot subsequently do "name = ...";
  • but crucially, it means that the reference is correctly published to other threads(see linked article for more details, or works such as Goetz et al, "Java Concurrency in Practice".
  • 这意味着不能将引用设置为另一个字符串——即您不能随后执行“name = ...”;
  • 但至关重要的是,这意味着引用已正确发布到其他线程(有关更多详细信息,请参阅链接文章,或 Goetz 等人的作品,“实践中的 Java 并发”。

回答by Nathan Feger

You are confusing immutable with final.

您将 immutable 与 final 混淆了。

String, like Integer and Long, is an immutable class in that the internal data is protected from modification through encapsulation.

String 与 Integer 和 Long 一样,是一个不可变的类,因为通过封装来保护内部数据不被修改。

However, like Ayman said, final refers to the pointer to the string.

然而,就像 Ayman 所说的,final 指的是指向字符串的指针。

回答by farhankhwaja

If a variable is marked as finalthen the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant.And if you try to change the value of that variable during the course of your program the compiler will give you an error.

如果一个变量被标记为final,则该变量的值不能改变,即final 关键字与变量一起使用时使其成为常量。如果您在程序运行过程中尝试更改该变量的值,编译器会给您一个错误。

NOTE :If you mark variable of a reference type as final, that variable cannot refer to any other object. However, you can change the object's contents, because only the reference itself is final.

注意:如果将引用类型的变量标记为 final,则该变量不能引用任何其他对象。但是,您可以更改对象的内容,因为只有引用本身才是最终的。

SOURCE : Final Keyword in Java

来源:Java 中的最终关键字

回答by Amrit

To deduce that String objects are Final by default is in itself a vague statement. The basics of Java dictate that if an instance variable is not pointing to a memory location it becomes eligible for Garbage collection. The same thing happens with the String objects. They are immutable but their references can be changed. To overcome this we can use "Final String s1 = "Final String" " the final keyword won't allow any assignment to s1 except at the time of First Declaration, making it truly immutable.

推断 String 对象默认为 Final 本身就是一个模糊的陈述。Java 的基础规定,如果一个实例变量没有指向内存位置,它就有资格进行垃圾收集。同样的事情发生在 String 对象上。它们是不可变的,但它们的引用可以更改。为了克服这个问题,我们可以使用 "Final String s1 = "Final String" " final 关键字不允许对 s1 进行任何赋值,除非在首次声明时,使其真正不可变。

public class DemoStringF 
{
    String s1; //Declaring an Instance Variable to type String. 

    public static void main(String... args)
    {
        DemoStringF d = new DemoStringF ();
        d.s1 = "Intializing s1 here"; //Initializing the s1

          System.out.println("Value ref. by s1 is " +d.s1); //Displays the String 
                                                            by which s1 is 
                                                            initialized.

         System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays the 
                                                                 value of the s1.

         d.s1 = d.s1.concat(" Adding String to s1"); //Changing the value ref. by 
                                                       s1.
        System.out.println("Value ref. by s1 after concat() is " +d.s1); 
                                                    //Displays a new value of s1.


        System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays 
                                                            the value of the s1.
    }

    }

enter image description here

在此处输入图片说明