Java String.charAt(int index) with an example

Strings are objects. Everything in Java is an object so a string. String in Java is a class that is used to operate with strings and is available in java.lang package.

The string class has many methods and one of them is charAt(). This method has one parameter which is an index and is used for getting a character at that index.

We all know that in programming, the index starts with 0.

Let’s take an example:

Suppose we have created a class. Now in the main method initialize a variable with string data type and assign a string value to that. With the help of the charAt() method, we can get the character at that index location.

Algorithm:

import java.lang package for using String methods.

import java.lang.*;

create a class and main method inside the same class.

public class CharacterString{
    public static void main(String[] args){
    }
}

Now inside the main method initialize a string and assign something to that string.

public static void main(String[] args){
    String my_name = "Tineshwar Sanu";
    System.out.println("Character at index 3:"+myname.charAt(3));
    System.out.println("Character at index 4:"+myname.charAt(4));
}
Output:
e
s

Similarly, let’s take another example:

public class practice{
    public static void main(String[] args){
        String myname = "Tina";
        System.out.println("character at 1 index:"+myname.charAt(1));
    }
}

We all know that in programming index starts with zero and ends with a length of that character -1, so if put something big index then it will throw an error ‘IndexOutOfBound’ exception. So we need to take care of that as well.

That’s all for this. Thank you.

Leave a Reply

Your email address will not be published.