Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

java - String and 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...