In this tutorial, we are going to see Method overloading and overriding interview questions.

1. What is method overloading?

Answer:
If two or more methods have same name , but different argument then it is called method overloading.
For example:
Array's sort method have many overloaded versions. You can sort array of double, int, String etc.

2. What are rules of method overloading?

Rules of Method overloading :
Number of Arguments
Overloaded method can have different number of arguments
Date type Overload method can have different data type for argument
Return type

Return type can be changed but either number of argument or data type of argument should also be changed..
Order of argumentsIf you change sequence of arguments then it is also valid method overloading provided you have different data types arguments.
ConstructorCan be overloaded

3. Can we overload static methods in java?

Answer:
Yes, we can overload static methods in java but we can not override them.

4. Can you overload main method?

Answer:
Yes, you can overload main method but only method with signature public static void main(String[] args) will be used when your class is invoked by JVM.

5. Can we change only return type while method overloading?

Answer:
You can not.If we change only return type, it will become ambiguous for compiler to figure out which method to call.That is why you can not change only return type.

6. What is method overriding?

Answer:
If subclass is having same method as base class then it is known as method overriding Or in another words, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding.

7. What are rules of method overriding?

Rules for method overriding:
Arguments Must not change
Return type Can't change except for covariant (subtype) returns
Access Modifier Must not be more restrictive. Can be less restrictive.
Exceptions Can reduce or eliminate but must not throw new/broader checked exceptions
ContructorCan not be overriden
Static methodCan not be overriden
final methodCan not be overriden

8.  Can you override static methods in java?

Answer:
No, you can not override static methods in java. Static methods belongs to class level not at object level.You can create static method with same name in child class and it won't give you compilation error but it is called method hiding. You won't get overriding behaviour with it.

9. Can you override private methods in java?

Answer:
No, you can not override private methods in java. Private methods are not visible to child class, hence you can not override it , you can only hide it.

10. Can you override final methods?

Answer:
Because final methods are meant to be not overridden.You declare a method final because you don't want it to be overridden in subclass.

11. What is static binding?

Answer:
When you compile Java program. During compilation process, compiler bind method call to actual method. This is called static binding and method overloading binding happens at compile time.

12. What is dynamic binding?

Answer:
Binding of overridden methods happen at runtime is known as dynamic binding.

13. What are Covariant return type in java?

Covariant return type means if subclass overrides any method, return type of this overriding method can be subclass of return type of base class method.
For example:
package org.arpit.java2blog;

public class BaseClass {

 public A m1() {
  System.out.println("In BaseClass method");
  return new A();
 }

 public static void main(String args[])
 {
  BaseClass b=new SubClass();
  b.m1();
 }
}

class SubClass extends BaseClass {
 public B m1() {
  System.out.println("In SubClass method");
  return new B();

 }
}

class A {
}

class B extends A {

}
Above example is perfect example of covariant return type.

14. Predict output of below program:

public class MethodOverloadingExample {
 
 public void methodTest(Object object)
 {
  System.out.println("Calling object method");
 }
 
 public void methodTest(String object)
 {
  System.out.println("Calling String method");
 }
 
 public static void main(String args[])
 {
  MethodOverloadingExample moe=new MethodOverloadingExample();
  moe.methodTest(null);
 }
}
Output:
Calling String method
Explanation:
When we have two overloaded version of same method, JVM will always call most specific method.

15. Predict output of below program:

public class MethodOverloadingExample {
 
 public void methodTest(Object object)
 {
  System.out.println("Calling object method");
 }
 
 public void methodTest(String str)
 {
  System.out.println("Calling String method");
 }
 
 public void methodTest(int i)
 {
  System.out.println("Calling int method");
 }
 
 public static void main(String args[])
 {
  MethodOverloadingExample moe=new MethodOverloadingExample();
  moe.methodTest(null);
 }
}
Output:
compile time error
Explanation:
When we have three overloaded version of same method, JVM will not able to decide which method to call this time.

16. Predict output of below program:

import java.io.IOException;

public class MethodOverrdingTestMain { 
 public static void main(String[] args) {
  B b=new B();
  try {
   b.method();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
class A{
 
 public void method() throws IOException
 {
  
 }
}
class B extends A{
 
 public void method() throws Exception
 {
  
 }
}
Output:
compile time error
Explanation:
As exception thrown by overridden method can not be more restrictive, it will result in compile time error.

In this tutorial, we are going to see Multitheading interview questions with answers.
Here is list of Multithreading interview questions.

1. What is thread in java?

Answer:
Thread can be called as light weight process. It can be referred as smallest part of process which can be executed concurrently with other parts(threads) of process.

2. What is Multithreading?

Answer:]
Multithreading is execution of multiple threads concurrently. Java supports multithreading , so it allows your application to perform two or more task concurrently. Multithreading can be of advantage specially when now a days, machine has multiple CPUs, so multiple tasks can be executed concurrently.

3. What are ways to create a thread in java?

Answer:
There are two ways to create a thread in java
  • By extending thread class
  • By implementing Runnable interface.
You can read about more at Java thread example.

4. Thread vs Runnable which is better approach to create a thread?

Answer:
Implementing Runnable interface is considered to be better approach than Extending Thread due to following reasons.
  • Java does not support multiple inheritance so if you extend Thread class and you can not extend any other class which is needed in most of the cases. 
  • Runnable interface represents a task and this can be executed with help of Thread class or Executors. 
  • When you use inheritance, it is because you want to extend some properties of parent, modify or improve class behavior. But if you are extending thread class just to create thread, so it may not be recommended behavior for Object Oriented Programming.

5. What are differences between thread and process?

Answer: 
You can go through difference between process and thread to see the differences.

6. What are differences between Sleep and wait in java?

Parameter
wait
sleep
Synchonized
wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException

It need not be called from synchronized block or methods
Calls on
wait method operates on Object and defined in Object class

Sleep method operates on current thread and is in java.lang.Thread
Release of lock
wait release lock of object on which it is called and also other locks if it holds any
Sleep method does not release lock at all
Wake up condition
until call notify() or notifyAll() from Object class
Until time expires or calls interrupt()
static
wait is non static method
sleep is static method
You can refer difference between sleep and wait in java for more details.

7. Define states of thread in java?

Answer: 
There are 5 states of thread in java
New : When you create a thread object and it is not alive yet.
Runnable:  When you call start method of thread, it goes into Runnable state. Whether it will execute immediately or execute after some times , depends on thread scheduler.
Running : When thread is being executed, it goes to running state.
Blocked : When thread waits for some resources or some other thread to complete (due to thread's join), it goes to blocked state.
Dead: When thread's run method returns, thread goes to dead state.

8. Can we call run method directly to start a thread?

Answer: 
No, you can not directly call run method to start a thread. You need to call start method to create a new thread. If you call run method directly , it won't create a new thread and it will be in same stack as main.
You can refer can we call run method directly to start a thread for more details

9. Can we start a thread twice in java?

Answer: 
No, Once you have started a thread, it can not be started again. If you try to start thread again , it will throw IllegalThreadStateException.
You can refer can we start thread twice for more details

10. How to make a main thread wait until all other threads finished execution?

Answer: 
You can make use of join method to achieve above scenario.
You can read more about join method.

11. What are daemon threads?

Answer: Daemon threads are low priority background threads which provide services to user threads. It's life depends on user threads. If no user thread is running then JVM can exit even if daemon threads are running. JVM do not wait for daemon threads to finish.

12. How can you change user thread to daemon thread?

Answer: setDaemon method can be used to mark thread as user thread. If you put setDaemon(true), it makes thread as daemon.

13. What is Synchronization?

Answer: Synchronization is ability to restrict access to shared resource to only one thread. When two or more threads need access to shared resource, there has to be some mechanism such that shared resource will be used by only one thread. The process by which we can achieve it is called Synchronization.

14. What is need of Synchronization? 

Let's understand this with the help of example.
Let's say you want to count number of request you got for a particular URL. If you get two requests at the same time, then count may be inconsistent.
Without Synchronization:
package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 also sees count as 20 and increment it to 21. This shows that count became inconsistent.
With Synchronization:
You can achieve Synchronization using two ways.
  • synchronized method
  • synchronized block
You can not use synchronized with  instance or class variables.

synchronized method

You can make whole incrementCount() method synchronized so no two thread can access it parallelly.
package org.arpit.java2blog;

public class RequestCounter {
 
 private int count;
 
 public synchronized int incrementCount()
 {
  count++;
  return count;
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

synchronized block

You can make use block to synchronize critical section in  incrementCount() method so no two thread can access block concurrently.
package org.arpit.java2blog;

public class RequestCounter {

 private int count;

 public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }
 }
}
For example:
Thread T1 sees count as 20 and increment it to 21. At the same time, thread t2 will now see count as 21 and increment it to 22.

15. Can you explain about Object level locking and class level locking?

There are two types of locking in java.
  • Object level locking 
  • Class level locking
Object level locking:
Object level locking means you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance. It is used if you want to protect non static data.
You can achieve Object level locking by following.

Make method synchronized:

public synchronized int incrementCount()
{
}

Using synchronized block and lock on this:

public int incrementCount() {
  synchronized (this) {
   count++;
   return count;
  }

Using synchronized block and lock on some other object:

private final Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }
Class level locking:
Class level locking means you want to synchronize static method or block so that it can be accessed by only one thread for whole class. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.
This can be achieved by following:

Make static method synchronized:

public static synchronized int incrementCount()
{
}

Using synchronized block and lock on .class:

public int incrementCount() {
  synchronized (RequestCounter.class) {
   count++;
   return count;
  }

Using synchronized block and lock on some other static object:

private final static Object lock=new Object();
public int incrementCount() {
  synchronized (lock) {
   count++;
   return count;
  }

16. Can two threads execute static and non static methods concurrently? 

Answer:
Yes, Since two threads will acquire lock on different objects, they can be executed concurrently without any issues.

17. If one method of class is synchronized and other method of same class is not synchronized? Can they be executed concurrently by two threads?

Answer:
Yes, because one thread will require lock to get into synchronized block but second thread which will execute non synchronized method that won't require any lock, so it can be executed concurrently.

18. Is it safe to call a synchronized method from another synchronized method?

Answer:
Yes, it is safe to call a synchronized method from another synchronized method because when you call synchronized method, you will get lock on this object and when you call another synchronized method of same class, it is safe to execute as it already has lock on this object.
For example:
public synchronized void method1() {
  method2();
  // some code
 }
 
 public synchronized void method2() {
  // some code
 }
You are actually doing this.
public void method1() {
  synchronized (this) {
   method2();
   // some code
  }
  
 }
 
 public void method2() {
  synchronized (this) {
  // some code
  }
 }
Here if any thread calls method2 from method1, it will already have lock on this object hence It is safe to execute.

19. What is deadlock?

Answer:
Deadlock is a situation where two or more threads are waiting for each other to release the resource.
For example:
Thread 1 have lock over object 1 and waiting to get lock on object 2. Thread 2 have lock over object 2 and waiting to get lock on object 1. In this scenario, both threads will wait for each other indefinitely.

20. What are differences between notify and notifyall?

Answer: 
You can go through difference between notify and notifyall to see the differences.

In this post, we are going to see difference between notify and notifyall in java.

notify():

When you call notify method on the object, it wakes one of thread waiting for that object. So if multiple threads are waiting for an object, it will wake of one of them. Now you must be wondering which one it will wake up. It actually depends on OS implementation.

notifyAll() :

notifyAll will wake up all threads waiting on that object unlike notify which wakes up only one of them.Which one will wake up first depends on thread priority and OS implementation.

Lets understand it with the help of example:
1. Create a class named File.java:
It is java bean class on which thread will act and call wait and notify method.
package org.arpit.java2blog.thread;

public class File {
 
 String name;
 boolean isCompleted;
 
 public File(String name) {
  super();
  this.name = name;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isCompleted() {
  return isCompleted;
 }
 public void setCompleted(boolean isCompleted) {
  this.isCompleted = isCompleted;
 }
 
}
2. Create a class named FileReader.java
This thread will wait until other thread call notify method, then after it will complete its processing. It will first take a lock on file object and will be called from synchronized block .So in this example, it will wait for FileWriter to complete the file.
package org.arpit.java2blog.thread;

public class FileReader implements Runnable{
 
 File file;
 
 public FileReader(File file) {
  super();
  this.file = file;
 }

 @Override
 public void run() {
  synchronized (file) {
   System.out.println(Thread.currentThread().getName()+" is waiting for the file to be completed: "+file.getName());
   try {
    file.wait();
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+": File has been completed now!! you can read it");
  }
 } 

}

3. Create a class named FileWriter.java
This class will notify thread(in case of notify) which is waiting on file object. It will not give away lock as soon as notify is called, it first complete its synchronized block. So in this example, FileWriter will complete the file and notify it to FileReaders.
package org.arpit.java2blog.thread;
public class FileWriter implements Runnable{

 File file;
 
 public FileWriter(File file) {
  super();
  this.file = file;
 }

 @Override
 public void run() {
  synchronized (file) {
   System.out.println("Write is going to start writing the file : " +file.getName() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   file.setCompleted(true);
   System.out.println("File has been completed now");
   
   file.notify();
   System.out.println("notify one reader");
  
  } 
 }
}
4. Create a class NotifyAndNotifyAllMain,java.
This is our main class which will create object of above classes and run it.
package org.arpit.java2blog.thread;

public class NotifyAndNotifyAllMain {
 
 public static void main(String args[])
 {
  // File object on which wait and notify method will be called
  File file=new File("Excel file");
  FileReader reader1=new FileReader(file);
  FileReader reader2=new FileReader(file);
  
  // FileReader threads which will wait for completion of file
  Thread thread1=new Thread(reader1,"Reader 1");
  Thread thread2=new Thread(reader2,"Reader 2");
  
  thread2.start();
  thread1.start();
  
  // To ensure both readers started waiting for the file
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   
   e.printStackTrace();
  }
  // FileWriter thread which will notify once file get completed
  FileWriter fileWriter=new FileWriter(file);
  Thread fileWriterThread=new Thread(fileWriter);
  fileWriterThread.start();
 }
}
In case of notify():
When you run above program, you will get following outputs:
Reader 2 is waiting for the file to be completed: Excel file
Reader 1 is waiting for the file to be completed: Excel file
Write is going to start writing the file : Excel file
File has been completed now
notify one reader
Reader 2: File has been completed now!! you can read it
So here,two FileReader threads(reader 1 and reader 2) are waiting for file to be completed,so they called file.wait(). Once FileWriter completes it's file, it called file.notify() and reader 2 thread gets up and completes its processing.
In case of notifyAll() :
Lets change FileWriter class to call file.notifyAll().
package org.arpit.java2blog.thread;
public class FileWriter implements Runnable{

 File file;
 
 public FileWriter(File file) {
  super();
  this.file = file;
 }

 @Override
 public void run() {
  synchronized (file) {
   System.out.println("Write is going to start writing the file : " +file.getName() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   file.setCompleted(true);
   System.out.println("File has been completed now");
   
   file.notifyAll();
   System.out.println("notify all readers");
  
  } 
 }
}
When you run above program, you will get following output:
Reader 2 is waiting for the file to be completed: Excel file
Reader 1 is waiting for the file to be completed: Excel file
Write is going to start writing the file : Excel file
File has been completed now
notify all readers
Reader 1: File has been completed now!! you can read it
Reader 2: File has been completed now!! you can read it
In case of notifyAll(), it notifies all threads waiting on that object.

In this tutorial, we are going to see differences between process and thread in java.
If you are working on multithreading in java, it is good to know differences between process and thread. How multithreading can improve performance by executing code in parallel.

Process vs Thread:

  • The process can be referred as program in execution whereas thread is part of process.
  • Process has its own address space whereas multiple threads share same address space of process. Each thread has its own stack.
  • Process can have multiple threads but thread is the smallest unit which can execute concurrently with other threads.
  • Process are quite heavyweight and have more overhead whereas thread is light weight and have less overhead.
  • Process do not depend on each other whereas threads are not independent as they share address space.
  • You do not require synchronization in case of process. Threads require synchronization to avoid unexpected scenarios.
  • Processes can communicate to each other using inter-process communication only where as thread can communicate directly as thread share same address space.
  • You can easily create new threads by calling thread's start method but you need to copy resources of parent process to create a new child process.

In this tutorial, we are going to see difference between throw and throws in java.

throw:

throw keyword is used to throw any custom exception or predefine exception.
For example:
Let's say you want to throw invalidAgeException when employee age is less than 18.
Create a Employee class as below.
package org.arpit.java2blog;

public class Employee {

 String name;
 int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  if(age < 18)
   try {
    throw new InvalidAgeException("Employee's age can not be less than 18");
   } catch (InvalidAgeException e) {
    e.printStackTrace();
   }
  this.age = age;
 }
 
}
Create InvalidAgeException class as below
package org.arpit.java2blog;

public class InvalidAgeException extends Exception{

 String message;
 
 InvalidAgeException(String message)
 {
  super(message);
  this.message=message;
 }
}
Now create a main class named EmployeeExceptionTest.java as below.
package org.arpit.java2blog;

public class EmployeeExceptionTest {
 public static void main(String[] args) {
  Employee e1 = new Employee();
  e1.setName("John");
  e1.setAge(25);

  Employee e2 = new Employee();
  e2.setName("Martin");
  e2.setAge(17);
 }
}
when you run above program, you will get below output:
org.arpit.java2blog.InvalidAgeException: Employee's age can not be less than 18
 at org.arpit.java2blog.Employee.setAge(Employee.java:19)
 at org.arpit.java2blog.ExceptionTest.main(ExceptionTest.java:14)

throws: 

throws keyword is used to declare list of all exception which method might throw. It delegates responsibility of handling exception to calling method.
For example:
Let's say you want to declare InvalidAgeException in setAge() method when employee age is less than 18 and InvalidAgeException exception should be handled in main method.
Create a Employee class as below.
package org.arpit.java2blog;

public class Employee {

 String name;
 int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) throws InvalidAgeException{
 if(age < 18)
  throw new InvalidAgeException("Employee's age can not be less than 18"); 
         this.age = age;
 }
 
}
Create InvalidAgeException class as below
package org.arpit.java2blog;

public class InvalidAgeException extends Exception{

 String message;
 
 InvalidAgeException(String message)
 {
  super(message);
  this.message=message;
 }
}
Now create a main class named EmployeeExceptionTest.java as below.
package org.arpit.java2blog;

public class EmployeeExceptionTest {
 public static void main(String[] args) {
  try {
   Employee e1 = new Employee();
   e1.setName("John");
   e1.setAge(25);

   Employee e2 = new Employee();
   e2.setName("Martin");
   e2.setAge(17);
  } catch (InvalidAgeException e) {
   e.printStackTrace();
  }
 }
}
when you run above program, you will get below output:
org.arpit.java2blog.InvalidAgeException: Employee's age can not be less than 18
 at org.arpit.java2blog.Employee.setAge(Employee.java:19)
 at org.arpit.java2blog.ExceptionTest.main(ExceptionTest.java:14)
If you notice, we have used throws keyword in Employee's setAge method instead of handling InvalidAgeException.
public void setAge(int age) throws InvalidAgeException{
 if(age < 18)
  throw new InvalidAgeException("Employee's age can not be less than 18"); 
         this.age = age;
 }
Now we have used try catch block in main method to handle InvalidAgeException.

Serialization is one of most important concept in java. If you are going to face core java interview, then you might be asked some questions from Serialization.

Question 1: What is Serialization?

Answer:
Java provides mechanism called serialization to persists java objects in a form of ordered or sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

So if we need to serialize any object then it can be read and deserialize it using object's type and other information so we can retrieve original object.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
ObjectOutputStream has many method for serializing object but commonly used method is
    private void writeObject(ObjectOutputStream os) throws IOException
    { 
        
    }
Similarly ObjectInputStream has
    private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
    {
        
    }

Question 2: What is need of Serialization? 

Answer:
Serialization is usually used when there is need to send your data over network or to store in files. By data I mean objects and not text.

Now the problem is your Network infrastructure and your Hard disk is hardware components that understand bits and bytes but not Java objects.

Serialization is the translation of Java object's values/states to bytes to send it over network or to save it.On the other hand, Deserialization is conversion of byte code to corresponding java objects.

Question 3: Can you explain about Concept of serialVersionUID?

Answer:
serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.You can read more at serialVersionUID in java serialization

Question 4: Is it necessary to implement Serializable interface if you want to serialize any object?

Answer:
Yes, it is necessary to implement Serializable interface if you want to serialize any object. Serializable is marker interface.Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.

Question 5: Can you Serialize static variables?

Answer :
No,you can't.As you know static variable are at class level not at object level and you serialize a object so you can't serialize static variables.

Question 6: How can you customize serialization process?

Answer :
You can customize Serialization process by defining writeObject and readObject method.Java serialization provides a mechanism such that if you have private methods with particular signature then they will get called during serialization and deserialization, so in this way, we can customize Serialization process.
For example:
private void writeObject(ObjectOutputStream os) throws IOException, ClassNotFoundException
 { 
  try {
   os.defaultWriteObject();
   os.writeInt(address.getHomeNo());
   os.writeObject(address.getStreet());
   os.writeObject(address.getCity());
  } 
  catch (Exception e) 
  { e.printStackTrace(); }
 }
 
 private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
 {
  try {
   is.defaultReadObject();
   int homeNo=is.readInt();
   String street=(String) is.readObject();
   String city=(String) is.readObject();
   address=new Address(homeNo,street,city);

  }
One thing should be kept in mind that ObjectInputStream should read data in same sequence in which we have written data to ObjectOutputStream.

Question 7: How can you avoid certain member variable of class to be serialized? 

Answer:
You can mark that variable as either static or transient. Let's see a simple example using transient variable.
Transient variable is the variable whose value is not serialized during serialization. You will get default value for these variable when you deserialize it.

Let's say you have Country class and you don't want to Serialize population attribute as it will change with time, so you can declare population attribute as transient and it won't serialized any more. 
Transient keyword example:
Create a classed called Country.java as below:
package org.arpit.java2blog;

import java.io.Serializable;

public class Country implements Serializable {  
  
 String name;  
 transient long population;  
   
 
 public Country() {
 super();
}
public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
    
}  

Create serializationMain.java as below:
package org.arpit.java2blog;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {

  Country india = new Country();
 india.setName("India");
 india.setPopulation(100000);
  try
  {
   FileOutputStream fileOut = new FileOutputStream("country.ser");
   ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
   outStream.writeObject(india);
   outStream.close();
   fileOut.close();
  }catch(IOException i)
  {
   i.printStackTrace();
  }
  
  System.out.println("serialized");
 }
}
When you run above program, you will get below output:
serialized

Now Create a classed called DeserializeMain.java as below:
package org.arpit.java2blog;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeMain {
 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  
  Country india = null;
       try
       {
          FileInputStream fileIn =new FileInputStream("country.ser");
          ObjectInputStream in = new ObjectInputStream(fileIn);
          india = (Country) in.readObject();
          in.close();
          fileIn.close();
       }catch(IOException i)
       {
          i.printStackTrace();
          return;
       }catch(ClassNotFoundException c)
       {
          System.out.println("Country class not found");
          c.printStackTrace();
          return;
       }
       System.out.println("Deserialized Country...");
       System.out.println("Country Name : " + india.getName());
       System.out.println("Population : " + india.getPopulation());
       
 }
}
When you run above program, you will get below output:
Deserialized Country...
Country Name : India
Population : 0
As you can see in above example, we have declared population as transient, so after deserialization, its value became 0 (Default value for long)

Question 8: What  if superclass is Serializable?  Does that mean child class is automatically Serializable?

Answer : Yes

Question 9: What if superclass is Serializable but you don't want subclass to be Serializable?

Answer : If you don't want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.

Question 10 :What is externalizable interface?

Answer: As name suggest it is externalilizing your serialization.If you want to customize your serialization mechanism then you can use it.It uses custom written mechanism to perform marshalling and unmarshalling of objects.Externalizable interface extends Serializable interface. If you implement this interface then you need to override following methods.
    @Override
 public void readExternal(ObjectInput arg0) throws IOException,ClassNotFoundException {

 }

 @Override
 public void writeExternal(ObjectOutput arg0) throws IOException {

 }

Question 11 : What are differences between Serializable and Externalizable in Java?

Answer :
Parameter
Serializable
Externalizable
Marker interface
It is marker interface. You don't have to provide implementation of any method.
Externalizable is not marker interface, you have to override writeExternal and readExternal method.
Control
Serializable interface has less control over serialization process and it is optional to override readObject and writeObject.
Externalizable interface has more control over serialization process and it is mandatory to override writeExternal and readExternal.
Performance
JVM uses reflection to perform serialization in the case of Serializable interface which is quite slow.
Programmer have to implement readExternal and writeExternal methods but it relatively results in better performance
Supersedes
NA
If you implement Externalizable interface and provide implementation of readExternal and writeExternal then it supersedes readObject and writeObject methods in that class. It is due to the fact that Externalizable extends Serializable interface.
Constructor called during Deserialization
Default constructor is not called during Deserialization process.
Default constructor is called during Deserialization process.

In this tutorial,  we are going to see differences between Serializable and Externalizable interface in Java.

Serializable :

It is marker interface and you do not have to provide any methods if you implement this interface. When if any class implement Serializable interface, JVM will take care of Serializing that object.

Externalizable:

As the name suggest it is externalizing your serialization.If you want to customize your serialization mechanism then you can use it.It uses custom written mechanism to perform marshaling and unmarshalling of objects.Externalizable interface extends Serializable interface. If you implement this interface, you need to provide implementation of readExternal() and writeExternal() method.

Externalizable vs Serializable: 

Parameter
Serializable
Externalizable
Marker interface
It is marker interface. You don't have to provide implementation of any method.
Externalizable is not marker interface, you have to override writeExternal and readExternal method.
Control
Serializable interface has less control over serialization process and it is optional to override readObject and writeObject.
Externalizable interface has more control over serialization process and it is mandatory to override writeExternal and readExternal.
Performance
JVM uses reflection to perform serialization in the case of Serializable interface which is quite slow.
Programmer have to implement readExternal and writeExternal methods but it relatively results in better performance
Supersedes
NA
If you implement Externalizable interface and provide implementation of readExternal and writeExternal then it supersedes readObject and writeObject methods in that class. It is due to the fact that Externalizable extends Serializable interface.
Constructor called during Deserialization
Default constructor is not called during Deserialization process.

Default constructor is called during Deserialization process.


In this tutorial, we will see how to rotate an array be K positions.

Problem:

N=6 and k=2
If Arr[] = {1, 2, 3, 4, 5, 6} and k=2
then rotated array will be  {5, 6, 1, 2,  3,  4}

Solution:

There are multiple ways to solve this problem.

Approach 1:

Move each number by 1 place and do it k times.
public static int[] rotateBruteForce(int[] nums, int k) {
		for (int i = 0; i < k; i++) {	
			for (int j = nums.length - 1; j > 0; j--) {
				// move each number by 1 place
				int temp = nums[j];
				nums[j] = nums[j - 1];
				nums[j - 1] = temp;
			}
                        System.out.println("Array rotation after "+(i+1)+" step");
			printArray(nums);
			System.out.println();
		}
        return nums;
    }
Time complexity: o(n*k)
Where n is number of elements and k denotes position shift.
Space complexity: o(1)

Approach 2:

You can rotate the array using temp array in o(n).
	public static int[] rotateExtraSpace(int[] nums, int k)
	{
		int n=nums.length;
		if(k > n) 
	        k=k%n;
	 
	    int[] result = new int[n];
	 
	    for(int i=0; i < k; i++){
	        result[i] = nums[n-k+i];
	    }
	 
	    int index=0;
	    for(int i=k; i<n; i++){
	        result[i] = nums[index++];
	    }
	    return result;
	}
Time complexity: o(n)
Space complexity: o(n)

Approach 3: 

This is the most optimized approach.
Algorithm for this approach works as below:
  • Reverse whole array.
  • Reverse first k elements
  • Reverse rest n-k elements.
For example:
let's say Array is {1,2,3,4,5,6,7,8}
You want to rotate by k position.
It will work as below:
  • You rotate the whole array. So array became: {8,7,6,5,4,3,2,1}
  • Reverse first k elements, so array became : {7,8,6,5,4,3,2,1}
  • Reverse rest of elements, so array became  : {7,8,1,2,3,4,5,6}
Java code:
public static int[] rotateOptimized(int[] nums,int k)
	{
		int n=nums.length;
		if(k > n) 
	        k=k%n;
		nums=reverse(nums,0,n-1);
		nums=reverse(nums,0,k-1);
		nums=reverse(nums,k,n-1);
		return nums;
	}
	public static int[] reverse(int[] nums,int start,int end)
	{
	
		while (start <= end ) {
			int temp=nums[start];
			nums[start]=nums[end];
			nums[end]=temp;
			start++;
			end--;
		}
		return nums;
	}
Time complexity: o(n)
Space complexity: o(1)

Complete Java program to rotate array by K positions:

package org.arpit.java2blog;

public class RotateArrayMain {

	public static void main(String[] args)
	{
		int nums[]={1,2,3,4,5,6,7,8};
		
		System.out.println("Rotate array by shifting one elements by 1 and do it k times");
		int[] result1=rotateBruteForce(nums,2);
		System.out.println("Final rotated array :");
		printArray(result1);
		System.out.println();
		System.out.println("================================");
		System.out.println("Rotate array using extra space");
		
		int nums2[]={10,20,30,40,50,60};
		int[] result2=rotateExtraSpace(nums2,5);
		printArray(result2);
		System.out.println();
		System.out.println("================================");
		System.out.println("Rotate array most optimized approach");
		int nums3[]={1,2,3,4,5,6,7,8,9,10};
		int[] result3=rotateOptimized(nums3,4);
		printArray(result3);
	}
	
	
	public static int[] rotateBruteForce(int[] nums, int k) {
		int n=nums.length;
		if(k > n) 
	        k=k%n;
		for (int i = 0; i < k; i++) {
			for (int j = n - 1; j > 0; j--) {
				// move each number by 1 place
				int temp = nums[j];
				nums[j] = nums[j - 1];
				nums[j - 1] = temp;
			}
		System.out.println("Array rotation after "+(i+1)+" step");
			printArray(nums);
			System.out.println();
		}
        return nums;
    }
	
	public static int[] rotateExtraSpace(int[] nums, int k)
	{
		int n=nums.length;
		if(k > n) 
	        k=k%n;
	 
	    int[] result = new int[n];
	 
	    for(int i=0; i < k; i++){
	        result[i] = nums[n-k+i];
	    }
	 
	    int index=0;
	    for(int i=k; i<n; i++){
	        result[i] = nums[index++];
	    }
	    return result;
	}
	
	public static int[] rotateOptimized(int[] nums,int k)
	{
		int n=nums.length;
		if(k > n) 
	        k=k%n;
		nums=reverse(nums,0,n-1);
		nums=reverse(nums,0,k-1);
		nums=reverse(nums,k,n-1);
		return nums;
	}
	public static int[] reverse(int[] nums,int start,int end)
	{
	
		while (start <= end ) {
			int temp=nums[start];
			nums[start]=nums[end];
			nums[end]=temp;
			start++;
			end--;
		}
		return nums;
	}
	
	public static void printArray(int []arr)
	{
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i]+" ");
		}
	}
}
When you run above program, you will get below output:
Rotate array by shifting one elements by 1 and do it k times
Array rotation after 1 step
8 1 2 3 4 5 6 7 
Array rotation after 2 step
7 8 1 2 3 4 5 6 
Final rotated array :
7 8 1 2 3 4 5 6 
================================
Rotate array using extra space
20 30 40 50 60 10 
================================
Rotate array most optimized approach
7 8 9 10 1 2 3 4 5 6 

 

Java tutorial for beginners Copyright © 2012