Wednesday, September 5, 2012

where Protocol of serialization is defined in java..??

Many of you used Serializable interface but have you ever think where the protocol of saving Serialization object is defned?
Today i share my knowledge about it how much i know

first lest go through the process of saving object.
class saveObject implements Serializable
{
public static void main(String args[])
    {
    saveObject sb=new saveObject();
    FileOutputStream fo=new FileOutputStream(fileName);
    ObjectOutputStream obs=new ObjectOutputStream(fo);
    obs.writeObject(sb);
    }
}
now if saveObject class implements Serializable then only it work else it throw exception saveObject is not Serialized
this protocol is define in inside ObjectOutputStream.writeObject(Object) method
lets check the method what it have
public final void writeObject(Object obj) throws IOException {
    if (enableOverride) {
        writeObjectOverride(obj);
        return;
    }
    try {
        writeObject0(obj, false);
    } catch (IOException ex) {
        if (depth == 0) {
        writeFatalException(ex);
        }
        throw ex;
    }
    }
here enableOverride is boolean type whose value get assign false inside ObjectOutputStream(fo) constructor
so  writeObject0(obj, false); get execute
now lets see what in  writeObject0(obj, false) method

    private void writeObject0(Object obj, boolean unshared)
    throws IOException
    {
    boolean oldMode = bout.setBlockDataMode(false);
    depth++;
    try {
        // handle previously written and non-replaceable objects
        int h;
        if ((obj = subs.lookup(obj)) == null) {
        writeNull();
        return;
        } else if (!unshared && (h = handles.lookup(obj)) != -1) {
        writeHandle(h);
        return;
        } else if (obj instanceof Class) {
        writeClass((Class) obj, unshared);
        return;
        } else if (obj instanceof ObjectStreamClass) {
        writeClassDesc((ObjectStreamClass) obj, unshared);
        return;
        }
       
        // check for replacement object
        Object orig = obj;
        Class cl = obj.getClass();
        ObjectStreamClass desc;
        for (;;) {
        // REMIND: skip this check for strings/arrays?
        Class repCl;
        desc = ObjectStreamClass.lookup(cl, true);
        if (!desc.hasWriteReplaceMethod() ||
            (obj = desc.invokeWriteReplace(obj)) == null ||
            (repCl = obj.getClass()) == cl)
        {
            break;
        }
        cl = repCl;
        }
        if (enableReplace) {
        Object rep = replaceObject(obj);
        if (rep != obj && rep != null) {
            cl = rep.getClass();
            desc = ObjectStreamClass.lookup(cl, true);
        }
        obj = rep;
        }

        // if object replaced, run through original checks a second time
        if (obj != orig) {
        subs.assign(orig, obj);
        if (obj == null) {
            writeNull();
            return;
        } else if (!unshared && (h = handles.lookup(obj)) != -1) {
            writeHandle(h);
            return;
        } else if (obj instanceof Class) {
            writeClass((Class) obj, unshared);
            return;
        } else if (obj instanceof ObjectStreamClass) {
            writeClassDesc((ObjectStreamClass) obj, unshared);
            return;
        }
        }
       
        // remaining cases
        if (obj instanceof String) {
        writeString((String) obj, unshared);
        } else if (cl.isArray()) {
        writeArray(obj, desc, unshared);
        } else if (obj instanceof Enum) {
        writeEnum((Enum) obj, desc, unshared);
        } else if (obj instanceof Serializable) {        //check this line
        writeOrdinaryObject(obj, desc, unshared);
        } else {
        throw new NotSerializableException(cl.getName());
        }
    } finally {
        depth--;
        bout.setBlockDataMode(oldMode);
    }
    }

as per different condition it perform the action i will not go in detail .Just go through the code where i comment check this line
here our condition get satisfied only if our class implements Serializable interface else it throw exception NotSerializableException
if obj not belong to Enum,String ,Class,ObjectStreamClass.
writeOrdinaryObject(obj, desc, unshared); do the rest thing of saving object
 
For reading object near about  same concept happened in
ObjectInputStream obi=new ObjectInputStream(new FileOutputStream(fileName));
obi.readObject()

Thursday, August 16, 2012

Cause of Error and Exception occur at Runtime in Java

1)java.lang.UnsupportedClassVersionError
This exception occur when you compile the java class with higher version of java environment and try to run that class file in lower version of java environment
for example if you compile the java class with java6 and try to  run that class with java5 you faced this type of exception

2)java.lang.NoClassDefFoundError
This exception occurs when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
possibility of this:
a) Class is not available in Java Classpath.
b) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
c) Any start-up script is overriding Classpath environment variable.
d) Because NoClassDefFoundError is a sub class of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
e) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to failure of static initialization is quite common.
f) If you are working in J2EE environment than visibility of Class among multiple Classloaders can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

3)java.lang.ClassNotFoundException
This exception is nor similair with java.lang.NoClassDefFoundError because ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws
java.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason.

4)java.lang.ClassCastException
This exception occur when we attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
         Object x = new Integer(0);
         System.out.println((String)x);

