Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming new line character from a string in java

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?

like image 375
Vicky Avatar asked Nov 28 '22 03:11

Vicky


1 Answers

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();
like image 93
Sotirios Delimanolis Avatar answered Dec 05 '22 15:12

Sotirios Delimanolis