A Step-By-Step Guide to charAt in Java

The Java charAt() method returns a character at a specific index position in a string. The first character in a string has the index position 0. charAt() returns a single character. It does not return a range of characters.

When you’re working with strings in Java, you may want to find out what character is at a certain position in the string.

Get offers and scholarships from top coding schools illustrationGet offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

That’s where the charAt() method comes in. The Java charAt() method is used to find the character associated with a certain position in a string. It can also return multiple characters in a string.

For instance, say you’re writing a program that retrieves the locations associated with a US telephone area code. You may want to retrieve the first three characters of a string that contains a phone number.

This tutorial will discuss how to use charAt() in Java, with reference to examples/

Java String Refresher

Strings are an important data type in any programming language because they allow you to work with text-based data in your code. In Java, strings are enclosed in double quotation marks (“”). Here’s an example of declaring a string in Java:

String company = "Google";

The company variable that we defined above would have the following index values:

Google12345

The first letter ‘G’ would have an index of 0, while the letter ‘L’ has an index of 4.

Java charAt

The built-in Java string charAt() method returns a character at a particular index position in a string. The first character has the index value 0 and so on for subsequent characters in the string.

If you want to retrieve the first character in a string, or the ninth, for instance, you can use charAt(). The syntax for the charAt() method is as follows:

char = string_name.charAt(index)

charAt() accepts one parameter: the index position of the character you want to retrieve.

charAt Java Example

Say that we are operating a coffee shop. We are offering a 5% discount to all customers whose names begin with the letter G. This is part of a promotion intended to boost sales and get more people into the store.

We want to create a program that retrieves the first letter of a name given to a barista. We could do so using the following code:

public class GetFirstLetter {
	public static void main (String[] args) {
		String name = "GRAHAM HENDERSON";
		char letter = name.charAt(0);
		System.out.println("The first letter of " + name + "'s name is " + letter + ".");
	}
}

When we run our code, the program returns the following response:

The first letter of GRAHAM HENDERSON's name is G.

First, we create a class called GetFirstLetter, which stores our code. Then, we defined a Java variable called name. This string stores the name of our customer. In this case, our customer’s name was Graham Henderson. We decide to write customer names in capital letters to reduce the chance a name is misread.

On the next line, we define a variable called letter. We used the “char” data type because letter is only going to store one character.

We assign this variable the value name.charAt(0). This returns the first character in our string. In other words, we retrieve the character with the index value 0. In this case, the charAt() method returned the character G.

Then, we print out a message to the console that told us the character at the specified index, which in this case is 1.

Retrieve Another Character

If we wanted to retrieve the second character in the string, we could make the following change to our code:

…
String name = "GRAHAM HENDERSON";
		char letter = name.charAt(1);
		System.out.println("The second letter of " + name + "'s name is " + letter + ".");
…

We made two changes. First, we changed the index number in the charAt() int index method to 1, which represents the second character in our string. Second, we changed the print message to say The second letter of…, instead of The first letter of….

Our code returns: R. This is a new string. Our original string has not been changed.

As you can see, our code retrieved the second character in our string.

Java String charAt: Count Occurrence Example

One useful application of the charAt() method is in a count occurrence algorithm. Count occurrence algorithms count how many times a particular value appears within a string, list, or other iterable object.

Let’s go back to the coffee shop. Suppose that too many customers were claiming our discount because G is such a common first letter in a name. We decided to change our deal so that you can get 5% off your purchase only if your name contains more than two G’s.

Here’s the code we could use to calculate whether a customer is eligible for our discount:

class GetLetters {
	public static void main (String[] args) {
		String name = "GRAHAM HENDERSON";

		int counter = 0;

		for (int i = 0; i <= name.length() - 1; i++) {
if (name.charAt(i) == 'G') {
counter++; 
}
}
		System.out.println(name + "'s" + " name contains " + counter + "G.");
	}
}

When we run our code, the program returns the following response:

GRAHAM HENDERSON's name contains 1 G.

We first define a class called GetLetters, which stores the code for our program. Then, we define a variable called name which stores our customer’s name.

Venus profile photoVenus profile photo

“Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!”

Venus, Software Engineer at Rockbot

We defined a variable called counter which keeps track of how many instances of the letter G exist in our string. Then, we created a Java for loop that looks through each value in our name variable.

The name.length() -1 tells us that our loop will keep going until it has passed through every letter in the name string.

Next, we defined an if statement. This statement checks whether the character at index position i. This is the part of our for loop that increases every time the loop runs, is equal to G.

Note that this comparison is case-sensitive. If our names were recorded in lowercase, the statement name.charAt(i) == ‘G’ would never evaluate to true.

If the character at index position i is equal to G, our counter increases by 1. On the final line of our code, we directed the program to print out a message to the console. This message tells us how many times the character G appears in the customer’s name.

Conclusion

The Java charAt() method retrieves the character that exists at a particular index value within a string. For instance, we could use charAt() to retrieve the 10th character in a string, or the 15th.

This tutorial explored how to use the charAt() method in Java. We went through an example step-by-step of the charAt() method being used, and we also discussed how charAt() can be used with Java count occurrence algorithms.

You’re now ready to start using charAt() like an expert in Java! To learn more about Java, read our guide on How to Code in Java.

1 Ratings