Saturday 14 June 2014

charAt (int index)

public char charAt(int index)
Returns the char value at the specified index.

class StringCharAt{
 public static void main(String args[]){
  String str = new String("Hello");
  
  System.out.println("str = " + str);
  System.out.println("Character at 0th position is " + str.charAt(0));
  System.out.println("Character at 1st position is " + str.charAt(1));
  System.out.println("Character at 2nd position is " + str.charAt(2));
  System.out.println("Character at 3rd position is " + str.charAt(3));
  System.out.println("Character at 4th position is " + str.charAt(4));
 }
}

Output
str = Hello
Character at 0th position is H
Character at 1st position is e
Character at 2nd position is l
Character at 3rd position is l
Character at 4th position is o

1. Throws IndexOutOfBoundsException if the index argument negative or not less than the length of this string.
class StringCharAtIndexOut{
 public static void main(String args[]){
  String str = new String("Hello");
  
  System.out.println("str = " + str);
  System.out.println("Character at 5th position is " + str.charAt(5));
 }
}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
        at java.lang.String.charAt(String.java:646)
        at StringCharAtIndexOut.main(StringCharAtIndexOut.java:6)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment