Search code examples
javastringtrim

Does java string.trim also trim "\n" as well


I was testing the java trim method

Test Code:

 public class Main {
    public static void main(String[] args) {
        String t = "testcode\n";        
        System.out.print(t.trim() + "**");              
    }
  }

Output:

testcode**

The documentation says:

Returns a copy of the string, with leading and trailing white-space omitted

But as we can see it also removed "\n"

Is this the expected behavior and documentation is misleading ?

ENVIRONMENT: oracle java7


Solution

  • Yes, \n is considered whitespace, so the trim() method would remove it along with any other trailing space in the String.