Sunday, January 19, 2025
HomeTechJava - Get string character by index

Java – Get string character by index

In Java, you can get a character from a string at a specific index using the charAt(int index) method provided by the String class. Here’s how it works:

Syntax

char charAtIndex = stringVariable.charAt(index);
  • stringVariable: The string you want to extract the character from.
  • index: The position of the character in the string (zero-based).

Example

public class Main {
    public static void main(String[] args) {
        String text = "Hello, World!";
        
        // Get the character at index 7
        char character = text.charAt(7);
        
        // Print the result
        System.out.println("Character at index 7: " + character); // Output: W
    }
}

Important Notes

  1. Index is Zero-Based:
    • The first character has an index of 0.
    • The last character has an index of string.length() - 1.
  2. Throws StringIndexOutOfBoundsException:
    • If the index is negative or greater than or equal to the string’s length, Java will throw this exception.
    • Example:
      String text = "Hello";
      char character = text.charAt(10); // Throws StringIndexOutOfBoundsException
      
  3. Iterating Through Characters:
    • You can iterate through all characters in a string using a for loop:
      public class Main {
          public static void main(String[] args) {
              String text = "Hello";
              
              for (int i = 0; i < text.length(); i++) {
                  System.out.println("Character at index " + i + ": " + text.charAt(i));
              }
          }
      }
      

If You Need a Substring

If you need more than one character, use the substring() method:

String text = "Hello, World!";
String substring = text.substring(7, 12); // "World"

Let me know if you have any additional questions!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x