Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
strings
index
get value
char

How to get a character from a string in Java

Educative Answers Team

In Java, the charAt() function returns a character at the specified index of a string.

svg viewer

Syntax

The general syntax of the charAt() function is as follows:

charAt(index)

The index is a parameter passed to the function which is an integer value, ranging from 0 to n-1, where n is the size of the string.

The charAt() function returns a character value present at the specific index.

Example

The following piece of code explains the functionality of the charAt() function.

class HelloWorld {
    public static void main( String args[] ) {
        String str = "Hello!";
        char ch = str.charAt(4);
        System.out.println(ch);
    }
}

Exception handling

In case the user gives an invalid input, that is, an index value less than 0 or greater than the size of the string, a string index out of bounds exception is thrown.

Execute the following code to see the exception:

class HelloWorld {
    public static void main( String args[] ) {
        String str = "Hello!";
        char ch = str.charAt(6);
        System.out.println(ch);
    }
}

RELATED TAGS

java
strings
index
get value
char
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring