×

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these Unicode results before and after text, removes the spaces if they are present, and then returns the string that was omitted. In Java, trimming characters is also facilitated by the trim() function. To remove every preceding and trailing whitespace from a text in Java, use the trim() method. It is described in the Java.lang package String class.

It needs to be noted as the important point that:

Note: The intermediate spaces are not removed by the trim() technique.

Method Signature

The following is the syntax or signature of the trim() function for the String class:

public String trim() 

Parameters: No parameters are accepted by the trim() function.

Return: trim() returns a String as its return type. No preceding or trailing spaces are included in the omitted string that is returned. Missing preceding and trailing spaces in a string.

Lets us have a look at how the trim method is implemented internally.

public String trim() {    
        int len = values.length;    
        int str = 0;    
        char[] valu = values;    /* the getfield opcode should be avoided */    
    
        while ((str < len) && (valu[str] <= ' ')) {    
            str++;    
        }    
        while ((str < len) && (valu[len - 1] <= ' ')) {    
            len--;    
        }    
        return ((str > 0) || (len < values.length)) ? substring(st, len) : this;    
    }    

The Java string trim() function is demonstrated below with the help of certain examples.

Example 1:

public class StringTrimDemo1{  
public static void main(String args[]){  
String s3="  hiii kamal   ";  
System.out.println(s3+"Koushik"); //without using the trim() method 
System.out.println(s3.trim()+"Koushik"); //with the use of trim() method  
}}  

Output:

Trim Java

Example 2:

Let us see another example for the trim() method.

The trim() method is used in the example to show how it works. By eliminating all trailing spaces, this technique shortens the string. Here's an illustration.

StringTrimDemo2.java.

// Java programme to show how the 
// Java string trim() technique works
import java.io.*;
class StringTrimDemo2 {
    public static void main (String[] args) {
         
      String s4 = "   Sahithi the senior   ";
       
      // Before using of the trim() method
      System.out.println("Before the Trim() method - ");
      System.out.println("String - "+s4);
      System.out.println("Size - "+s4.size());
       
      // using the trim() method on the s4 string
      S4=s4.trim();
       
      // After using the Trim() method
      System.out.println("\nAfter the Trim() method - ");
      System.out.println("String - "+s4);
      System.out.println("Size - "+s4.size());
       
    }
}

Output:

Trim Java

Example 3:

To determine whether a string contains only white spaces or not, use the trim() method. The identical thing is demonstrated in the example below.

StringTrimDemo4.

public class StringTrimDemo4  
{  
// it is the main method  
public static void main(String argvs[])  
{  
  
String sr = " xyz ";  
  
if((sr.trim()).length() > 0)  
{  
System.out.println("The string includes characters besides blank spaces \n");  
}  
else  
{  
System.out.println("There are just white spaces in the string \n");     
}  
  
sr = "    ";  
  
if((sr.trim()).length() > 0)  
{  
System.out.println("The string includes characters besides blank spaces \n");  
}  
else  
{  
System.out.println("There are just white spaces in the string \n");     
}   
}  
}  

Output:

Trim Java

Example 4:

Although strings through Java are immutable, the trim() method's manipulation of a string by removing whitespace results in a new string is returned. The reference to the same text is returned if the alteration is not carried out by the trim() method. Consider the example that follows.

Let the file name of the program is StringTrimDemo9.

public class StringTrimDemo9  
{  
// it is the main method  
public static void main(String argvs[])  
{  
// the string has blank spaces in it
// reducing the spaces. As a result results in the
// creation of a new string
String sr = " xyz ";    
// sr4 stores a new string   
String str4 = sr.trim();  
// Different hashcodes exist for sr and sr4.
System.out.println(sr.hashCode());  
System.out.println(sr1.hashCode() + "\n");  
// there is no white space in the string p.
// the s reference is returned as a result
// after calling the trim() method
String p = "xyz";  
String p1 = p.trim();  
// p and p1 share the same hashcode.
System.out.println(p.hashCode());  
System.out.println(p1.hashCode());  
}  
}  

Output:

Trim Java

Related Topics

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

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.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 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.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.