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.SignatureThe signature or syntax of the String class trim() method is given below: Returnsstring with omitted leading and trailing spaces Internal implementationJava String trim() Method ExampleFileName: StringTrimExample.java Test it NowOutput hello string javatpoint hello stringjavatpoint Java String trim() Method Example 2The 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 3The 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 4Since 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 Next TopicJava String valueOf() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India