1. Introduction
Trimming a string in Java means to remove the leading and trailing whitespaces from the string. The trim() method in Java is used for this purpose. This method is particularly useful in situations where we are reading user input, reading files, or dealing with strings where unwanted whitespaces can be present.
2. Program Steps
1. Define a main method to serve as the entry point of the program.
2. Declare and initialize a String with leading and trailing whitespaces.
3. Call the trim() method on the initialized String.
4. Print the original String and the trimmed String to the console.
3. Code Program
public class StringTrimExample {
public static void main(String[] args) {
// Step 2: Declare and initialize a String with leading and trailing whitespaces
String originalString = " This is a string with leading and trailing spaces. ";
// Step 3: Call the trim() method on the initialized String
String trimmedString = originalString.trim();
// Step 4: Print the original String and the trimmed String to the console
System.out.println("Original String: [" + originalString + "]");
System.out.println("Trimmed String: [" + trimmedString + "]");
}
}
Output:
Original String: [ This is a string with leading and trailing spaces. ] Trimmed String: [This is a string with leading and trailing spaces.]
4. Step By Step Explanation
– Step 1: The main method is defined as the entry point of the program.
– Step 2: A String named originalString is declared and initialized with leading and trailing whitespaces.
– Step 3: The trim() method is called on originalString to remove the leading and trailing whitespaces, and the result is stored in a new String named trimmedString.
– Step 4: Both the originalString and the trimmedString are printed to the console, demonstrating the effect of the trim() method.
This simple Java program effectively demonstrates the usage of the trim() method to remove unwanted leading and trailing whitespaces from a String.