1

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?

Shashank Setty
  • 138
  • 1
  • 9
  • 2
    With [charAt()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#charAt-int-). Read the [tutorial](https://docs.oracle.com/javase/tutorial/) too, unless you intend to guess how the language works, instead of studying how it works. – Kayaman Dec 09 '19 at 10:15
  • *String* is a character array, to access a specific index you need to use `inputString.charAt(2)` – Nicholas K Dec 09 '19 at 10:16
  • Does this answer your question? [Get string character by index - Java](https://stackoverflow.com/questions/11229986/get-string-character-by-index-java) – OAM Dec 09 '19 at 10:24

2 Answers2

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You cannot get a character at a given index as you would do for a an array because String isn't an array per say. It is a class.

The method charAt is what you are looking for:

input.charAt(2)

The signature of the method is the following:

public char charAt(int index);

And the javadoc says:

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned.

D. Lawrence
  • 943
  • 1
  • 10
  • 23