Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
CharAt
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Now that we have explored the concept of index in Java, let's see the index related functions that exist in the String class. The charAt method returns a single character from a specified index. The syntax is as follows, stringname.charAt(any integer) and the return value is a single character char, not a String. In a case where the index is negative or greater than stringname.length()-1, you will receive a runtime error. Let's see a few examples of the charAt method.
CharAtMethodExample.java
package exlcode;
public class CharAtMethodExample {
public static String exampleVariableOne = "Hello World!";
// returns the character at a specific index
// and assigns it to char variables
public static char exampleVariableTwo = exampleVariableOne.charAt(0);
public static char exampleVariableThree = exampleVariableOne.charAt(11);
public static char exampleVariableFour = exampleVariableOne.charAt(6);
public static void main(String[] args) {
System.out.println(exampleVariableTwo);
System.out.println(exampleVariableThree);
System.out.println(exampleVariableFour);
}
}
The index for the first character of a String has an index of zero, meaning 'H' is printed when the statement exampleVariableOne.charAt(0); is called. If you point at an index where there is a space, the charAt() method will return a character containing ' '. This method, along with indexOf() method are extremely useful when working with strings.