What is a charAt?
The java charAt() method of String class is used for getting a substring from the string.
public final class String extends Object implements Serializable, Comparable<String>, CharSequence, Constable, ConstantDesc
...
The String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Beginning with JDK 9, all of java.lang is part of the java.base module. The String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Java Platform, Standard Edition & Java Development Kit Version 16 API Specification |
Module java.base |
Package java.lang |
Class String |
Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete.
Syntax of String charAt() method
public char charAt(int index)
The java string charAt() method returns a char value at the given index number. The index value should lie between 0 and length()-1.
String charAt Example
package com.yuriyni.java.base.java.lang;
public class CharAtDemo {
public static void main(String[] args) {
String myStr = "Hello World";
char h0 = myStr.charAt(0);
char e1 = myStr.charAt(1);
char l2 = myStr.charAt(2);
char l3 = myStr.charAt(3);
char o4 = myStr.charAt(4);
char space5 = myStr.charAt(5);
char w6 = myStr.charAt(6);
char o7 = myStr.charAt(7);
char r8 = myStr.charAt(8);
char l9 = myStr.charAt(9);
char d10 = myStr.charAt(10);
//char whatWillBePrinted11 = myStr.charAt(11);
System.out.print(h0);
System.out.print(e1);
System.out.print(l2);
System.out.print(l3);
System.out.print(o4);
System.out.print(space5);
System.out.print(w6);
System.out.print(o7);
System.out.print(r8);
System.out.print(l9);
System.out.print(d10);
//System.out.print(whatWillBePrinted11);
}
}
Output
Hello World
charAt Exception
charAt method throws IndexOutOfBoundsException
– if the index
argument is negative or not less than the length of this string.
Here are some more examples of how String charAt can be used:
package com.yuriyni.java.base.java.lang;
public class CharAtDemo2 {
public static void main(String[] args) {
String myStr = "I Love Java";
//Returns the index within this string of the first occurrence of the specified character.
int index = myStr.indexOf("J");
//Returns the char value at the specified index.
char myChar = myStr.charAt(index);
System.out.print(myChar);
}
}
Output
J