Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Getting a Character by Index From a String in Java

$
0
0

1. Introduction

The charAt() method of the String class returns the character at a given position of a String. This is a useful method that has been available from version 1.0 of the Java language.

In this tutorial, we will explore the usage of this method with some examples. We'll also learn how to get the character at a position as a String.

2. The charAt() Method

Let's take a look at the method signature from the String class:

public char charAt(int index) {...}

This method returns the char at the index specified in the input parameter. The index ranges from 0 (the first character) to the total length of the string – 1 (the last character).

Now, let's see an example:

String sample = "abcdefg";
Assert.assertEquals('d', sample.charAt(3));

In this case, the result was the fourth character of the string – the character “d”.

3. Expected Exception

The runtime exception IndexOutOfBoundsException is thrown if the parameter index is negative or if it's equal to or greater than the length of the string:

String sample = "abcdefg";
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(sample.length()));

4. Get Character as a String

As we mentioned earlier, the charAt() method returns a char. Often, we need a String literal instead.

There are different ways to convert the result to a String. Let's assume below String literal for all the examples:

String sample = "abcdefg";

4.1. Using the Character.toString() Method

We can wrap the result of charAt() with Character.toString() method:

assertEquals("a", Character.toString(sample.charAt(0)));

4.2. Using the String.valueOf() Method

Finally, we can use the static method String.valueOf():

assertEquals("a", String.valueOf(sample.charAt(0)));

5. Conclusion

In this article, we learned how to use the charAt() method to get a character at a given position of a String. We also saw what exception could occur when using it and a few different ways of getting the character as a String.

And, as always, all the snippets can be found over on Github.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles