Java – StringBuilder charAt() method

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

1. StringBuilder’s charAt(int index) method :

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

1.1 Method Signature:

public char charAt(int index);

1.2 Returns:

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

1.3 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()

2. Examples on StringBuilder.charAt() method :

  • To get charvalue at specified indexposition 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

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java - StringBuilder delete() method
Java - StringBuilder capacity() method