Why String is Immutable in Java?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • usern
    New Member
    • Sep 2020
    • 2

    Why String is Immutable in Java?

    Why String is Immutable in Java?
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    #2
    Something related https://bytes.com/topic/java/answers...ng#post3826024

    Consider two string objects with the same content, JVM would allocate the same memory space for em in the pool and enable what is called "object sharing". If you want to see the proof that it's happening behind the scenes, verify the hashcode of both objects. Now try changing the content of one of the objects and print the hashcode. It'd be different. Why immutable? Since they both are using the same memory area; imagine one object manipulating the content. The changes would be reflected in the other one too, which is something you wouldn't want. The garbage collector isn't usually allowed in this area because of the same reason. It wouldn't want to free the memory space just when one object is done using it.

    Comment

    • anilreddy01
      New Member
      • Sep 2020
      • 1

      #3
      The string is Immutable in Java because String objects are cached in the String pool. ... Another reason why String class is immutable could die due to HashMap. Since Strings are very popular as the HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap.

      Comment

      • sarbjitgrewal
        New Member
        • Sep 2020
        • 19

        #4
        In Java, string is immutable since string objects are cached in the String pool.

        Comment

        • Naheedmir
          New Member
          • Jul 2020
          • 62

          #5
          The String is Immutable when String literals are shared among multiple customers; there is a risk where one customer's action would influence all other customers. A string is widely used as a parameter for various java classes. If String is not immutable, a file would be changed and lead to a serious security threat.

          Comment

          • Riya Bajpai
            New Member
            • Feb 2023
            • 18

            #6
            In Java, the string is immutable because of security, synchronization and concurrency, caching and class loading. The String objects are cached in the String Pool and it makes String immutable.

            Comment

            Working...