Java Programming Examples Tutorial Index

Java String Programs

This program shows how to remove white spaces from within a string which is having extra spaces.



Example:

public class JavaTrim {
    public static void main(String a[]){
        String MyString = "  Avatar   ";
        System.out.println(MyString.trim());
    }
}

Program Output:

JavaTrim

Explanation:

In this program, the class is named as JavaTrim which is having an access specifier as public. Within this class, the main method has been defined.

This program contains a package which is by default available to every Java program. The package is import java.lang.*; All the basic programming methods and requirements comes under this Java package.

This main() method is having a String class which defines a variable name MyString and is initialized with a value named as "     Avatar      " having spaces following it. Now the thing is you have to eliminate the spaces from within the string.

This is possible using the trim() method which is already defined within the String class. This method is used to return a copy of the string and omitting the trailing white spaces. The syntax is: <access specifier> String trim(). This returns a replica of any given string with starting and ending white space(s) removed from the string.

This type of methods are usually used, where user enters extra spaces and the programmer's need to take care of that thing while programming, eliminating those spaces for making the string looks as the space is also having its own ASCII value.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram