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.

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

 

 

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.

Output:
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
Print Friendly, PDF & Email
String methods - substring
String methods - Concat and contains
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 7, 2015

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