×

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

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

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

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.