Tuesday, August 2, 2022

Java String charAt() Method With Examples

If you are trying to get characters by index with in a String in Java then charAt() method can be used.

Java String charAt() method

  • char charAt(int index)- You can get the character at a specified index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1. So the index ranges from 0 to length() - 1.

If the index argument is negative or not less than the length of this string then the IndexOutOfBoundsException is thrown.

Java String charAt() method examples

1. Getting character at specified index in the String.

public class StringCharAt {

 public static void main(String[] args) {
  String str = "Example String";
  
  System.out.println("Character at index 0 (First Character)- " + str.charAt(0));
  
  System.out.println("Character at index 3 (Fourth Character)- " + str.charAt(3));
  
  System.out.println("Last Character of the String- " + str.charAt(str.length()-1));
 }
}

Output

Character at index 0 (First Character)- E
Character at index 3 (Fourth Character)- m
Last Character of the String- g

2. Using charAt() method with an index that is out of range, resulting in IndexOutOfBoundsException.

public class StringCharAt {

 public static void main(String[] args) {
  String str = "Example String";
  //Out of range index
  System.out.println("char- " + str.charAt(18));
 }
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 18
 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
 at java.base/java.lang.String.charAt(String.java:702)
 at org.netjs.prgrm.StringCharAt.main(StringCharAt.java:8)

That's all for this topic Java String charAt() Method With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods
  2. String Pool in Java
  3. Why Java String is Immutable
  4. Find The First Repeated Character in a String Java Program
  5. Java String Interview Questions And Answers

You may also like-

  1. How to Pass Command Line Arguments in Eclipse
  2. Just In Time Compiler (JIT) in Java
  3. super Keyword in Java With Examples
  4. strictfp in Java
  5. Lambda Expressions in Java 8
  6. How to Inject Null And Empty String Values in Spring
  7. Spring Web MVC Tutorial
  8. Multiple Inheritance in Python

No comments:

Post a Comment