+ 1
Compare two string
if someone can tell me why my code always print out s1 great than s2 and help me debug thanks String s1="Welcome to Java"; String s2="Welcome into java"; if (s1.compareTo(s2) > 0){ System.out.print("s1 greater than s2"); } else if (s1.compareTo(s2) == 0){ System.out.print("s1 and s2 have same"); } else{ System.out.print("s1 less than s2"); } } }
1 Answer
+ 6
I believe you already know that string is an array if characters. Therefore the comparison process each character in both strings until it finds any difference or reach to the end of string.
You get the expected result as 't' > 'i' and it returns a positive integer which fulfills the first condition.
Check the official JavaDoc below to find out more if you're interested:-
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo(T)