0
 Can someone please tell me how to print this arry with **forEach** loop

 class TestVar2{
     public static void main(String args[]){

     int x[] = {1,2,3,5,6}; // x array
     arrayPrint(x);         // passing x[] into arrayPrint method
     }

    public static void arrayPrint(int[]... z){
     for(int i[] : z){           // for each loop
      System.out.print(i[0]);    // print 0th position of array
        }
  } 
}

How to print the whole array instead of one element with this loop ?

Jatinder Kumar
  • 455
  • 5
  • 13
  • Iterate i[] with a simple for loop. for (int j = 0; j < i.length; j++){System.out.print(i[j]);} – pringi Jan 05 '17 at 14:16
  • See this for more http://stackoverflow.com/questions/22059802/how-to-print-all-of-arrays-with-for-loop-in-java – pringi Jan 05 '17 at 14:17
  • Thanks for reply.. but i want to do this with foreach loop. Is it possible or not? – Jatinder Kumar Jan 05 '17 at 14:19
  • 1
    Possible duplicate of [What's the simplest way to print a Java array?](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – CPHPython Jan 05 '17 at 14:20
  • No @CPHPython, In possible duplicate they solve with their class methods i.e Array class methods. – Jatinder Kumar Jan 05 '17 at 14:25
  • @JatinderKumar then please add to your question that you do not want to use "Array class methods" (people answering this question may not know that), and while you're at it, you can also remove the first line in the code block (which is repeated in the question's title). – CPHPython Jan 05 '17 at 14:34

1 Answers1

0

For having a foreach loop you need to have objects. int is a primitive type (not an Object). Replace int by Integer.

public static void main(String args[]){

    Integer x[] = {1,2,3,5,6}; // x array
    arrayPrint(x);         // passing x[] into arrayPrint method
  }

  public static void arrayPrint(Integer[]... z){
    for(Integer i[] : z){           // for each loop
      for (Integer j : i){
        System.out.print(j);    
      }
    }
  }
pringi
  • 3,987
  • 5
  • 35
  • 45