String charAt()
Let us understand charAt() method
This method returns the character at the specified index and Index starts from 0
Method signature
- public char charAt(int index)
public char charAt(int index)
This method throws StringIndexOutOfBoundsException exception
When, index
is either negative or greater than or equal to the size of the string
Example
- public class CharAtExample1{
- public static void main(String args[]){
- String str="javainsimpleway";
- char ch=str.charAt(6);//returns the char value at the 6th index
- System.out.println(ch);
- }
- }
public class CharAtExample1{ public static void main(String args[]){ String str="javainsimpleway"; char ch=str.charAt(6);//returns the char value at the 6th index System.out.println(ch); } }
Example : When size of the String is greater than chatAt()
- public class CharAtExample2{
- public static void main(String args[]){
- String str=" javainsimpleway ";
- char ch=str.charAt(20);//trying to return the char value at the 20th index
- System.out.println(ch);
- }
- }
public class CharAtExample2{ public static void main(String args[]){ String str=" javainsimpleway "; char ch=str.charAt(20);//trying to return the char value at the 20th index System.out.println(ch); } }
Example : When the index value is Negative
- public class CharAtExample3{
- public static void main(String args[]){
- String str=" javainsimpleway ";
- char ch=str.charAt(-1);//specified negative index
- System.out.println(ch);
- }
- }
public class CharAtExample3{ public static void main(String args[]){ String str=" javainsimpleway "; char ch=str.charAt(-1);//specified negative index System.out.println(ch); } }