trim() vs strip() in Java

Sheeraz Gul Sep 05, 2022
trim() vs strip() in Java

This tutorial demonstrates the differences between Java’s trim() and strip() methods.

Java trim() vs strip()

The trim() and strip() methods are both used for the string type data and somehow perform the same operations. Both methods eliminate the trailing and leading whitespaces from a string.

However, both methods have a few differences. The table below demonstrates the differences between the trim() and strip() methods.

trim() strip()
The trim() method was added from the JDK version 10. The strip() method was added from the JDK version 11.
The trim() method will always allocate a new string object. The strip() method will optimize the stripping to an empty string and then return the interned String constant.
The trim() will eliminate the trailing and leading whitespaces where the codepoint for the space character is less than or equal to U+0020. The strip() method also eliminates the trailing and leading whitespaces, but it will use the Character.isWhitespace(int) method to determine the space character.

As the strip() method is a Unicode standard, it is recommended over the use of trim(). Let’s try an example to show the use of trim() and strip().

package delftstack;

public class Trim_Vs_Strip {

    public static void main(String[] args) {

    	// case 1: simple string with trailing space
        final String DemoString1 = " www.delftstack.com ";
        System.out.println(DemoString1.trim().equals(DemoString1.strip()));
        // return --> true

        // case 2: string with leading \t and trailing \r
        final String DemoString3 = "\t www.delftstack.com \r";
        System.out.println(DemoString3.trim().equals(DemoString3.strip()));
        // return --> true

        // case 3: string the Unicode of whitespace
        final String DemoString2 = "www.delftstack.com \u2005";
        System.out.println(DemoString2.trim().equals(DemoString2.strip()));
        // return --> false

        // case 4: Unicode less than the white space.
        final String DemoString4 = "\u2001";
        System.out.println(DemoString4.trim().equals(DemoString4.strip()));
        // return --> false
    }
}

The code above compares the trim() and strip() methods on the different types of strings, and it shows that both methods perform in different ways in different scenarios.

See output:

true
true
false
false
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java String