String Methods


🙋 Need help? Ask an expert now!

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.
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) {

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.

Edit Me on GitHub!

Application Question

Consider the following code segment:

String varOne = "Hello World!";

What is printed as a result of executing this code segment?