How to find the length of a String using the Java String compareTo() method
Coding River
How to find the length of a String using the Java String compareTo() method
In this video, we will talk about the compareTo() method, which is used to compare two String values. As a disclaimer, this method is used to compare String values. That means it will only compare a String with another String.
In the case of the comparison between String values, each character of both String values is converted into a Unicode value. If both String values are equal the method returns 0 If the first String is inferior to the one inside the brackets the method will return a negative value If the first String is greater than the one inside the brackets the method will return a positive value
public class CompareToExample { public static void main(String args[]) { String sentence1 = "Hello world !"; String sentence2 = "How are you doing today ?"; String sentence 3= "How are you doing today ?";
Int value = sentence1.compareTo(sentence2);
System.out.println("Comparison between Sentence 1 and Sentence 2: "+ value);
int value2 = sentence2.compareTo( sentence3 );
System.out.println("Comparison between Sentence 2 and Sentence 3 : "+ value2);
int value4 = sentence1.compareTo(“Hello world !”);
System.out.println("Comparison between Sentence 1 and a String : "+ value4);
} }
Note: the Java String compareTo() method is case sensitive int value4 = sentence1.compareTo(“HELLO WORLD !”); System.out.println("Comparison between Sentence 1 and a String : "+ value4);
If we would like to ignore the case of both Strings while comparing them comparing them, we need to use the compareToIgnoreCase()
How to find the length of a String using the String compareTo() method
In this video, we will see how to get the length of a String using the compareTo() method.
You may be wondering, how is this possible?
Well, all you have to do is to compare a String with an empty String using the compareTo() method. As soon as the method evaluates, it will return the length of the non-empty String
String word1 = "coding";
String word2 = ""; //empty string
//it would return the length of str1 as a positive number word1.compareTo(word2); // 6
//it would return the length of str1 as a negative number word2.compareTo(word1);
The second statement will return a negative value because the empty String is used to invoke the method and the other String is used as a parameter
Integer.compare(int x , int y) / Double.compare(double x , double y) (Fix error : Cannot invoke the compareTo(int) Java In this video, we will talk about how fix this error “Cannot invoke the compareTo(int). I guess that you are getting this error because you want to compare two integers or two decimal numbers. So, the problem is with the me ... https://www.youtube.com/watch?v=QXG-xlSrR5k
8638492 Bytes