Tutorials

Java String Methods


String charAt() method


In java, charAt( ) method returns the character present at the provided index within the given String.

 

Index of the String starts from 0.

For example, in Sun:

S is at index 0, u is at index 1 and n is at index 2.

 charAt in java String by tutorialsinhand.com

 

If you enter index greater than the length of the String or negative index then the program will throw StringIndexOutOfBoundException

 

Example of charAt()

Given below is the simple java program to find the character present at provided index. 


package string;

public class charAtDemo {

      public static void main(String[] args) {

            int index = 2;
            String str = "Sunrise";  //index starts from 0

            char ch = str.charAt(index);
            System.out.println("Character at index: "+ ch);
      }

}

OUTPUT

Character at index: n

 

 

Similarly you can also check for character at other index as well. Samples are shown below:

  • If you provide value of index as 0, then output will be → Character at index: S
  • If you provide value of index as 5, then output will be → Character at index: s
  • If you provide value of index as 6, then output will be → Character at index: e
  • If you provide value of index as greater than 6 (String length), then output will be → Character at index: StringIndexOutOfBoundException
 

To verify the above output, we request you to replace the value index from 2 to any of the above values and run the program.

 

 Write a java program to print the character at each index of the given String.

Given below is the java program that prints character at each index. 

Here we have used for loop to iterate over the String and print chararacter at each index while traversal.

package string;

public class charAtDemo {

	public static void main(String[] args) {

		String str = "Sunrise";  //index starts from 0

		for(int i=0; i<str.length(); i++){
			char ch = str.charAt(i);
			System.out.println("Character at index: "+ i +" is: "+ ch);
		}
	}

}

OUTPUT

Character at index: 0 is: S
Character at index: 1 is: u
Character at index: 2 is: n
Character at index: 3 is: r
Character at index: 4 is: i
Character at index: 5 is: s
Character at index: 6 is: e
 
Practice programs:
  1. Write a java program to print the characters at odd index.
  2. Write a java program to print the character at the middle index.
  3. Write a java program to print the char at each index using while loop.


Please Share this page
Views : 133
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!