Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example

What Is the Java String.charAt() Method?

The String.charAt() method returns the character at a specific index within a string. In Java, string indices are zero‑based, ranging from 0 to length() - 1.

Method Signature

public char charAt(int index)

Parameter

index – a single int value specifying the position of the desired character.

Return Value

Returns the character (type char) located at the given index.

Exceptions

Throws StringIndexOutOfBoundsException if index is negative or greater than or equal to the string’s length.

Practical Example

public class CharAtExample {
    public static void main(String[] args) {
        String s = "This is String CharAt Method";
        // Character at index 0
        System.out.println("Character at 0 position is: " + s.charAt(0));
        // Character at index 5
        System.out.println("Character at 5th position is: " + s.charAt(5));
        // Character at index 22
        System.out.println("Character at 22nd position is: " + s.charAt(22));
        // Attempt to access an invalid index
        char invalid = s.charAt(-1);
        System.out.println("Character at -1 position is: " + invalid);
    }
}

Output:

Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Key points to remember:

Java

  1. Encapsulation in Java: A Comprehensive Guide with Practical Example
  2. Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
  3. Java String length() Method: How to Get a String’s Size (Example)
  4. Mastering Java String.indexOf(): Locating Substrings & Practical Examples
  5. Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
  6. Java String.contains() Method: How to Check for Substrings – Practical Examples
  7. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  8. Polymorphism in Java: A Comprehensive Guide with Practical Examples
  9. Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
  10. Mastering Java's split() Method: A Practical Guide with Code Examples