×

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

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

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

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

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

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

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

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.