java.lang.String charAt()

Description :

This java tutorial focuses on the charAt() method of java.lang.String class. This method returns a char value specified on the index input. So basically this article just shows an example on practical usage of charat method.

Practical Usage :

During my career as a developer, I have encountered many instances that we have to deal with a fixed width String input and every character on the String passed to our java code signifies something. This method will handle such scenario.

Method Syntax :

public char charAt(int index)

Parameter input :

  • index – This method accepts only one input which is index in int data type.

Method Returns :

This method returns a char datatype at based on the index input as the method parameter.

Exception :

IndexOutOfBoundsException

– The charAt() method of String class throws this exception whenever the index provided on the method argument is outside the range of the String. The maximum index argument is expected to be String length -1.

Java Code Example :

This example source code gets the character gender from a String source using the charAt method. The format of the source string is AgeGenderName, thus our code get the Gender character and then gives an output interpreted from the gender character.

package com.javatutorialhq.tutorial;

/*
 * This java example source code shows the usage of String.charAt
 *
 */

public class StringCharAtDemo {

    public static void main(String[] args) {
        // initialize our source string
        String strVal = "16MDaniel Crieg";

        // Get a character at specified index
        char gender = strVal.charAt(2);

        // Test the the character element
        if(gender == 'M'){
            System.out.println("Male");
        }
        else if(gender == 'F'){
            System.out.println("Female");
        }
        else{
            System.out.println("Unknown");
        }
    }

}

 Sample Output :

Running the charAt() example source code will give you the following output

java string charAt method example

java string charAt method example

Exception Scenario :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15
	at java.lang.String.charAt(Unknown Source)
	at com.teknoscope.tutorial.StringCharAtDemo.main(StringCharAtDemo.java:16)

Suggested Reading List: