0

In python, you can do this:

for item in [a, b, c, d]:
    some-code

Is something similar possible in java, where you declare the array in the for loop condition area?

My gut reaction is to do this:

public static void main(String[] args) {
    for (String string : String myArr[] = {a, b, c, d}) {
        some-code
    }
}

But that does not work

Note: I did a preliminary search before asking, the similar-seeming question I found (Initializing an array in Java using the 'advanced' for each loop [duplicate]) is different.

Dpmon
  • 13
  • 1
  • 1
    `for (String string : new String[] {"a", "b", "c", "d"}) {...}`? – Johannes Kuhn Apr 05 '20 at 17:54
  • See also: [How to initialize an array in Java?](https://stackoverflow.com/questions/1938101/how-to-initialize-an-array-in-java) and [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – Mark Rotteveel Apr 05 '20 at 17:58

1 Answers1

1

Well, you learn something new everyday. Apparently you can initialize an array but you must define the type and not just use an array initializer.

This works

        for (String string : new String[] { "a", "b", "c" }) {
            //code
        }

This doesn't work because it's unaware of type.

        for (String string : { "a", "b", "c" }) {
            //code
        }
Jason
  • 4,590
  • 2
  • 9
  • 18
  • Thanks so much! Also, is it possible to create an array of other arrays like this? Let's say you have the other arrays' data ready, then is it possible to define the 2D array with syntax like this? – Dpmon Apr 05 '20 at 18:02
  • "This doesn't work because it's unaware of type." No, this doesn't work because the array initializer syntax only works in the initializer of a variable declaration. – Andy Turner Apr 05 '20 at 18:42
  • (As in: `String[] arr; arr = {};` doesn't work either, despite there being as much information about what type of array to create as `String[] arr = {}`). – Andy Turner Apr 05 '20 at 18:58