1 2 Previous Next 22 Replies Latest reply: Oct 29, 2007 8:54 AM by 807603 RSS

    string immutability

    807603
      Hi
      I am confused when they say that string is immutable and we need to use StringBuffer instead....

      But why the piece of code below is compiling if string be immutable ?
      public class Main {
          
          /**
           * @param args the command line arguments
           */
          public static void main(String[] args) {
             
              
      String  mystring ="Hello how are you ";
      mystring ="Are you fine ";
      System.out.println(mystring);
          
          }
          
      }
        • 1. Re: string immutability
          807603
          but why do you think the code is showing any String being mutated?
          • 2. Re: string immutability
            791266
            @Op. You aren't modifying the string referenced by mystring. You are changing so that the variable is pointing to a new string.

            Kaj
            • 3. Re: string immutability
              807603
              have not we mutated the string by changing its size to something different ?
              • 4. Re: string immutability
                791266
                Sangfroid wrote:
                have not we mutated the string by changing its size to something different ?
                No, you have changed a pointer.
                • 5. Re: string immutability
                  794254
                  First off, like it's been mentioned above, you're not changing the String object at all, you're simply reassigning the reference variable that was pointing to that String to a different String object.

                  Second, Strings are immutable because once created, you cannot modify their content. That's fixed. All the methods that you call on Strings that seem to modify the string, toUpperCase(), toLowerCase(), trim() etc, are all returning new String objects, the original one is unmodified.

                  ----------------------------------------------------------------
                  People on the forum help others voluntarily, it's not their job.
                  Help them help you.
                  Learn how to ask questions first: http://www.catb.org/~esr/faqs/smart-questions.html
                  ----------------------------------------------------------------
                  • 6. Re: string immutability
                    807603
                    nogoodatcoding wrote:
                    Second, Strings are immutable because once created, you cannot modify their content. That's fixed.
                    Except...
                    import java.lang.reflect.*;
                    
                    public class ImmutableStringDemo {
                    
                        public static void main(String[] args) throws Exception {
                            String string = "foo";
                            assert "foo".equals(string);
                    
                            new StringChanger().change(string);
                            assert "bar".equals(string);
                        }
                    }
                    
                    class StringChanger {
                    
                        public void change(String s) throws IllegalAccessException {
                            Field[] fields = s.getClass().getDeclaredFields();
                            for (Field f : fields) {
                                f.setAccessible(true);
                                if (f.getType() == char[].class) {
                                    f.set(s, "bar".toCharArray());
                                }
                            }
                    
                        }
                    }
                    Don't try this at home, all standard caveats apply.

                    ~
                    • 7. Re: string immutability
                      794254
                      yawmark wrote:
                      ...
                      Way over my head, I'm afraid :(
                      • 8. Re: string immutability
                        807603
                        nogoodatcoding wrote:
                        Way over my head, I'm afraid :(
                        Strings are immutable by design. Through sneaky, underhanded, fragile, improper code, you can change the contents of a String object. It's never a good idea to do so, however, no matter how many times I post this silly bit of code when someone says, "You can't change a String."

                        :o)

                        ~
                        • 9. Re: string immutability
                          791266
                          yawmark wrote:
                          nogoodatcoding wrote:
                          Way over my head, I'm afraid :(
                          Strings are immutable by design. Through sneaky, underhanded, fragile, improper code, you can change the contents of a String object. It's never a good idea to do so, however, no matter how many times I post this silly bit of code when someone says, "You can't change a String."

                          :o)

                          ~
                          Reflection and ugly hacks makes it hard to state anything about anything. E.g. you can't call a private methods, you can't throw checked exceptions that aren't declared in throws etc.
                          • 10. Re: string immutability
                            794254
                            I still have to make my way through the Reflection API so I guess I'll be coming back to your 'silly bit of code' later :) But it's a good thing to know I guess, at least that something like this is possible.
                            • 11. Re: string immutability
                              807603
                              for what purpose this java.lang.reflect mainly used ??
                              • 12. Re: string immutability
                                796447
                                Sangfroid wrote:
                                for what purpose this java.lang.reflect mainly used ??
                                http://www.ask.com/web?q=java+reflection
                                • 13. Re: string immutability
                                  807603
                                  Sangfroid wrote:
                                  for what purpose this java.lang.reflect mainly used ??
                                  NOT for changing the value of a String object.

                                  Often for run-time binding (correct term?)--that is, deciding what implementation of a class to use at run-time instead of compile time. For example, Eclipse uses Reflection extensively because third-parties contribute plugins through "extension points," where the user can define in an XML file what classes to use for new functionality. As a result, Eclipse's code doesn't actually know about the third-party classes, but can still load them into the program without a recompile.

                                  Obviously Eclipse wouldn't be the only example here.
                                  • 14. Re: string immutability
                                    807603
                                    Reflection and ugly hacks makes it hard to state anything about anything.
                                    Indeed!

                                    ~
                                    1 2 Previous Next