9 Replies Latest reply: Jul 8, 2013 8:15 PM by EJP RSS

    Reason behind creating java.lang.String immutable

    mjmjava
      What was the reason behind creating java.lang.String immutable

      Regards
        • 1. Re: Reason behind creating java.lang.String immutable
          gimbal2
          Guaranteed thread safety is one thing that comes to mind. A generic research (read: google) into immutability should give you a list of benefits.

          And do note that you're basically asking a question only the people who designed the String class can answer, which was over 15 years ago.
          • 2. Re: Reason behind creating java.lang.String immutable
            rp0428
            >
            What was the reason behind creating java.lang.String immutable
            >
            The 'somewhat circular' reason is to ensure that a String ALWAYS has the protections associated with a 'final' object.

            The term 'immutable' is just another word for 'final'. The difference is that the term 'final' is part of the Java language and can be used, or not used, at the discretion of the programmer.

            But the term 'immutable' is NOT part of the Java language and can NOT be used by the programmer. It acts just as if the programmer had used the word 'final' except the compiler IS REQUIRED to automatically treat immutable objects as if the word 'final' had been used.

            So an immutable object is just an object that the compiler has treated as 'final' even though the 'final' declaration has not been used.

            Strings have special uses in Java and require the protections that 'final' provides.

            The Java Language Specification provides the only official explanations.
            http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

            In section 10.9 it declares that immutability
            >
            10.9 An Array of Characters is Not a String
            In the Java programming language, unlike C, an array of char is not a String,
            and neither a String nor an array of char is terminated by '\u0000' (the NUL
            character).
            A String object is immutable, that is, its contents never change, while an array of
            char has mutable elements.
            >
            That means 'A string object is treated as final'.

            And then section 17.5 provides the benefits that 'final' fields are provided
            >
            17.5 final Field Semantics
            Fields declared final are initialized once, but never changed under normal
            circumstances. The detailed semantics of final fields are somewhat different from
            those of normal fields. In particular, compilers have a great deal of freedom to
            move reads of final fields across synchronization barriers and calls to arbitrary or
            unknown methods. Correspondingly, compilers are allowed to keep the value of a
            final field cached in a register and not reload it from memory in situations where
            a non-final field would have to be reloaded.

            final fields also allow programmers to implement thread-safe immutable objects
            without synchronization. A thread-safe immutable object is seen as immutable
            by all threads, even if a data race is used to pass references to the immutable
            object between threads. This can provide safety guarantees against misuse of an
            immutable class by incorrect or malicious code. final fields must be used correctly
            to provide a guarantee of immutability.
            >
            Those paragraphs mention:

            1. freedom to move reads of final (i.e. immutablel) fields across synchronization barriers and calls to arbitrary or unknown methods. That allows for certain compiler and performance optimizations that would otherwise not be possible.

            2. allowed to keep the value of a final field cached in a register and not reload it from memory. That also allows for compiler and performance optimizations.

            3. allow programmers to implement thread-saf immutable objects WITHOUT SYNCHRONIZATION. More performance optimizations - string objects are HEAVILY used, even internally, throughout Java.

            4. protection against misuse of an immutable class by incorrect or malicious code.

            Summary: 'immutable' simply means that 'final' was applied automatically by the compiler.
            • 3. Re: Reason behind creating java.lang.String immutable
              EJP
              The 'somewhat circular' reason is to ensure that a String ALWAYS has the protections associated with a 'final' object.
              There is no such thing as a 'final' object.
              The term 'immutable' is just another word for 'final'.
              No it isn't.
              The difference is that the term 'final' is part of the Java language and can be used, or not used, at the discretion of the programmer.
              The difference is that 'final' applies to variables and 'immutable' applies to objects.
              But the term 'immutable' is NOT part of the Java language and can NOT be used by the programmer. It acts just as if the programmer had used the word 'final' except the compiler IS REQUIRED to automatically treat immutable objects as if the word 'final' had been used.
              This doesn't make any sense. 'Immutable' doesn't act on the compiler at all. There is no such requirement.
              So an immutable object is just an object that the compiler has treated as 'final' even though the 'final' declaration has not been used.
              More nonsense. The compiler doesn't know anything about 'immutable'.
              Strings have special uses in Java and require the protections that 'final' provides.
              And also the protections that immutability requires.
              The Java Language Specification provides the only official explanations.
              Which don't include what you claim above.
              >
              10.9 An Array of Characters is Not a String
              In the Java programming language, unlike C, an array of char is not a String,
              and neither a String nor an array of char is terminated by '\u0000' (the NUL
              character).
              A String object is immutable, that is, its contents never change, while an array of
              char has mutable elements.
              >
              That means 'A string object is treated as final'.
              No it doesn't. You need to stop conflating these two concepts. They are not the same.
              Summary: 'immutable' simply means that 'final' was applied automatically by the compiler.
              Once again this is all complete and utter nonsense. There is no 'immutable' keyword, ergo no action by the compiler at all,, in any way, whatsoever.

              'Immutable' simply means that there are no mutator methods.
              • 4. Re: Reason behind creating java.lang.String immutable
                rp0428
                >
                There is no 'immutable' keyword
                >
                Which is EXACTLY what I said above.
                >
                'Immutable' simply means that there are no mutator methods.
                >
                Now you're the one talking nonsense.

                Immutability has NOTHING to do with whether there are, or are not, mutator methods.

                It simply means that, once instantiated the state cannot be modified.
                • 5. Re: Reason behind creating java.lang.String immutable
                  EJP
                  There is no 'immutable' keyword
                  Which is EXACTLY what I said above.
                  Along with a lot of nonsense about how the compiler magically takes notice of it anyway, and an imaginary equivalence with 'final'.
                  Immutability has NOTHING to do with whether there are, or are not, mutator methods.

                  It simply means that, once instantiated the state cannot be modified.
                  Which is indicated by the lack of mutator methods. Methods to mutate the object. If there are no ways to mutate the object it isn't mutable. It's a tautology. Rather than nonsense for example.
                  • 6. Re: Reason behind creating java.lang.String immutable
                    mjmjava

                    EJP 

                    Do i get to know exactly what is immutable in java , what was the need of creating it as immutable

                    Regards

                    • 7. Re: Reason behind creating java.lang.String immutable
                      mjmjava

                      EJP   @rp0428   What does exactly immutable means in java , why strings are immutable

                       

                      Regards

                           

                      • 8. Re: Reason behind creating java.lang.String immutable
                        jwenting

                        EJP wrote:

                        Immutability has NOTHING to do with whether there are, or are not, mutator methods.

                        It simply means that, once instantiated the state cannot be modified.
                        Which is indicated by the lack of mutator methods. Methods to mutate the object. If there are no ways to mutate the object it isn't mutable. It's a tautology. Rather than nonsense for example.

                        which is nonsense.

                        It's quite possible to access an object's public (or protected) fields without mutator methods and modify them if they're not final.

                        And using trickery, inner classes, reflection etc. and bytecode engineering, possibly private fields as well.

                         

                        So no, mutator methods are not a requirement for an object to be mutable.

                         

                         

                        public class X {
                           private class Y {
                              private int i;
                           }
                        
                          private Y y;
                          
                          public void q() {
                             if (y == null) {
                                 y = new Y();
                             }
                             y.i = 42;
                          }
                        }
                        
                        • 9. Re: Reason behind creating java.lang.String immutable
                          EJP

                          What I actually wrote was 'if there are no ways to mutate an object it isn't mutable': that is most certainly a tautology, most certainly not nonsense, and not contradicted by anything you have written above. I also wrote that lack of mutator methods is an 'indication' of immutability. Do read what I actually wrote, not what you think I wrote.