5)java.lang.ArrayIndexOutOfBoundsException
This exception occur when we accessed the array with an illegal index. The index is either negative or greater than or equal to the size of the array.
we always have to remember that The array indexes in Java start from 0 and go to array.length - 1

6)java.lang.NullPointerException
This exception is most common and every developer faced this exception once in there life.This exception occur when you performed any operation for null object.
To avoid this kind of exception check the null condition before performing any operation of object
for example
String s=null;//here s  is null at present and now if we preform
s.toString();//here you faced NullPointerException

always check null like
if(s!=null)
{
s.toString();
}
 

If you really enjoyed this
give feedback
thanks...... :)
    

Thursday, June 7, 2012

Jvm not only read Bytecode created by compiler and run it,apart from it, it do a lot work for us

while running this program i get stuck.
class A{
    static{
        System.out.println("A");
    }
    public static void main(String ar[]){
        System.out.println("A's main ");
    }
}
class B extends A{
    static{
        System.out.println("B");
    }
}
public class C {
    static{
        System.out.println("C");
    }
    public static void main(String[] args) {
        B.main(null);

    }

}

Now lest run the class C and see what the o/p is:
C
A
A's main 

As per java concept whenever class loaded in memory its static block get executed.its fine.....
now just move step by step for above program.
first class C is loaded in memory so class C static block execute first, then main() method get executed
now let see what inside main method of class C?
B.main(null)
ok

now what class B have?
have one static block only inside and extending class A..ok
now what class A have?
have a main method and one static block.here everything is fine
through class B we reaching to class A's main method because class B extending class A fine....
but when i check the output i have seen class B static block is not get executed means class B is not loaded to memory but without loading class B how class A get loaded..????
i discuss with many people, some say compiler do some edition when we compile the class.but what compler do..???
compiler never have a right to delete our single character then how class B get erased/override and if B is not erase/override then why class B is not loaded on the line executing"B.main(null)"
so by saying that compiler take care of this is absolutely wrong because compiler ony make our word meaningfull like for String it make java.lang.String and perform some complusray task if we not did like extending Object class and creating default constructor if we not create
Then i study JVM ,to know what actual JVM do
and  finally get the answer for this issue

Class are made available to a running program by the Java Virtual Machine. This is done through a process of loading, linking, and initialization. Loading is the process of locating the binary representation of a type and bringing it into the JVM. Linking is the process of taking the type and incorporating it into the runtime state of the JVM so that it can be executed. Initialization is the process of executing the initializers of a type (static initializers for classes; static field initializers for classes and interfaces). When a type becomes unreachable (i.e. the running application has no references to the type), it becomes eligible for garbage collection. This collection is called type unloading.

Here are the step follow when we run our any java program:
   1. Given a class's fully qualified name, produce a stream of binary data that represents that type
   2. Parse the stream of binary data produced in step #1 into internal structures in the method area of the JVM. The method area is a logical area of memory in the VM that is used to store information about loaded types.
   3. Create an instance of class java.lang.Class that represents the class indicated in step #1

According to this lets explain tha above details
B.main(null) come under binary data as mention in step #1
while parsing the data JVM link main(null) directly to class A becuase Main method exist in class A and load only class A
because of that class B not get overloaded


If you really enjoyed this
give feedback
thanks...... :)

Monday, March 19, 2012

Is downcasting is possible regarding object in Java

By the begining of Languages downcasting has a issue.lets checks with C-language
void main()
{
long i=98765431;
byte j=(byte) i;
printf(j);
}
here data overflow and get unexcepted result.
Before discussing this topic first we go through the defination of Upcasting and downcasting


What is upcasting?UpCasting is defined as casting a reference of a parent class type to a type of a reference to a child class.
What is downcasting?Downcasting is defined as casting a reference of a child class type to a type of a reference to a parent class.


Upcasting can de done automatically means implicity in java and
Downcasting we have to do explicity else we get compile time error


now lets going through the defination of upcasting and downcasting code the java program and check....


class parent
{}
class child extend parent
{
public static void main(String args[])

{
line 1: parent p=new child(); //upcasting happened complile and run successfully
line 2: child c=new parent(); // downcasting but not explicity so we get compile time error
line 3: child c1=(child) new parent(); // downcasting explicity compile success but give run time error class cast exception
}
}


now just read the downcasting defination above and check line 3 of above program,we are doing downcasting but it not happening here.


many of us say downcasting is happened in java and gave the example mention below


class parent
{}
class child
{

public static void main(String args[])

{
line 1: parent p=new child(); //upcasting
line 2: child c=(child) p; //downcasting,compile and run success
}
}


look carefully at line 2 we really doin downcasting,i don't think downcasting is not suitable word here we are doing here typecasting

in simple we can say that:
at line 1 we create object of child and say that you are parent type
and at line 2 we again saying to same child object that you are child type here where is the parent object that we are casting to child type..????

what is my opion on this issue is there i posted on this blog....
still have little bit confusion and hoping someone to clear this confusion

If you really enjoyed this
give feedback
thanks...... :)