Java Program to remove whitespace from the beginning and end of a string

Java 8Object Oriented ProgrammingProgramming

Use the trim() method to remove whitespace from the beginning and end of a string.

Let’s say the following is our string with whitespace.

str1 = " The Big Bang Theory ";

Now, let us trim all the whitespaces from the beginning and the end.

String str2 = str1.trim();

The following is the final example with output.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str1 = " The Big Bang Theory ";
      System.out.println("String: "+str1);
      String str2 = str1.trim();
      System.out.println("Updated string (trimming spaces): "+str2);
   }
}

Output

String: The Big Bang Theory
Updated string (trimming spaces): The Big Bang Theory
raja
Published on 06-Dec-2018 16:35:39
Advertisements