0
public class X {

    public static void main(String[] args) {

        String s1=" abc xyz ";
        System.out.println(s1.length());
        s1.trim();
        System.out.println(s1.length());
        System.out.println(s1.trim().length());
    }
}

O/p:

9
9
7

Kindly explain to me why s1.trim().length() is 7 and not 9 as s1 will still be pointing to the old string ie " abc xyz " ?

11
  • 4
    Strings are immutable. Commented May 13, 2014 at 8:25
  • See also stackoverflow.com/questions/14919019/… Commented May 13, 2014 at 8:29
  • @devnull just checked your profile@SO, It is so funny that, in "about me" section we have "tried" to find the similar thing. :-D Commented May 13, 2014 at 8:29
  • @Duncan You feel like a superhero? :-) Commented May 13, 2014 at 8:29
  • @Duncan Yes, you weren't aware? You can use the hammer for closing a question containing a tag for which you have a gold badge. Commented May 13, 2014 at 8:30

3 Answers 3

2
s1=s1.trim(); // trim() returns the "trimmed" String. You have to set it back to the reference
Sign up to request clarification or add additional context in comments.

Comments

1

s1.trim(); does return trimmed string so capture in some variable to modify it.

in your case it left s1 as it is. so when you call s1.length() it provide original s1s length.

if you want to modify it try s1=s1.trim();

Comments

0

Trim returns the new string rather than modifying it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.