The Wayback Machine - http://web.archive.org/web/20241109230919/https://www.geeksforgeeks.org/java-string-trim-method-example/
Open In App

Java String trim() Method

Last Updated : 26 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The trim function in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of the space character is ‘\u0020’. The trim() method in Java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The trim() in Java also helps in trimming the characters.

Note: The trim() method doesn’t eliminate middle spaces.

Java String trim()

Method Signature

public String trim()

Parameters

  • The trim() method accepts no parameters. 

Return Type

  • The return type of trim() method is String. It returns the omitted string with no leading and trailing spaces. 

Below are examples to show the working of the string trim() method in Java. 

Examples of Trim() in Java

Example 1:

The trim function to remove whitespaces from the left and right of the string can be used when we want to join multiple strings together.

Below is the implementation of the topic:

Java




// Java program to demonstrate working
// of java string trim() method
import java.io.*;
  
// Driver Class
class GFG {
      // Main Function
    public static void main (String[] args) {
        
          // Three strings declared
        String x="geeks ";
          String y="for ";
          String z="geeks";
        
          // Printing without trim function
          System.out.println(x+y+z);
        
          // Using trim function to get result
          System.out.println(x.trim()+y.trim()+z.trim());
    }
}


Output

geeks for geeks
geeksforgeeks

Example 2:

After using the trim function it returns the string rather than making changes to the original string.

Below is the implementation of the above topic:

Java




// Java program to demonstrate working
// of java string trim() method
  
class Gfg {
  
    // driver code
    public static void main(String args[])
    {
        // trims the trailing and leading spaces
        String s
            = "  geeks for geeks has all java functions to read  ";
  
        // Printing String after removing the whitespaces
        // from the string
        System.out.println(s.trim());
  
        // Printing string to observe
        System.out.println(s);
    }
}


Output

geeks for geeks has all java functions to read
  geeks for geeks has all java functions to read  

Time Complexity: O(n)
Auxiliary Space: O(1)

Example 3:

While using the trim function as we get two strings original and returned string both are different in case we are removing the whitespaces from the original string.

Below is the implementation of the above topic:

Java




// Java program to demonstrate working
// of java string trim() method
import java.io.*;
  
// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args)
    {
        // String declared
        String s1 = "   Geeks For Geeks   ";
  
        // Before Trim() method
        System.out.println("Before Trim() - ");
        System.out.println("String - " + s1);
        System.out.println("Length - " + s1.length());
  
        // applying trim() method on string s1
        String s2 = s1.trim();
  
        // After Trim() method
        System.out.println("\nAfter Trim() - ");
        System.out.println("String - " + s2);
        System.out.println("Length - " + s2.length());
  
          // Comparing both the strings
        if (s1 == s2) {
            System.out.println("\nEqual");
        }
        else {
            System.out.println("\nNot Equal");
        }
    }
}


Output

Before Trim() - 
String -    Geeks For Geeks   
Length - 21

After Trim() - 
String - Geeks For Geeks
Length - 15

Not Equal

Time Complexity: O(n)
Auxiliary Space: O(1)



Similar Reads

