How to remove space in string both end in java Program

public class StringTrimExample {
  public static void main(String args[]) {
    String s1 = " hello string	";
    System.out.println(s1 + "TechSarvam"); //without trim() System.out.println(s1.trim()+"TechSarvam");//with trim()
  }
}

Step-by-Step Breakdown:

1. Class and Method Declaration:

public class StringTrimExample 

{

   public static void main(String args[]) 

{

  • The program declares a class StringTrimExample.
  • The starting point of execution is the main approach.

2. String Declaration:

String s1 = ” hello string\t”;

  • A string s1 is declared and initialized with the value ” hello string\t”.
  • Notice that this string has a leading space (” “) before “hello”, and there is a trailing whitespace (tab character) after “string”. The tab is denoted as \\\\\\\\t in Java.

3. Print Without Using trim()

System.out.println(s1 + “TechSarvam”);

  • This statement prints the string s1 concatenated with the string “TechSarvam”.
  • The string s1 still retains leading and trailing whitespaces that will get reflected in the output.

4. Using trim() Method:

System.out.println(s1.trim() + “TechSarvam”);

  • The trim() method is used on the string s1 which removes any leading and trailing white spaces (spaces, tabs, etc.)
  • From the string, all the leading spaces and the trailing tab are removed after applying the trim().
  • This line prints the string s1 trimmed with “TechSarvam”.

Program Output:

Without trim():

When we print s1 + “TechSarvam”, the string s1 is still holding its leading space and the trailing tab. It’ll look something like this:

hello string TechSarvam

  • In the above case, the printed leading space before  “hello”  and the tab character after  “string”.

Using trim():

When we invoke s1.trim(), the leading and trailing whitespaces are removed. The output will be:

hello stringTechSarvam

  • The leading space before  “hello”  and the tab after  “string”  is gone.

Full Program Output:

hello string TechSarvam

hello stringTechSarvam

Summary

  • Using trim(): The string loses the leading and trailing whitespaces, including spaces and tabs.
  • With trim(): Removes leading and trailing whitespaces.
  • The program shows how the trim() method can clean up strings by removing unnecessary spaces or tabs at the start and end of the string.

Leave a Comment

Your email address will not be published. Required fields are marked *