×

Trim Method in String Java

What is a String?

Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings

Trim Method:-

There are numerous methods available in Java. One of these, the trim method in Java, will be the subject of this discussion. The Java trim method is a built-in function for removing leading and trailing spaces from a string. Let's take a closer look at the subject.

In Java, the trim() function can also be used to trim characters.

But it is also Noted that the trim() method does not remove spaces in the middle.

Syntax:

public String trim()

Return Type:

Trim() returns a String as its return type. The excluded string is returned with no leading or trailing spaces.

Parameters:

The trim method does not have any parameters.

How does the Trim Method work?

'u0020' is the Unicode value for the space character. Trim in Java examines whether the Unicode value 'u0020' is present before and after the given string when the code is processed in Java. If the Unicode value 'u0020' exists, the trim method in Java removes the spaces and produces a new string.

Now let’s take a view on some Examples:

// Java string trim() method

class Gfg {
public static void main(String args[])
{
// trims the leading spaces
String s = " welcome to my world  ";
System.out.println(s.trim());
// trims the leading spaces there also
s = "I want to become a programmer  ";
System.out.println(s.trim());
}
}

Output:

Welcome to my world
I want to become a programmer 

Points to remember:

  • In Java, the trim() method does not eliminate spaces in the center of a string.
  • In Java, the trim() method creates a new String object without any leading or trailing spaces.
  • This approach does not change the original string.

Example :

class Main {
  public static void main(String[] args) {
    String str = "Hey my name is John    ";


    String newStr = str.trim();
      
    System.out.println(newStr);  
  }
}

Output:

My name is John

Explanation:

The string "My name is John" is given to us in the preceding example. There is one leading space and four trailing spaces in the supplied string. Now, when the code is compiled, the trim function in Java will meet 1 'u0020' character at the start and 4 'u0020' characters at the conclusion. As a result, it would remove all of these words and return a new string that reads "My name is John."

Example[removing all whitespace characters]:

To remove all whitespace characters from a string, we can use the replaceAll() function in Java.

The example below demonstrates how to remove all whitespace characters from a string.

class Main {
  public static void main(String[] args) {
    String str = "My name is John    ";
    String newStr= str1.replaceAll("\\s", "");
    System.out.println(newStr);  
  }
}

Output:

MynameisJohn

Explanation:

We're given the string "My name is John" in this example, and we're meant to remove all whitespace characters. The str1.replaceAll() function is used to do this.

The first parameter is a whitespace regex, and the second parameter is an empty string. As a result, the replaceAll method will replace all whitespace characters in the string with an empty string, yielding a new string containing the text "MynameisJohn."

Conclusion:

In Java, the trim() function removes excess leading and trailing spaces from a string.

It accepts no arguments and returns a new string 

In Java, the trim() method does not remove any middle spaces.

'u0020' is the Unicode value for the space character.

The trim technique looks for the space's Unicode value and removes it.

The replaceAll() method can be used to remove all whitespace characters from a string.

Example: Program to show the working of java string trim() method

class GFG {
public static void main (String[] args) {
String s1 = "   hello world   ";
// Before Trim method
System.out.println("Before Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
// applying trim method string s1
s1=s1.trim();
// After Trim method
System.out.println("\nAfter Trim() - ");
System.out.println("String - "+s1);
System.out.println("Length - "+s1.length());
}
}

Output:

Before Trim - 
String -    hello world   
Length - 17
After Trim - 
String – hello world

Related Topics

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.