×

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1.

Syntax:

public char charAt (int index)

Parmeters

It accepts only one parameter that is the index of the character.

Returns

charAt() method returns char value present at the specified index in the string.

Throws:

The method throws IndexOutOfBoundsException if index is negative or greater than the length of the string.

Example 1:

public class CharAtEx1 {
    public static void main(String args[]) {
        String str = "Welcome to tutorialandexample ";
          char ch1 = str.charAt(0);
          char ch2 = str.charAt(3);
          char ch3 = str.charAt(5);
          char ch4 = str.charAt(8);
        char ch5 = str.charAt(15);
          char ch6 = str.charAt(17);
          System.out.println("Character at 0 index is: "+ch1);
          System.out.println("Character at 3rd index is: "+ch2);
          System.out.println("Character at 5th index is: "+ch3);
          System.out.println("Character at 8th index is: "+ch4);
        System.out.println("Character at 15th index is : "+ch5);
        System.out.println("Character at 17th index is : "+ch6);
    }
}

output :

Character at 0 index is: W
Character at 3rd index is: c
Character at 5th index is:
Character at 8th index is: t
Character at 15th index is : r
Character at 17th index is : a

Example 2 :- StringIndexOutOfBoundsException with charAt()

public class CharAtEx2
{
    public static void main(String args[])
    { 
String TE="tutorialandexample";
//returns the char value at the 19th index 
char c=TE.charAt(19);
System.out.println(c); 
    }
}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
19at java.lang.String.char
At(String.java:658)at CharAtEx1.main(CharAtEx1.java:7)

Example 3 :

public class CharAtEx3{
public static void main(String[] args) { 
        String str = "Welcome to tutorialandexample portal";         
        for (int i=0; i<=str.length()-1; i++) { 
            if(i%2!=0) { 
                System.out.println("Char at "+i+" place "+str.charAt(i)); 
            } 
        } 
    } 
}

Output:

Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place t
Char at 13 place t
Char at 15 place r
Char at 17 place a
Char at 19 place a
Char at 21 place d
Char at 23 place x
Char at 25 place m
Char at 27 place l
Char at 29 place
Char at 31 place o
Char at 33 place t
Char at 35 place l

Example 4:

public class CharAtEx4
{
public static void main(String[] args)
    {
        String str = "Welcome to tutorialandexample !";
        System.out.println("Here String is = " + str);
        // Get the character at positions 0 and 10.
        int index1 = str.charAt(5);
        int index2 = str.charAt(29);
        char ch = str.charAt(17);
        // Print out the results.
        System.out.println("The character at position 5 is " +
            (char)index1);       
        // Here returns the char value at the 29th index i.e. is empty space 
        System.out.println("The character at position 29 is " +
            (char)index2);
        System.out.println("The Character at 17th index is : "+ch);
    }
}

Output:

Here String is = Welcome to tutorialandexample !
The character at position 5 is m
The character at position 29 is
The Character at 17th index is : a

Example 5:

public class Freq_test {
public static void main(String[] args) {
          String str = "Tutorial times";
          int count;
          for(int i=0;i<str.length();i++)
          {
                   count = 0;
                   for(int j=0;j<str.length();j++)
                   {
                             if(str.charAt(i)==str.charAt(j))
                             {
                                      count++;
                             }                          
                   }
                   System.out.println(str.charAt(i)+" occurs "+count+" times");
          }
}
}

Output:

T occurs 1 times
u occurs 1 times
t occurs 2 times
o occurs 1 times
r occurs 1 times
i occurs 2 times
a occurs 1 times
l occurs 1 times
occurs 1 times
t occurs 2 times
i occurs 2 times
m occurs 1 times
e occurs 1 times
s occurs 1 times

Related Topics

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.