4

The output of below program:

public class TestClass {

    public static void main(final String[] args){
        String token = "null\n";
        token.trim();
        System.out.println("*");
        System.out.println(token);
        System.out.println("*");
    }
}

is:

*
null

*

However

How to remove newlines from beginning and end of a string (Java)?

says otherwise.

What am I missing?

Community
  • 1
  • 1
Vicky
  • 16,679
  • 54
  • 139
  • 232
  • 2
    Strings are immutable ... Read trim documentation – njzk2 Sep 19 '13 at 15:35
  • The accepted answer of the question you're referring to shows the correct usage of trim() btw... – fvu Sep 19 '13 at 15:39
  • @All: Sorry people.. my mistake.. please don't downvote! :( :( – Vicky Sep 19 '13 at 15:40
  • possible duplicate of [How to remove newlines from beginning and end of a string (Java)?](http://stackoverflow.com/questions/7454330/how-to-remove-newlines-from-beginning-and-end-of-a-string-java) – njzk2 Sep 19 '13 at 15:40

2 Answers2

21

Since String is immutable

token.trim();

doesn't change the underlying value, it returns a new String without the leading and ending whitespace characters. You need to replace your reference

token = token.trim();
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
13

Strings are immutable. Change

token.trim();

to

token = token.trim();
NPE
  • 486,780
  • 108
  • 951
  • 1,012