java.lang.illegalstateexception:

In this post i am going to discuss about the java.lang.illegalstateexception. Let us see What is meant by this exception?When will be this exception is thrown? and how to fix it?

What is meant by illegalstateexception?

As you read the name of this exception you can able to understand that a particular framework used in your program is under illegal state.Lets have a look at this exception in detail.

This exception may arise in your program mostly if you are dealing with the collection framework of java.util.package.There are many collections like List,Queue,Tree,Maps.Out of which List and Queues(Queue and Deque) tend to throw this illegal state exception at particular conditions.Note that this exception is not just limited to this Collection Framewok.

When will be this exception is thrown?

In java API it is given that "this exception will be thrown, when we try to invoke a particular method at an inappropriate time."Let us see what are the situations on which this exception will be thrown.

1.In case of List collection we use next() method of the Iterator interface to traverse through the

List.We know about the remove() method which is used to remove a particular item in the list.

In order to remove the first object from the list that contains string objects,we have to follow these steps:

List li=new LinkedList();

-----

-------

Iterator i=li.iterator();

i.next(); // visits the object

i.remove();//removes the object

If you call the remove() method before (or without) calling the next() method then this illegal state exception will be thrown as it will leave the List collection in an unstable state.

Similarly, if you want to modify a particular object we will use the set() method of the ListIterator() interface as follows:

List li=new LinkedList();

-----

-------

ListIterator i=li.listIterator();

i.next(); //visits the object

i.set("hello");//modifies the object

Note:

"If you have modified the list after visiting the object ,then using the set() method will throw this illegalstateexception" .

i.set("hello");//Now,using this set() method will throw an illegalstateexception.

2.In case of queues, if you try to add an element to a queue,then you must ensure that the queue is not full.If this queue is full then we cannot add that element, thus causing this exception to be thrown.

Instantiation Exception

I have discussed about this exception in detail in my new post.To have a look at it click here..

In this Post let us discuss about the java.lang.instantiation exception in detail.Let us know what is meant by this exception?why this exception is thrown? and how to solve it.

What is meant by Instantiation Exception?

There are certain classes exists for which we cannot create objects.Lets see what are those classes.

1.We all know that an abstract class cannot be instantiated.But there are some other ways available, through which we can try to instantiate a abstract class.If we use the newInstance() method for creating the object then we will not get that error at compile time.But you will get this Instantiation exception thrown.

2.An abstract class,an interface,even primitive data types like int,float,double,byte can also be represented as the Class objects.Except ordinary class other classes cannot be instantiated.

3.A class that has no default constructor i.e a constructor with no arguments.This default constructor is needed only when an argumented constructor is already defined, otherwise it is not needed.

Look at the following example to understand how to use newInstance() method

class A

{

}

class B

{

......

Class a=Class.forName("A");//representing an ordinary class

a.newInstance();

}

As you see this is another way of instantiating a class.The Class.forName() method will return the object of class Class.Using that object we can call the newInstance() method to instantiate the class A.

Similarly for an interface like Serializable() we can do as follows

Class b=Serializable.class;

b.newInstance();

Here Serializable is an interface but i have represented it as a class using the newInstance() method.

When will be this exception is thrown?

When we try to instantiate the following classes using the newInstance() method, then this exception will be thrown.

Solution:

In java, as far i know there is no way available to instantiate an abstract class or an interface or the primitive data types.So,its better to avoid these statements from the program.If this exception arises due to the absence of a default constructor,it can be overcome by defining a no argument constructor(default constructor)

UnsupportedOperationException:

This is One of the most commonly experienced exception by the java programmers who deals with the immutable or unmodifiable objects.In this post lets see how to deal with this exception.Before that let us absorb what exception is this?when it will be thrown? and finally how to fix this exception.

What is meant by UnsupportedOperationException?

The UnsupportedOperationException tells us that a particular operation cannot be performed as it was restricted for use against a particular object.This exception extends the Runtimeexception which serves as a super class for a group of run-time exceptions.

When this UnsupportedOperationException is thrown?

