java-string-trim

Java String trim() method is used to remove leading and trailing whitespaces from a string. This method treats any character whose Unicode codepoint is less than or equal to ‘U+0020’ as a whitespace character.

  • If the string contains only whitespaces, an empty string is returned.
  • If there are no leading and trailing whitespaces in the string, the reference to the same string is returned.
  • Java String is immutable, so the original string object value remains unchanged.

Java String trim() Example

Let’s look at a simple example of String trim() method.

Output:

I am appending a few non-whitespace characters while printing the string so that the difference is clearly visible in the output.

Let’s look at another example using the JShell interpreter.

String trim() vs strip() Method

Java 11 added many new methods in the string class. One of them is the strip() method that does the same job as the trim() method.

However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character.

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.

References

By admin

Leave a Reply