String trim method

This is an example of how to use the trim method of String class. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Trimming a String implies that you should:

  • Create a new String.
  • Use trim() method of String. This method returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class StringTrimMethod {
	public static void main(String[] args) {
		String s = "   Java Code Geeks   ";
		System.out.println("Original String:'" + s + "'");
		// remove leading and trailing space from string use
		String sTrimmed = s.trim();
		System.out.println("Trimmed String:'" + sTrimmed + "'");



Original String:'   Java Code Geeks   '
Trimmed String:'Java Code Geeks'

This was an example of how to trim method of String in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button