Java String trim()

The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.

The string trim() method doesn't omit middle spaces.

Signature

The signature or syntax of the String class trim() method is given below:

Returns

string with omitted leading and trailing spaces

Internal implementation

Java String trim() Method Example

FileName: StringTrimExample.java

Test it Now

Output

hello string   javatpoint
hello stringjavatpoint   

Java String trim() Method Example 2

The example demonstrates the use of the trim() method. This method removes all the trailing spaces so the length of the string also reduces. Let's see an example.

FileName: StringTrimExample2.java

Output

22
  hello java string   
17
hello java string

Java String trim() Method Example 3

The trim() can be used to check whether the string only contains white spaces or not. The following example shows the same.

FileName: TrimExample3.java

Output

The string contains characters other than white spaces 

The string contains only white spaces

Java String trim() Method Example 4

Since strings in Java are immutable; therefore, when the trim() method manipulates the string by trimming the whitespaces, it returns a new string. If the manipulation is not done by the trim() method, then the reference of the same string is returned. Observe the following example.

FileName: TrimExample4.java

Output

The string contains characters other than white spaces 

The string contains only white spaces





Latest Courses