All Posts

Java charAt() method

Java charAt() method

The Java charAt() method is used to retrieve the character at a specified index from a String. This method is part of the String class, and it returns the character located at the given index of the string.

Syntax

The basic syntax of charAt() is as follows:

public char charAt(int index)

index – The index of the character you want to retrieve. The index starts from zero. The first character is at index 0, the second character is at index 1, and so on.

Example

This method returns the character located at the String’s specified index. The string indexes start from zero. Let’s demonstrate the use of the charAt() method with an example.

package com.testingdocs.programs;

public class CharAtDemo {

	public static void main(String args[]) {
		String str ="www.TestingDocs.com";
		int index = 7;
		char result= str.charAt(index);
		
		System.out.println("The String is : " + str);
		System.out.println("The character at " + index + " is : "+ result);
	}
}

Program Output

The program produces the following output:

The String is : www.TestingDocs.com

The character at 7 is : t

 

Java charAt method

Java Tutorials

Java Tutorial on this website: