Search code examples
javachar

Is it possible to get only the first character of a String?


I have a for loop in Java.

for (Legform ld : data)
{
    System.out.println(ld.getSymbol());
}

The output of the above for loop is

Pad

CaD

CaD

CaD

Now my question is it possible to get only the first characer of the string instead of the whole thing Pad or CaD

For example if it's Pad I need only the first letter, that is P
For example if it's CaD I need only the first letter, that is C

Is this possible?


Solution

  • String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

    So, assuming getSymbol() returns a String, to print the first character, you could do:

    System.out.println(ld.getSymbol().charAt(0)); // char at index 0