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 the specified index 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:

https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!

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