How to get the first character of a string in Java

Learn how to get the first character of a string in Java. There are 3 ways to achieve our goal:
1. Using charAt() [Recommended]
2. Using substring()
3. Converting String to a Char Array

Read Also: Print Quotation Marks in Java

Let's dive deep into the topic:

1. Using charAt()

We can directly get the first character of the String using String's class charAt() method. This method helps in getting the specific single character at the specified index number as shown below in the code example.

public class FirstCharacterOne {
    public static void main(String args[]) {
      String givenString = "BeinPresent";
      /*charAt() returns specific single character at the
        specified index number.*/
      char firstCharacter = givenString.charAt(0);
      System.out.println(" first character is "+ firstCharacter);
    }
}


Output:
first character is B

2. Using substring()

In the below code example, the first character of the givenString is 'A'. We will use String's class substring() method to get the first character of a string in Java. substring() method accepts two parameters beginIndex and endIndex. Remember that it will return a substring of a givenString.  The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

public class FirstCharacterTwo {
    public static void main(String args[]) {
      String givenString = "AliveisAwesome";
      /*substring() takes two parameters beginIndex and endIndex,
      beginIndex is inclusive while endIndex is excluded*/
      String firstCharacter = givenString.substring(0,1);
      char[] charArray = firstCharacter.toCharArray();
      System.out.println(" first character is "+charArray[0]);
    }
}


Output:
first character is A

3. Using toCharArray()

Another way to get the first character of a string in Java is toCharArray() method. First, we need to convert the givenString into char[]. We can get the first character by passing index 0 in the char[] as shown below in the code example:

public class FirstCharacterThree {
    public static void main(String args[]) {
      String givenString = "LoveYourself";
      char[] charArray = givenString.toCharArray();
      System.out.println(" first character is "+ charArray[0]);
    }
}


Output:
first character is L

That's all for today. Please mention in the comments in case you have any questions related to how to get the first character of a string in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry