2 Replies Latest reply: May 10, 2011 9:29 AM by 796440 RSS

    String puzzle

    824049
      Hi,

      I am new to Java and understood that String is immutable but not able to find the answer for below question:-

      String z = "12345";
      System.out.println(z.replace("5","6")); //output is "12346"

      where as

      Stirng z = "12345";
      z.replace("5,"6");
      System.out.println(z); //o/p is "12345".

      what is the difference between putting z.replace("5","6") outside println and inside println ?
        • 1. Re: String puzzle
          802316
          Inside the println, you are printing the result of the replace.
          Outside the println, you are calculating the replace, discarding the result which is returned and printing the original value.

          What you may have indended was
          String z = "12345";
          z = z.replace("5", "6");
          System.out.println(z); //o/p is "12346".
          This question doesn't have anything to do with IO. Perhaps the "New to Java" forum is a better place next time. ;)
          • 2. Re: String puzzle
            796440
            821046 wrote:
            what is the difference between putting z.replace("5","6") outside println and inside println ?
            None. z.replace() behaves exactly the same way in both cases, but your code is only looking at the result in one of the cases.