Get character at specific position in a String

charAt(int position) method of String Class can be used to get the character at specific position in a String.

Return type of charAt(int position) is char.

Index or position is counted from 0 to length-1 characters. i.e 0 th index is taken as first character and last character is length-1.

Example 1(find the second character in String)

class StringTest{

public static void main(String args[]){

String str=new String("abcd123");

char secondchar=str.charAt(1);

System.out.println("The second character of String str is "+secondchar);

}

}

Output

The second character of String str is b


Example 2(printing characters one by one)

class StringTest{

public static void main(String args[]){

String str=new String("abcd123");

System.out.println("Printing characters one by one");

for(int i=0;i<7;i++){

System.out.println(str.charAt(i));

}

}

}

Output

Printing characters one by one

a

b

c

d

1

2

3


Example 3(checking vowels in a String character by character)

class StringTest{

public static void main(String args[]){

String str=new String("abcd123");

System.out.println("Checking vowels in a String character by character");

for(int i=0;i<7;i++){

char temp=str.charAt(i);

if(temp=='a'||temp=='e'||temp=='i'||temp=='o'||temp=='u'){

System.out.println(i+1+" character is a vowel");

}

else{

System.out.println(i+1+" character is not a vowel");

}

}

}

}

Output

Checking vowels in a String character by character

1 character is a vowel

2 character is not a vowel

3 character is not a vowel

4 character is not a vowel

5 character is not a vowel

6 character is not a vowel

7 character is not a vowel