1

I can do this:

char n[] = {'a', 'b', 'c', 'd', 'e'};
for (char n2: n)
{
    System.out.println(n2);
}

But why not this:

String n = "abcde";
for (char n2: n)
{
   System.out.println(n2);
}

I get this error when I try to print characters of string object using the for-each loop: enter image description here

How can I fix it? Any help is appreciated. Thanks!

  • *for-each* only allows us to iterate over arrays or instances implementing `Iterable` interface. String is none of those but you could use `yourString.toCharArray()` and get `char[]` array filled with characters from your string. – Pshemo Jun 15 '21 at 17:34
  • 1
    Does this answer your question? [How do I apply the for-each loop to every character in a String?](https://stackoverflow.com/questions/2451650/how-do-i-apply-the-for-each-loop-to-every-character-in-a-string) – csalmhof Jun 15 '21 at 17:38

1 Answers1

2

You can get char array from string and iterate in the way doing for char[] in earlier scenario. Below is the code sample:

public class Main {

public static void main(String[] args) {
    String abc = "Fida";
    //Invoke String class toCharArray() method on string object
    for (char a : abc.toCharArray()) {
        System.out.println(a);

    }

}

}

Atul Kumar
  • 99
  • 8