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.


The method charAt(int index) returns the character at the specified index. Index should be between 0 and string length-1.

Note: Method throws IndexOutOfBoundsException if the index is less than zero or greater than equal to the length of the string.
Output: Returns the substring – W




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.

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.

Output: Compare val1 and val2 : 0
Compare val2 and val3 : -10
Compare val3 and val4 : 31
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
String methods - substring
String methods - Concat and contains
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 7, 2015

    […] char charAt(int index) […]