How to initialize and compare strings?

Java Programming Java 8Object Oriented Programming

<p style="">Following example compares two strings by using str compareTo (string), str compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the ascii difference of first odd characters of compared strings.</p><h3>Example</h3><p><a class="demo" href="http://tpcg.io/6hecJn" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">public class StringCompareEmp{ &nbsp; &nbsp;public static void main(String args[]) { &nbsp; &nbsp; &nbsp; String str = &quot;Hello World&quot;; &nbsp; &nbsp; &nbsp; String anotherString = &quot;hello world&quot;; &nbsp; &nbsp; &nbsp; Object objStr = str; &nbsp; &nbsp; &nbsp; System.out.println( str.compareTo(anotherString) ); &nbsp; &nbsp; &nbsp; System.out.println( str.compareToIgnoreCase(anotherString) ); &nbsp; &nbsp; &nbsp; System.out.println( str.compareTo(objStr.toString())); &nbsp; &nbsp;} }</pre><h3>Output</h3><p>The above code sample will produce the following result.</p><pre class="result notranslate">-32 0 0</pre><h2>String compare by equals()</h2><p>This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.</p><h3>Example</h3><p><a class="demo" href="http://tpcg.io/IRTckh" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">public class StringCompareequl{ &nbsp; &nbsp;public static void main(String []args) { &nbsp; &nbsp; &nbsp; String s1 = &quot;tutorialspoint&quot;; &nbsp; &nbsp; &nbsp; String s2 = &quot;tutorialspoint&quot;; &nbsp; &nbsp; &nbsp; String s3 = new String (&quot;Tutorials Point&quot;); &nbsp; &nbsp; &nbsp; System.out.println(s1.equals(s2)); &nbsp; &nbsp; &nbsp; System.out.println(s2.equals(s3)); &nbsp; &nbsp;} }</pre><h3>Output</h3><p>The above code sample will produce the following result.</p><pre class="result notranslate">true false</pre><h2>String compare by == operator</h2><h3>Example</h3><p><a class="demo" href="http://tpcg.io/G4phVc" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">public class StringCompareequl{ &nbsp; &nbsp;public static void main(String []args) { &nbsp; &nbsp; &nbsp; String s1 = &quot;tutorialspoint&quot;; &nbsp; &nbsp; &nbsp; String s2 = &quot;tutorialspoint&quot;; &nbsp; &nbsp; &nbsp; String s3 = new String (&quot;Tutorials Point&quot;); &nbsp; &nbsp; &nbsp; System.out.println(s1 == s2); &nbsp; &nbsp; &nbsp; System.out.println(s2 == s3); &nbsp; &nbsp;} }</pre><h3>Output</h3><p>The above code sample will produce the following result.</p><pre class="result notranslate">true false</pre>
raja
Updated on 22-Jun-2020 11:39:31

Advertisements