What is serialization?


  • Serializable means transferable
  • The concept of transferring object of a class from one location to another location is known as Serialization.
  • All the java classes can be divided into two. 
  • The classes whose objects can be transferable .  Objects of all classes  that are implementing serializable  interface can be transferable
  • The classes whose objects can't be transferable .  Objects of all classes  which are not implementing serializable  interface cant be tranferable.
  • To transfer the object need to convert to byte stream :  serializing 
  • To receive Object need to convert from byte stream to Object : deserializing
  • Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

public class Student implements java.io.Serializable
{
   public String name;
   public int number ;
   
}
 
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "harsha";
       
     e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/student.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
} 
     Deserialization
     
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Student e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Student ) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("student class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized student...");
      System.out.println("Name: " + e.name);

      System.out.println("Number: " + e.number);
By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient. - See more at: http://www.javabeat.net/what-is-transient-keyword-in-java/#sthash.TMBQ2f9K.dpuf

    }
} 
 

Transient Keyword: 

  • The keyword transient in Java used to indicate that the variable should not be serialized
  • By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient.
  • If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.

How to write custom Exception?

  • "MyException" is our exception class name. You can give any name of your choice.
    Important thing to be noted is our class extends "Exception" class. This is all we need to do make a custom defined exception
    "Now we define a constructor of my class. This constructor takes a "String" argument. We call super class' constructor(super class here is "Exception class") and pass this string to it. Not java creates a new Exception with the message as in the string passed.

    •   public class MyException extends Exception

      {

          public MyException(String message)        

          { 

              super(message);       

          }     

      }
public class ExceptionDemo 
    {     
        public static void main(String args[]) throws Exception   
        {         
            ExceptionDemo exceptionDemo = new ExceptionDemo();        
            exceptionDemo.displayNumbers();   
        }     
        public void displayNumbers() throws MyException   
        {         
            for(int i=0;i<10;i++)      
            {     
               try{       
                System.out.print(i);          
                if(i==6)          
                {                 
                  throw new MyException("My ExceptionOccurred");             
                }
               catch(Exception e){
              System.out.println(e);
            }    
        }
    }

 

Output: 1 2 3 4 5 6  My exception occured

Why do we need Synchronization?

  • The "Synchronized" keywords prevents concurrent access to a block of code or object by multiple Threads.  
  • Synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race.
  • To prevent consistency problem and thread interference .

Producer consumer problem:


Common   class
package com.instanceofjavaforus;

public class Common {
    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6

What is Synchronization?

  • The concept of avoiding multiple threads entering into a common functionality of common object  simultaneously is known as thread safe or synchronization.
  • we implement the concept of thread safe  using synchronized keyword. The functionality of Synchronized keyword is to avoid multiple threads entering into a common functionality of common functionality. 

Producer consumer problem:

Common   class:

package com.instanceofjavaforus;

public class Common {
    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6

what is the difference between method overloading and method overriding?

Method Overloading in java

  • Method overloading is nothing but defining multiple methods with same name with
    different parameters is known as method overloading
  • while compile time itself we know which method going to get executed.
  • Overloading gives better performance compared to overriding. The reason is that the
    binding of overridden methods is being done at runtime.
  • Argument list should be different while doing method overloading.
  • Return type of overloaded methods should be same.
    static binding is used for overloaded methods
Method overloading interview questions java  

  1. package com.instanceofjava;
  2. class A{
  3.  
  4. public void show(int a){
  5. System.out.println("saidesh");
  6. }
  7.  
  8. public void show(int a,int b){
  9. System.out.println("ajay");
  10. }
  11.  
  12. public void show(float a){
  13. System.out.println("vinod");
  14. }
  15. public static void main(String args[]){
  16.  
  17. A a=new A();
  18.  
  19. a.show(10);
  20. a.show(1,2);
  21. a.show(1.2);
  22.  
  23. }
  24. }
Output:

  1. saidesh
  2. ajay
  3. vinod

Method Overriding in java:
  • Method overriding is nothing but defining multiple methods with same name with
    same definition in super class and sub class is known as Method overriding.
    While Run time only now which method is Executed.
  • Overriding gives slower performance compared to overloading.The reason is that the
    binding of overridden methods is being done at run time.
  • Argument list should be same while doing method overriding.
    Polymorphism applies to overriding. 
  • In method overriding the return type of overriding method can be different from overridden
    method.
  • Dynamic binding used for method overriding methods
Top 10 Interview Programs and questions on method overriding in java  


difference between overloading and overriding in java

What is abstract class and interfaces ?

Abstract Class:

  • Abstract class means hiding the implementation  and showing the function definition to the user is known as Abstract class
  • Abstract classes having Abstract methods and normal methods (non abstract methods) will be there.
  • Abstract classes having methods will be anything means public ,private,protected.
    In Abstract classes  variables will be anything( public, private, protected)
    For Abstract classes we not able to create object directly.But Indirectly we can create object using sub class object.
  • A Java abstract class should be extended using keyword “extends”.
  • A Java abstract class can have instance methods that implements a default behavior.
    If you know requirement and partially implementation you can go for Abstract classes.
    abstract  class  can extend from a class or from an abstract class.
  • Abstract class can extend only one class or one abstract class at a time. so Abstract classes can't support multiple inheritance.
  • In comparison with java Interfaces, java Abstract classes are fast.
    If you add new method to abstract class, you can provide default implementation of it. So you don’t need to change your current code.
  • Abstract classes can have constructors .
    We can run an abstract class if it has main() method.

Interface :

  • Interface nothing but some set of rules.
  • Interfaces having only Abstract methods.it is purely Achieve Abstraction.
  • In Interfaces by default the methods will be public abstract methods.
  • In Interfaces by default the variables will be static final .
  • For Interfaces we can't create object directly or Indirectly but we can give sub class object reference to interface .
  • Java interface should be implemented using keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know Any requirement and any implementation you can go for Interfaces.
  • Interface can extend only from an interface
  • Interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactical not implementation of multiple inheritance).
  • In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add new method to interface, you have to change the classes which are implementing that interface
  • Interface having no constructor.
    we can’t run an interface because they can’t have main method implementation.

     Click here for more points with example

    Select Menu