jwkoo
jwkoo

Reputation: 2653

difference between java literal array declaration and with new method

    String test1 = "test";
    String test2 = "test";

    System.out.println(test1 == test2); // true

test1 and test2 points to the same object, so the outcome is true.

    String test1 = new String("test");
    String test2 = new String("test");

    System.out.println(test1 == test2); // false

test1 and test2 points to the different object, so the outcome is false.

so the question is that, what is the difference between,

    int[] test = {1,2,3}; // literal
    int[] test = new int[] {1,2,3}; // non-literal

I am confused of this since,

    int[] test1 = new int[]{1,2,3};
    int[] test2 = new int[]{1,2,3};

    System.out.println(test1 == test2); // false

and

    int[] test1 = {1,2,3};
    int[] test2 = {1,2,3};

    System.out.println(test1 == test2); // also prints false

I expected that the latter case`s outcome would be true, the same reason with the case of String example above.

Is test1 and test2 pointing at the different array object?

Upvotes: 0

Views: 1045

Answers (2)

zemiak
zemiak

Reputation: 401

for declaration array are both ways possible

int[] a = new int[] {1,2,3,4,5};
int[] b = {7,8,9,10};

but after the declaration, with the first way you can assign new array to existing variable of the same type, with second way no.

a = new int[] {1,1,1,1};  // ok
b = {2,2,2,2,2};          // error: illegal start of expression

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201507

Java int[] are not ever intern'd. Only String (and the wrapper types for limited values). tl;dr Don't compare object equality with ==. That only compares references with instance types. Here array equality can be determined with Arrays.equals(int[], int[]) and String with String.equals. Arrays don't override Object#equals(Object).

int[] test1 = { 1, 2, 3 };
int[] test2 = { 1, 2, 3 };
System.out.println(Arrays.equals(test1, test2)); // <-- true
System.out.println(test1.equals(test2)); // <-- false

As for why they differ - Java String is immutable (as are the primitive types). Here we can change a value in one of the arrays. We would be surprised (as users) if the other also changed.

Upvotes: 2

Related Questions