The Stack and the Heap
————————–
The heap stores all objects, including arrays and all the class variables.
The stack stores all the local variables including parameters.

When a method is called Java creates a stack frame (or called an activation record). It stores the parameters and the local variables. The JVM maintains an entire stack of “stack frames”. When the method completes, its stack frame is erased. Most OS give enough space for a few thousands of stack frames.

Thread.dumpstack()
———————-
This method when called will print out the contents of the stack frame. Its present in the java.lang package and so doesnt need to be imported.

Parameter passing
——————–
In Java , the parameters are passed by value. That is they are copied.

The variable a will be created in present stack frame. When the function donothing() is called, a new stack frame is created on top of the previous frame and the variable x resides in this frame. Note that no change happens to a after the function completes. The frame is erased once the function exits.

When the parameter is a reference, the reference is copied and not the object it is pointing to.

In the local stack variable b is created. The object is created in heap with the variable i inside it. b points to object. set3() creates a parameter ib, both in new stack frame and then ib points to object pointed by b. The value of the object is changed by ib which is reflected on b, since both point to the same thing.

The difference here is that now a new object is created by the setBad() function and its value of ib is being set. The old heap object still retains its value. This happens to be a common programming error.

Binary Search
—————-
Used to search a sorted array. Suppose we want to search in a sorted int array. In this example , we try to find whether the variable “find” exists in the array, if so then return its array index. If not, return failure. This is going to be a predefined constant like FAILURE = -1. I have used a recursive algorithm.

Scope and Recursion
———————-
Scope of a variable : is portion of the program , actual lines of code, that can access the variable.
1. Class variables: (static fields) are in scope everywhere in the class except where shadowed by local variables. (like when using “this”)
2. Fully qualified class variable:For example “System.out” is not ambiguous. They are in scope everywhere in the class and are not shadowed. If public, they are in scope in ALL classes.
3. Instance variables: These are in scope in methods that are not static, except when shadowed.
4. Fully qualified instance variable: For example: “this.name” Same as 2.
5. Local variables: which includes parameters, only in scope in the block that defines them.