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 " ?

user3296744
  • 169
  • 3
  • 9
  • 4
    Strings are __immutable__. – devnull May 13 '14 at 08:25
  • See also http://stackoverflow.com/questions/14919019/string-trim-function-is-not-working – Alexis C. May 13 '14 at 08: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 – Kent May 13 '14 at 08:29
  • @Duncan You feel like a superhero? :-) – Alexis C. May 13 '14 at 08: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. – devnull May 13 '14 at 08:30
  • @Duncan Also see http://meta.stackoverflow.com/questions/254589/when-did-i-get-superpowers -- I've made use of the _hammer_ in a certain tag and it's very satisfying. – devnull May 13 '14 at 08:31
  • @Kent Yes, I'm _actually_ trying to find it. – devnull May 13 '14 at 08:32
  • @Kent Who's that kid with the vim shirt on? – devnull May 13 '14 at 08:34
  • @devnull not my son... :-D it is a photo on internet named **vim rocks**. – Kent May 13 '14 at 08:36
  • @Kent I always thought that it would be your son. Finally asked about it and the doubt was cleared. (Otherwise I'd have been tempted to say that it's unfair. Give your son a chance to familiarize with _emacs_ too :-D – devnull May 13 '14 at 08:38
  • @devnull I would buy one for my son when he can wear, and I would for sure replace the logo then... perhaps this summer or next. but no doubt, it must be vim shirt! :-) vim rocks!! – Kent May 13 '14 at 08:54

3 Answers3

2
s1=s1.trim(); // trim() returns the "trimmed" String. You have to set it back to the reference
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
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();

Sanjay Rabari
  • 2,091
  • 1
  • 17
  • 32
0

Trim returns the new string rather than modifying it.

rethab
  • 7,170
  • 29
  • 46