In Java, how do you compare strings? Java provides us with compareto, "= =", equals to the string comparison, the following describes their differences.
Example one: CompareTo comparing the size of data
CompareTo (String) comparetoignorecase (String) compareTo (object string)
The example compares two strings by using the above function and returns an int type. If the string equals the argument string, it returns 0, the string is less than the argument string, the return value is less than 0, the string is greater than the argument string, and the return value is greater than 0.
The basis for judging the size of a string depends on the order in which they are in the dictionary.
Package com.de.test; /** */Publicclass stringa {publicstatic void Main (string[] args) { = "String"; = "string"; = str; System.out.println (Str.compareto (ANOTHERSTR)); System.out.println (Str.comparetoignorecase (ANOTHERSTR)); System.out.println (Str.compareto (objstr.tostring ()));} }
Executing the above code produces the following result
-3200
Example two: Comparing Strings using Equals (), "= ="
With Equals () and = =, the difference is that equals compares content equality, = = compares the referenced variable address for equality.
Packagecom.de.test; Public classStringa { Public Static voidMain (string[] args) {String S1= "Hello"; String S2= "Hello"; String S3=NewString ("Hello"); String S4=NewString ("Hello"); System.out.println ("S1:" +S1); System.out.println ("S2:" +S2); System.out.println ("S3:" +S3); System.out.println ("S4:" +S4); System.out.println ("----------compare whether content is equal---------------"); System.out.println (s1.equals (S2)); System.out.println (S2.equals (S3)); System.out.println (S3.equals (S4)); System.out.println ("----------Compare reference addresses for equality---------------"); System.out.println (S1==S2); SYSTEM.OUT.PRINTLN (S2==S3); System.out.println (S3==S4); }}
Executing the above code produces the following result
S1:hellos2:hellos3:hellos4:hello----------Compare whether content is equal---------------truetrue True ----------Compare reference addresses for equality---------------truefalse false
Java Basics (i) how strings compare strings