Saturday, February 14, 2009

Java Issues and Solutions - 3

Common Exceptions and Solutions:

java.lang.NullPointerException;
Problem:The JVM throws null pointer exception when object accessing is dereferenced or not assigned any value.
Ex:
String s;
s.toUpper();
Customer c = null;
c.getName();

Solution:
Make sure that the object is assigned a proper value or its not dereferenced.
Ex: String s = "Test";
s.toUpper();
StringBuffer s = "";
s.append("test");
Customer c = new Customer();
c.getName();

Best Practise: Add null check before accessing any object.
Ex:
Customer c = someObject.getCustomer();
if( c != null)
{
c.getName();
}

java.lang.ClassCastException;
Problem:
The JVM throws class cast exceptions when your are trying to type cast one object which is not a type or sub type of that object.
Ex: X x = (X) y ; here Y should be either instance of X or it should be subtype of X.
class Customer{ -- }
clas Vehicle{ -- }
Vehicle v = new Vehicle();
Customer c = (Customer)v;
Here v is not an instance of Customer and its not s subtype of Vehicle, if you are trying to do this casting the JVM cannot caste the Vehicle object to Customer then it throws class caste exception.

Solutions:
Make sure that your trying to cast the appropriate type that is the exact instance of that class or sub type of that.
Ex:
X y = new X();
X x = (X) y;
class Vehicle{--}
class Car extends Vehicle{--}
Car c = new Car();
Vehicle v =(Vehicle)c;

BestPractise: Use intanceof check before casting the object
Ex:
class Vehicle{--}
class Car extends Vehicle{--}
Car c = new Car();
if( c instanceof Vehicle)
{
Vehicle v =(Vehicle)c;
}

java.lang.ArithmeticException:
Problem:
Mostly this exception will be thrown while trying to divide one variable or value by zero.
Ex:
int x = 10;
int result = x/0; or
int y = 0;
int result = x/y;

Solution: Make sure the divider value is not zero
BestPractise: Use != 0 check or >0 check for the divider before using in the arithmetic operation depending on the scenario.
int x = 10; int y = 0;
if(y > 0)
{
int result = x/y;
}

java.lang.NumberFormatException:
Problem:
This exceptions is thrown when your are trying convert a non numeric string to numeric.
Ex:
String responseCodeString = "x123";
int responseCode = Integer.parseInt(responseCodeString);
Solution:
Make sure that the string contains only digits or keep the statement in try catch block String responseCodeString = "123";
try{
int responseCode = Integer.parseInt(responseCodeString);
}catch(Exception e)
{
}

BestPractise: Use try catch block for this type of statements

java.lang.ArrayIndexOutOfBoundsException:
Problem:
This exception will be thrown while trying to access an index in an array which is more than the length of the array.
Ex:
String[] books = new String[3]; //allocates 3 places with index of 0,1 and 2
String thirdBook = books[3]; //the index 3 is not available in the above created array, it throws exception
Solution:
Make sure that you are using proper index before accessing the array or use the .length property to get the array size and do the operation.
String[] books = new String[3];
String thirdBook = books[2];// the index 2 is available in the above created array which returns third element
BestPractise:
Use .length property of the array before accessing its elements. int index = 3;
int size = books.length;
if(size > index)
{
String bookName = books[index];
}
This is mainly used in for loops as below.
for(int i=0;i<books.length;i++)
{
String bookName = books[i];
}

java.lang.NoClassDefFoundError:
Problem:
This exception is thrown when the specified class is not available at run time, this may happen because the class is not present in the current directory and not in the class path.
Solution;
1.Make sure that class is available in the current directory or
2.Make sure that class path is set for the specified class if it is not in the current directory or
3.Make sure that jar file is added in the class path if the class is present in any jar file
BestPractise:
Place all the classes or jar files at one place(like lib folder) and set the path to the place.

java.lang.IllegalStateException:
Problem:
This exceptions thrown when you are performing illegal operations on the object like accessing a closed IO stream or starting a thread which is already started etc.,
Ex:
1. con.close();
con.flush(); //The connection is already closed there is no meaning to flush the data for the connection.
2. t1.start(); //where t1 is a thread
t1.start(); //The thread has been already started again calling start leads to illegal state exception
Solution:
Check for the scenarios like where trying to performing illegal operation

java.lang.NoSuchMethodException:
Problem:
When we are calling the method on the object is not available
Solution:
Check for the below scenarios.
1. Check whether the calling method is defined on that object
2. Check whether the access modifier is private if it is accessing from the other class
3. Check whether the parameters and return types are proper

Java Issues and Solutions - 2

How to set the path?
Solution:
You can set the path in two ways.

1.Set the path at command prompt.
set path = "%path%;.;JAVA_HOME\bin";
%path% tells that the old "path" variable values should be remained as it is and the new values should be appended to the old 'path'variable value.
"." represents the current directory
It is a temporary solution the path variable is available only for the current session,
that is till the command prompt is closed.
Ex: C:\Mydirectory\JavaPrgs>set path = %path%;.;C:\Java\Jdk1.5\bin"; where C:\Java is the installation folder for Jdk.15

2.Set the path in MyComputer Environment variable.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "PATH" and enter the variable value as %path%;.;C:\java_home\bin; and click OK.
This is the permanent solution, this works fine till the java is there in the specified directory or the path variable available in the EnvironmentVariables.

How to set the classpath?
Solution:
Setting the classpath is very similar to setting the path variable.
This is also can be done in two ways.

