String methods – charAt() and compareTo()
I this post, we will discuss about string methods charAt() and compareTo().
Let’s discuss them one by one with examples.
charAt():
The method charAt(int index)
returns the character at the specified index. Index should be between 0 and string length-1.
1 2 3 4 5 6 7 |
public class ExampSubstring { public static void main(String[] args) { String val1 = "Hello World"; System.out.println("Returns the character - "+val1.charAt(6)); // returns W } } |
compareTo():
The method compareTo()
is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison.
If both the strings are equal then this method returns number 0 else it will return positive or negative value.The result is positive if the first string is lexicographically greater than the second string else the result would be negative.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class ExampCompareTo { public static void main(String[] args) { String val1 = "Hello World"; String val2 = "Hello World"; String val3 = "How are you?"; String val4 = "How are you doing?"; System.out.println("Compare val1 and val2 : "+val1.compareTo(val2)); System.out.println("Compare val2 and val3 : "+val2.compareTo(val3)); System.out.println("Compare val3 and val4 : "+val3.compareTo(val4)); } } |
Compare val1 and val2 : 0
Compare val2 and val3 : -10
Compare val3 and val4 : 31
String compareToIgnoreCase():
It is similar to the method compareTo(). The only difference is it ignores the case like uppercase and lower case while comparing i.e. it is not case sensitive.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class ExampCompareTo { public static void main(String[] args) { String val1 = "Hello World"; //String in lowercase String val2 = "HELLO WORLD"; //String in uppercase String val3 = "How are you?"; String val4 = "How are you doing?"; System.out.println("Compare val1 and val2 : "+val1.compareToIgnoreCase(val2)); System.out.println("Compare val2 and val3 : "+val2.compareToIgnoreCase(val3)); System.out.println("Compare val3 and val4 : "+val3.compareToIgnoreCase(val4)); } } |
Compare val2 and val3 : -10
Compare val3 and val4 : 31
1 Response
[…] char charAt(int index) […]