{"id":89318,"date":"2024-03-07T18:00:26","date_gmt":"2024-03-07T12:30:26","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=89318"},"modified":"2024-03-07T18:00:26","modified_gmt":"2024-03-07T12:30:26","slug":"java-string-compareto-method","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/","title":{"rendered":"Java String compareTo() Method with Examples"},"content":{"rendered":"<p>The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string. It returns either a positive, negative, or 0.<\/p>\n<p>The Unicode value of each character in the strings is used to compare the strings when comparing strings. Inferring the relative order of strings based on their character sequences is key.<\/p>\n<h2>Explanation<\/h2>\n<p>The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string. It returns either a positive, negative, or 0.<\/p>\n<p>The Unicode value of each character in the strings is used to compare the strings when comparing strings.<\/p>\n<p>A positive integer (difference of character value) is returned when the first string is lexicographically superior to the second string.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>public int compareTo(String anotherString)<\/p>\n<p><strong>Parameter:<\/strong><\/p>\n<ul>\n<li><strong>string2 &#8211;<\/strong>A String that represents the second string that will be compared<\/li>\n<li><strong>object-<\/strong> thing that represents the thing being compared<\/li>\n<\/ul>\n<p><strong>Return Value:<\/strong><\/p>\n<ul>\n<li><strong>An int value:<\/strong> 0 if the strings are equal, 0 if the strings are lexicographically shorter than the other strings, &gt; 0 if the strings are longer (have more characters) than the other strings.<\/li>\n<li>If string1 is greater than string2, a positive number is returned.<\/li>\n<li>If string1 is less than string2, a negative integer is returned.<\/li>\n<li>It returns 0 if string1 and string2 are equal.<\/li>\n<\/ul>\n<p><strong>Example 1:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TechVidvanCompareTo {\n    public static void main(String argvs[]) {\n        String a1 = new String(\"INDIA IS MY COUNTRY\");\n        String a2 = new String(\"india is my country\");\n        System.out.println(a1.compareTo(a2));\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>-32<\/p>\n<p><strong>Example 2:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TechVidvanCompareTo{  \npublic static void main(String args[]){  \nString b1=\"Hello\";  \nString b2=\"\";  \nString b3=\"Everyone\";  \nSystem.out.println(b1.compareTo(b2));  \nSystem.out.println(b2.compareTo(b3));  \n}}<\/pre>\n<p><strong>OUTPUT:<\/strong><\/p>\n<p>5<br \/>\n-7<\/p>\n<h3>Use of Java String CompareTo():<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TechVidvanCompareTo{\n    public static void main(String args[]) {\n        String a1 = \"hello\";\n        String a2 = \"hello\";\n        String a3 = \"meklo\";\n        String a4 = \"hemlo\";\n        \n        System.out.println(a1.compareTo(a2));\n        System.out.println(a1.compareTo(a3));\n        System.out.println(a1.compareTo(a4));\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>0<br \/>\n-5<br \/>\n-1<\/p>\n<p>Java allows us to compare Strings based on their content and references. It is used in reference matching (by the == operator), sorting (by the compareTo() method), and authentication (by the equals() method).<\/p>\n<p><strong>Diagram:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/10\/java-string-compare-to-diagram.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-89325\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/10\/java-string-compare-to-diagram.webp\" alt=\"java string compare to ( )diagram\" width=\"500\" height=\"212\" \/><\/a><\/p>\n<h3>Types of Java compareTo():<\/h3>\n<p><strong>The compareTo() method has three different iterations, which are as follows:<\/strong><\/p>\n<ul>\n<li>the use of int comparisonUsing the formula To(Object obj),<\/li>\n<li>compareTo(String anotherString),<\/li>\n<li>compareToIgnoreCase(String str)<\/li>\n<\/ul>\n<h3>Technical details:<\/h3>\n<h4>Case Sensitivity:<\/h4>\n<p>Uppercase and lowercase characters are regarded differently by compareTo() since it is case-sensitive.<\/p>\n<h4>Null handling:<\/h4>\n<p>NullPointerException will be thrown if either the invoking string or anotherString is null.<\/p>\n<h3>Exception from String CompareTo():<\/h3>\n<ul>\n<li>If this object cannot be compared to the supplied object, a ClassCastException will occur.<\/li>\n<li>Whenever the provided object is null, a NullPointerException is thrown.<\/li>\n<\/ul>\n<h3>Advantages of Java String CompareTo():<\/h3>\n<ul>\n<li><strong>Lexicographic Comparison:<\/strong> You can compare strings lexicographically (in a dictionary-style) with the compareTo() function.<\/li>\n<li><strong>Standardized Comparison:<\/strong> It uses a standardized comparison algorithm, so while comparing strings, you can count on consistent results.<\/li>\n<li><strong>Simplicity:<\/strong> Comparing strings is made easy and plain without the need to create original comparison logic.<\/li>\n<\/ul>\n<h3>Disadvantage of Java String CompareTo():<\/h3>\n<ul>\n<li><strong>Case Sensitivity:<\/strong> Because compareTo() is case-sensitive, it treats capital and lowercase letters differently. If you need to compare objects without regard to case, this could produce surprising results.<\/li>\n<li><strong>The CompareTo method performs case-<\/strong> and culture-sensitive comparisons using both of its overloads. This approach cannot be used for ordinal comparisons or culturally blind comparisons.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>We have extensively discussed the CompareTo() function in Java. We briefly discussed the use of the CompareTo() method and then moved on to see how using this method can help reduce a significant amount of code in a program.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string. It returns either a positive, negative, or 0. The Unicode value of each character in the&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":89322,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[5389,5390,296,5391,5392,5393,250,5394],"class_list":["post-89318","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-compareto-method","tag-compareto-method-in-java","tag-java","tag-java-compareto-method","tag-java-string-compareto","tag-java-string-compareto-method-with-examples","tag-learn-java","tag-string-compareto-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java String compareTo() Method with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java String compareTo() Method with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-07T12:30:26+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\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=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java String compareTo() Method with Examples - TechVidvan","description":"The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.","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:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/","og_locale":"en_US","og_type":"article","og_title":"Java String compareTo() Method with Examples - TechVidvan","og_description":"The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2024-03-07T12:30:26+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java String compareTo() Method with Examples","datePublished":"2024-03-07T12:30:26+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/"},"wordCount":505,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#primaryimage"},"thumbnailUrl":"","keywords":["compareTo() method","compareTo() method in java","java","java compareTo() method","java string compareTo()","java string compareTo() method with examples","Learn Java","string compareTo() method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/","url":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/","name":"Java String compareTo() Method with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#primaryimage"},"thumbnailUrl":"","datePublished":"2024-03-07T12:30:26+00:00","description":"The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-string-compareto-method\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java String compareTo() Method with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89318","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=89318"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89318\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=89318"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=89318"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=89318"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}