String charAt()

Let us understand charAt() method


This method returns the character at the specified index and Index starts from 0

Method signature

1
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

1
2
3
4
5
6
7
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()

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
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);  
}
}  


About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on