Tuesday, July 7, 2009

Stack and Heap in java

Stack in java is used to store methods and local variables or stack variable.
It is useful in threading and exception handling. As per the behavior of stack (LIFO) Last In First Out, the elements in the stack depends on each other.

For example

 void test() { 
int a;
chain();
}

Here while running the above code, first test() method will get invoked. After that chain() will be called..now test() will be in the top of stack memory.
After the execution of chain() only, the test() will finish its execution (as per LIFO).

On the other hand Heap is mainly used to store Objects. Whatever objects (instance variables) that is created is stored in Heap only.

Java uses Pass-by-Value and no pass-by reference

Java uses Pass-by-Value and no pass-by reference

Java does manipulate objects by reference, and all object variables are references.
However, Java doesn't pass method arguments by reference; it passes them by value.
 public void swap1(int var, int var2) { 
int temp = var1;
var1 = var2;
var2 = temp;
}

When swap1() returns, the variables passed as arguments will still hold their original values.
The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well.
 public void swap2(Point arg1, Point arg2) { 
arg1.x = 100;
arg1.y = 100;

Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}

public static void main(String[] args) {
Point pnt1 = new Point(0, 0);
Point pnt2 = new Point(0, 0);
System.Out.printIn("X= " + pnt1.x + " Y=" + pnt1.y);
System.Out.printIn("X= " + pnt2.x + " Y=" + pnt2.y);
}

IF we execute this main() method, we see the following output:
X= 0 Y= 0
X= 0 Y= 0
X= 100 Y= 100
x= 0 y= 0

Sunday, June 28, 2009

Sort a list of Objects based on their names

 List sortSubPanelBasedOnNames(List subPanels) { 
Collections.sort(subPanels, new Comparator() {
public int compare(TestPanel panel1, TestPanel panel2) {
return (panel1.getInspectorName()).compareTo(panel2.getInspectorName());
}
});
return subPanels;
}