As the name implies that this exception is thrown when the requested operation cannot be supported. As i have said before this exception is thrown by almost all of the Concrete collections like.
1.Lists
2.Queue
3.Set
4.Maps.

Let us have a quick overview of java collection frameworks related to our discussion.

All those collections that i have listed above are used to store some values and provides some means to traverse the values and even allows the modification of collection.We can create views for those Collections except queue.

You may wonder what is a view?.A view is a read-only format of the collections,which means that through view we can traverse the collections and even we can retrieve values.But if you try to modify the collection using view object this will cause an UnsupportedOperationException to be thrown.For creating Unmodifiable views java provides the following methods.1.Collections.unmodifiableCollection.
2.Collections.unmodifiableList
3.Collections.unmodifiableSet
4.Collections.unmodifiableSortedSet
5.Collections.unmodifiableMap
6.Collections.unmodifiableSortedMap.

Note:

1.The Map collections allow the use of remove() method but does not support add() method using the view object.
2.The un modifiable views does not support either add() or remove() method.

An another important cause of this exception is the use of wrappers between the collections and the primitive types.

How to overcome UnsupportedOperationException?

As we know the cause of this exception it will be quite easy to deal with it.Since view objects do not allow
modification of the collection,the solution that i suggest you is to use the object of the collection rather than using the view object for modification.

UnsupportedClassVersionError:

This Unsupported class version error is one of the common exceptions in java programming. It belongs to java.lang.package.In this post i am going to discuss about this UnsupportedClassVersion error in detail.

What is meant by Unsupported Class Version error?

As the name indicates that the class file that you are trying to execute is not supported by this Java Virtual Machine.You may wonder why this class file is not supported? after all this is a class file containing the byte codes.

Before going to discuss about this exception let us have a glance at the file format of the class file.We all know that the class file is formed when we compile the program..

This class file consists of a two important version numbers.

1.Minor version number

2.Major version number

These two version numbers decide whether this class file is supported by this virtual machine or not.

When this Unsupported Class Version Error is thrown?

When trying to execute the class file,java interpreter first reads the magic numbers 0x CA FE BA BE which identifies whether it is a class file or not,immediately after this magic number the version numbers are located.When the Java Virtual Machine identifies that the virtual numbers in the class file are different from what it can be able to support, then this exception is thrown.

This exception mainly occurs if you compile the program using the Java virtual Machine of higher version and trying to execute in the JVM of lower version.

How to fix this Exception?

If there is a way available to convert your class file from higher version to lower version then your problem might be solved.Fortunately a jar package had already been developed for this purpose,which is known as "Retroweaver".

This Retroweaver enables you to convert a class file from higher version to lower version.But one of the disadvantage of this jar file is it enables you to convert only class files created using jdk 1.5 to its lower version.It does not support class files generated using jdk1.6 and other higher versions.

Search for the keyword Retroweaver in Google and download it from available links.After downloading it extract the file using Winzip .There you can see a folder "release" which lists some jar files.The jar file retroweaver-ex.jar provides you the graphical interface for converting the class files.

If you use jdk 1.6 for developing your programs, I suggest you to use the same JVM to execute the program which You used to compile it.I guess this will fix the problem.

You can also download the desired JVM that supports the class file to be executed from the internet and install it.

To find the class version number that your JVM supports use the following program.

Program:

import java.lang.*;

import java.util.Properties;

import java.io.*;

public class Prop

{

public static void main(String args[])

{

System.out.println(System.getProperty("java.class.version"));

}

}

Output:

50.0

Here,

Major version number: 50

Minor Version number:0

To find the version number of the class file that you are trying to execute, use the following program and supply the name of the class file as input to the program.

ExceptionInInitializerError:

In this post i am going to discuss about the Exception In Initialize Error.This java exception belongs to the java.lang. package.This exception extends the Linkage Error.On seeing this exception you might have no idea about the exception as i have confused.

What is Exception In Initialize Error?

On seeing the name of the exception you may be able to guess that this exception is related to initialization of a variable.Yes of course this error is related to the initialization of a static variables.The variable may be of primitive type or user defined type.You might all have known about the static initializer of a class.

