I got a question about the following piece of code.
class MemArr{
int[] mem = {1,2};
}
public class Test{
public static void main(String[] args){
MemArr[] x = new MemArr[2]; //line 1
x[0] = new MemArr(); //line 2
x[1] = null; //line 3
//line 4
}
}
How many objects are created in total and how many objects are eligible for garbage collection when line 1 is reached?
I think, that at line 1, there were 5 objects created (1 array x, 2 objects of MemArr in the array x, 2 member variables of integer array for the objects of MemArr)
At line 2, two objects were created (one MemArr object and its member variable mem).
At line 3 when x[1] is set to null, I think that there were in total 4 objects which are eligible for the GC, but I am not very sure about this.
MemArr[] x = new MemArr[2];
This creates a new MemArr array of 2 elements but it doesn't initialize any of the 2 elements. After that declaration, x[0] and x[1] are both null: the array was instantiated but not its content.
x[0] = new MemArr();
This really assigns a new MemArr to the first element of the array. So it creates one MemArr and another array for the internal int[] mem that it contains.
x[1] = null;
This line doesn't do anything; the value was already null, as said before.
The first line creates a single array object of 2 elements. Both elements are null by default, so no MemArr objects are created.
The second line creates one MemArr object and one internal array object inside that object.
The third line doesn't create any object. In fact, it makes no difference since x[1] is already null.
Related
This question already has answers here:
Arrays in Java and how they are stored in memory
(3 answers)
Create an array of references
(3 answers)
Closed 24 days ago.
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.
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.
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.
Given the following code, how many objects are created within main() and after the execution of line 15, how many objects are eligible for garbage collection?
class Test
{
int[] dz = {1, 2, 3, 4, 5};
}
public class MarksDriver
{
public static void main(String[] args)
{
Test[] da = new Test[3];
da[0] = new Test();
Test d = new Test();
da[1] = d;
d = null;
da[1] = null; //line 15
//some code
}
}
3 created, 0 eligible
4 created, 1 eligible
5 created, 2 eligible
3 created, 2 eligible
None of the above
Ok first of all, Please don't mark it as Homework. This is a question from a test at my college. According to me there should be 2 objects those are created and 1 is eligible for garbage collection after line 15. It's because there are only two new operators used for creating objects and the object that 'd' was referring to at the beginning is lost after line 15 so it will be freed of memory. So I marked the last option that is none of the above. But my Teacher marked it wrong and said the answer is 5,2. She gave some explanation that I didn't get a hint of.
So can anyone explain this?
When we write
Test d = new Test();
2 objects are created one is d other one is member array dz
same way with
da[0] = new Test();
2 objects are created one is stored in da[0] other one is member array dz
and one more object is created by
Test[] da = new Test[3];
so total 5 objects created
with these 2 lines of code there is no reference for one object of class test created at line 13 which makes it eligible for garbage collection which in turn also makes the member array dz eligible for garbage collection, so 2 objects become eligible for garbage collection after line 15
d = null;
da[1] = null;
5 created, 2 deletable
Two Test objects are created. But each contains an array object so that is a total of four objects.
Additionally the array da is created. That is 5 objects.
When d is nulled, then two objects can be garbage collected: the array that d contains and d itself.
...
Perhaps teacher is wrong and "none of the above" is right because the underlying true answer is 6 and 2 because surely a sixth object is created: the MarksDriver object!
I look everywhere and cannot find an answer or a hint to my problem. I'm sure it has probably something to do with arrays being passed by reference and me having to possibly copy the elements and pass them to my instance variable, but I just can't figure it out.
to just keep things simple
We create Wallet class that represents a wallet that can hold up to 10 bills. We are specifically told to not use Array Lists and to work with arrays.
Wallet has two instance variables, but the only one I have problems on is this one
private int contents[ ];
my main is creating new Wallet object by the following calls
int a[ ] = {100, 50, 20, 1};
Wallet myWallet = new Wallet(a);
in my constructor, I have to allocate memory for the contents[ ] instance variable and then grab the elements from a[] and have them inside of the contents array.
public Wallet(int a [ ])
System.out.println("Constructor #2 called.");
//allocate memory for contents[]
contents = new int[MAX] //supposed to be of size 10, given info
//initialize contents[] from a[]
stuck here, how to I assign them to each other?
how do I copy 100,50,20,1 to contents at i = 0 - 3, and have reset of elements = 0?
You could use Arrays.copyOf(int[], int) and something like
public Wallet(int[] a) {
System.out.println("Constructor #2 called.");
this.contents = Arrays.copyOf(a, 10);
}
This question already has answers here:
What is the difference between a variable, object, and reference? [duplicate]
(5 answers)
Closed 7 years ago.
Consider the following:
array1 contains a list.
int[] unSorted = array1; a new initialized array works as a (duplicate).
Arrays.sort(array1); suppose to sort only the original Array array1.
The problem occurs when I use the sort method Arrays.sort. It sorts all Arrays that are linked to array1, including the (duplicate)!! Why is that? It should change only the array that is declared inside the parentheses! Isn't it?
Your unSorted is not "a new initialized array". It is just a different name for the same array.
Arrays are Objects, not primitives. They are passed around as pointers, not as copies.
If you want a copy, use java.util.Arrays#copyOf.
Consider the following example: array & copy both refer to the same object - which is not the case with store.
import java.util.Arrays;
class Test {
public static void main(String[] args) {
// array & copy both refer to the same Object
double[] array = {5,4,3,2,1};
double[] copy = array;
// the following array is filled up "by hand" - thus it has no reference to the previous object
double[] store = new double[array.length];
for (int i = 0; i < array.length ; i++) {
store[i] = array[i];
}
Arrays.sort(array);
System.out.println("array"); // 1,2,3,4,5
for (double d: array)
System.out.println(d);
System.out.println("copy"); // 1,2,3,4,5
for (double d: copy)
System.out.println(d);
System.out.println("store"); // 5,4,3,2,1
for (double d: store)
System.out.println(d);
// Primitives show a different behaviour
double a = 5;
double b = a;
System.out.println(a + " / " + b); // 5 / 5
a = 10;
System.out.println(a + " / " + b); // 10 / 5
}
}
array1 isn't actually an array: it's a reference to an array. It's a bit like if you give someone a business card with your office address, that card isn't the actual office, but rather something that tells you how to reach the office.
When you do int[] unSorted = array1, you're making a copy of the reference, not the array. Again, it's like someone copying down the info on your business card.
And when you perform an operation on unSorted (like moving its elements to sort then), what you're actually doing is performing an operation on the object it points to. It's like saying, "go to the office specified on the business card called unSorted, and move the chair at desk 1 to desk 2."
If you then went to the office specified on the business card called array1, you would of course expect that the chair has moved there, since it's the same office.
If you want a copy, you have to create one. There are a few ways to do that, but the easiest is to use Arrays.copyOf.
Look at it this way :
You have a controller for a television (the array of course) and manage to duplicate the controller : you still have one television with multiple controllers.
If you change the television channel with one controller, even if you didn't touch the others, the televisions state has changed.
The same logic has to be applied to your problem.
Your unsorted variable is a reference.
Remember references point to an object.
So when you declared and instantiated array1, you may have done the following:
int[] array1 = new int[/*Any positive integer*/]
When declaring your unsorted reference variable, you did not instantiate a new array, you simply created a reference variable which points to the same object as array1.
Consider the image below:
So array1 and unSorted point to the same object, so of course if you call a method on either one of them you will effect the same object.
Because they are all the same array, not 'other arrays'.
You need to think about what you mean by 'all other arrays that are linked'.
Suppose there is a class MyObject which has a MyClass() constructor and is properly implemented.
When we call that line of code will it create instances of the MyClass object or will something else happen?
Edit: apparently this question was not very well-received. I'm sorry if it's vague or something. It was simply a homework question that asks for T/F.
I meant to ask:
if we have
MyClass[][] x = new MyClass[n][n]; // where n is a number
Will it create n*n instances of MyClass objects or merely n*n null references?
It turns out that
MyClass[][] x = new MyClass[n][n]; // where n is a number
x[0][0] = new MyClass();
is different from
MyClass x = new MyClass();
Each slot in the Array would be initially null if the Array is of any object (Primitive data types would simply yield their default value). Just like String x; where x would be null, just in this case, it's an array of null values.
The Array is still the same type of objects it was created for, such a String, just all the slots are null and would need to be instantiated. eg bigArray[1] = new String("Hello!");
If you'd like the array to contain some sort of default, you'll need to fill the array.
MyObject array = new MyObject[3]; //New array that can hold three
for(int i = 0; i < array.length; i++){ //Start i at zero, while it's less than the spots in the array, and add one every time
array[i] = new MyObject(); //Set the spot to a "real" object now.
}