Java: StringBuilder charAt() method

In this article, we will discuss StringBuilder’s charAt() method which returns character at a specified index-position

 

charAt(int index) method:

  • This method returns single character at the specified index-position

Method Signature:

public char charAt(int index);

Returns:

  • Return char-value at the specified index-position from the invoking StringBuilder object

Throws:

IndexOutOfBoundsException is thrown, if the input index value is out of range i.e.;

  • Index-position is negative (<0)
  • Index-position is greater than StringBuilder length()

 

Examples on charAt() method:

  • To get char-value at specified index-position from the invoking StringBuilder

StringBuilderCharAtMethod.java

package in.bench.resources.stringbuilder.methods;

public class StringBuilderCharAtMethod {

	public static void main(String[] args) {

		// StringBuilder
		StringBuilder sb = new StringBuilder("Google.com");

		// return character value at 3th index position
		char charAt1 = sb.charAt(3); 

		// print to console
		System.out.println("1. StringBuilder character at"
				+ " 3th index position is : "
				+ charAt1);


		// return character value at 9th index position
		char charAt2 = sb.charAt(9); 

		// print to console
		System.out.println("2. StringBuilder character at"
				+ " 9th index position is : "
				+ charAt2);

		// return character value at 0th index position
		char charAt3 = sb.charAt(0); 

		// print to console
		System.out.println("3. StringBuilder character at"
				+ " 0th index position is : "
				+ charAt3);
	}
}

Output:

1. StringBuilder character at 3th index position is : g
2. StringBuilder character at 9th index position is : m
3. StringBuilder character at 0th index position is : G

 

References:

 

Happy Coding !!
Happy Learning !!

Java: StringBuilder delete() method
Java: StringBuilder capacity() method