×

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 Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.