Advertisement



< Prev
Next >



String charAt() method




As per the name of the method goes, charAt() method of String class is used to determine a character at a particular index in a string.



Signature of charAt()


public char charAt(int index)






Note


When calling charAt() method, the first index in a String object is counted as 0.




Calling charAt() to extract a char at a particular index in a String.


Here in the upcoming code, we have initialized a Sring object with a value and we are calling charAt() method to determine the character present at a particular index in this String object.
// Program to find a character at a particular index of a String.


class StringCharAt
{
public static void main(String[] ar)
{
String str= new String("Keep Smiling");
System.out.println("Original String is "+ str);

//Searching for a character at index 0 in String
char c = str.charAt(0);

System.out.println("character at the index 2 of "+ str + " is " + c);

//Searching for a character at index 5 in String
c = str.charAt(4);

System.out.println("character at the index 4 of "+ str + " is " + c);

//Searching for a character at index 5 in String
c = str.charAt(7);

System.out.println("character at the index 7 of "+ str + " is " + c);
}
}


Output is :


Original String is Keep Smiling
character at the index 2 of Keep Smiling is K
character at the index 4 of Keep Smiling is 
character at the index 7 of Keep Smiling is i


Program Analysis





Advertisement




Exception in calling chatAt() method.

Here in the next code, an Exception is raised when we are trying to determine a character at an out-of-range index in the String object..
// Program to find a character at a particular index of a String.


class StringCharAt
{
public static void main(String[] ar)
{
String str= new String("Mexico");

//Searching a character at index 9.
char c = str.charAt(9);

System.out.println("Original String is "+ str);
System.out.println("Character at the index 9 of "+ str + " is " + c);
}
}


Output is :


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
        at java.lang.String.charAt(Unknown Source)
        at StringCharAt.main(StringCharAt.java:11)


Program Analysis





Please share this article -




< Prev
Next >
< length() method
lastIndexOf() method >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON


Advertisement