String’s trim method is used to remove leading and trailing space. Sometimes, you get extra leading or trailing space and your program does not work as expected. It returns String object after removing leading and trailing spaces.
When you run above program, you will get below output:
String’s trim method does not remove middle spaces.
String trim example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; public class StringTrimExample { public static void main(String[] args) { String str = " Hello world from "; //without trim() System.out.println("Without trim"); System.out.println("----------------------"); System.out.println(str+"java2blog.com"); System.out.println("----------------------"); // with trim() System.out.println("nWith trim"); System.out.println("----------------------"); System.out.println(str.trim()+"java2blog.com"); } } |
1 2 3 4 5 6 7 8 9 10 |
Without trim ---------------------- Hello world from java2blog.com ---------------------- With trim ---------------------- Hello world fromjava2blog.com |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.