Java 8 – How to get a specific character from String ?

In this article, we will discuss and learn how to get a specific character from String in Java 1.8 version

Already in one of the previous article, we discussed how to get a character from a String using earlier versions of Java like 5 or 7, etc.

Get a specific character from String:

  • charAt(index) method of String
    • Retrieves a character at the specified index-position from the String
    • If specified index-position is within the range i.e., 0 <= index <= (str.length -1) then it retrieves a character
    • Otherwise, java.lang.StringIndexOutOfBoundsException is thrown for out-of-index character

package in.bench.resources.java8.string.methods;


public class GetACharacterFromString {

	public static void main(String[] args) {

		// string
		String str = "BenchResources.Net";

		// 1. get character at 5th index-position
		char ch1 = Stream.of(str).map(s -> s.charAt(5)).findFirst().get();
		System.out.println("char at 5th index-position is = " + ch1);

		// 2. get character at 15th index-position
		char ch2 = Stream.of(str).map(s -> s.charAt(15)).findFirst().get();
		System.out.println("char at 15th index-position is = " + ch2 + "\n\n");

		// 3. exception - out of index
		char chEx = Stream.of(str).map(s -> s.charAt(18)).findFirst().get();
		System.out.println("char at 18th index-position is = " + chEx);


char at 5th index-position is = R
char at 15th index-position is = N

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 18
	at java.base/java.lang.StringLatin1.charAt(
	at java.base/java.lang.String.charAt(
	at in.bench.resources.java8.string.methods.GetACharacterFromString
	at java.base/$3$1.accept(
	at java.base/$StreamBuilderImpl.tryAdvance(
	at java.base/
	at java.base/
	at java.base/
	at java.base/
	at java.base/$FindOp.evaluateSequential(
	at java.base/
	at java.base/
	at in.bench.resources.java8.string.methods.GetACharacterFromString

Related Articles:


Happy Coding !!
Happy Learning !!

Java 8 – How to check whether particular word/letter is present in the String ?
Java 8 – How to Sort String List by its length ?