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");
}
}
}
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
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
String str = " Java Programming ";
System.out.println(str.replaceAll(" ", ""));
replaceAll
removes all the white spaces in the string str
, so the output will be JavaProgrammingString str = null;
System.out.println(str.trim());
java.lang.NullPointerException
, since the value of str
is null
and trim
cannot be invoked on null
string.String name = " Merit Campus ";
str
using trim
method such that the output should be Merit Campus