Java String charAt() Method

Java String Char() Method

What is String?

In Java, an string class is a series of characters that are interpreted literally by a script. The string can be either only letters or be letters and numbers in most programming languages.

Strings in Java are immutable, which means that once you create a string object, its value cannot be changed.you can create new strings by concatenating existing strings or by creating a new string that is a substring of an existing string.

To know more about String Class in java read the complete article.

 

String charAt() Method:

The charAt() method in Java is a method of the String class and is used to retrieve the character at a specified index in a string.

Note:StringIndexOutOfBoundsException is given when the given specified index number is equal to this string length or the specified given index number is greater, or it is a negative number.  The first char value is at index 0

Index:

The index of the character to return is represented by an integer.

Throws:

 if the given index number is greater than or equal to this string length or a negative number. 

Returns:

 The index of the character to return is an integer. 

Syntax:

 public char charAt(int index)

Let’s look at a string-related Java program where the charAt() method is used to perform an operation on the given string.

Examples : Return the Sixth character (6) of a string

Run
public class Main {
  public static void main(String[] args) {
    String myStr = "Hello PrepInsta";
// returns character at index 6
    char result = myStr.charAt(6);
    System.out.println(result);
  }
}

Output

P

Examples : Return the Fifteenth character (15) of a string

Run

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello PrepInsta";
// returns character at index 15
    char result = myStr.charAt(15);
    System.out.println(result);
  }
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 15
at java.lang.String.charAt(String.java:658)
at Main.main(Main.java:4)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription