-2

I tried to print all the elements in an array using both for loop and foreach loop.

In for loop, I got addresses of elements instead of elements themselves. But by using for loop I got the elements themselves. So how this is working even I didn't override toString method also but am getting elements!!

public class ArrayReturn {
    public static int[] Multi(int []a)
    {
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]*2;
        }
        return a;
    }
    public static void main(String[] args) {
        int ar[] = {2,3,4,5,6,7};
        int z[] = Multi(ar);
        for (int i = 0; i < z.length; i++) {
            System.out.println(z);
        }
        for (int i : z) {
            System.out.println(i);
        }
        
    }
}
OUTPUT
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
4
6
8
10
12
14

I expected either address from both loops or elements. But I got address in for loop and elements in foreach loop.

H D VIVEK
  • 13
  • 2
  • "In for loop, I got addresses of elements instead of elements themselves." - **No**; you got **some numbers**, which happen to be the ones you can use to **index** the array. "I expected either address from both loops or elements." I can't understand why. If they did the same thing, what would be the point of putting both of them into the language? – Karl Knechtel Feb 08 '23 at 03:09
  • In your `for` loop you are just printing `z` each iteration, which has nothing to do with the loop. – tgdavies Feb 08 '23 at 03:11
  • 1
    "So how this is working even I didn't override toString method also but am getting elements!!" The elements of the array **are integers**, so they would look the same way as what you get from the other loop - just with different values. The weird `[I@5a07e868` things that you see printed have **nothing to do with** "elements" (and "element" is not a type; it just means "one of the things that is in the array); that is the text that Java uses to display **the array**. It does that because the code says `System.out.println(z);`, and `z` means **the array**. – Karl Knechtel Feb 08 '23 at 03:13
  • In Java, an array is a reference type. The line `System.out.println(z);` uses the [default `toString` method](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Object.html#toString()), inherited from `Object`. See https://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode . – Old Dog Programmer Feb 08 '23 at 03:19

1 Answers1

0

As others have told you, in your for loop you're printing the array z, so for that reason it's printing the object address what you're seeing. If you want to print the value stored in each position, you have to use the for loop's index.

    for (int i = 0; i < z.length; i++) {
        System.out.println(z[i]);
    }
jmartinez
  • 71
  • 1
  • 5