Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Trim
Java String Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java String Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java Strings.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
The trim() method trims off any leading or ending black spaces, but leaves the spaces in the middle. Take a look below to see an example of this method's function.
TrimmingStringExample.java
package exlcode;
public class TrimmingStringExample {
public static String exampleVariableOne = " Hello World! ";
// returns a String with leading and trailing whitespace omitted
// and assigns it to a String variable
public static String exampleVariableTwo = exampleVariableOne.trim();
public static void main(String[] args) {
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
The original text has extra spaces before and after, making it inefficient and odd-looking when printed. This method creates a new String without added spaces at the beginning or the end while leaving the space in between.
The trim method is extremely useful when the programmer deals with user input data within the application. Extraneous spaces on either end of user input is a common problem, and those issues are easily solved using the trim method.