Trim (Remove leading and trailing spaces) a string in Java
Given a string, remove all the leading and trailing spaces from the string and return it. Examples: Input : str = " Hello World " Output : str = "Hello World" Input : str = " Hey there Joey!!! " Output : str = "Hey there Joey!!!" We can eliminate the leading and trailing spaces of a string in Java with the help of trim(). trim() method is defined u
2 min read
JSTL fn:trim() Function
In JSTL the fn:trim() function is used to remove the leading and trailing whitespaces in the given input or specified string. The fn:trim() function also helps in properly cleaning up and standardizing the formatting of strings within the JSP. In this article, we will see the detailed syntax and the parameters of this function. We will also see the
2 min read
Collator compare(String, String) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two string and it will return 0, positive and negative values as an output according to the result. Syntax: public abstract int compare(String source, String target) Parameter: This method takes two strings between which comparison is going to take place.Return Valu
2 min read
Collator equals(String, String) method in Java with Example
The equals() method of java.text.Collator class is used to check if both strings are identical or not. Syntax: public boolean equals(String source, String target) Parameter: This method takes two strings between which comparison is going to take place. Return Value: if both strings are equal to each other then it will return true otherwise false. B
2 min read
StringJoiner Class vs String.join() Method to Join String in Java with Examples
Prior to Java 8 when we need to concatenate a group of strings we need to write that code manually in addition to this we needed to repeatedly use delimiter and sometimes it leads to several mistakes but after Java 8 we can concatenate the strings using StringJoiner class and String.join() method then we can easily achieve our goal. Example: Withou
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
String Literal Vs String Object in Java
Compare string initialization performance for String Literal and String object. String Literal String str = "GeeksForGeeks"; This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value "GeeksForGeeks", th
2 min read
Convert Set of String to Array of String in Java
Given a Set of Strings, the task is to convert the Set into an Array of Strings in Java. Examples: Input: Set<String>: ["ForGeeks", "A Computer Portal", "Geeks"] Output: String[]: ["ForGeeks", "A Computer Portal", "Geeks"] Input: Set<String>: ["G", "e", "k", "s"] Output: String[]: ["G", "e", "k", "s"] Method 1: Naive Method. Get the Set
6 min read
Convert a Set of String to a comma separated String in Java
Given a Set of String, the task is to convert the Set to a comma separated String in Java. Examples: Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: Set<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" Approach: This can be achieved with the help of join() method of String as fol
1 min read
Convert an ArrayList of String to a String Array in Java
In Java, as we all know ArrayList class is derived from the List interface. Here we are given an ArrayList of strings and the task is to convert the ArrayList to a string array. Illustration: Input : ArrayList = [ "Geeks", "for", "Geeks" ] Output: String[] = {"Geeks", "for", "Geeks"}Input : ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "S
3 min read
Java.lang.String.copyValueOf() in Java
The copyValueOf() primarily copies the content of a character array into the string. Two variants of this function are available and both are discussed in this article. Implementation 1 : Syntax: public static String copyValueOf(char[] ch) Parameters: ch : The character array. Return Value : This function returns the string with the contents of cha
3 min read
Java.lang.String class in Java | Set 2
Java.lang.String class in Java | Set 1 In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable. Now lets discuss some of the methods provided by String class. Methods: public int codePointAt(int index) - It takes as parameter a index which must be from 0 to length() - 1. a
5 min read
String.getByte() Method in Java
In Java, getBytes() encodes a string into a sequence of bytes using the named character set and storing the result into a new byte array. This function can be implemented in two ways. Both ways are discussed below as follows: getBytes()getBytes(Charset charset)Let us discuss and implement the first use case which is as follows: Java String getBytes
3 min read
String matches() Method in Java with Examples
Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same. Variants of String match
4 min read
Java String replaceAll() Method
The String replaceAll method in Java searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. Let us learn about Java replaceAll string method in this article. Java String replaceAll() This method replaces each substring of the string that matc
2 min read
Java String valueOf() Method
In Java, valueOf() method converts data from its internal form into a human-readable form. It is a static method that is overloaded within a string for all of Java's built-in types so that each type can be converted properly into a string. It is called when a string representation of some other type of data is needed for example during a concatenat
3 min read
Java String equalsIgnoreCase() Method with Examples
In Java, equalsIgnoreCase() method of the String class compares two strings irrespective of the case (lower or upper) of the string. This method returns a boolean value, true if the argument is not null and represents an equivalent String ignoring case, else false. Syntax of equalsIgnoreCase()str2.equalsIgnoreCase(str1);Parametersstr1: A string tha
2 min read
Java String isEmpty() method with example
Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of the String class is included in Java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0. Syntax of Java
3 min read
Java String contains() method with example
The java.lang.String.contains() method searches the sequence of characters in the given string. It returns true if the sequence of char values is found in this string otherwise returns false. Implementation of contains() methodpublic boolean contains(CharSequence sequence) { return indexOf(sequence.toString()) > -1; } Here conversion of CharSequ
2 min read
Java String subSequence() method with Examples
The Java.lang.String.subSequence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty
2 min read
String toString() Method in java with Examples
String toString() is the built-in method of java.lang which return itself a string. So here no actual conversion is performed. Since toString() method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly. Syntax : public String toString() Parameter: The method does no
1 min read
Matcher quoteReplacement(String) method in Java with Examples
The quoteReplacement(String string) method of Matcher Class is used to get the replacement String literal of the String passed as parameter. This String literal acts as the parameter for the replace methods. Hence quoteReplacement() method acts as the intermediate in the replace methods. Syntax: public static String quoteReplacement(String string)
2 min read
Matcher start(String) method in Java with Examples
The start(String string) method of Matcher Class is used to get the start index of the match result already done, from the specified string. Syntax: public int start(String string) Parameters: This method takes a parameter string which is the String from which the start index of the matched pattern is required. Return Value: This method returns the
2 min read
Matcher group(String) method in Java with Examples
The group(String string) method of Matcher Class is used to get the group of the match result already done, from the specified string. Syntax: public String group(String string) Parameters: This method takes a parameter string which is the String from which the group index of the matched pattern is required. Return Value: This method returns the gr
2 min read
Matcher replaceAll(String) method in Java with Examples
The replaceAll(String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public String replaceAll(String stringToBeReplaced) Parameters: This method takes a parameter stringToBeReplaced which is the String to be replaced in the ma
2 min read
Matcher replaceFirst(String) Method in Java with Examples
The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched pattern in the matcher string. Syntax: public String replaceFirst(String stringToBeReplaced) Parameters: The string to be replaced that is the String to be replaced in the matcher. Return Type
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters: This method takes two parameters: builde
3 min read
Matcher appendReplacement(StringBuffer, String) method in Java with Examples
The appendReplacement(StringBuffer, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuffer buffer, String stringToBeReplaced) Parameters: This method takes two parameters: buffer: w
3 min read
ZoneOffset of(String) method in Java with Examples
The of(String) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offsetId passed as the parameter. This method takes the offsetId as parameter in the form of String and converts it into the ZoneOffset. The ID of the returned offset will be normalized to one of the formats described by getId(). The
2 min read
PrintWriter println(String) method in Java with Examples
The println(String) method of PrintWriter Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Syntax: public void println(String string) Parameters: This method accepts a mandatory parameter string which is the String to be printed in the Stream. Return Value: This method d
2 min read
three90RightbarBannerImg