trim() with Input data

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Examine the following code:

String userData = "     745   ";
String fixed;
fixed = userData.trim();

Answer:

  • Has the trim() method been used correctly?     Yes
  • How many objects have been created?     2

trim() with Input data

The trim() method creates a new String. The new String contains the same characters as the old one but has whitespace characters (blanks, tabs, and several other non-printing characters) removed from both ends (but not from the middle). So, for example, after the last statement

String userData = "     745   ";
String fixed;

fixed = userData.trim();

the new String referenced by fixed will contain the characters "745" without any surrounding spaces.

(Usage Note:) This method is often useful. Extraneous spaces on either end of user input is a common problem.

QUESTION 15:

Inspect the following:

String dryden = "   None but the brave deserves the fair.   " ;
System.out.println( "|" + dryden.trim() + "|" );

What is printed out?