charAt() Method in Java
The charAt() method returns characters at the specific index in a String. The indexing starts from 0 i.e. the first character’s index is 0 then 1 and so on. But the index of the last character is length() – 1.
Syntax of charAt() Method:
char charAt(int index)
Example of charAt() method in Java
Let us understand this method by implementing a simple example below. If we want to get the character at a specific position in a string:
Java
// Java program to demonstrate // charAt() method of String class import java.io.*; public class StringExample { public static void main(String []args) { String s = "Deepshikha" ; //String System.out.println(s.charAt( 3 )); // prints character at index 3 System.out.println(s.charAt( 6 )); // prints character at index 6 } } |
Output
p i
Explanation of the Program:
- We have a String, in which we have performed the implementation of charAt() method.
- The index is zero based, so the s.charAt(3) prints “p” and s.charAt(6) prints “i“.
Difference Between charAt() and substring() Method in Java
In Java, the charAt() method of the String class is used to extract the character from a string. It returns the character at the specified index in the String. The substring() method is used to extract some portion from the actual String and the actual string remains the same as it is. After that, the method returns a new string.
In this article, we will learn charAt() vs substring() methods in Java.
Contact Us