Popular Tutorials
Start Learning JavaCreated with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Java String Methods
- Java String split()
- Java String compareTo()
- Java String compareToIgnoreCase()
- Java String length()
- Java String replace()
- Java String replaceAll()
- Java String substring()
- Java String equals()
- Java String equalsIgnoreCase()
- Java String contains()
- Java String indexOf()
- Java String trim()
- Java String charAt()
- Java String toLowerCase()
- Java String concat()
- Java String valueOf()
- Java String matches()
- Java String startsWith()
- Java String endsWith()
- Java String isEmpty()
- Java String intern()
- Java String getBytes()
- Java String contentEquals()
- Java String hashCode()
- Java String join()
- Java String replaceFirst()
- Java String subSequence()
- Java String toCharArray()
- Java String format()
Java String charAt()
The charAt() method returns the character at the specified index.
Example
class Main {
public static void main(String[] args) {
String str1 = "Java Programming";
// returns character at index 2
System.out.println(str1.charAt(2));
}
}
// Output: v
Syntax of charAt()
The syntax of the string charAt() method is:
string.charAt(int index)
Here, string is an object of the String class.
charAt() Parameters
- index - the index of the character (an
intvalue)
charAt() Return Value
- returns the character at the specified
index
Note: If the index passed to chartAt() is negative or out of bounds, it throws an exception.
Example: Java String charAt()
class Main {
public static void main(String[] args) {
String str1 = "Learn Java";
String str2 = "Learn\nJava";
// first character
System.out.println(str1.charAt(0)); // 'L'
// seventh character
System.out.println(str1.charAt(6)); // 'J'
// sixth character
System.out.println(str2.charAt(5)); // '\n'
}
}
In Java, the index of Strings starts from 0, not 1. That's why chartAt(0) returns the first character. Similarly, charAt(5) and charAt(6) return the sixth and seventh character respectively.
If you need to find the index of the first occurrence of the specified character, use the Java String indexOf() method.
Did you find this article helpful?
