What is the use of charAt () method?

The Java String charAt[int index] method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and [length of string-1]. For example: s.charAt[0] would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException, if the index value passed in the charAt[] method is less than zero or greater than or equal to the length of the string [index=length[]].

Java String charAt[] Method example

Lets take an example to understand the use of charAt[] method. In this example we have a string and we are printing the 1st, 6th, 12th and 21st character of the string using charAt[] method.

public class CharAtExample {
   public static void main[String args[]] {
	String str = "Welcome to string handling tutorial";
	//This will return the first char of the string
	char ch1 = str.charAt[0];
		
	//This will return the 6th char of the string
	char ch2 = str.charAt[5];
		
	//This will return the 12th char of the string
	char ch3 = str.charAt[11];
		
	//This will return the 21st char of the string
	char ch4 = str.charAt[20];
		
	System.out.println["Character at 0 index is: "+ch1];
	System.out.println["Character at 5th index is: "+ch2];
	System.out.println["Character at 11th index is: "+ch3];
	System.out.println["Character at 20th index is: "+ch4];
   }
}

Output:

Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

IndexOutOfBoundsException while using charAt[] method

When we pass negative index or the index which is greater than length[]-1 then the charAt[] method throws IndexOutOfBoundsException. In the following example we are passing negative index in the charAt[] method, lets see what we get in the output.

public class JavaExample {
   public static void main[String args[]] {
	String str = "BeginnersBook";
	//negative index, method would throw exception
	char ch = str.charAt[-1];
	System.out.println[ch];
   }
}

Output:

Java String charAt[] example to print all characters of string

To print all the characters of a string, we are running a for loop from 0 to length of string – 1 and displaying the character at each iteration of the loop using the charAt[] method.

public class JavaExample {
   public static void main[String args[]] {
	String str = "BeginnersBook";
	for[int i=0; i

Chủ Đề