-1

I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.

What I do not understand is, if the compiler goes on and compiles it but displays [I@60e53b93 (which seems to me to be an address), is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?

So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.

So what I basically did was:

    int [] arr = {1,2,3,4,5,6};
    int[]arar={1,2,3,4,5,6};
    while (arar==arr){
        arr[0]=2;
    }

    System.out.println(arr);

and so I was basically expecting a red flag but then the code ran and displayed [I@60e53b93 which I did not understand why?

Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?

lnogueir
  • 1,859
  • 2
  • 10
  • 21
How why
  • 351
  • 2
  • 8

2 Answers2

0

Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)

Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.

If you want to display the array contents, you have to loop over the array:

for(int elem : arr) {
  System.out.println(elem);
}
Benjamin M
  • 23,599
  • 32
  • 121
  • 201
0

Two things are going on here:

  • arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
  • System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.

You can solve both problems by using static methods from Arrays:

while (Arrays.equals(arr, arar)) {
  ...
}
System.out.println(Arrays.toString(arr));
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413