Mateusz Piotrowski Mateusz Piotrowski - 4 months ago 11
Java Question

What's the difference between string[i] and string.charAt(i) in Java?

I've encoutered an error while writing a line like this:

String string;
if (Character.isLetter(string[i])) {...}


Eclipse tells me that
The type of the expression must be an array type but it resolved to String
.

It does not raise the error if I use
string.charAt(i)
though.

My question is:
What is the difference between
string[i]
and
string.charAt(i)
in
Java
?
Are there any delicate aspects of using one or another?

I've tried to find a solution by myself, but I've encoutered
javascript
version of this problem only. (Example: Difference between str[0] and str.charAt(0))

Answer

This might clear things up for you:

public static void main(String[] args) {
  String str = "my name is Muneeb";
  String[] strarray = str.split(" "); //split on white space.

  for(int i=0; i<str.length(); i++){
     System.out.println(str.charAt(i));
  }

  for(int i=0; i<strarray.length; i++){
     System.out.println(strarray[i]);
  }
}

The first output will be:

m
y

n
a
m
e

i
s

M
u
n
e
e
b

The second output will be:

my
name
is
Muneeb