A static initializer is a block enclosed within curly braces without having any name and return type except having the keyword static as follows

static

{

//initialization of values;

}

The static initializer block is meant for initializing the static variables.

Why this ExceptionInInitializer Error is thrown?

If any error occurs during the initialization of variables inside the static initializer block of a class then this error would be thrown.Thus we have to understand that this exception is thrown ,when other exceptions arise in the static initializer block.In the error message the original cause for this exception is also shown.

How to fix this exception?

Since this exception arises in consequence of some other exceptions that arises in the static initializer block.

We have to ensure that the original cause of this exception is fixed otherwise we cannot be able to deal with this exception in any way.

Example situations of this exception:

import java.io.*;

import java.lang.*;

class Exin

{

private static String name;

private static char c;

public Exin(String n)

{

name=n;

}

static

{

c=name.charAt(12);

}

}

public class Exin1

{

public static void main(String args[])

{

Exin e=new Exin("ganesh");

}

}

Exception thrown:

Exception in thread "main" java.lang.ExceptionInInitializerError

at Exin1.main(Exin1.java:22)

Caused by: java.lang.NullPointerException

at Exin.(Exin1.java:14)

... 1 more

Note that in the above program i have tried to access the 12th character in the string "ganesh" using the method charAt() which causes null pointer exception thereby causing the ExceptionInInitializer error.

ClassCastException:

The java.lang.ClassCastException is one of the common exception that is experienced by beginners.Let us know in detail what does it mean?, When it is thrown?and how to fix this exception in this post.

What is meant by java.lang.classcastexception?

You might all be familiar with the word Cast in the programming context.In most of the programming languages Cast refers to conversion.In this exception is is given that Class Cast Exception.So it indicates that in our program we have tried to "convert an object of one class type in to an object of another class type".

Note:

There is one possibility in casting an object,"If a class extends a parent class then the child class object can be casted to its parent class".The reverse process is not possible in most of the programming languages.

Look at the following snippet to understand it:

Class Parent

{

..........

...........

}

Class Child extends Parent

{

...........................

}

Class Sample

{

......

Child c=new Child();

Parent p=c; //converting an object of child type to its parent type

}

In this sample program i have tried to cast an object of class Child to its Parent class type.This is a legitimate casting.

But the reverse casting is not allowed that is

Child c=new Child();

Parent p=new Parent();

c=p; // casting an object of parent type to its child type which is not allowed

When will be this exception is thrown?

There are two main occasions on which this exception will be thrown.

1.As i have already told when you try to cast an object of Parent class to its Child class type this exception will be thrown.

2.When you try to cast an object of one class into another class type that have not extended the other class or they don't have any relationship between them.

See the example,

Class A

{

}

Class B

{

}

B bobject=new B();

A aobject=new A();

aobject=(A)bobject; //throws an ClassCastException

Reason: Trying to cast an object of class B to the type A.

Examples like trying to cast an String object into an Integer will throw this classcastexception.

output:

As you see the output of this program we can able to understand that i have tried to cast an object of Parent class to its Child class type.

Example 2:

import java.util.*;

import java.lang.*;

class Listimpl{

public Listimpl(T a)

{

i=(List)a;

i.get(0).intValue();

}

private List i;

}

class Castimpl

{

public static void main(final String[] args)

{

List s = new LinkedList();

s.add("jesus");

Listimpl i = new Listimpl(s);

}

}

This kind of exceptions also arises when we are dealing with Generic Programming.Look at the above program to understand this problem.

In the above program, I have anticipated for the List of Integer type in the constructor Listimpl but actually i have created the object for Listimpl as String type.

Since i have used List as the cast type(i=List(a);) the compiler would not bother about the type of the List that we are assigning to the List i of Integer type.

So it does not shows any compilation error while assigning to an list of Integer object type.

As the value stored in that list is a string object, when we try to convert it into an integer value using the intValue() method, class cast exception is thrown.

This kind of exceptions usually occur in the situations like,we may be anticipating an integer object from the client system but we actually received the String object,we may expect integer values as the result of a query from the database but the actual value stored in the database may be a String value.

Solution:

So,when trying to cast an object of one class type into another class type ensure that the type to be casted is of its parent type.

In this post i am going to deal with the object not serializable exception thrown because of containing a non-serializable object.This is another important reason for this exception to be thrown. i have already dealt with this exception thrown because of not implementing the serializable interface.

What is meant by a non-serializable object?

An object of a class that does not implement the serializable interface is called a non-serializable object. For example, you could have created an object for a class that does not implement the serializable interface,like

class Sample // A class not implementing the serializable interface{......

......... }

Sample sampleobject=new Sample(); //Here 'sampleobject' is a non-serializable object.There are certain classes exists in the JDK library which cannot be serialized by default.

-->

When this exception is thrown?

If a class that implements the serializable interface contains statements that refers to an non-serializable object,then the object of that class becomes non-serializable even though it implements the Serializable() interface and if you try to serialize the object then this exception will be thrown.

How to fix this exception?

One solution that i suggest you is to make the non-serializable object into a serializable one by making the class of the non-serializable object to implement the Serializable() interace or remove the reference to that object.

Not Serializable Exception:

The java.io.notserializable exception is one of the common exception experienced by the java programmers who uses object serialization and de-serialization concepts.In this post let us discuss about the object not serializable exception.

What is meant by java.io.notserializableException:

This exception indicates that the object that you are trying to serialize is not serializable for some reasons.This exception belongs to java.io.package.This exception is thrown while serialization of objects are performed. Let us see the two important reason for which this exception is thrown.

When this notserializable Exception is thrown?

As i have told before there are two important reason for which this exception is thrown. Let us consider first and the most important reason for which this exception is thrown.

The first reason for which an object becomes not serializable is that the class of the object do not implements the serializable interface.

Conditions:

It should be noted that if we want to serialize an object of class then that class must implement the serializable interface or it must extend the class which implements the serializable interface.

If the above mentioned conditions are not met then the objects cannot be serialized.

How to fix the not serializable exception?

1. Make the class of the object which you are trying to serialize to implement the Serializable() interface.

2.Otherwise extend the class which implements the Serializable() interface.

Example situation for this exception:

import java.io.*;

import java.util.*;

class Parent

{

Parent()

{

}

String parentname;

Parent(String name)

{

parentname=name;

}

}

class Child1 extends Parent implements Serializable

{

Child1(String name)

{

super(name);

}

}

class Child2

{

public static void main(String args[])

{

Child1 c1=new Child1("ganesh");

Parent p=new Parent("Jesus");

try

{

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));

out.writeObject(c1);

out.writeObject(p);

out.close();

ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));

Parent pa=(Parent)in.readObject();

Parent parent = (Child1) in.readObject();

in.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Exception thrown:

java.io.NotSerializableException: Parent

at java.io.ObjectOutputStream.writeObject0(Unknown Source)

at java.io.ObjectOutputStream.writeObject(Unknown Source)

at Child2.main(Child2.java:35)

This Exceptions shows that i have tried to serialize the instance of the Parent class which does not implements the serializable interface in the class Child2.

I have highlighted the statements which causes this Exceptions in Bold in the program.

Note that the class Parent does not implements the serializable interface which is the sole reason this exception.This exception can be avoided by making the class Parent to implement the Serializable interface.

I have dealt with the java.io.NotSerializableException thrown because of a serializable object containing a non-serializable object in the other post java.io.NotSerializableException : containing a non-serializable .

Invalid Class Exception: no valid constructor

The Invalid class exception is one of the commonly experienced exception by the java programmers who use object serialization in their program.There are three main causes for this exception to be thrown.They are,

1.serial version of the class

2.containing unknown data types,

3.no-arg constructor.

In this post we will discuss about the third reason "No-arg constructor".How the absence of a no-arg constructor causes this exception to be thrown.

What is meant by Invalid class exception?

As the name of the exception indicates that, the class of the object which is serialized or deserialized becomes invalid due to one of the reasons which i have listed out before.This causes the class to be

