Wednesday, July 7, 2010

Exception Handling in Java (when to use try catch/throw/throws)

Exception Handling is one of the important thing in any programming language. It was made easy in java using run-time error management. People wonder that what is exception? Exception is an event, which occurs during the execution of a program that disrupts the normal flow of program's instructions. Then the next point is why these exceptions arise? Answer to this question is very simple, Exceptions are thrown when a program violate the rules of any programming language or the constraints of the execution environment.

Exceptions are generated in two ways: 1. By Java run time environment 2. Manually generated by code written by a programmer.

A program can handle the exceptions or leave it to the callers of the program or to the default run time exception handler(are called uncaught exceptions).

The first doubt arise is why we use exception handling if there is a default run time exception handler? Becoz there are two benefits: it is easy to fix the error, and second it prevents the program from automatically terminating.

There are four ways to handle exceptions

1. Using try catch block
2. Using Throw
3. Using Throws
4. Using finally


Let me examine each way with simple example and discuss each in detail

1. Try Catch: Try catch is the very simple form to handle exceptions. Enclose the code inside try block to monitor any exceptions. Immediately after try block, include catch block to catch any exceptions thrown in try block as shown in the below example

try
{
//block of code to execute
}
catch(Exception1)
{

}
catch(Exception2)
{

}

Exception1 and Exception2 are type of exceptions thrown by code in try block.

2. Throw: Throw is used when the programmer wants to throw an exception explicitly using Throwable instance not by the java run time environment. More specifically throw is used when the programmer wants to throw his/her own exceptions. Throw statement requires a single argument: throwable object. Flow of execution stops immediately after throw statement; all subsequent statements are not executed.

Example:

