×

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

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.