Question

I'm trying to do some practice for an exam and need some help (did I do them correctly? If not, why?) on these problems about java primitives and java objects. These are all true or false.

  1. The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: int x = 7;

    False, because it is pass by value since int is primitive

  2. The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: Integer x = 7;

    True, because it is referencing an object stored on the heap

  3. If you pass the variable ‘x’ as declared in (1) to a method, that variable is passed by reference, and its value may be modified by the called function.

    False,because Java only does pass by value

  4. If you pass the variable ‘x’ as declared in (2) to a method, a copy of that variable is created in the heap, and passed to the function, so that the function’s object reference is pointing to a distinct place in memory.

    True, because variable is in the stack but it is pointing to a place in the heap

Thank you all for the help.

Was it helpful?

Solution

(4) is false for two reasons:

  • "a copy of that variable is created in the heap" is false. Only objects are on the heap. The local variable in a function is not on the heap. The value of that variable is simply passed, i.e. copied into the stack frame of the called function.
  • "the function’s object reference is pointing to a distinct place in memory." is false. The function's reference will point to the same place in memory. That's the point of passing -- the value of the variable inside the function is the same as the value that was passed. The value of a reference is where it points.

OTHER TIPS

4) If you pass the variable ‘x’ as declared in (2) to a method, a copy of that variable is created in the heap, and passed to the function, so that the function’s object reference is pointing to a distinct place in memory.

Okay, this can be a little sketchy. If dealing with objects, you are not creating a copy of the object and passing the copy to the method. You are creating a copy of the reference to the object, and passing that over by value.

Actually there is a reason 2 is wrong - but its probably not the reason the person who set it expects.

 Integer x = 7;

Will get turned into:

 Integer x = Integer.valueOf(7);

Which will re-use a cached value for all integers in the range -128 to +127 inclusive. (It may reuse them for other values too).

So you will get a reference to an object which is present in the JVM implementation dependant cached storage for common Integer values.

False because Integer is an object. So you will be passing just the reference to the object address in the function. It is standard in Java.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top