The [trim()](<http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim-->)
method returns a new String with the leading and trailing whitespace removed.
String s = new String(" Hello World!! ");
String t = s.trim(); // t = "Hello World!!"
If you trim
a String that doesn’t have any whitespace to remove, you will be returned the same String instance.
Note that the [trim()](<http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim-->)
method has its own notion of whitespace, which differs from the notion used by the [Character.isWhitespace()](<http://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char->)
method:
U+0000
to U+0020
are considered whitespace and are removed by trim()
. This includes U+0020 'SPACE'
, U+0009 'CHARACTER TABULATION'
, U+000A 'LINE FEED'
and U+000D 'CARRIAGE RETURN'
characters, but also the characters like U+0007 'BELL'
.U+00A0 'NO-BREAK SPACE'
or U+2003 'EM SPACE'
are not recognized by trim()
.