弦乐和终曲

发布于 2024-07-21 13:34:48 字数 185 浏览 5 评论 0原文

下面的语句有什么区别

String name = "Tiger";

final String name ="Tiger";

虽然String类是final类,但为什么我们需要创建一个String“CONSTANT”变量作为final?

What is difference between in the following statements

String name = "Tiger";

final String name ="Tiger";

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

吐个泡泡 2024-07-28 13:34:48

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

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

  • Final class:该类不能被子类化。
  • Final方法:该方法不能被重写。
  • Final变量:该变量只能被赋值一次。

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

final in this context means that the variable name can only be assigned once. Assigning a different String object to it again results in a compile error.

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

  • final class: The class cannot be subclassed.
  • final method: The method cannot be overridden.
  • final variable: The variable can only be assigned once.

See the Wikipedia article on final in Java for examples on each case.

请爱~陌生人 2024-07-28 13:34:48

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

java.lang.String 类是最终类。 这意味着您无法继承它。

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

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

String 是 Final 的原因之一是防止传递实现可变行为的 String 子类的实例来代替 String。

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

"final" means different things in the two cases.

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

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.

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.

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.

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.

撩发小公举 2024-07-28 13:34:48

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

  • 这意味着引用不能被引用。设置为另一个字符串 - 即您不能随后执行“name = ...”;
  • 但至关重要的是,这意味着引用正确发布到其他线程(有关更多详细信息,请参阅链接文章,或 Goetz 等人的“Java Concurrency in Practice”等作品。

Remember that Java final keyword serves two purposes in this case:

  • 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".
左岸枫 2024-07-28 13:34:48

您将不可变与最终混淆了。

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

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

You are confusing immutable with final.

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

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

时间你老了 2024-07-28 13:34:48

查看最终关键字的最终结论

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

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

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

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

final String gender = "male";
gender = "female"; // won't compile you cannot reassign gender cause it's final
单调的奢华 2024-07-28 13:34:48

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

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

来源:Java 中的最终关键字

If a variable is marked as final then 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.

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.

SOURCE : Final Keyword in Java

夜血缘 2024-07-28 13:34:48

推断 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.
    }

    }

输入图片此处描述

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文