Menu
Topics Index
...
`


Strings > Modifying a String >
Siva Nookala - 04 Apr 2016
trim is used to trim/remove whitespace from the beginning and the end of the string that invoked this method. It returns a NEW (new object) string with leading and trailing whitespace removed or the SAME string if it has no leading or trailing whitespace.

trim of String class
class Trim
{
    public static void main(String arg[])
    {
        String s1 = "   ToMerit   ";
        System.out.println("Before using trim : ");
        System.out.println(s1);
        String s2 = "Welcome" + s1.trim() + "Campus";
        System.out.println("After using trim : "); // LINE A
        System.out.println(s2.trim());
        String s3 = " Welcome To Merit Campus ";
        System.out.println("Before using trim : ");
        System.out.println(s3);
        System.out.println("After using trim s3 : "); // LINE B
        System.out.println(s3.trim());
        String s5 = s1.trim();
        if (s1 == s5)
        {
            System.out.println("s1 and s5 are Equal");
        } else
        {
            System.out.println("s1 and s5 are Not Equal"); // LINE C
        }
        String s6 = "Welcome to Merit Campus";
        String s7 = s6.trim();
        if (s6 == s7)
        {
            System.out.println("s6 and s7 are Equal"); // LINE D
        } else
        {
            System.out.println("s6 and s7 are Not Equal");
        }
    
    }
}
OUTPUT

Before using trim :
   ToMerit  
After using trim :
WelcomeToMeritCampus
Before using trim :
Welcome To Merit Campus
After using trim s3 :
Welcome To Merit Campus
s1 and s5 are Not Equal
s6 and s7 are Equal

DESCRIPTION

The program explains how the trim() behaves when invoked with different kinds of strings. s1, which contains lead and ending whitespace is trimmed which can be observed from LINE A. s3 contains whitespaces in between the string too. But we can see from the output at LINE B that such spaces are not removed by trim. LINE C supports the point that if there are leading and trailing spaces, a new string (a new reference) is created. If there are no such spaces, the original string itself is returned which can be understood at LINE D

THINGS TO TRY
  • Try for the below code.
    String str = "          Java            Programming        ";
    System.out.println(str.replaceAll(" ", ""));
    Here replaceAll removes all the white spaces in the string str, so the output will be JavaProgramming
  • Try for the below code.
    String str = null;
    System.out.println(str.trim());
    The above code throws java.lang.NullPointerException, since the value of str is null and trim cannot be invoked on null string.
  • Try trimming the below string and print.
    String name = "      Merit Campus         ";
    Remove the leading and tailing white spaces for the string str using trim method such that the output should be Merit Campus

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App