BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String charAt() Method example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

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 ❯

Top Related Articles:

  1. Java StringBuffer ensureCapacity()
  2. Java StringBuilder capacity() Method
  3. Java String indexOf() Method
  4. Java StringBuilder offsetByCodePoints()
  5. Java String startsWith() Method with examples

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

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 Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap