Table of contents
1.
Introduction
2.
Syntax of Java String trim() Method
3.
Parameters of Java String trim() Method
4.
Return Value of Java String trim() Method
5.
 
5.1.
Internal Implementation
6.
Examples of Java String trim() Method
6.1.
 
6.2.
Example-1
6.3.
Example-2
7.
Remove All Whitespace Characters
8.
Difference Between String strip() and Java String trim() Method
9.
Frequently Asked Questions
9.1.
What is the purpose of the trim function in Java?
9.2.
How does the trim in Java work?
9.3.
Does trim in Java remove the newline?
9.4.
What does trim () remove?
10.
Conclusion 
Last Updated: Oct 7, 2024

Java String trim() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java String trim() Method is a built-in function used to remove leading and trailing whitespace from a string. It helps clean up unnecessary spaces at the beginning or end of a string, but does not affect spaces within the string. This method is commonly used to process user inputs or format data for consistent output.

Java String trim() Method

Syntax of Java String trim() Method

The syntax of the trim in java is:

string.trim()

 

Here, a string is an object of the String class.

Parameters of Java String trim() Method

The trim() method in java doesn't take any parameters.

Return Value of Java String trim() Method

  • Removes whitespace from the beginning and end of a string.
  • If there is no whitespace at the beginning or end of the string, it returns the original string.

 

 

 

Internal Implementation

public String trim() {    
        int len = value.length;    
        int st = 0;    
        char[] val = value;    /* avoid getfield opcode */
    
        /* Remove leading Space */
        while ((st < len) && (val[st] <= ' ')) {    
            st++;    
        }
  
        /* Remove trailing Space */
        while ((st < len) && (val[len - 1] <= ' ')) {    
            len--;    
        }    
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 
You can also try this code with Online Java Compiler
Run Code

 

Must Read: Java System Out Println

Examples of Java String trim() Method

Example

 

Before and After trim

Example-1

In this example, we will know how to remove the spaces from both ends using the trim in java.

class Main{
 
    // driver code
    public static void main(String args[])
    {
 
        // trims the trailing and leading spaces
        String s = "   Hello ninjas!  ";
        System.out.println(s.trim());
 
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

Hello ninjas!

Example-2

This is another example to understand how the trim in java works. We will print the String length before and after using trim in java program.

// program to demonstrate working trim in java
import java.io.*;
class Main{
   public static void main (String[] args) {
       
     String s1 = "   this string has leading and trailing spaces   ";
     
     // Before Trim() method
     System.out.println("Before Java String Trim() method - ");
     System.out.println("String - "+s1);
     System.out.println("Length - "+s1.length());
     
     // applying trim() method on string s1
     s1=s1.trim();
     
     // After Trim() method
     System.out.println("\nAfter Java String Trim() method - ");
     System.out.println("String - "+s1);
     System.out.println("Length - "+s1.length());
     
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Before Java String Trim() method - 
String -    this string has leading and trailing spaces   
Length - 49

After Java String Trim() method - 
String - this string has leading and trailing spaces
Length - 43

 

Must Read Type Conversion in Java

Remove All Whitespace Characters

For removing all whitespace characters from a string, we use the String replaceAll() method.

class Main {
  public static void main(String[] args) {
    String str = "Hello\nNinjas \n\n ";
    String result;

    // replace all whitespace characters with empty string
    result = str.replaceAll("\\s", "");

    System.out.println(result);
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

HelloNinjas

Difference Between String strip() and Java String trim() Method

  • From Java 11, many new methods in the string class came. Among them is the strip() method that does the same job as the trim in java.
  • However, the strip() method uses Character.isWhitespace() method to check if the Character is whitespace. 
  • This method uses Unicode code points, whereas the trim in java identifies any character having a codepoint value less than or equal to 'U+0020' as a whitespace character.
  • The strip() method is recommended to remove whitespaces because it uses the Unicode standard.


Must Read String Args in Java

Frequently Asked Questions

What is the purpose of the trim function in Java?

The trim in Java removes whitespace from both ends of a string and returns a new String without modifying the original strings. Here, the whitespace context is all the whitespace characters (space, tab, no-break space, etc.)

How does the trim in Java work?

The trim in java removes all leading and trailing whitespace characters from the current string. Each trailing and leading trim operation stops when it encounters a non-white-space character. For example, if the current string is "pqr xyz, "the Trim method returns "pqr xyz."

Does trim in Java remove the newline?

The function trim in java is used to get rid of whitespaces (spaces, newlines, etc.) from the beginning and end of the string. It also removes all the line terminator characters (LF, CR, etc.)

What does trim () remove?

The trim() method in Java removes leading and trailing white spaces from a string, including spaces, tabs, and newline characters. However, it does not remove white spaces between words or characters within the string, only those at the start and end.

Conclusion 

The Java String trim() Method removes leading and trailing white spaces from a string, ensuring cleaner input and more reliable data handling. It’s particularly useful for processing user input or external data, without altering internal spaces between words. Overall, trim() improves string manipulation and input validation, making it a key tool for Java developers.

Check out this problem - Multiply Strings

We hope that this blog has helped you enhance your knowledge regarding trim function in java and if you want to learn more, check out articles on Code360.

Live masterclass