Search code examples
javastringsubstringsyntax-errorassign

How do I access a specific index in a String in java?


here's a sample code I wrote,

public static void main(String []args){
        String inputString = "apple";
        char a = inputString[2]; //one
        System.out.println(inputString[2]); //two
    }

both one and two gives me an error saying Array type expected; found: 'java.lang.String' what am I doing wrong? how do I access a specific index in a String?


Solution

  • You are trying to access the String's characters as if it was an array of characters. You should use the charAt method instead:

    char a = inputString.charAt(2);
    

    In order for array access to work, you should first obtain the array of characters of the given String:

    char[] chars = inputString.toCharArray();
    char a = chars[2];
    

    This is useful when iterating over the characters of the String.