This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 1844

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
Spring Tutorials, OCAJP Mock Questions, 400+ OCPJP Mock Questions
It is sorta covered in the JavaRanch Style Guide.
subject: trim method
Similar Threads
How many String Object are created in the following code ??
how many String objects are created
How many String objects are created in the code
Behaviour of String and StringBuffer class.