Menu
Topics Index
...
`


Strings > Character Extraction >
Siva Nookala - 04 Apr 2016
This method takes an index as a parameter and returns the character that is present at that index of the string. Indexing starts from zero. i. e index of 1st character is 0, 2nd character is 1 and so on. The index of the last character is the length of the string - 1.
CharAtString
class CharAt
{
    public static void main(String arg[])
    {
        String s1 = "Merit Campus";
        char c1 = s1.charAt(0); //LINE A
        System.out.println(c1);
        char c2 = s1.charAt(4);  //LINE B
        System.out.println(c2);    
    }
}
OUTPUT

M
t

DESCRIPTION

At LINE A, 0 is passed as parameter and character at 0th index is returned. At LINE B, character at 4th index(5th character) is returned.

THINGS TO TRY
  • Include the below code line at LINE A
    char c1 = s1.charAt(12);
    java.lang.StringIndexOutOfBoundsException is thrown, since the passed value is greater than the string ending index.(Index begins with 0 and ends with the index String length -1)
  • Include the below code line at LINE B
    char c1 = s1.charAt(-1);
    java.lang.StringIndexOutOfBoundsException is thrown because the index is less than the string starting index.

Another String method, startsWith(), can be confused with the function of charAt(0). The difference lies in the result of either method: charAt(0) will return a character, whereas startsWith() is a test, returning a boolean.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App