Trim

String Methods

Trim

🙋 Need help? Ask an expert now!

The trim() method trims off any leading or ending black spaces, but leaves the spaces in the middle. Take a look below to see an example of this method's function.

TrimmingStringExample.java
package exlcode;

public class TrimmingStringExample {

  public static String exampleVariableOne = "      Hello World!      ";
  // returns a String with leading and trailing whitespace omitted
  // and assigns it to a String variable
  public static String exampleVariableTwo = exampleVariableOne.trim();

  public static void main(String[] args) {
    System.out.println(exampleVariableOne);
    System.out.println(exampleVariableTwo);
  }
}

The original text has extra spaces before and after, making it inefficient and odd-looking when printed. This method creates a new String without added spaces at the beginning or the end while leaving the space in between.

The trim method is extremely useful when the programmer deals with user input data within the application. Extraneous spaces on either end of user input is a common problem, and those issues are easily solved using the trim method.

Edit Me on GitHub!

Application Question

Which of the following will print the String "Hello"?