0

In java array carries reference to a memory location and objects does that too. So when we create an array of objects, does that mean that the array carries reference to more references?

I asked this question to my professor, but didn't quite understand what he explained.

1
  • 1
    Your question mentions 'reference to a memory location'. That's not really a thing in Java - references aren't exactly the same as C/C++ pointers. If an array has objects in it then it is really holding references to those objects. Could you give an example with some code of what you are asking? Commented Jan 25, 2023 at 3:57

2 Answers 2

0

When you write:

  Object[] array = new Object[10];

the variable array contains a reference. This reference points to an array object, which can contain 10 references. These references are all null at the point that the array is created.

Once you write:

  array[0] = new Object();

array[0] now contains a reference to an Object instance.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes.

Suppose you have code like this:

 class Foo { ... 
     public int getBar () { ... 
     public void setBar (int bat) { ... 

Now, elsewhere you have code like this:

 Foo [] glorblarr = new Foo [12]; 
 Foo flarg = new Foo ();
 ...  
 flarg.setBar (100);
 glorblarr [7] = flarg;
 System.out.println (flarg.getBar () + "  " + glorblarr [7].getBar ());
 glorblar [7].setBar (987);
 System.out.println (flarg.getBar () + "  " + glorBlarr [7].getBar ());

You should expect the output to be this:

  100  100
  987  987

At this point, globarr [7] refers to the same Object as flarg. That is, one Object, but it is accessible via two names / references. At least until one of the references is changed to point to something else (or null), one is an alias for the other.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.