How to get a character from a string in Java?

How to get a character from a string in Java? Answer

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);
    }
}
How to get a character from a string in Java? Review:

In our experience, we suggest you solve this How to get a character from a string in Java? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the How to get a character from a string in Java?

Find on Educative

Conclusion:

I hope this How to get a character from a string in Java? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.