Java – StringBuffer charAt() method

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

1. String’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 StringBuffer 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 StringBuffer length()

2. Examples on charAt() method:

  • To get char-value at specified index from invoking StringBuffer

StringBufferCharAtMethod.java

package in.bench.resources.stringbuffer.methods;

public class StringBufferCharAtMethod {

	public static void main(String[] args) {

		// StringBuffer
		StringBuffer sb = new StringBuffer("BenchResources.Net");

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

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

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

		// print to console
		System.out.println("2. StringBuffer character "
				+ "at 15th index-position is : " + charAt2);
	}
}

Output:

1. StringBuffer character at 5th index-position is  : R
2. StringBuffer character at 15th index-position is : N

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - StringBuffer delete() method
Java - StringBuffer capacity() method