Search This Blog

Friday, May 31, 2019

How Object Mapper works internally!!


Usually when we work with Json or XML based data objects ,we use some convertors or mappers with it. Object Mapper is one of the data format converter which converts data or objects into different different format.

I was working with one of my project and there we had used lombok for Data objects , when I use it with ObjectMapper , I got to know that ,its not able to convert into type 'Map'. I have just removed lombok annotation and put getters and setters into that Data Object . After these steps that object easily got converted into Map type.

I am writing few points which happens when mapper gets executed. 


Without Annotations:

Without any annotations, it does what is called POJO mapping, it just uses reflection on the instance members and uses some rules about how to map the keys in the json to the names of the instance members. *note: it works on private members as well as public or package protected as well
If it doesn't match the names of the instance members, then it starts trying to match the getXXX and setXXX methods, if it doesn't match anything then it gives up.

With Annotations:

It uses the metadata supplied by the annotations to do the mapping and conversions.
It is always better to explicitly use the annotations when you have the source to add them to, then there is no guess work on what gets mapped to what.
Remember explicit is always better than implicit!

Wednesday, May 22, 2019

Banking Domain interview Questions on Java Part-5

Lets do more questions in java for banking domain companies preparations -

Set A:
1) There are two table t1 and t2 , t2 contains null element . will the inner join contains the null elements as well.
2) There is class A{
A(){
A();
}
Can constructor call it recursively?


3) There is class A {
Functionality();
}
Class B extends class A{
Functionality();
}
Class a functionaly has some code ( common + different ) and class b has some code( common + different ) . without using interface / class . we don’t want to use the common functionality in the derived class.


4) Design parking lot with design patterns using motorcycle( 1 spot ) , car ( 2spot) , bus ( 3 spot) . What will happen when the spot of motorcycle get exhausted . how will you accommodate further motorcycle.
5) There are two table t1 and t2 . t1 contains composite primary key ( a,b,c ) . can foreign key be allowed on single column ( a ) .
6) interface has default method . how to call that method from the derived class?
7) Can we call abstract class method from the derived class?
8) What is super key , candidate key , composite key?
9) What is composition?
10) With keyword in the sql?
11) Use enum in switch case . what does enumConstant.name() return ?
12) Integer pa = null.
Int i = pa;
What is the value of i ?
13) Class Test {
int a , b;
static sum(){
multiply();
}
Multiply(){
}




}
Will it work?
14) Internal working of concurrenthashmap? Why hashmap can have null and concurrenthashmap is not null?
15) Try block with three catch1 , catch2, catch3 . how will you throw exception from catch1 and should be caught in catch3.
16) Whats the new feature in exception class of java 1.8 ?
17) String s = NULL ( capital without quotes ). What will happen?
18) How to create immutable object in java?
19) How to handle diamond problem having two interface with same default method ?
20) What will concurrenthashmap return when we call clear() method simultaneously with threads( reading and writing ) ?
21) How will you handle high memory issue in java application. Please provide all the steps?

Set B:
1) Overview and architecture of previous project.




2) Having a list of 0s and non-zeros like -
7 0 2 8 0 0 5 0
Algo for getting below output
7 2 8 5 0 0 0 0


Scenario A - using same array
Scenario B - using different array.




3) Intra-day stock prices are present in a list -
e.g. [ 30, 40, 75, 60, 100, 10, 25, 65, .....]
Algo to find the buy and selling values in order to make maximum profit.
Buy order should be before Sell order.


Scenario A - You can buy stock only once and sell only once.
Scenario B - You can buy and sell as many times as possible.




4) A module matches the buy and sell orders to carry out a transaction whenever price matches.
We have to add another module which keeps track of the total traded value (in Dollars) of the stock in the day till current time.
What will be the features of the new module. (In terms of concurrency)




5) Messaging Techniques - Synchronous / Asynchronous.
Features and usage of JMS, Web Services, REST, JSON, XML, etc.




6) I we have to design an email server. What will the different classes and its attributes.
(Mail, User, Views, DLs, Attachments and relationship between them.)




7) 2 database Tables-
Employee (Name, Dept_ID, Salary),
and Dept(Dept_Name, Dept_ID)
SQL query to get the name of employees who have salary more than the average salary in their department.




8) Some questions related to Agile methodology - Capacity planning, Sprint Meetings, Task Allocation, etc.




9) Advantages of Spring Boot over normal Spring Applications.


Set C:
1. What is Encapsulation
2. Composition vs Inheritence
3. Any example in which we can use both composition and inheritence
4. What is polymorphism
5. What do mean by final
6. How we can override final method
7. Can we call non static method from static method. If not then what we will have do to call non static method from static method.
8. How we call static method from non static method
9. Do constructor can have return type
10. Can we call constructor from another constructor
11. Static String variable in Interface and it’s accessibility through implementing/Extending class
12. Java 8 default method.
13. Difference between abstract class and interface after java8 default feature
14. Diamond problem
15. What do you mean by immutable object. How can we create immutable object
16. What if use clone method to clone object while creating immutable object
17. What happen if we clone string
18. try with 3 catch, if first catch throws exception then what will happen
19. What is transient
20. What is volatile
21. Swap string without any third variable
22. What are marker interfaces
23. What is inner join.
24. Difference between primary key and unique key
25. Why concurrenthaspmap not allow null key. What happens if 3 threads are reading concurrenhashmap and we call clear method. How clear works internally



I hope all questions are relevant to banking domain companies interview questions in Java.
Feel free to comment in comment box for any query or concerns.

Banking Domain interview Questions on Java Part-4

I hope you have completed all three parts of banking domain interview questions, now its time to jump over next set of questions .

Section A:

1) Current project explanation from cv
2) Roles and responsibilities in past projects
3) Technologies you know
4) Spring Cyclic dependency if class has B bean and class B has class A bean as @Autowired
5) Spring @Autowired annotation
6) In Spring is @Autowired B b in class A not get autowire then what is the problem scenarious in this and its fix
7) Abstract versus Interface
8) Duplets like 1, -1 , 3, -3 in array, and how to find number of duplets
9) Scenario based:- If many number of TREDS transaction are going on in threads and each transaction giving its value money amount and to find the total sum at any time of all previous transactions and threads transaction are going on from moring 9AM to 3:30 PM and at any time to evaluate total amount of all previous transactions.


Section B:
write the the linkedlist template class.
• Asked to write your stack using array and some question on functions push and pop and when/how will you resize it, give implementation logic.
• Problem statement : you have a file of 1000 line, read the line of file by using 10 thread in such a way line one read by thread 1, 2nd by thread 2, line 3 read by thread 3............. line 10 read by thread 10 again line 11 read by thread 1........ line 20 read by thread 10 .... and so on....
1) some question on wait , notifyAll() and synchronization and logic.
• Problem Statement: There is one way linked list find the Nth element from last.
Section C:
1. Static String variable in Interface and it’s accessibility through implementing/Extending class
2. Default method in java
3. Final modifier for to method of implementing class of interface and extending class of abstract class
4. Linked list vs Tree set
5. Hashmap-(get/put method functionality – Collision resolution, improvements in java 8, null as key, multithreading issues with synchronized map, comparison with Hash table, when it will behave as linklist and performance comparison in the same case with linklist time+space both).
6. Concurrent Hashmap- Read/Write/Delete functionality and their parallelism in case of multiple threads
7. Three threads needs to execute and main method waits for their finish, Join functionality internal working, wait internal working
8. What is executor framework and type of pools and way of returning futures
9. Scenario: Multiple threads are executing with one thread throwing unhandled runtime exception, what will be returned in future
10. Design patterns:- Singlton/ Difference between builder vs Factory
11. Joins in sql
12. Composite Key in sql
13. referential integrity
14. Composite key vs Foreign key relationship
15. Algorithm/Puzzle:
Array of 10 numbers: shift by two elements {0,1,2,3,4,5,6,7,8,9}{0,1,1,2,3,4,5,6,7}


Puzzle: Cut a rectangular cake in two equal half without using any scale to measure.

Banking Domain interview Questions on Java Part-3

Now its time for part-3 of CitiBank questions on Java. If you could learn all the sets which i am providing here . Then no one can stop you to crack banking domain companies interviews.

Section A:
1. Brief Introduction about Technical Back Ground, followed by some Questions related to project.
2. How do you create your Multi-Threaded Server, asked about its structure how to handle the request, how to maintain the pool how will you create Pool, how to ensure that thread return to Pool (Do not use any existing API to create the Pool)
3. Employee Object has Instance member which is used to generate the hash Code , put that object in a key and now change the state of the Object , what will happen in get Method and along this with worst case complexity when it will happen , race condition in Hash Map.
4. ++ operator, using volatile in multithreaded environment if use then why if not then what is reason and followed by question related to volatile.
5. Implement Linked List in Java
6. How does Array List is growable when backed by array.
7. Collections.SynchronizedList how does it return the synchronized Array List Reference and follow up by questions related to decorator pattern.
8. Why does Linked List don’t have Constructor which takes the initial capacity as an argument.
9. Can we make sure that Thread A will always start before Start Thread B.
10. How does Concurrent Hash Map maintain the lock and which locking mechanism is used by this.
11. Tree Map and its internal Structure.
12. Class have a method which return reference is there any need to make it thread safe as object is created in inside the method follow up by question related to Thread Safety how to make the class Thread Safe except Immutable.
13. Sleep and Wait Difference.




Section B:


1. Introduction .
2. Any particular challenge which you have faced in your last project .
3. Technologies which you have used in your last project .
4. Question over the string
String a= “test”;
String b= new (“test”)


Difference between them above two objects .
5. What is Spring bean
6. What is environment in spring
7. How to find all the duplets(Like 1,-1 is one duplet) from the given array . Array can be like 1,-1,-1,2,-1,-2,-5
8. How to make the class Singleton
9. There are two objects House and Person and the behavior move in that how I can design my system to implement the move behavior .
Example like : If I want to find that what all we need to do if I want to go out from living room to outside of the house .
Section C:
Question 1
Find out top 10 words from multiple files.


Question 2
There are 3 threads:


1st thread prints {1, 4, 7, …}
2nd thread prints {2, 5, 8, …}
3rd thread prints {3, 6, 9, …}


How will you print {1, 2, 3, 4, 5, 6, 7, 8, 9, ...}? (Write pseudocode).
few questions more from this program


Question 3
find out middle index from linked list


Question 4
Few questions based on non-static synchronization method and static synchronization method. As per design, is it best practice to have both in one class


Section D:
Introduction
2. Whether the String is Palindrome?
3. What is stop method in Thread? (interrupt)
4. We have a huge file, find max occurrence of a keyword in that file.
5. Different methods in a hashmap, return type of values() method of Map.
6. Internal working of a HashMap. How does get and put work?
7. How can you ensure that 6 threads read the file sequentially.
8. ++ operator, using volatile in multithreaded environment if use then why if not then what is reason and followed by question related to volatile.
9. How to take thread dump?


Section E:
Q1. What is the difference between REST and SOAP?


Q2. Exception handling in REST


Q3.Difference PUT and POST?


Q4. There is paragraph with sentences and sentences contains words.
How will you define the order of the n number of threads such that each thread executes one after the other in the order of starting and print the n words for each sentence in each paragraph.

Banking Domain interview Questions on Java Part-2

Including here part-2 of CitiBank interview questions in Java.
Section A.
Q1. Composition v/s Inheritance.
Q2. HashMap, hashcode() and equals() contract.
Q3. Resizing or Rehashing in HashMap.
Q4. Difference between HashMap and Concurrent HashMap.
Q5. Locking in Concurrent HashMap and internal working.
Q6. Any updation in HashMap in jdk8.-balanced tree
Q7. We have an array of integer
Like : 5, 0, 3, 0, 1, 2, 0, 0, 6
Output should be : 5, 3, 1, 2, 6, 0, 0, 0, 0
Q8. We have 100 stories building and 2 eggs. How you will find the safest floor.
(Assume 45th floor is the safest floor. Below 45th floor all floors will be safe and above will be unsafe. (Safe means if we drop egg from the safe floor it will not break, From unsafe egg will break.)) .
Q9. Find the reminder from the method
public long reminder(long a, long b){
// calculate reminder of a and b and return (Long does not support % operator)
}
Q10. What will happen if finalize method throw runtime exception. Will System.gc() will start or the program will exit.
Q11. public int add(int a, int b){ return a+b; }
Above code is in multithreaded environment. Do we need to make it thread safe or it is already thread safe.
Q12. Class Circle{
public void printBlankCircle(){
//some code here
}
public void printBlankCircle(){
//some code here
}
}
Above class is in multithreaded environment? You have to ensure that two threads can simultaneously approach both the methods but 2 threads cannot access same method at same time.


Q13. Employee table
Columns : Name, dept, salary, doj
Write a query to find second highest salary for each department.
Section B:
1) How to maintain the count of the Instances created for a class
2) Replace the nth element of the array with the Largest element found on the right side of it


Asked about the sudo code for this scenario


[3],[2],[1]


[2],[2],[1]


[2],[1],[1]


3) Design a System based on the Input and Output are Provided below


Input: there is a stock Trade data coming each second


Output: System will Publish or Produce top 10 Traded stocks




4) Inter thread Communication Techniques




5) DB Related question:


Two tables Employee(empname,empid,depid,salary) and Department(depname, depid)


Find the average salary of the Employees working inside the same department


Section C:
Scenario 1
There are 3 threads:


1st thread prints {1, 4, 7, …}
2nd thread prints {2, 5, 8, …}
3rd thread prints {3, 6, 9, …}


How will you print {1, 2, 3, 4, 5, 6, 7, 8, 9, ...}? (Write pseudocode).




Scenario 2
There is an Employee class with member variables(String name, int id). Create following objects of Employee class:
Employee emp1 = new Employee(1, "John");
Employee emp2 = new Employee(1, "John");


Create hashmap:
Map<Employee, Employee> map = new HashMap<>();


map.put(emp1, emp1); //put emp1 object into hashmap
Q : If we try to get value using map.get(emp2) then what will return?


Follow up question
map.put(emp2, emp2); //now put emp2 object into hashmap
Q : What will be the size of HashMap?




Scenario 3
There is an existing HashMap using in a project and having lots of data then how will you sort this HashMap on the basis of Keys? (Without using TreeSet).




Scenario 4
There is a linkedlist data structure containing 10 elements, then how will you find the nth last(for e.g. 3rd last or 5th last etc.) element? (Write pseudocode).




Scenario 5
There is an Employee class with member variables(String name, int id) then how will you prevent multiple write access of setter method for name field
in case of multi-threaded environment?
I am sure after watching out all the questions from part-1 and part-2 , you will gain more and more knowledge on cracking banking domain company interviews .
You can comment below to discuss the questions in detail.

Banking Domain interview Questions on Java Part-1

I am including some of the interview questions which are asked in citibank from different different individuals . Right now I am not including answers of these questions but very soon will add the same as well!!

Interview - A


1. Ask details about last assignment, what are the component, roles and responsibility; 2.use of multithreading and singleton design pattern in last assignment.
3. Singleton Design pattern, double check 4.what are the collection used, which one is favourite data structure 5.you have less memory resource, you have an array , once your array gets full how will you insert new element in array without removing existing element.
6.you have an employee class which contains a arraylist of address , how will you make this class immutable, how will you ensure that client could not remove address from arraylist.
7.what are spring scopes.
8.Two bean id are declared for a single class in spring xml, how many instance will be created.
9. Any question for me.



Interview - B


1. Spring - which one is better – setter or constructor injection
2. In a sorted data how will you find a number with maximum occurrence.
3. About previous project and multithreading and batch processing experience.
4. There is a function that accepts two parameters and returns their sum. How will you synchronize access to it.
5. There are hundred threads, a module is there which can at most allow 5 threads. how to implement the same.
6. Experience in design patterns? What is template design pattern and its usage.


Interview - C


1. From sorted and duplicate elements find frequency of a given element.
2. Find loop in linked list
3. HashMap questions
4. Find nth element from bottom of a linked list
5. How to make class Immutable


Interview - D




1.Brief about yourself and project.
2.Basic pillars of OOPS.
3.Difference between abstract and Interface.
4.How to show end User a message without changing the method signature of already existing class only change the method body (no overriding). For e.g : your withdrawal limit has Exceeded more than 40,000.
5.hashmap and its internal working and some scenario based questions.for e.g hashmap<Object,Object> hm = new Hashmap<>(); hm.put(CAR,TRUCK);// what is the Output : hm.get(new CAR(1,”hatchback”));[CAR and TRUCK are different classes with key value already put in the hashmap]
6.Create your Custom HashMap and what are the functionalities you will put and specifically about Entry class.
7.how to implement custom Singly linkedList.
8.how a hashmap converts map into a keySet or entrySet for e.g set<Entry.map<K,V>> = hm.entrySet<K,v>; (internal working).
9.how to find nth element in a singly linked list.
10.How to ensure the Order of Threads without using wait and notify.



Interview - E


1. Brief Introduction about yourself and Describe the project and technologies you have worked on.
2. Difference between Thread and Process?
3. What are the parameters to keep in mind to convert a application into multithreaded application?
4. A batch takes 3hr to complete without multithreading, what will be the impact if 50 threads are run to complete the batch?
5. Given a class
class counter{


int count;


public void increment()
{
count++
}
}
a. If 2 threads are run what will be the value of variable count.
b. Is there any issue in above code.
c. What will happen if count is declared as volatile
d. How to resolve the issues of above code.
5. When can we use only Volatile?
6. What is deadlock. Write code to generate a deadlock?
7. Write a code to create deadlock using singelton class?
8. Min requirement to generate a deadlock(Min objects / Min threads that are required)?
9. How to create a synchronized map?
10. Difference between ConcurrentHashMap and SynchronizedMap?
11. We have 25 reader threads. Which map would you prefer to use in this scenario.(Hashmap or ConcurrentHashMap or SynchronizedMap)?
12. Write a program to print 1,2,3,4,5...and so on using Threads. Given when thread T1 prints only even number and thread T2 prints only odd number.(Order needs to be sequential).
13. Difference between LinkedList and ArrayList?
14. When will you prefer to use linkedlist and when will you prefer ArrayList?
15. Write a code to generate a node of single linked list?
16. Describe the benefits of TreeSet?
17. What the requirements to implement TreeSet for storing custom Objects?
18. Given a TreeSet<Objects> : Now 2 objects 1 of Employee Class and Other of Department class are inserted in set. What will be the size of the set?
19. What do you mean by StackOverFlowException?
20. Write a code to generate StackOverFlowException?



Why Object is super class of every class in Java

The Object class is the base for Java Language and we all reading the below sentences from day one of our Java Programming.

Every class is a Child of the Object class.
Every class in Java extends Object class.
Object class is the super class of every Java Class.


We all read the above lines and stop there. Only few have a return question about the reason behind making the Object class as a super class. There is no secret reason or any magic behind making Object as a super class. Keeping it simple and short, the reason is Inheritance. Yes. The same key feature of OOP, inheritance theory applies here too. To reduce the code duplication.

If you observe the methods in Object class, those the basic methods that every class should contain and they are very basic features or functionalities that every class should have and support (like getting Class name, String representation of Object etc. ).

Object class provides the basic functionality methods which are already implemented in it. You need not to provide(optional) implementation for those methods unless you have a specific requirement. In such cases, you need to override those methods in your Class. Otherwise the default implementation in Object class executes.

Let's divide the methods of Object class by features and you'll realize why those methods put in Object Class.

For string representation of Class :
 toString(); 
For copy of an object :
 clone(); 
For checking equality of an object :
 equals(); 
To support hash techniques on object :
 hashCode();
To support garbage collection :
 finalize();
To give the Class name of object :
 getClass();
To support syncronization on object :
 public final void notify()  
 public final void notifyAll()  
 public final void wait()  
 public final void wait()  
 public final void wait()

If you see, all the methods mentioned is a part of basic feature for every class and Java designers already implemented for you. Otherwise every developer is to keep writing these implementation on their own and end of the day, there will be no business logic written (of course bugs are obvious). Otherwise each person implements in their own style and there will be no uniqueness even. So designers separated these basic functions and made a Class and extended inbuilt.

Other than that big gotcha, there are other uses as well in designer minds. For example to make generic functions with Object as a parameters to methods, to provide default implementations as well, since every Class in Java Is-A Object.

Look at a function which we can write the functionality without even knowing the actual Object being passed to it. For the method writeObject() ,you can pass any instance to it, since it accept all types of Objects. Any ways with Java 1.5 we have generics included for the same purpose..
public final void writeObject(Object obj)

How Serialization works in Java(A brief introduction)

Inheritance in Java Serialization - Example and Explanation

In our previous discussions we came across, Serialization, serialVersionUID and transient variable. In this particular blog we will see ?Inheritance in Serialization?.

Add caption

In case of inheritance, when we want to serialize an object there may be three possible scenarios. 

(1) If Super class is Serializable

In case super class is Serializable than all its subclasses will be serializable by default. No need to implement serializable interface in subclass explicitly. See the implementation below. 

\src\com\javanjvm\core\Human.java

  1. package com.javanjvm.core;    
  2.     
  3. import java.io.Serializable;    
  4.     
  5. /**  
  6.  * @author bharat 
  7.  */    
  8. public class Human implements Serializable {    
  9.     
  10.  private static final long serialVersionUID = 1L;    
  11.     
  12.  String gender;    
  13.  String color;    
  14.     
  15.  Human(String gender, String color) {    
  16.   this.gender = gender;    
  17.   this.color = color;    
  18.  }    
  19.     
  20.  public String getGender() {    
  21.   return gender;    
  22.  }    
  23.     
  24.  public void setGender(String gender) {    
  25.   this.gender = gender;    
  26.  }    
  27.     
  28.  public String getColor() {    
  29.   return color;    
  30.  }    
  31.     
  32.  public void setColor(String color) {    
  33.   this.color = color;    
  34.  }    
  35.     
  36. }    


