beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java String charAt() Method example

By Chaitanya Singh | Filed Under: String handling

The Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1). For example: s.charAt(0) would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException, if the index value passed in the charAt() method is less than zero or greater than or equal to the length of the string (index<0|| index>=length()).

Java String charAt() Method example

Lets take an example to understand the use of charAt() method. In this example we have a string and we are printing the 1st, 6th, 12th and 21st character of the string using charAt() method.

public class CharAtExample {
   public static void main(String args[]) {
	String str = "Welcome to string handling tutorial";
	//This will return the first char of the string
	char ch1 = str.charAt(0);
		
	//This will return the 6th char of the string
	char ch2 = str.charAt(5);
		
	//This will return the 12th char of the string
	char ch3 = str.charAt(11);
		
	//This will return the 21st char of the string
	char ch4 = str.charAt(20);
		
	System.out.println("Character at 0 index is: "+ch1);
	System.out.println("Character at 5th index is: "+ch2);
	System.out.println("Character at 11th index is: "+ch3);
	System.out.println("Character at 20th index is: "+ch4);
   }
}

Output:

Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

IndexOutOfBoundsException while using charAt() method

When we pass negative index or the index which is greater than length()-1 then the charAt() method throws IndexOutOfBoundsException. In the following example we are passing negative index in the charAt() method, lets see what we get in the output.

public class JavaExample {
   public static void main(String args[]) {
	String str = "BeginnersBook";
	//negative index, method would throw exception
	char ch = str.charAt(-1);
	System.out.println(ch);
   }
}

Output:
Java String charAt method

Java String charAt() example to print all characters of string

To print all the characters of a string, we are running a for loop from 0 to length of string – 1 and displaying the character at each iteration of the loop using the charAt() method.

public class JavaExample {
   public static void main(String args[]) {
	String str = "BeginnersBook";
	for(int i=0; i<=str.length()-1; i++) {
		System.out.println(str.charAt(i));
	}
   }
}

Output:

B
e
g
i
n
n
e
r
s
B
o
o
k

Java String charAt() example to count the occurrence of a character

In this example, we will use the charAt() method to count the occurrence of a particular character in the given string. Here we have a string and we are counting the occurrence of character ‘B’ in the string.

public class JavaExample {
   public static void main(String[] args) {  
        String str = "BeginnersBook"; 
        
        //initialized the counter to 0
        int counter = 0;  
        
        for (int i=0; i<=str.length()-1; i++) {  
            if(str.charAt(i) == 'B') { 
            	//increasing the counter value at each occurrence of 'B'
                counter++;  
            }  
        }  
        System.out.println("Char 'B' occurred "+counter+" times in the string");  
   }  
}

Output:
Java String charAt() example

Reference

String charAt() javadoc

❮ PreviousNext ❯

Comments

  1. Randon says

    January 6, 2017 at 6:49 AM

    Could u please explain a function to retrieve the first letter from a group of word in java

    Reply
    • Vladimir says

      November 3, 2018 at 5:29 AM

      yourString.charAt(0);

      A group of words is simply a string with a couple of blank space characters. The index 0 of the String is your first letter.

      Reply
    • Amir says

      November 7, 2018 at 3:42 PM

      String s=”hello”;
      char c = s.chartAt(0); // first letter of a word.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorials

  • Learn Java
  • OOPs Concepts
  • Java Collections

Java String

  • Java String

Java String Methods

  • String charAt()
  • String compareTo()
  • String compareToIgnoreCase()
  • String contains()
  • String concat()
  • substring
  • String valueOf()
  • String startsWith()
  • String equals()
  • String format()
  • String endsWith()
  • String indexOf()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String split()
  • String trim()
  • String intern()
  • String isEmpty()
  • String matches()
  • String regionMatches()
  • String contentEquals()
  • String toCharArray()
  • String getBytes()
  • String join()
  • String getChars()
  • String copyValueOf()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap