Home > Java > javaTutorial > Why is String class immutable or final in Java?

Why is String class immutable or final in Java?

WBOY
Release: 2023-08-20 22:05:09
forward
1039 people have browsed it

Why is String class immutable or final in Java?

The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.

  • Security Parameters are typically represented as String in network connections, database connection URLs, usernames/passwords, etc. If it was mutable, these parameters could be changed easily.
  • Synchronization and Concurrency making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching when compiler optimizes our String objects, it seems that if two objects have the same value (a =" test", and b =" test") and thus we need only one string object (for both a and b, these two will point to the same object).
  • Class loading String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state).

Example:

public class StringImmutableDemo {
   public static void main(String[] args) {
      String st1 = "Tutorials";
      String st2 = "Point";
      System.out.println("The hascode of st1 = " + st1.hashCode());
      System.out.println("The hascode of st2 = " + st2.hashCode());
      st1 = st1 + st2;
      System.out.println("The Hashcode after st1 is changed : "+ st1.hashCode());
   }
}
Copy after login

输出:

The hascode of st1 = -594386763
The hascode of st2 = 77292912
The Hashcode after st1 is changed : 962735579
Copy after login

The above is the detailed content of Why is String class immutable or final in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template