\src\com\javanjvm\core\Man.java

  1. package com.javanjvm.core;    
  2.     
  3. /**  
  4.  * @author bharat 
  5.  */    
  6. public class Man extends Human {    
  7.     
  8.  private String name;    
  9.  private String address;    
  10.     
  11.  Man(String gender, String color, String name, String address) {    
  12.   super(gender, color);    
  13.   this.name = name;    
  14.   this.address = address;    
  15.  }    
  16.     
  17.  public String getName() {    
  18.   return name;    
  19.  }    
  20.     
  21.  public void setName(String name) {    
  22.   this.name = name;    
  23.  }    
  24.     
  25.  public String getAddress() {    
  26.   return address;    
  27.  }    
  28.     
  29.  public void setAddress(String address) {    
  30.   this.address = address;    
  31.  }    
  32.     


\src\com\javanjvm\core\Implementation.java

  1. package com.javanjvm.core;    
  2.     
  3. import java.io.FileInputStream;    
  4. import java.io.FileNotFoundException;    
  5. import java.io.FileOutputStream;    
  6. import java.io.IOException;    
  7. import java.io.ObjectInputStream;    
  8. import java.io.ObjectOutputStream;    
  9.     
  10. /**  
  11.  * @author bharat 
  12.  */    
  13. public class Implementation {    
  14.  public static void main(String args[]) {    
  15.     
  16.   /*  
  17.    * Assigning values to Man class's instance  
  18.    */    
  19.   Man man = new Man("Male""Black""Anderw""Delhi");    
  20.     
  21.   /*  
  22.    * Serializing Man's instance  
  23.    */    
  24.   try {    
  25.    FileOutputStream fileOutputStream = new FileOutputStream(    
  26.      "serialObject.ser");    
  27.    ObjectOutputStream objectOutputStream = new ObjectOutputStream(    
  28.      fileOutputStream);    
  29.    objectOutputStream.writeObject(man);    
  30.     
  31.   } catch (FileNotFoundException e) {    
  32.    // TODO Auto-generated catch block    
  33.    e.printStackTrace();    
  34.   } catch (IOException ioe) {    
  35.    // TODO Auto-generated catch block    
  36.    ioe.printStackTrace();    
  37.   }    
  38.     
  39.   /*  
  40.    * Deserializing Man's instance  
  41.    */    
  42.   Man manout = null;    
  43.     
  44.   try {    
  45.    FileInputStream fileInputStream = new FileInputStream(    
  46.      "serialobject.ser");    
  47.    ObjectInputStream inputStream = new ObjectInputStream(    
  48.      fileInputStream);    
  49.    manout = (Man) inputStream.readObject();    
  50.     
  51.   } catch (FileNotFoundException e) {    
  52.    // TODO Auto-generated catch block    
  53.    e.printStackTrace();    
  54.   } catch (IOException ioe) {    
  55.    // TODO Auto-generated catch block    
  56.    ioe.printStackTrace();    
  57.   } catch (ClassNotFoundException cnf) {    
  58.    // TODO Auto-generated catch block    
  59.    cnf.printStackTrace();    
  60.   }    
  61.     
  62.   /*  
  63.    * Printing values from deserialized Man's object  
  64.    */    
  65.   System.out.println("Printing value of Deserailized Man's instance :");    
  66.   System.out.println("Gender: " + manout.getGender());    
  67.   System.out.println("Color: " + manout.getColor());    
  68.   System.out.println("Name: " + manout.getName());    
  69.   System.out.println("Address: " + manout.getAddress());    
  70.     
  71.  }    
  72.     
  73. }    

Output:Here is expected output, printing values for deserialized object.



(2) If Super class is not Serializable but subclass is

In case super class is not Serializable than to serialize the subclass?s object we must implement serializable interface in subclass explicitly. In this case the superclass must have a no-argument constructor in it. See the implementation below. 

\src\com\javanjvm\core\Human.java

  1. package com.javanjvm.core;    
  2.     
  3. /**  
  4.  * @author bharat 
  5.  */    
  6. public class Human {    
  7.  String gender;    
  8.  String color;    
  9.     
  10.  Human() {    
  11.  }    
  12.     
  13.  Human(String gender, String color) {    
  14.   this.gender = gender;    
  15.   this.color = color;    
  16.  }    
  17.     
  18.  public String getGender() {    
  19.   return gender;    
  20.  }    
  21.     
  22.  public void setGender(String gender) {    
  23.   this.gender = gender;    
  24.  }    
  25.     
  26.  public String getColor() {    
  27.   return color;    
  28.  }    
  29.     
  30.  public void setColor(String color) {    
  31.   this.color = color;    
  32.  }    
  33.     
  34. }    


\src\com\javanjvm\core\Man.java

  1. package com.javanjvm.core;    
  2.     
  3. import java.io.Serializable;    
  4.     
  5. /**  
  6.  * @author Nagesh Chauhan  
  7.  */    
  8. public class Man extends Human implements Serializable {    
  9.     
  10.  private static final long serialVersionUID = 1L;    
  11.  private String name;    
  12.  private String address;    
  13.     
  14.  Man(String gender, String color, String name, String address) {    
  15.   super(gender, color);    
  16.   this.name = name;    
  17.   this.address = address;    
  18.  }    
  19.     
  20.  public String getName() {    
  21.   return name;    
  22.  }    
  23.     
  24.  public void setName(String name) {    
  25.   this.name = name;    
  26.  }    
  27.     
  28.  public String getAddress() {    
  29.   return address;    
  30.  }    
  31.     
  32.  public void setAddress(String address) {    
  33.   this.address = address;    
  34.  }    
  35.     
  36. }    


\src\com\javanjvm\core\Implementation.java

  1. package com.javanjvm.core;    
  2.     
  3. import java.io.FileInputStream;    
  4. import java.io.FileNotFoundException;    
  5. import java.io.FileOutputStream;    
  6. import java.io.IOException;    
  7. import java.io.ObjectInputStream;    
  8. import java.io.ObjectOutputStream;    
  9.     
  10. /**  
  11.  * @author bharat  
  12.  */    
  13. public class Implementation {    
  14.  public static void main(String args[]) {    
  15.     
  16.   /*  
  17.    * Assigning values to Man class's instance  
  18.    */    
  19.   Man man = new Man("Male""Black""Anderw""Delhi");    
  20.     
  21.   /*  
  22.    * Serializing Man's instance  
  23.    */    
  24.   try {    
  25.    FileOutputStream fileOutputStream = new FileOutputStream(    
  26.      "serialObject.ser");    
  27.    ObjectOutputStream objectOutputStream = new ObjectOutputStream(    
  28.      fileOutputStream);    
  29.    objectOutputStream.writeObject(man);    
  30.     
  31.   } catch (FileNotFoundException e) {    
  32.    // TODO Auto-generated catch block    
  33.    e.printStackTrace();    
  34.   } catch (IOException ioe) {    
  35.    // TODO Auto-generated catch block    
  36.    ioe.printStackTrace();    
  37.   }    
  38.     
  39.   /*  
  40.    * Deserializing Man's instance  
  41.    */    
  42.   Man manout = null;    
  43.     
  44.   try {    
  45.    FileInputStream fileInputStream = new FileInputStream(    
  46.      "serialobject.ser");    
  47.    ObjectInputStream inputStream = new ObjectInputStream(    
  48.      fileInputStream);    
  49.    manout = (Man) inputStream.readObject();    
  50.     
  51.   } catch (FileNotFoundException e) {    
  52.    // TODO Auto-generated catch block    
  53.    e.printStackTrace();    
  54.   } catch (IOException ioe) {    
  55.    // TODO Auto-generated catch block    
  56.    ioe.printStackTrace();    
  57.   } catch (ClassNotFoundException cnf) {    
  58.    // TODO Auto-generated catch block    
  59.    cnf.printStackTrace();    
  60.   }    
  61.     
  62.   /*  
  63.    * Printing values from deserialized Man's object  
  64.    */    
  65.   System.out.println("Printing value of Deserailized Man's instance :");    
  66.   System.out.println("Gender: " + manout.getGender());    
  67.   System.out.println("Color: " + manout.getColor());    
  68.   System.out.println("Name: " + manout.getName());    
  69.   System.out.println("Address: " + manout.getAddress());    
  70.     
  71.  }    
  72.     
  73. }    


Output:Here is expected output, printing values for deserialized object.



If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. As we can see in the output figure above ?Gender? gets a default value and ?Color? is getting null because of no default value set. 


(3) If the superclass is serializable but we don?t want the subclass to be serialized.

To prevent subclass from being serialized we must implement writeObject() and readObject() method and need to throw NotSerializableException from these methods. 

Here we are done with 'Inheritance in Java Serialization'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.