

{"id":130581,"date":"2025-11-10T18:00:54","date_gmt":"2025-11-10T12:30:54","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=130581"},"modified":"2025-11-10T18:05:18","modified_gmt":"2025-11-10T12:35:18","slug":"java-string-trim-method","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/","title":{"rendered":"Java String trim() Method with Examples"},"content":{"rendered":"<p>The trim() method in Java is a vital String function that removes leading and trailing whitespace from a String. In this article, we will explore the purpose and usage of trim() through examples.<\/p>\n<p>In Java, whitespace characters include spaces, tabs, newlines, carriage returns, and form feeds. These are represented by the Unicode value &#8216;\\\\u0020&#8217;. The trim() method helps remove extra whitespace from the beginning or end of a string. However, it does not affect any spaces in the middle of the string.<\/p>\n<h2>Purpose of Java trim() Method<\/h2>\n<p><strong>The main purpose of Java trim() is to:<\/strong><\/p>\n<ul>\n<li>Remove leading whitespace characters<\/li>\n<li>Remove trailing whitespace characters<\/li>\n<\/ul>\n<p>This helps sanitise user input strings and format output strings cleanly in Java.<\/p>\n<h3>Java String trim() Method<\/h3>\n<p><strong>The trim() method in Java signature is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public String trim()<\/pre>\n<p>It takes no parameters and returns a new String without leading or trailing whitespace from the original string.<\/p>\n<h3>Examples of trim() in Java<\/h3>\n<p>Let&#8217;s go through some examples to understand the working of trim():<\/p>\n<h4>Example 1: Removing leading and trailing spaces<\/h4>\n<p>This example demonstrates how the trim() method eliminates extra leading and trailing spaces in a string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TrimExample {\r\n    public static void main(String[] args) {\r\n        String str = \"   Hello World     \";\r\n        String trimmed = str.trim();\r\n\r\n        System.out.println(\"Original String: '\" + str + \"'\");\r\n        System.out.println(\"Trimmed String: '\" + trimmed + \"'\");\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nOriginal String: &#8216; Hello World &#8216;<br \/>\nTrimmed String: &#8216;Hello World&#8217;<\/p>\n<h4>Example 2: Impact on original string<\/h4>\n<p>This example shows that trim() does not modify the original string:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TrimExample {\r\n    public static void main(String[] args) {\r\n        String str = \"   Welcome to Java   \";\r\n\r\n        System.out.println(\"Before trim: \" + str);\r\n\r\n        String newStr = str.trim();\r\n\r\n        System.out.println(\"After trim: \" + newStr);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nBefore trim: Welcome to Java<br \/>\nAfter trim: Welcome to Java<\/p>\n<h4>Example 3: Comparing the original and the returned string<\/h4>\n<p>Let&#8217;s compare the original and returned string to see the difference:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TrimExample {\r\n    public static void main(String[] args) {\r\n        String str = \"  Hello World   \";\r\n\r\n        System.out.println(\"Original: \" + str);\r\n\r\n        String trimmed = str.trim();\r\n\r\n        System.out.println(\"Trimmed: \" + trimmed);\r\n\r\n        boolean areEqual = str.equals(trimmed);\r\n\r\n        System.out.println(\"Original equals Trimmed: \" + areEqual);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nOriginal: Hello World<br \/>\nTrimmed: Hello World<br \/>\nOriginal equals Trimmed: false<\/p>\n<p>Time Complexity: O(n)<br \/>\nAuxiliary Space: O(1)<\/p>\n<h3>Conclusion<\/h3>\n<p>In conclusion, the trim() method in Java is a valuable tool for handling and cleaning up strings, ensuring cleaner and more sanitised user input and formatted output. We&#8217;ve explored its purpose and usage and provided examples that demonstrate its functionality. Remember that the trim() method doesn&#8217;t affect spaces within the string itself, only the leading and trailing ones. It&#8217;s a simple yet powerful method that can make your Java code more robust and user-friendly.<\/p>\n<p>So, the next time you encounter strings with unwanted whitespace, consider using the trim() method to tidy things up. Its time complexity is O(n), and it uses O(1) auxiliary space, making it an efficient choice for string manipulation in Java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The trim() method in Java is a vital String function that removes leading and trailing whitespace from a String. In this article, we will explore the purpose and usage of trim() through examples. In&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":134374,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[31278,31280,31283,31078,8152,31279,31282,31281],"class_list":["post-130581","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-string-trim-method","tag-java-string-trim-method-with-examples","tag-java-trim-method","tag-java-tutorials","tag-learn-java","tag-string-trim-method-in-java","tag-trim-method","tag-trim-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String trim() Method with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"The Java trim() method is a valuable tool for cleaning up strings, ensuring cleaner and more sanitised user input and formatted output.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String trim() Method with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"The Java trim() method is a valuable tool for cleaning up strings, ensuring cleaner and more sanitised user input and formatted output.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2025-11-10T12:30:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-11-10T12:35:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java String trim() Method with Examples - DataFlair","description":"The Java trim() method is a valuable tool for cleaning up strings, ensuring cleaner and more sanitised user input and formatted output.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String trim() Method with Examples - DataFlair","og_description":"The Java trim() method is a valuable tool for cleaning up strings, ensuring cleaner and more sanitised user input and formatted output.","og_url":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2025-11-10T12:30:54+00:00","article_modified_time":"2025-11-10T12:35:18+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java String trim() Method with Examples","datePublished":"2025-11-10T12:30:54+00:00","dateModified":"2025-11-10T12:35:18+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/"},"wordCount":383,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp","keywords":["java string trim() method","java string trim() method with examples","java trim() method","java tutorials","Learn Java","string trim() method in java","trim() method","trim() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/","url":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/","name":"Java String trim() Method with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp","datePublished":"2025-11-10T12:30:54+00:00","dateModified":"2025-11-10T12:35:18+00:00","description":"The Java trim() method is a valuable tool for cleaning up strings, ensuring cleaner and more sanitised user input and formatted output.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-string-trim-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-string-trim.webp","width":1200,"height":628,"caption":"java string trim()"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-string-trim-method\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Java String trim() Method with Examples"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49","name":"TechVidvan Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","caption":"TechVidvan Team"},"description":"TechVidvan Team provides high-quality content &amp; courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.","url":"https:\/\/data-flair.training\/blogs\/author\/test001\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/130581","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/86671"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=130581"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/130581\/revisions"}],"predecessor-version":[{"id":147024,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/130581\/revisions\/147024"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/134374"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=130581"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=130581"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=130581"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}