class Throw
{
static void hello()
{
try
{
throw new NullPointerException("throw")
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
hello();
}
}

Output of the above program is: java.lang.NullPointerException: throw

Here I'm trying to throw NullPointerException which is a subclass of Exception.

3. Throws: If a callable method is capable of causing an exception that it doesn't handle, it must specify the behavior of the exception so that the callers will handle the exception. In this case we can use throws as shown in the below example.

type method-name(parameter list) throws exception-list
{
//body of method
}

type is the return type of the method, method-name is the name of the method and exception-list is the list of exceptions that a method can throw. If other class methods wants to call this method, it has to handle the exceptions thrown by this method.

4. Finally: When exception occurs, the code after the statement which causes the exception will not be executed. For example, if we open a file and an exception occurs without closing the file, it lead to memory shortage. Finally block is provided to avoid this problem. Code written in finally block is get executed even after the exception arises except when System.exit(0) is used inside try or catch block.

Please refer to this article for more information on finally block

Monday, July 5, 2010

Difference between Application Server and Web Server

Whoever is reading this article must have little bit of knowledge on what is server, application server and web server.

Web server handles HTTP (Hyper Text Transfer Protocol) requests, where as Application server servers business logic to application programs through many protocols like RMI IIOP (Remote Method Invocation Internet Inter-Orb Protocol), TCP/IP including HTTP. Web servers basically respond to user requests using HTTP. To process a request, A web server may respond with static HTML page, image, send a redirect, or delegate dynamic response generation to some other programs like JSP, ASP, server side java script or some other server side technology.

Web server delegation model is very simple. When a request comes into web server, it simply passes the request to other program which can efficiently handle the request, it doesn't provide any additional functionality beyond simply providing an environment in which the server side program can execute and pass back responses to web server.

Application Server exposes its business logic to its client applications through many protocols including HTTP. Application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on object. The information traveling back and forth from application server to its clients is not restricted to HTML. Instead, the information is a program logic. Since the program logic takes the form of data and method calls and not static HTML, the client can employ exposed business logic however it wants.

Application server also behaves like a web server but the converse is not true. Using application server, the business logic is separated from the markup. So that the code can be reused.

Please refer this example which differentiate application server and web server

Application server also provides some additional services like transaction management, security management, resource management and so on. If the application server is used, then the developer can only concentrate on business logic, not on additional services as they are already provided by the application server.

Web Server Examples: Apache, Apache Tomcat

Application Server Examples: Glassfish, Websphere, weblogic

Tuesday, June 15, 2010

Difference between Delete, Truncate and Drop in SQL

Delete is a DML (Data Manipulation Language) command where as Truncate and DROP are DDL (Data Definition Language) commands.

Three are used to remove rows from the table, but there are few differences

If we use Delete on any table, all rows in that table are deleted, but it doesn't free the space containing the table.

Ex: DELETE FROM TABLE_NAME WHERE CONDITION

If 'where' condition is not specified in the above example, all the rows in the corresponding table are deleted.

Truncate is also used to delete the rows from the table, but it frees the space containing the table

Ex: TRUNCATE TABLE TABLE_NAME

Drop is used to delete the entire table including rows, privileges, relationships with other tables.

Ex: DROP TABLE TABLE_NAME

Delete operation can be rolled back (B'coz Delete is a DML command), where as Truncate and drop operations can't be rolled back (B'coz these two are DDL commands).

Tuesday, June 8, 2010

Why Multiple Inheritance is not supported in java using classes

Why Multiple inheritance is not possible in java using classes means that it can be achieved using something else. We can use interfaces to make multiple inheritance possible in java.

Let us first discuss why its not possible with classes using a simple example

Let us assume we've two programmers A and B

A has written a class named ClassA which is inheriting ClassSuper and overriding one of its methods called Hello()

B has written a class named ClassB which is inheriting ClassSuper and overriding one of its methods called Hello()

Now, if multiple inheritance is allowed in java, another programmer called C wanted to extend both the clasess ClassA and ClassB which are written by A and B programmers respectively.

He is not overriding the method Hello() in his class. What if he calls method Hello()?

How does Java Virtual Machine(JVM) know which Hello() method (from ClassA or ClassB) to call?

This is the reason why multiple inheritance is not possible in java. But, still it can be achieved using interfaces. One must implement all the methods presented in interface if he is implementing interface. So, there is no possibility of confusion that which method to call, because java doesn't allow same method signatures in one class or interface.

Friday, June 4, 2010

Different types of variables in java

There are three types of variables in java
1. Instance Variables
2. Static Variables
3. Local Variables

1. Instance Variables: Instance variables are also called global variables. Each instance of the class has its own copy of instance variables (This is the fact that they are called instance variables). These variables are not declared with in any of the methods in a class but they are declared with in the class. These variables are also called non-static fields.

2. Static Variables: Static variables are defined with in the class with static key word (This is the fact that they are called static variables). Static modifier tell the compiler that there is only one copy of this variable exists regardless of how many times the class has been instantiated.

3. Local Variables:
Local variables are defined with in the method. They are only accessible with in that method.

Here is the example for variables

public class Variables
{
public static int staticVariable = 0;
int instanceVariable = 0;
public static void main(String args[])
{
String localVariable = "Hello";
System.out.println(localVariable);
}
}

From the example:

Instance Variable is int instanceVariable = 0;
Static Variable is public static int staticVariable = 0;
Local Variable is String localVariable = "Hello";

Thursday, May 27, 2010

When to use Interface and abstract class

Interfaces are contracts between groups of programmers who write code without any knowledge of what other programmers are writing. To keep them (Programmers) know what other programmers are doing, interfaces are the way in java.

Abstract classes are same as interfaces, with few differences. They can contain implemented method bodies, fields which are not static and final. They are useful when some methods are common for classes and some method implementations are different. So, we can implement common methods in abstract class and write method (which are not implemented) signatures in it. What ever the class is implementing abstract class will provide their own method implementations for methods which are not implemented in abstract class.

Look at this tutorial if you've more doubts on this topic.

Wednesday, May 26, 2010

Need for Just In Time compiler


Basic function of just in time compiler is to transform bytecode into machine dependent code. Instead of interpreting bytecod line by line, it converts bytecode into machine dependent code very fast (It tries to identify which instructions will be executed next, so that it can execute code in advance). It's used to increase the performance. One can see the performance difference if the same method is called more than one time.

Difference between Synchronized method and Synchronized block

Why we need synchronization in multithreading?

Because multithreading introduces asynchronous behavior to your programs, there must be a way to enforce synchronicity when you need it. For example, when you want two threads to communicate and share a complicated data structure, you need some way to ensure that they never conflict with each other.

One way to synchronize object methods is using synchronized methods as shown below

synchronized void call(String message)
{
System.out.println(message);
}

But, it'll not work in all cases. For example, if you want to synchronize access to objects of a class that was not designed for multithreading or what if the class was not created by you, but by some third party and you don't have access to the code? Solution is that you simply put calls to the methods defined by this class inside a synchronized block as shown below

Synchronized(Object)
{
statements to be synchronized
}

Here Object is a reference to the object being synchronized. Synchronized block ensures that a call to a method that is member of this object occurs only after the current thread has successfully entered object's monitor. (Monitor is an exclusive lock for the object being synchronized)

Tuesday, May 25, 2010

Difference between final, finally and finalize

Final is used to declare constants as shown in below example.

int final a = 10;

Class can also be a final class, which shows that the class can't be subclassed.

Method can also be final method, which shows that the method can't be overridden.

Finally is used to release any resources used in try catch block to free memory. It is placed after try-catch block. Code in finally block is executed always irrespective of the exception thrown except when System.exit(0) is called. It is shown in the below example

try
{
System.out.println("Enter your name:");
String name = scan.next();
System.out.println(name);
}
catch(IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
finally
{
scan.close();
System.out.println("Closed");
}
Code in finally block is get executed. If you put System.exit(0) inside try block or inside catch block, then finally block is not called.

finalize() method is called before an object is collected by garbage collector to free any resources being used by that object

Difference between String and String Buffer in java

String is a immutable object, where StringBuffer is a mutable object in java. Still you'll be able to change string using '+' operator. But every time you add some thing to string object using '+', a new string object is created, So, more memory is need to hold those new objects. If you just use concat method of string object, it'll not concatenate the new string as shown in below example.

String abc = "Hello ";
abc.concat("changed");
System.out.println(abc);

Most of the people think that output of the above example is 'Hello changed' (with out single quotes). That's correct, but new object has been created with value 'Hello changed' (Without single quotes) and the previous value is recommended for garbage collection.

String abc = "Hello ";
abc += "changed";
System.out.println(abc);

Output of the above code is 'Hello changed' (without single quotes). But, a new string object is created to hold the string "Hello changed".

If you use StringBuffer instead of String in the above two examples you'll save memory(example 2) and you'll get the output what you intended for (example 1) as shown in the below example

StringBuffer abc = new StringBuffer("Hello ");
abc.append("changed");
System.out.println(abc);

Output: Hello changed

Thursday, May 20, 2010

How to access method variable in a innser class declared inside method

Variables declared inside a method can be used inside the inner class declared inside this method. But, those variables must be declared as final variables as shown in the below example.


public class InnerClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InnerClass ic = new InnerClass();
ic.inner();
}
public void inner()
{
final int a = 10;
class Inner
{
public Inner()
{
System.out.println(a);
}
}
new Inner();
}
}

Output: 10

How to call Constructor from Constructor in the same class

You can call one constructor from another constructor if the class has more than one constructor in java. Here is the example. Note that constructor call must be the first statement in a constructor

public class Constructor {
int a;
int b;
Constructor()
{
this(1, 2);//This must be the first call.
System.out.println("hello");
}
Constructor(int a, int b)
{
System.out.println(a+", "+b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Constructor();
}
}

Output:
1, 2
hello