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
You may also like-
No comments:
Post a Comment