Java String.charAt() Method

Java String.charAt() Method

By Yashwant Chavan, Views 1042, Date 15-Nov-2016

In this tutorial you will learn about String.charAt() method. This method returns the char value at the specified index.

tags java

Refer below steps

  • String.charAt(int index) method returns the char value at the specified index. An index ranges start from 0 to length()-1.
  • It throws IndexOutOfBoundsException if the index argument is negative more than length of the string. Refer last scenario where we are trying to get char at 25th position.

Java String length example

package com.technicalkeeda.app;

public class StringCharAt {
    public static void main(String[] args) {
        String str = "technicalkeeda";

        char t = str.charAt(0);
        System.out.println("char at 0th index:- " + t);

        char n = str.charAt(4);
        System.out.println("char at 4th index:- " + n);

        char outOfIndex = str.charAt(25);
        System.out.println(outOfIndex);
    }
}

Output

char at 0th index:- t
char at 4th index:- n
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
 at java.lang.String.charAt(String.java:658)
 at com.technicalkeeda.app.StringCharAt.main(StringCharAt.java:13)

Suggested Posts

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]