Difference between trim() and strip() methods in Java

In this article, you will learn the difference between trim() and strip() methods of the String class in Java.

trim() strip()
trim() method available since the early release of JDK (JDK1.0). strip() method added in the JDK 11 release.
It eliminates the leading and trailing white space, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character). It also eliminates the leading and trailing white space character and it uses Character.isWhitespace(int) method to determine a white space character.
The trim() method always allocates a new String object. strip() method optimizes stripping to an empty String by returning an interned String constant.

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.

Let’s have a look at the below examples.

package org.websparrow;

public class JavaTrimVsStrip {

    public static void main(String[] args) {

        // test case 1
        final String str1 = " websparrow.org ";
        System.out.println(str1.trim().equals(str1.strip())); // return --> true

        // test case 2
        final String str2 = "webspparrow.org \u2005";  // Unicode of white-space
        System.out.println(str2.trim().equals(str2.strip())); // return --> false

        // test case 3
        final String str3 = "\t websparrow.org \r";
        System.out.println(str3.trim().equals(str3.strip())); // return --> true

        // test case 4
        final String str4 = "\u2000";
        System.out.println(str4.trim().equals(str4.strip())); // return --> false




  1. Java – isBlank() vs isEmpty() method of String class
  2. Java – isBlank() vs isEmpty() method of String class
  3. String (Java SE 11 & JDK 11 )

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.