-1
public class ClassSET12 {
    public static void main(String[] args) {
        int a[] = { 1, 2, 3, 4, 5 };
        int b[] = { 6, 7, 8, 9, 10 };
        int c[] = alternativeIndicesElements(a, b);
        for (int d : c)
            System.out.println(d);
    }

    public static int[] alternativeIndicesElements(int[] a, int[] b) {
        int c[] = new int[a.length];
        if (a.length == b.length)
            for (int i = 0; i < a.length; i++)
                if (i % 2 == 0)
                    c[i] = b[i];
                else
                    c[i] = a[i];
        return c;
    }
}

What is for(d:c) and what does it do in this program and is there any other method to do this?

deHaar
  • 17,687
  • 10
  • 38
  • 51
Fayeq Najuib
  • 1
  • 2
  • 5
  • `for (int d : c)` means *for each integer value `d` in the array of integers `c`* execute the loop body... Here it means *print every element `d` in `c`*. – deHaar Oct 25 '18 at 10:18
  • 1
    Please don't get into the habit of using single letters for variable names. All identifiers should be nice and descriptive, to make your program as readable as possible. Also in the name of readability, I strongly recommend using `{ }` characters after every `while`, `for`, `if` and `else` statement. – Dawood ibn Kareem Oct 25 '18 at 10:23
  • @deHaar got it thanks!! – Fayeq Najuib Oct 25 '18 at 10:27
  • @DawoodibnKareem Thanks a lot for your suggesstion.Will follow it.This was a demo program actually and wote in a hurry. – Fayeq Najuib Oct 25 '18 at 10:29

1 Answers1

3

This is a foreach loop:

for(int d:c)
    System.out.println(d);

A different version of:

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

d corresponds to c[i]

In Java8 you can print elements of c with a single line:

IntStream.of(c).forEach(System.out::println);

This is like the for loop above and means for each element of c print c[i]

Hülya
  • 3,353
  • 2
  • 12
  • 19
  • How does :: method reference work in println – Fayeq Najuib Oct 25 '18 at 10:43
  • The `::` syntax was introduced in `Java 8` to reference methods. It is used to refer a method of an existing class. For further information you can take a look at here: https://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8 – Hülya Oct 25 '18 at 11:21