• 1 reply
  • Latest Post - ‏2011-10-04T09:36:28Z by VenkatRArra
2 Posts

Pinned topic How does an Object is returned in Java vs C?

‏2011-09-07T04:37:30Z |
Hello experts,

I have a doubt that how does an object is returned by a method in Java.

Inferences for above statement:
In C we know that the memory allocated locally inside a function will vanish when the function returns

char *getName() 

char name[]=

return name 

The caller of the function will get a pointer to the array.Although the pointer points a garbage unknown location since the array was local, it has now been destroyed.

Now I have a doubt the same thing works in Java

public String getName() 
{ String name=
//name here is local as above;memory allocated for the object locally 

return name; 

The caller of the method will correctly get the desired String passed.

Now my question is How the pointer (or reference in Java) is returned when it is compared to C.
Hope I made my points clear

Hoping to get a reply soon
Updated on 2011-10-04T09:36:28Z at 2011-10-04T09:36:28Z by VenkatRArra
  • VenkatRArra
    2 Posts

    Re: How does an Object is returned in Java vs C?

    In Java all objects are created on heap and local objects (on stack) have references to those heap addresses.
    JVM maintains the reference of local object and passes it to the calling method. Following is the method JVM uses when objects are returned from a method.

    The JVM uses several opcodes, one for each return type. These opcodes do not take operands. If there is a return value, it must be on the operand stack. The return value is popped off the operand stack and pushed onto the operand stack of the calling method's stack frame. The current stack frame is popped, and the calling method's stack frame becomes current. The program counter is reset to the instruction following the instruction that invoked this method in the first place.