string.charAt()

string.charAt() Returns the character present at the input position of the string.
Syntax
string.charAt(input)
input is an integer staring from 0 ( first position )

Here are some examples with output.
String my_str="Welcome to plus2net";
System.out.println(my_str.charAt(0)); // W
System.out.println(my_str.charAt(3)); // c
System.out.println(my_str.charAt(15)); // 2
Note that first position of the string starts from 0. So what happens if we give negative integer as input or any position more than the length of the string?

That will raise exception.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Examples by using charAt()

We will display a strting by using each char in a line. We are using one for loop here.
String my_str="plus2net";
for(int i=0;i<my_str.length();i++) {
	System.out.println(my_str.charAt(i));
}
Output
p
l
u
s
2
n
e
t
Note : length() method returns length or total number of chars present in the string.

How to print string in reverse order?
String my_str="plus2net";
for(int i=my_str.length()-1;i>=0;i--) {
	System.out.print(my_str.charAt(i));
}
Output
ten2sulp


All String functions

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer