Menu
Topics Index
...
`

CharAtString - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App