I have problems with the following exercise since I couldnt attend the lesson where the topic has been explained. I tried to help myself with some videos on youtube, but it didn't really make me confident about the result I had. I would be very thankful if someone helped me out a bit.
The following Java code is given:
public class Programstructures {
public static int f(int n, int m) {
if (0 == n) {
return m + 1;
}
if (0 == m) {
return n + 1;
}return m + n;
}
public static void main(String[] args) {
if (0 < args.length) {
int v = Integer.parseInt(args[0]);
v = f(v, Integer.parseInt(args[1]));
System.out.println(v);
}
}
}
a) Investigate for all variables and function arguments, that exist in the given program, whether they are placed on the heap or on the stack.
b) Outline the state of the stack after the start of function f.
I got the following results:
a) n, m, v : stack. args[] : heap.
b) I am not sure. I'd love some explaination here :/
Thanks in advance!
I couldnt mark the question as homework, sorry.
The stack is where local variables and arguments to functions are stored. If
a()
callsb()
andb()
callsc()
, then their local variables and arguments (if any) will be stored on the stack. In this case,a()
's variables will come first, thenb()
's, thenc()
's. This makes returning from a function easy, because whenc()
returns, getting rid of its local variables and arguments just means deleting the last part of the stack.The heap is basically a just that -- a heap of memory. Whenever you create an object, it is stored somewhere in the heap until it is finalized and deleted.
If you create an object within a function, the object will go on the heap, but the reference to the object will go on the stack.