my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes trim method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "trim method" Watch "trim method" New topic

trim method

Vishnu Prakash
Ranch Hand

Joined: Nov 15, 2004
Posts: 1026

Execute the program like java StringTest1 alpha beta
Arg beta

Question: Why the trim method is not removing the trailing whitespaces in String s2.

Servlet Spec 2.4/ Jsp Spec 2.0/ JSTL Spec 1.1 - JSTL Tag Documentation
Michael Imhof

Joined: Nov 07, 2004
Posts: 24
If you're looking at the API doc for java.lang.String (
you'll find the definition for the method trim():
"Returns a copy of the string, with leading and trailing whitespace omitted."

So in your example this means:

" Arg ".trim() will return a new String "Arg" and will be saved
in s1.

" Arg " + args[1] is a new String " Arg Beta" and will be saved in s2.
" Arg Beta".trim will return a new String "Arg Beta" and
will be saved in s2.

Correct output is:

Arg Beta

Krishna Srinivasan
Ranch Hand

Joined: Jul 28, 2003
Posts: 1850

this will work:

String2 you are appending string and using trim method.

String s2 = " Arg "+arg[1] ;
There is no space for triming.

class StringTest1 {
public static void main(String[] args) {
String s1 = " Arg ";
s1= s1.trim();
System.out.println(s1+ args[1] );

String s2 = " Arg " ;
s2= s2.trim();


Krishna Srinivasan
OCAJP 7/8 Exam, 400+ OCPJP Mock Questions
I agree. Here's the link:
subject: trim method
It's not a secret anymore!