Thursday, 13 July 2017

String charAt() in java ~ foundjava

Java String charAt()

The java string charAt() method returns a char value at the given index number. The index number starts from 0. It returns StringIndexOutOfBoundsException if given index number is greater than this string or negative index number.

Signature

The signature of string charAt() method is given below:
  1. public char charAt(int index)  

Parameter

index : index number, starts with 0

Returns

char value

Specified by

CharSequence interface

Throws

StringIndexOutOfBoundsException : if index is negative value or greater than this string length.

Java String charAt() method example

  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name="javatpoint";  
  4. char ch=name.charAt(4);//returns the char value at the 4th index  
  5. System.out.println(ch);  
  6. }}  

Output:
t

StringIndexOutOfBoundsException with charAt()

Let's see the example of charAt() method where we are passing greater index value. In such case, it throws StringIndexOutOfBoundsException at run time.
  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name="javatpoint";  
  4. char ch=name.charAt(10);//returns the char value at the 10th index  
  5. System.out.println(ch);  
  6. }}  
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

No comments:

Post a Comment