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;
}

Wednesday, May 21, 2008

What are Immutable and Mutable Objects (String vs StringBuffer)

 public static void main(String[] arg) { 
/* String */

String a = "abc";
String b = "def";
String c = "def";

System.out.println(a.hashCode());
a += "xyz";
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
System.out.println(a);

/* StringBuffer */

StringBuffer sb = new StringBuffer("wer");
System.out.println(sb.hashCode());
sb.append("ert");
System.out.println(sb.hashCode());
}


Output:
-------

96354
-1424366089
99333
99333
abcxyz
17523401
17523401

Explanation:
------------

Mutable and Immutable objects :
The objects whose values can be changed in the same address, are Mutable objects.
The objects whose values cannot be changes in the same address, are Immutable objects.

Example : String and StringBuffer

The main difference, String is Immutable whereas StringBuffer is Mutable.
String is Notsynchronized whereas StringBuffer is Synchronized.
String doesnt have an append method whereas StringBuffer has.


Important Note:
In the code above, when a String "def" is assigned to 'b', it is stored at address "99333".
Again, if I assign the same String "def" to "c", it points to the same address "99333".

Wednesday, April 9, 2008

Converting a substring to Integer in C++

#include < iostream >
#include < sstream >
#include < cctype >

int main()
{
std::string s = "dsdhjsahdk dsdjdsaj 36782367 sdjdhak";

int j = 0;
std::stringstream cstr;
cstr << s;
int i = 0;
char ch;

while( cstr >> ch )
{
if( std::isdigit(ch) )
{
cstr.putback(ch);
break;
}

if( ( j = s.find(" ", j) )== std::string::npos )
{
cstr.seekg(-1);
break;
}

cstr.seekg(++j, std::ios::beg);

}

if(cstr)
{
cstr >> i;
}
std::cout << i;

return 0;

}

Friday, January 4, 2008

Diff between calling a start()->run() method AND calling run() method directly without start() method

If the run() method of a Thread is called directly without start() method. It fails to obey properties of Thread. It acts as a normal method.

Example: without using start()

 class ThreadA extends Thread { 
ThreadA() {
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am in run method " + i + " " + this.getName());
try {
this.sleep(500);
} catch (InterruptedException ie) {
System.out.println(ie);
}
}
}
}

public class Threadtest {
public Threadtest() {
}

public static void main(String[] args) {
Thread t1 = new Thread(new ThreadA(), "t1");
Thread t2 = new Thread(new ThreadA(), "t2");
t1.run();
t2.run();
}
}

The output will be:
I am in run method 0 Thread-0
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 4 Thread-1

But,
if the lines t1.run() and t2.run() are replaced by t1.start() and t2.start() then the output is,

I am in run method 0 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 4 Thread-1

How to handle exceptions in JSP?

You can catch exceptions in a JSP page like you would do in other Java classes. Simply put the code which can throw an exception/s between a try..catch block.

<%
try {
// Code which can throw can exception
} catch(Exception e) {
// Exception handler code here
}
%>


There is yet another useful way of catching exceptions in JSP pages. You can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where you can display a useful message to the user.

To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.

* Form.html - Display a Form to the user to enter his or her age.
* FormHandler.jsp - A JSP Page which receives this value and prints it on the user screen.
* ExceptionHandler.jsp - An exception handler JSP page which is actually an error page to which control will be
passed when an exception is thrown.


Form.html page
--------------
<html>
<head>

</head>
<body>

<form action="FormHandler.jsp" method="post">
Enter your age ( in years ) :
<input type="text" name="age" />
<input type="submit" value="Submit" />
</form>

</body>
</html>


FormHandler.jsp
---------------
<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>

</head>
<body>

<%-- Form Handler Code --%>
<%
int age;
age = Integer.parseInt(request.getParameter("age"));
%>

<%-- Displaying User Age --%>

<p>Your age is : <%= age %> years.</p>

<p><a href="Form.html">Back</a>.</p>

</body>
</html>


ExceptionHandler.jsp
--------------------
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exception Occurred!</title>
</head>
<body>

<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>

</body>
</html>


Conclusion:
-----------
Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing.