Java offers a lot of methods. In this tutorial we would be discussing one of them, that is, the trim method in Java. The Java trim method is basically a built-in function that removes leading and trailing spaces. Let us study the topic in detail.
The agenda for this article is as follows:
Starting off with the definition!
What is the Trim method in java?
The Java trim method is a built-in function that removes leading and trailing spaces. The space character has a specific Unicode value – ‘u0020’. The trim method is defined under the class of java.lang package. Whenever the trim method is called, a new string object is returned.
Note: this method does not eliminate the middle spaces of the String.
Different method locate the Unicode value for the space character, as soon as it finds it before or after the string, it eliminates it and returns the string.
Moving on, let’s see the syntax:
Syntax:
The syntax is pretty simple.
public String trim()
Let us now implement this through a Java code!
Example:
public class Example{ public static void main(String args[]){ String s1=" hello Rachel "; System.out.println(s1+"green");//without trim() System.out.println(s1.trim()+"green");//with trim() } }
Output:hello Rachel green
hello Rachelgreen
This is how easily you can implement the trim method in Java.
With this, we come to an end of this article. I hope you have understood the trim in Java and its implementation through some real-time examples.
Now that you have understood trim basics through this article, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification courses are designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Mention it in the comments section of this blog and we will get back to you as soon as possible.