invalid and the objects of which cannot be serialized or deserialized.This class extends the ObjectStreamException.

When this InvalidClassException:no valid constructor is thrown?

This type of exception is thrown when inheritance is involved in the program.When inheritance is involved, the serialization process proceeds by serializing the objects of child classes first and then moves up the hierarchy until the non-serializable parent class is reached.

When the objects are to be deserialized it starts from the non-serializable parent class and moves down the hierarchy.Since the parent class is non-serializable the state information about the members of the parent class can only be retrieved from the default constructor as it cannot be retrieved from the stream.Since this state information is available only in the default constructor the absence of which makes the class invalid.

Example of the InvalidClassException:

import java.io.*;

import java.util.*;

class Parent //non-serializable parent class

{

String parentname;

//absence of no-arg constructor

Parent(String name)

{

parentname=name;

}

}

class Child1 extends Parent implements Serializable

{

Child1(String name)

{

super(name);

}

}

class Child2

{

public static void main(String args[])

{

Child1 c1=new Child1("ganesh");

try

{

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"));

out.writeObject(c1);

out.close();

ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"));

Parent p = (Child1) in.readObject();

in.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Output:

java.io.InvalidClassException: Child1; Child1; no valid constructor

at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)

at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at Child2.main(Child2.java:34)

In the above program i have implemented a parent class Parent which is extended by a child class Child1. As i have told before the objects of class Child1 are serialized. When de-serializing it searches for default constructor in the parent class Parent as it is not present, this exception will be thrown.

sc serialVersionUID = 1, local class serialVersionUID = 2

at java.io.ObjectStreamClass.initNonProxy(Unknown Source)

at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)

at java.io.ObjectInputStream.readClassDesc(Unknown Source)

at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at Readobject.main(Readobject.java:13)

Note that when executing the above programs for the second time i have purposefully changed the Serial Version Unique Id to 1L while reading the objects(de-serializing).Because of this invalid class Exception is thrown.

InterruptedIOException:

The Interrupted IOException is thrown when the input or output transfer has been terminated because the thread performing it was interrupted.Simply it shows us that the I/O transfer has been interrupted.

This type of exceptions usually occur in the network programming wherein the client tries to communicate with the server.

If the host is unreachable the client/Server waits for a long time and you are at the mercy of the underlying operating system to time out eventually.

Rather than waiting for a long time to timeout,you can also be able to interrupt the thread by using the InterruptedIOException,thereby terminating the socket connection.

For this purpose a method called setSoTimeout() is provided in which you can specify the value of the timeout.

If the waiting time exceeds the timeout value then the InterruptedIOException is thrown to indicate the sockect connection termination.

Program:

import java.io.*;

import java.net.*;

public class Server{

ServerSocket SSocket;

Socket connection = null;

ObjectOutputStream out;

ObjectInputStream in;

String message;

Server(){}

void run()

{

try{

SSocket = new ServerSocket(5000, 10);

SSocket.setSoTimeout(10000);

System.out.println("Waiting for connection");

connection = SSocket.accept();

System.out.println("Connection received from " + connection.getInetAddress().getHostName());

out = new ObjectOutputStream(connection.getOutputStream());

out.flush();

in = new ObjectInputStream(connection.getInputStream());

out.writeObject("Connection successful");

do{

try{

message = (String)in.readObject();

System.out.println("client>" + message);

if (message.equals("done"))

out.writeObject("done");

}

catch(ClassNotFoundException c)

{

c.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

}while(!message.equals("done"));

}

catch(InterruptedIOException e)

{

System.out.println("InterruptedIOException");

e.printStackTrace();

}

catch(IOException ioException){

ioException.printStackTrace();

}

finally{

try{

in.close();

out.close();

SSocket.close();

}

catch(IOException ioException){

ioException.printStackTrace();

}

}

}

public static void main(String args[])

{

Server server = new Server();

while(true){

server.run();

}

}

}

The above program shown is an example of socket connection.This program acts as a server and it has a timeout value set for 10 seconds.If any client fails to communicate to the server within 10 seconds then InterruptedIOException will be thrown.This Exception will be more useful in client side.

Batch File:

In this post i am going to show you the implementation of java program to create a batch file.

We might all wonder about "what is a batch file?","what a batch file contains?". The batch file contains only the DOS commands which we would type in the command prompt.

If you have seen any application,the installation package of the software may contain one or more batch files.These batch files are designed to perform the predefined tasks in the background.

We can able to configure the batch file on our own to perform the tasks that we want to do.

For eg. Initially,when we start to learn java we used the command prompt to compile and execute our program.Before compilation we may have to configure some settings like setting the class path,path etc.

These type of settings can be easily configured by using the batch file rather than typing the commands manually.

ArrayIndexOutOfBoundsException:

The ArrayIndexOutOfBounds Exception is common in the java program that uses array for storing the values.There are many exceptions associated with the arrays like ArrayStorageException and ArrayIndexOutOfBounds Exception.Let us discuss about the ArrayIndexOutOf Bounds Exception.

What is meant by ArrayIndexOutOfBoundsException?

The ArrayIndexOutOf Bounds Exception message gives us some knowledge about this exception.This exception message indicates that a particular statement in the program tries to access the value in the index(Position number of the particular value in the array) which is either greater than or negative or equal to the size of the index.

For eg) Let String a[]={"a","b","c"};

Here a[0]=a;

a[1]=b;

a[2]=c;

Here 1,2,3.. represents the index value.

Briefly said ,it shows us that we are trying to access the index position which is either greater or negative to the size of the array.

When will be this exception is thrown?

As i have said before ,the only reason for this exception to be thrown is: using the index(position) greater than or negative to the size of the array.For eg.If the size of the array is 4 and we are trying to access the value at index 5 will cause this exception to be thrown.

How to Fix this Exception?

In many occasions you might think of increasing the size of the array to mitigate this exception.But this is not the desired solution.If your programming logic is not correct then even if you increase the size of the array this exception will be thrown.So try to correct the statement that causes this exception.So while dealing with arrays ensure that your statement tries to access the value only within in the size of the array.

In this post i am going to tell you all about the most commonly found Exception:- Data source not found and no default driver specified.This is one of the sql Exception which would be thrown when the jdbc:odbc connection is not performed correctly.First of all we must know about the two important things in any database connection

Data source name:

Data source name is nothing but the database name in which u would create tables to

store the data.

Default Drivers:

There are many drivers available in your computer for making jdbc:odbc connection each for specific database.For eg Microsoft Access Driver for creating a connection with the MS Access database.Similarly for sql,mysql and sybase.

This error would occur when creating a jdbc:odbc connection for MS Access database.when i am doing a simple mini-project which makes use of MS Access for back-end support i encountered this error.

Here is the part of the project code which involves making a database connection

In the above program,under the comment line Creating the database connection,i have used the data source name as Prodb21 and the table name as prod21. Lets see how i created the database connection for this part of the program.

Creating a jdbc:odbc Connection:

1) Go to control panel and choose System Security->Administrative tools or simply search in the search toolbar in the control panel for the keyword ODBC.

2) In that Administrative tools window select Data Sources(ODBC).

3) Then ODBC data source administrator window will appear.In that select System DSN tabOn the right side of the window there will be a ADD button.Click it to add a driver for this database connection,then create new source window will appear.

Error 1722 in java

Error 1722: There is a problem with this windows installer package. A program run as part of the setup did not finish as expected.Contact your support personnel or package vendor.

This error is an install shield error code.This indicates that the installation process has failed.

One way that resolves this problem is uninstalling the corrupted java package. This can be done as follows:

Remove all the traces of Java Runtime from your computer. Do this by clicking the Windows "Start" button and clicking the "Control Panel."

Double-click "Add or Remove Programs" (Windows Vista users) to open the programs window. For Windows Vista users, click "Program and Features" and click "Uninstall a Program" to open the programs window.

Scroll through the Programs window and select the Java application you have and click "Remove/Uninstall" to remove it from your computer.

Try downloading and installing Java (see Resources) again. Move to the next step if you run into the 1722 error again.