Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain the output that I am getting while compiling this program?

Tags:

java

I executed the below mentioned code, when I got a strange output. Can anyone please explain why I am getting this output ?

Code:

public class Bar {

    static void foo( int... x ) {
        System.out.println(x);
    }
    static void foo2( float... x ) {
        System.out.println(x);
    }
    public static void main(String args[])
    {
            Bar.foo(3,3,3,0);
            Bar.foo2(3,3,3,1);
            Bar.foo(0);
    }
}

Output

[I@7a67f797
[F@3fb01949
[I@424c2849

Why are we getting the "[I@"/"[F@" prefixes and the 8 alphanumeric characters to follow, are they memory address ?

like image 440
Shubhankar Raj Avatar asked Nov 30 '13 09:11

Shubhankar Raj


3 Answers

Java arrays have a toString() method that simply display the type of the array ([I), followed by an @, followed by the hash code of the array (7a67f797). This value is almost meaningless. And toString() is the method called on every object passed to System.out.println().

If you want to see the contents of the array, then use java.util.Arrays.toString(array).

like image 120
JB Nizet Avatar answered Nov 05 '22 20:11

JB Nizet


float... is syntactic sugar for float[], so

System.out.println(x);

...is trying to output an array. So you're getting the default toString behavior of objects, rather than the values in the array.

To output the array, either loop through it, or use something like Arrays.toString:

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

...and the 8 alphanumeric characters to follow, are they memory address ?

No, they're just the object's hash code (this is covered in the first link above).

like image 24
T.J. Crowder Avatar answered Nov 05 '22 21:11

T.J. Crowder


Use this to see values in array.

System.out.println(x[0]);
System.out.println(x[1]);
....
System.out.println(x[3]);
like image 30
Bishan Avatar answered Nov 05 '22 21:11

Bishan