Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
WillRamos Avatar asked Mar 02 '26 23:03

WillRamos


1 Answers

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.

like image 154
Jeroen Vannevel Avatar answered Mar 05 '26 13:03

Jeroen Vannevel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!