×

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

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

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.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Awesome explanation of Strings 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.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.