Search code examples
javaspecificationsjava-6

When Reference Types Are the Same - Arrays


I was reading JavaSE 6 specs, then I've made a test to solve some doubts.

Two reference types are the same run-time type if:

  • They are both class or both interface types, are defined by the same class loader, and have the same binary name (§13.1), in which case they are sometimes said to be the same run-time class or the same run-time interface.
  • They are both array types, and their component types are the same run-time type (§10).

Running the code below...

public class Test {
    public static void main(String[] args) {
        String str = "" + new String(" ");
        String[] strArr = {str};
        String[] strArr2 = {str};
        System.out.println("strArr == strArr2 : " + (strArr == strArr2));
    }
}

...I was expecting the following output:

strArr == strArr2 : true

But the current output is:

strArr == strArr2 : false

What I'm missing?


Solution

  • Just because they're the same type, doesn't mean they're the same object.

    When you do

    String[] strArr = {str};
    String[] strArr2 = {str};
    

    You're creating two arrays consisting of the same contents, but the arrays themselves are two separate objects.

    They are the same type (an array of strings) but they're not the same object (reference X and reference Y). When you say strArr == strArr2 you're asking whether they are the same object (or instance, if you prefer that terminology).

    The JLS you are quoting is at a different level of what you are talking about, it merely says that String[] and String[] are the same type.