In this tutorial, we will discuss the Java StringBuilder charAt() method with the help of examples.
The syntax of charAt() method is:
sb.charAt()
Here, sb
is an object of StringBuilder
class.
charAt() Description
public char charAt(int index): This method returns the character present at the specified index. The first char of StringBuilder
is at index 0, second one is at index 1 and so on.
charAt() Parameters
The charAt() method of Java StringBuilder class takes a single parameter:
- index: The character present at this index is returned by the
charAt()
method
The index argument must be greater than or equal to 0, and less than the length of the sequence, otherwise it would throw IndexOutOfBoundsException
charAt() Return Value
Returns the character present at the index that we pass as an argument to the charAt()
method.
Example 1: Printing all characters of a StringBuilder
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("TEST STRING"); System.out.println("String is: "+sb); for(int i=0; i<sb.length(); i++){ System.out.println("Character at index "+i+ " is: "+sb.charAt(i)); } } }
Output:
Example 2: When negative index is passed
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); //negative index in charAt() System.out.println(sb.charAt(-5)); } }
Output:
Example 3: When index is equal or greater than the length
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("Text"); //The string 'Text' has index from 0 to 3 //so no char at the index 4 System.out.println(sb.charAt(4)); } }
Output:
Example 4: Characters at specified index
class JavaExample{ public static void main(String[] args) { StringBuilder sb = new StringBuilder("BeginnersBook"); System.out.println("Char at index 0: "+sb.charAt(0)); System.out.println("Char at index 5: "+sb.charAt(5)); System.out.println("Char at index 12: "+sb.charAt(12)); } }
Output:
Recommended Posts:
Leave a Reply