1.Set the classpath at command prompt.
set classpath = "%classpath%;.;JAVA_HOME\lib";
%path% tells that the old "classpath" variable values should be remained as it is and the new values should be appended to the old 'classpath'variable value.
"." represents the current directory
It is a temporary solution the classpath variable is available only for the current session,
that is till the command prompt is closed.
Ex: C:\Mydirectory\JavaPrgs>set classpath = %classpath%;.;C:\Java\Jdk1.5\lib"; where C:\Java is the installation folder for Jdk.15

2.Set the classpath in MyComputer Environment variable.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "CLASSPATH" and enter the variable value as %classpath%;.;C:\java_home\lib; and click OK.
This is the permanent solution, this works fine till the java is there in the specified directory or the classpath variable available in the EnvironmentVariables.

How to set the Tomcat configuration variables?
Solution:
To run the Tomcat server you have to configure two variables in the EnvironmentVariables

1. JAVA_HOME : this is the Java installation home directory.
To configure this variable; Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "JAVA_HOME" and enter the variable value as C:\Java\Jdk.15;
(say java is installed in the C:\Java\Jdk1.5 directory) and click OK.

2. CATALINA_HOME : this is the Tomcat installation home directory.
To configure this variable; Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables
In User variables click on the New and give the Variable name as "CATALINA_HOME" and enter the variable value as C:\Tomcat5.0;
(say java is installed in the C:\Tomcat5.0 directory) and click OK.
(If tomcat is installed in the C:\jakarta_tomcat\Tomcat5.0 folder then set the value to this)

How to set the classpath to jdbc thin driver(that is type-4 driver) for oracle?
Solution:
To use the jdbc thin driver for oracle the classpath has to be set to the classes_111.jar or classes_12.jar or ojdbc14.jar depending on the oracle version.
For oracle 10XE thin driver classes are available in the ojdbc14.jar, you can set classpath to this jar in the EnvironmentVariables.
Right click on the MyComputer and select properties, select Advanced Tab and click on the EnvironmentVariables,
if the CLASSPATH variable is already present click on the Edit and add the jar file path at the end of the classpath variable value.
Ex: %classpath%;.;C:\Java\Jdk1.5\lib;C:\oracleexe\app\oracle\product\10.20.0\server\jdbc\lib\ojdbc14.jar;
Depending on the oracle version search for the above mentioned jars and set the classpath to that jar as it is in the above example.
If the above mentioned jar names are in the zip format say classes_111.zip then rename the extension from zip to jar either directly or by
extracting then set the classpath to classes_111.jar
If your developing the application through the Eclipse or any other IDE add the jar in the classpath libraries in the below manner.
Right click on the project, select properties, select JavaBuildPath, select Libraries tab,click on the AddExternalJars button,
browse and select the jar click OK.

How to set the class path to run the servlets?
Solution:
1. Either set the class path to servlet-api.jar or j2ee.jar
2.Or add the jar to the class path of the project

Java Issues and Solutions - 1

How to convert an array to list?
Solution:
This is an example to convert String of arrays to list of arrays.//Say array is initialized as below
String[] s = new String[3];
s[0] = "test1";
s[1] = "test2";
s[2] = "test3";
//Method to convert array to list
private List convetArrayToList(String[] s)
{
List testList = new ArrayList();

//Conversion from array to list
int size = s.length;
for(int i=0;i<size;i++)
{
testList.add(s[i]);
}
return testList;
}

How to convert a list to array?
Solution:

This is an example to convert array list to String of arrays.
//Say list is initialized as below
List testList = new ArrayList();testList.add("test1");
testList.add("test2");
testList.add("test3");
//Method to convert list to array
private String[] convetListToArray(List list)
{
String[] s = new String[list.size()];
Iterator listIterator = list.iterator();
int i = 0;
while(listIterator.hasNext())
{
Object temp = listIterator.hasNext();
if(temp instanceof String)
s[i++] = (String) temp;
}
return s;
}

How to convert a numeric string to integer or double etc.,?
Solution:
Use the parseXXX method of that data types wrapper class.
String intString = "123";
int value = Integer.parseInt(intString);
String doubleString = "123.45";
double value = Double.parseDouble(doubleString);

How to store the elements in sorted order?
Solution:
Use tree set to store the elements, it stores the elements in sorted order.
Set s = new TreeSet();
s.add("CCC");
s.add("AAA");
s.add("GGG");
s.add("BBB");
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
Object temp = setIterator.next();
String value = (String)temp;
System.out.println(value);
}
This will return the elements in the below order.
AAA
BBB
CCC
GGG

How get all the elements of a map without knowing the keys? or How to iterate through a map elements ?
We can't directly iterate through the map, you can do it by getting all the keys of the map into a set, iterating that set and by passing the set element to map as key you can get the corresponding value from map.
Map m = new Map();
m.put("1", "First");
m.put("2", "Second");
m.put("3", "Third");
m.put("4", "Fourth");
//Get all the keys from map
Set s = m.keySet();
Iterator setIterator = s.iterator();
while(setIterator.hasNext())
{
String key = (String) setIterator.next();
//Pass each key to the map to get the map value
//to the corresponding key
String value = (String)m.get(key);
System.out.println("The key is: "+key+" :value is: "+value);
}
This will give the output:
The key is: 1 :value is: First
The key is: 2 :value is: Second
The key is: 3 :value is: Third
The key is: 4 :value is: Fourth