Rayyan Merchant
Rayyan Merchant

Reputation: 157

Printing An Empty Array

In order to test a program I wrote these statements:

public class asdf{
  public static void main(){
    int arr[] = new int[5];
    System.out.println(arr);
  }
}

The output I got was:

[I@1df6ed6

Is this a garbage value or something different?

Upvotes: 1

Views: 10519

Answers (2)

Nathaniel Ford
Nathaniel Ford

Reputation: 21269

What is being printed is the memory address of the object. In order for the object to print a human-readable string it has to have toString() implemented in such a way that it is human-readable. Memory addresses will change each time you execute a program, and are generally represented in a way that is not particularly useful (unless you're doing deep magic with the operating system).

One way to get this is to use the java.util.Arrays utility to convert each element of the array to a String.

Upvotes: 2

pushkin
pushkin

Reputation: 10247

The "garbage value" is actually the address of the array (where it is stored in memory).

If you want to print the contents, you need to first import java.util.Arrays; and then

System.out.println(Arrays.toString(myArray);

Upvotes: 1

Related Questions