String charAt() Method

      No Comments on String charAt() Method




When is String charAt() Method Used??

String charAt() Method is used to get the char value at a specified index.
The index starts from 0 to (length of string -1) .

The below demo program explains how to use charAt() method on Strings.

package com.masterjavatutorial;
public class Test {

	public static void main(String[] args) {
		String str = "HelloWorld";
		for(int i=0;i<str.length();i++){
			System.out.println("Character at index "+i+" in HelloWorld = "+str.charAt(i));
		}
		
	}

}

Output of the above program is as below:

Character at index 0 in HelloWorld = H
Character at index 1 in HelloWorld = e
Character at index 2 in HelloWorld = l
Character at index 3 in HelloWorld = l
Character at index 4 in HelloWorld = o
Character at index 5 in HelloWorld = W
Character at index 6 in HelloWorld = o
Character at index 7 in HelloWorld = r
Character at index 8 in HelloWorld = l
Character at index 9 in HelloWorld = d

When the index in charAt() is more than the length of String

When the index passed in charAt() as an argument to get char at that index is more than the length of String, then in that case it would throw StringIndexOutOfBoundsException.

The below demo program explains this situation:

package com.masterjavatutorial;
public class Test {

	public static void main(String[] args) {
	    String str = "HelloWorld";
            System.out.println(str.charAt(20)); 		
	}

}

The above program should throw exception as the index is more than the length of String. The output of the above program is as below:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
	at java.lang.String.charAt(String.java:658)
	at com.masterjavatutorial.Test.main(Test.java:7)






Leave a Reply