Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Java interview – Serialization

Java Serialization Interview Questions and Answers

1. What is Serialization?

Serialization is the process of converting an object and its states to a binary stream that can then be saved into a database, cached or sent over the network to another JVM.

2. What is Deserialization?

Deserialization is the process of converting back a serialized object.

import java.io.Serializable;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class User implements Serializable {

	private static final long serialVersionUID = 3L;

	private String name;

	private int age;

	private String email;

	transient private double height;

	//setters and getters

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		String path = "serialized_user.ser";

		User serializedUser = serialize(path);

		System.out.println("serializedUser=" + serializedUser.toString());

		User deserializedUser = deserialize(path);
		
		System.out.println("deserializedUser=" + deserializedUser.toString());

	}

	private static User serialize(String path) throws IOException {

		FileOutputStream fileStream = new FileOutputStream(path);

		ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);

		User user = new User();
		user.setAge(21);
		user.setName("Laulau");
		user.setEmail("folaukaveinga@gmail.com");
		user.setHeight(6.3);

		objectStream.writeObject(user);

		objectStream.close();
		fileStream.close();

		return user;
	}

	private static User deserialize(String path) throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(path);
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

		User user = (User) objectInputStream.readObject();

		objectInputStream.close();
		fileInputStream.close();

		return user;
	}

}

Result

serializedUser=User[name=Laulau,age=21,email=folaukaveinga@gmail.com]
deserializedUser=User[name=Laulau,age=21,email=folaukaveinga@gmail.com]

3. What is Externalization?

Serialization is not very efficient. If you serialize bloated objects having a lot of attributes and properties, you do not wish to serialize. This is where Externalization in Java comes into the picture. Externalization is an advanced way of serialization. It is whenever you need to customize the serialization mechanism.

The class you want to be externalized must implement the Externalizable interface, then serialization of the object will be done using the method writeExternal(). When the Externalizable object is reconstructed at the receiver’s end, an instance will be created using no-argument constructor and this method is called readExternal().

This basically serves the purpose of custom Serialization, where you can decide what to store in a stream.

When to use Externalization?

When you want or need to serialize only part of an object, Externalization is the best option.

How to use Externalization?

By implementing the Externalizable interface, you control the process of reading and writing the objects during serialization and de-serialization process, you need to have the object’s class implemented the interface java.io.Externalizable. Only then you can implement your own code to read and write the object’s states. The methods, readExternal() and writeExternal() are defined by the Externalizable interface.

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Member implements Externalizable {

	public static final long serialVersionUID = 2L;

	private String name;

	private int age;

	private String email;

	transient private double height;

	// setters and getters

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		System.out.println("writing object state...");
		// TODO Auto-generated method stub
		out.writeObject(name);
		out.writeObject(email);
		out.writeInt(age);
		out.writeDouble(height);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		System.out.println("reading object state...");
		this.name = (String) in.readObject();
		this.email = (String) in.readObject();
		this.age = in.readInt();
		this.height = in.readDouble();
	}
}
public class ExternalizeDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		String path = "externalized_member.ser";

		Member externalizedMember = serialize(path);

		System.out.println("externalizedMember=" + externalizedMember.toString());

		Member dexternalizedMember = deserialize(path);

		System.out.println("dexternalizedMember=" + dexternalizedMember.toString());
	}

	private static Member serialize(String path) throws IOException {

		FileOutputStream fileStream = new FileOutputStream(path);

		ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);

		Member member = new Member();
		member.setAge(21);
		member.setName("Laulau");
		member.setEmail("folaukaveinga@gmail.com");
		member.setHeight(6.3);

		System.out.println(member.toString());

		objectStream.writeObject(member);

		objectStream.close();
		fileStream.close();

		return member;

	}

	private static Member deserialize(String path) throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(path);
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

		Member member = (Member) objectInputStream.readObject();

		objectInputStream.close();
		fileInputStream.close();

		return member;
	}
}

Result

Member[name=Laulau,age=21,email=folaukaveinga@gmail.com]
writing object state...
externalizedMember=Member[name=Laulau,age=21,email=folaukaveinga@gmail.com]
reading object state...
dexternalizedMember=Member[name=Laulau,age=21,email=folaukaveinga@gmail.com]

4. What are the differences between Serialization and Externalization?

Externalizable provides us with writeExternal() and readExternal() methods that give us control on what attributes and values to serialize. Correct implementation of the Externalizable interface can improve the performance of application drastically.

ExternalizationSerialization
UIDNo need to have it but for best practice you must have itNeeds a serialVersionUID
StorageStore the data per attribute.Store the whole object directly.
AccessProvides complete control to the serialization and deserialization process.No access

5. How many methods does Serializable have?

Zero. Serializable is a marker interface.

6. What is a serialVersionUID? What happens when you don’t explicitly provide?

serialVersionUID is a version control id. It is basically the hashcode of the object. So if you change the object(add or remove an attribute) then the hashcode will be different so an already serialized object will not be able to deserialize. Java serialization process relies on correct serialVersionUID for recovering the state of the serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch

When an object is serialized, the serialVersionUID is serialized along with the other contents. Later when that is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. If the numbers do not match then, InvalidClassException is thrown.

serialVersionUID is a 64-bit hash of the class name, interface class names, methods and fields. Serialization runtime generates a serialVersionUID if you do not add one. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations and can produce different serialVersionUID in different environments.


If you don’t provide it, Java will provide it for you.

7. What happens if an object is serializable but it includes a reference to a non-serializable object?

Java will throw a NotSerializableException. To fix this issue you can do either one of these two things:

a. Make the non-serializable object serializable by making its class implement the Serializable interface.

b. Make the non-serializable object transient or static.

8. If a class is serializable but its superclass in not, what will be the state of the instance variables inherited from super class after deserialization?

The state will be its default value. For example:

int age; -> age = 0;

String name; -> name = null;

9. To serialize an array or a collection all the members of it must be serializable. True /False?

true

All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. This means you do not really need to write anything specific to serialize collection objects. However, you should keep the following things in mind before you serialize a collection object – Make sure all the objects added in a collection are Serializable.

10. While serializing you want some of the members not to serialize, how do you achieve it?

If you don’t want any field to be part of the object’s state then declare it either static or transient based on your need and it will not be included during the serialization process.

Variables marked with transient are not included in the process of serialization and are not part of the object’s serialized state.

The static variables belong to a class are not part of the state of the object so they are not saved as part of the serialized object.

Why static variables are not serialized in Java?

The Java variables declared as static are not considered part of the state of an object since they are shared by all instances of that class. Saving static variables with each serialized object would have following problems

  • It will make redundant copy of same variable in multiple objects which makes it in-efficient.
  • The static variable can be modified by any object and a serialized copy would be stale or not in sync with current value.

11. What should you take care of when serializing an object?

You should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

12. Suppose a superclass of a new class implements Serializable interface, how can you avoid new class to being serialized?

Use Externalization and exclude the new class from the serialization process.

13. What are the ways to speed up Object Serialization? How to improve Serialization performance?

The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.

  • Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
  • Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
  • Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.
  • Use Externalizable interface and implement the readExternal and writeExternal methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.

14. Do constructors get invoked or run at deserialization?

When an instance of a serializable class is deserialized, the constructor does not run. If constructors were invoked it will give back the initial values rather than the value they had at the time of serialization.

15. What are the compatible and incompatible changes when dealing with versioned serialized objects during serialization?

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

  • Adding fields – When the class being reconstituted has a field that does not occur in the stream, that field in the object will be initialized to the default value for its type.
  • Adding or removing classes – Comparing the class hierarchy in the stream with that of the current class can detect that a class has been deleted or added.
  • Adding or removing writeObject/readObject methods
  • Changing the access to a field – The access modifiers public, package, protected, and private have no effect on the ability of serialization to assign values to the fields.
  • Changing a field from static to nonstatic or transient to nontransient – When relying on default serialization to compute the serializable fields, this change is equivalent to adding a field to the class. The new field will be written to the stream but earlier classes will ignore the value since serialization will not assign values to static or transient fields.

List of incompatible changes:

  • Deleting fields
  • Changing a nonstatic field to static or a nontransient field to transient
  • Changing the declared type of a primitive field
  • Changing a class from Serializable to Externalizable or vice versa is an incompatible change since the stream will contain data that is incompatible with the implementation of the available class.
  • Changing a class from a non-enum type to an enum type or vice versa
  • Removing either Serializable or Externalizable is an incompatible change since when written it will no longer supply the fields needed by older versions of the class.
  • Changing the writeObject or readObject method
  • Moving classes up or down the hierarchy – This cannot be allowed since the data in the stream appears in the wrong sequence.

16. What are the guidelines for using serialVersionUID?

  • You must declare serialVersionUID because it gives us more control. For example, Default rules for generating serialVersionUID can be too strict in some cases. For example when the visibility of a field changes, the serialVersionUID changes too. or sometimes you just want to forbid deserialization of old serialized objects then you can just change serialVersionUID.
  • Include this field even in the first version of the class, as a reminder of its importance
  • You must not only declare it but also maintain it. You should change serialVersionUID when there is some change in the definition of data stored in the class. For example, data type of field is changed.

17. Does setting the serialVersionUID class field improve Java serialization performance?

Declaring an explicit serialVersionUID field in your classes saves some CPU time only the first time the JVM process serializes a given Class. However the gain is not significant, In case when you have not declared the serialVersionUID its value is computed by JVM once and subsequently kept in a soft cache for future use.

18. Suppose you have a class in which you serialized and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?

It depends on whether a class has its own serialVersionUID or not. As we know that if we don’t provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hashCode of the object. By adding any new field there is a chance that new serialVersionUID generated for that class version is not the same as the serialized object. In this case, Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

October 10, 2019

Java interview – Exception

October 10, 2019

Java interview – I/O

October 10, 2019

Java interview – Concurrency

 

1. Why is there a need for multi-threading?

Multi-threading allows your program to execute logic in parallel. For example: if you are tasked to develop an API endpoint to download a file, read from the database, run calculations, call another API, then this will be an expensive task in terms of resources and time.

  • STEP-I: Read from DB => 10 milliseconds
  • STEP-II: Run calculations => 20 milliseconds
  • STEP-III: Download a file from AWS S3 => 3 seconds
  • STEP-IV: Call Stripe API to get user’s credit card info => 2 seconds

As you can see, it will take 5+ seconds with the best-case scenario. This isn’t too bad but still, users expect a faster response than 5+ seconds. If we use multi-threading to execute these steps in parallel then we can decrease the response time significantly.

  • STEP-I: Read from DB => 10 milliseconds
  • STEP-II: Run calculations, Download a file from AWS S3, Call Stripe API to get user’s credit card info => 3 seconds

Now instead of 5+ seconds, our new response time is 3 seconds.

2. What is multi-threading?

Multi-threading is executing a series of logic in parallel. Example: a web server is using multi-threading to execute multiple requests from clients(web browsers or mobile apps) at the same time.

3. What is a thread?

A thread is an independent path of execution within a program. Many threads can run concurrently within a program, either asynchronously or synchronously.

4. What are the differences between a thread and a process?

Threads share memory among themselves. A process does not share memory.

Threads are lightweight compared to processes.

Context switching between threads is usually less expensive than between processes.

The cost of thread intercommunication is relatively low compared to that of process intercommunication.

Threads allow different tasks to be performed concurrently.

Java Multithreading

Process Vs Threads

5. How can you create a thread?

There are two ways you can create a thread. You can extend the Thread class or implement the Runnable interface. Implementing the Runnable interface is preferred by many because it allows you to implement other interfaces or extend another class.

Using the Thread class

public class MemberThread extends Thread {

	@Override
	public void run() {
		super.run();
                // coding to execute
		System.out.println("run MemberThread...");
	}
}

Using the Runnable interface

public class UserRunnable implements Runnable {

	public UserRunnable() {
		super();
		System.out.println("UserRunnable");
	}

	@Override
	public void run() {
                // code to execute
		System.out.println("running UserRunnable..");
	}
}

 

public class ThreadCreationDemo {

	public static void main(String[] args) {
		Thread userThread = new Thread(new UserRunnable());
		userThread.start();
		
		MemberThread memberThread = new MemberThread();
		memberThread.start();
	}

}

Result

UserRunnable
running UserRunnable..
start MemberThread...
run MemberThread...

6. What are the different statuses of a thread?

a. NEW – a new Thread instance that was not yet started via Thread.start().

b. RUNNABLE – a running thread. It is called runnable because at any given time it could be either running or waiting for the next quantum of time from the thread scheduler. A NEW thread enters the RUNNABLE state when you call Thread.start() on it.

c. RUNNING – In this state, the thread scheduler picks the thread from the ready state, and the thread is running.

c. BLOCKED – a running thread becomes blocked if it needs to enter a synchronized section but cannot do that due to another thread holding the monitor of this section.

d. WAITING – a thread enters this state if it waits for another thread to perform a particular action. For instance, a thread enters this state upon calling the Object.wait() method on a monitor it holds, or the Thread.join() method on another thread.

e. TIMED_WAITING – same as the above, but a thread enters this state after calling timed versions of Thread.sleep()Object.wait()Thread.join() and some other methods.

f. TERMINATED – a thread has completed the execution of its Runnable.run() method and terminated.

The state of a Thread can be checked using the Thread.getState() method.

Java thread life cycle

Thread Life cycle in java, Thread States in java, thread life cycle

7. What is the difference between the Runnable interface and the Callable interface?

The Runnable interface does not have a return value or to throw unchecked exceptions.

The Callable interface has a return value. It can also throw exceptions. Callable is generally used in ExecutorService instances to start an asynchronous task and then call the returned Future instance to get its value.

FutureTask<Integer> futureTask = new FutureTask<Integer>(new CustomerCallable());

Thread customerCallableStart = new Thread(futureTask);
customerCallableStart.start();

try {
	int result = futureTask.get();
	System.out.println("result: " + result);
} catch (InterruptedException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (ExecutionException e) {
	// TODO Auto-generated catch block
        e.printStackTrace();
}

8. What is context-switching?

In Context switching, the state of the thread or process is stored so that it can be restored and execution can be resumed from the same point later. Context switching enables multiple threads or processes to share the same CPU.

9. What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.

Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

10. What is the difference between the start() method and the run() method?

The start() method is used to start a newly created thread, while start() internally calls run() method.

When you invoke run() directly, the execution will run on the main thread. It won’t create a new thread for you.

11. What is the difference between user threads and daemon threads?

When we create a Thread in java program, it’s known as user thread. A daemon thread runs in the background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.

12. How can we pause the execution of a Thread for a specific time?

We can use the Thread class sleep() method to pause the execution of a thread for a duration of time. Note that this will not stop the processing of the thread, once the thread is awake from sleep, it states gets changed to runnable and based on thread scheduling, it gets executed.

13. What do you understand about Thread Priority?

Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS-dependent. We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.

14. How can we make sure that the main thread is the last thread to finish in Java Program?

We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function

15. How does thread communicate with each other?

When threads share resources, communication between Threads is important to coordinate their efforts. Object class wait(), notify() and notifyAll() methods allow threads to communicate about the lock status of a resource.

16. What is the difference between wait() and sleep() method?

The wait() method releases the lock but the sleep() method doesn’t.

The wait() method is defined in Object class but the sleep() method is from the Thread class.

17. Is it possible to start a thread twice?

No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead state. Therefore, if we try to start a thread twice, it will give a runtime Exception “java.lang.IllegalThreadStateException”.

18. What are daemon threads?

Daemon threads are low priority threads that provide the background support and services to the user threads. Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. We can make a user thread a daemon thread by calling the setDaemon() method. We can only do this before the thread is starting otherwise it will throw an exception. There are two methods for daemon thread available in the Thread class.

  • public void setDaemon(boolean status): It used to mark the thread daemon thread or a user thread.
  • public boolean isDaemon(): It checks the thread is daemon or not.

19. Why Thread sleep() and yield() methods are static?

Thread sleep() and yield() methods work on the currently executing thread. So there is no point in invoking these methods on some other threads that are in a wait state. That’s why these methods are made static so that when this method is called statically, it works on the currently executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads.

20. How can we achieve thread-safety in Java?

There are several ways to achieve thread-safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using the volatile keyword, using immutable classes and Thread-safe classes.

 

21. What is the volatile keyword in Java

It is used to mark a variable as “being stored in main memory”. More precisely that means, that every read of a volatile variable will be read from the computer’s main memory, and not from the CPU cache and that every a write happens to a volatile variable will be written to main memory, and not just to the CPU cache.

A change in a volatile variable is visible to all other threads so one variable can be used by one thread at a time.

In a multithreaded application where the threads operate on non-volatile variables, each thread may copy variables from main memory into a CPU cache while working on them, for performance reasons. If your computer contains more than one CPU, each thread may run on a different CPU. That means, that each thread may copy the variables into the CPU cache of different CPUs.

Threads may hold copies of variables from main memory in CPU caches.


With non-volatile variables, there are no guarantees about when the Java Virtual Machine (JVM) reads data from the main memory into CPU caches or writes data from CPU caches to the main memory. This can cause problems.

Using volatile is sometimes not enough. It is recommended to use synchronized to guarantee that the reading and writing of the variable are atomic.

22. Which way is more preferred – Synchronized method or Synchronized block?

The synchronized block is the more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.

23. Can you synchronize a static method?

Yes, if you do you will be synchronizing the class so only one thread can enter into a synchronized static method.

24. What is Threadlocal?

The Threadlocal class enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to the same Threadlocal variable, the two threads cannot see each other’s Threadlocal variables.

If we want to use an ExecutorService and submit a Runnable to it, using ThreadLocal will yield non-deterministic results – because we do not have a guarantee that every Runnable action for a given userId will be handled by the same thread every time it is executed.

Use it when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object.

public class UserThreadLocal extends Thread {

	private static final AtomicInteger id = new AtomicInteger(0);

	ThreadLocal<String> privateName = ThreadLocal.withInitial(() -> " John--" + id.incrementAndGet());

	@Override
	public void run() {
		super.run();
		System.out.println("run..." + privateName.get());
	}
}

25. What is Java Thread Dump, How can we get Java Thread dump of a Program?

A thread dump is a list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool, etc. I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal-based tool, we can create a script to generate thread dump at regular intervals to analyze it later on.

26. 30 commonly asked interview questions related to Java concurrency

  1. Question: What is concurrency in Java? Answer: Concurrency is the ability of a program to execute multiple tasks concurrently. It allows for efficient utilization of system resources and improved program performance.

  2. Question: What is a thread in Java? Answer: A thread is a lightweight unit of execution within a program. It allows multiple parts of a program to execute concurrently.

  3. Question: How can you create a thread in Java? Answer: There are two ways to create a thread in Java: by extending the Thread class or by implementing the Runnable interface.

  4. Question: What is the difference between the start() and run() methods of a thread? Answer: The start() method is used to start a new thread and internally calls the run() method, which contains the code that will be executed by the thread.

  5. Question: What is thread synchronization? Answer: Thread synchronization is the coordination of multiple threads to ensure their safe and orderly execution. It is used to prevent race conditions and ensure data consistency.

  6. Question: How can you synchronize a block of code in Java? Answer: You can use the synchronized keyword to synchronize a block of code by enclosing it within a synchronized block or by declaring a synchronized method.

  7. Question: What is the purpose of the volatile keyword in Java? Answer: The volatile keyword is used to declare a variable whose value may be modified by multiple threads. It ensures that changes to the variable are immediately visible to other threads.

  8. Question: What is a race condition? Answer: A race condition occurs when multiple threads access and modify shared data concurrently, leading to unpredictable results. It can be resolved using synchronization mechanisms.

  9. Question: What are the differences between wait() and sleep() methods in Java? Answer: The wait() method is used for inter-thread communication, allowing a thread to wait until another thread notifies it. The sleep() method is used to pause the execution of a thread for a specified amount of time.

  10. Question: What is a deadlock? Answer: A deadlock occurs when two or more threads are blocked forever, each waiting for a resource that the other thread holds. Deadlocks can be avoided by careful resource allocation and proper synchronization.

  11. Question: Explain the concept of thread pooling. Answer: Thread pooling involves creating a pool of reusable threads to execute tasks. It reduces the overhead of creating and destroying threads for each task, resulting in improved performance.

  12. Question: What is the Executor framework in Java? Answer: The Executor framework provides a higher-level abstraction for managing and executing threads. It decouples task submission from execution policies.

  13. Question: What is the purpose of the Callable interface in Java? Answer: The Callable interface is similar to the Runnable interface, but it can return a result and throw checked exceptions. It is used with the ExecutorService to execute tasks and retrieve results.

  14. Question: What is the Java Memory Model (JMM)? Answer: The Java Memory Model defines the rules and guarantees for the interaction of threads and memory. It ensures visibility and ordering of memory operations across multiple threads.

  15. Question: Explain the concept of atomic operations in Java. Answer: Atomic operations are indivisible operations that are performed as a single unit of execution. They ensure that operations on shared data are thread-safe and free from race conditions.

  16. Question: What is a semaphore in Java concurrency? Answer: A semaphore is a synchronization primitive that controls access to a shared resource. It allows aContinuing from the previous response, here are more Java concurrency interview questions along with their answers:

  17. Question: What is the purpose of the CountDownLatch class in Java? Answer: The CountDownLatch class is used to synchronize threads by allowing them to wait until a certain number of operations or events have occurred before proceeding.

  18. Question: What is the purpose of the CyclicBarrier class in Java? Answer: The CyclicBarrier class is used to synchronize multiple threads by making them wait at a barrier until all threads have reached it. Once all threads have arrived, they can proceed simultaneously.

  19. Question: What is the purpose of the ReentrantLock class in Java? Answer: The ReentrantLock class provides a more advanced locking mechanism than the synchronized keyword. It allows for finer-grained control over locking and supports features like fairness and interruptible locks.

  20. Question: What is the purpose of the ReadWriteLock interface in Java? Answer: The ReadWriteLock interface provides a way to have multiple threads simultaneously read from a shared resource, while only allowing one thread to write to it at a time. It improves concurrency in scenarios with frequent reads and infrequent writes.

  21. Question: What is the purpose of the BlockingQueue interface in Java? Answer: The BlockingQueue interface provides a thread-safe queue implementation that supports blocking operations, such as waiting for elements to become available or waiting for space to become available for adding elements.

  22. Question: What is the purpose of the ThreadLocal class in Java? Answer: The ThreadLocal class provides a way to create thread-local variables, where each thread has its own copy of the variable. It is useful for maintaining thread-specific data.

  23. Question: What is the purpose of the volatile keyword in relation to multi-threading? Answer: The volatile keyword ensures that a variable’s value is always read from and written to main memory, rather than being cached in a thread’s local cache. It guarantees visibility of the variable’s latest value across multiple threads.

  24. Question: What is the purpose of the join() method in Java? Answer: The join() method is used to make a calling thread wait until a target thread completes its execution. It is often used to ensure that the main thread waits for all worker threads to finish before proceeding.

  25. Question: What is the purpose of the notify() and notifyAll() methods in Java? Answer: The notify() method is used to wake up a single thread that is waiting on the same object’s monitor, while the notifyAll() method wakes up all threads waiting on the object’s monitor. These methods are used for inter-thread communication.

  26. Question: Explain the concept of thread starvation and how it can be avoided. Answer: Thread starvation occurs when a thread is perpetually denied access to the CPU or resources it needs. It can be avoided by implementing proper thread scheduling, fairness policies, and resource management.

  27. Question: Explain the concept of thread starvation and how it can be avoided. Answer: Thread starvation occurs when a thread is perpetually denied access to the CPU or resources it needs. It can be avoided by implementing proper thread scheduling, fairness policies, and resource management.

  28. Question: What is the purpose of the ForkJoinPool class in Java? Answer: The ForkJoinPool class is used for parallelizing tasks that can be divided into subtasks and executed concurrently. It is based on the divide-and-conContinuing from the previous response, here are more Java concurrency interview questions along with their answers:

  29. Question: What is the purpose of the CompletableFuture class in Java? Answer: The CompletableFuture class provides a way to handle asynchronous computations and compose them in a non-blocking manner. It allows for chaining and combining asynchronous operations.

  30. Question: Explain the concept of non-blocking and asynchronous programming in Java. Answer: Non-blocking and asynchronous programming techniques allow for concurrent execution of tasks without blocking the calling thread. Non-blocking operations return immediately, and the result is delivered at a later time, often through callbacks or promises.

 

 

 

 

 

 

 

October 10, 2019

Java interview – OOP

 

1.What is Object-oriented Programming?

Object-oriented programming is a programming model or approach where the programs you create are organized around objects rather than logic and functions. The states and behaviors of an object are represented as member variables and methods. This approach is ideal for the programs that are large and complex and need to be actively updated or maintained. Here below is an example of OOP where this little piece is focused on Person. There can be other entities like payment method, Account, etc. Programs are organized into entities.

2. What are the advantages of OOPs?

Simplicity: Domain models or entities are modeled after real-world objects. It is easier to understand and to relate to. The program structure is also easier to comprehend.

Modularity: Each object is decoupled from other objects of the system.

Modifiability: It is easy to make minor changes in the data or the functionalities in an OO program. Changes inside a class do not affect any other part of a program since the only public interface that the external world has to a class is through the use of methods.

Extensibility: Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.

Maintainability: Objects can be maintained separately, making locating and fixing problems easier.

Reusability: Objects can be reused in different programs.

 

3. What is the difference between procedural programming and OOPs?

  1. Procedural language is based on functions but object oriented language is based on real world objects.
  2. Procedural language gives importance on the sequence of function execution but object oriented language gives importance on states and behaviors of the objects.
  3. Procedural language exposes the data to the entire program but object oriented language encapsulates the data.
  4. Procedural language follows top down programming paradigm but object oriented language follows bottom up programming paradigm.
  5. Procedural language is complex in nature so it is difficult to modify, extend and maintain but object oriented language is less complex in nature so it is easier to modify, extend and maintain.
  6. Procedural language provides less scope of code reuse but object oriented language provides more scope of code reuse.

 

4. What are the core concepts of OOPs?

  1. Inheritance: Inheritance is a process where one class acquires the properties and functionalities of another.
  2. EncapsulationEncapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  3. AbstractionAbstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users.
  4. PolymorphismPolymorphism is the ability of a variable, function or object to take multiple forms.
  5. Composition
  6. Association
  7. Aggregation
  1. Classes and Objects:

    • Classes are the blueprint or template that defines the structure and behavior of objects. They encapsulate data and methods.
    • Objects are instances of classes. They represent specific entities that have state (data) and behavior (methods).
  2. Encapsulation:

    • Encapsulation is the process of bundling data (attributes/fields) and methods that operate on the data within a single unit, i.e., a class.
    • It provides data hiding, where the internal implementation details of a class are hidden from the outside world, and access to the data is controlled through methods.
    • Encapsulation helps maintain data integrity, improves code organization, and facilitates modularity and reusability.
  3. Inheritance:

    • Inheritance allows a class to inherit the properties (fields and methods) of another class, known as the superclass or parent class.
    • The class that inherits the properties is called the subclass or child class.
    • Inheritance promotes code reuse, allows for the creation of specialized classes from a general superclass, and supports the concept of polymorphism.
  4. Polymorphism:

    • Polymorphism means the ability of objects of different classes to respond to the same method invocation in different ways.
    • Polymorphism in Java is achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).
    • Method overriding allows a subclass to provide a different implementation of a method that is already defined in its superclass.
    • Method overloading allows multiple methods with the same name but different parameters to be defined in the same class.
  5. Abstraction:

    • Abstraction is the process of representing complex real-world entities as simplified models in code.
    • Abstract classes and interfaces are used to achieve abstraction in Java.
    • Abstract classes are classes that cannot be instantiated but can be used as base classes for subclasses. They can have abstract methods (without implementation) and concrete methods.
    • Interfaces define a contract of methods that a class must implement. They provide a way to achieve multiple inheritance and allow for programming to interfaces.
  6.  

5. What is the difference between Abstraction and Encapsulation?

  1. “Program to interfaces, not implementations” is the principle for Abstraction and “Encapsulate what varies” is the OO principle for Encapsulation.
  2. Abstraction provides a general structure of a class and leaves the details for the implementers. Encapsulation is to create and define the permissions and restrictions of an object and its member variables and methods.
  3. Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using four types of access level modifiers: public, protected, no modifier and private.

Abstraction:

  • Abstraction is a concept that focuses on representing complex real-world entities as simplified models in code.
  • It involves the process of identifying and extracting essential features and behavior of an entity, while ignoring unnecessary details.
  • Abstraction allows you to create abstract classes and interfaces in Java.
  • Abstract classes are classes that cannot be instantiated but can be used as base classes for subclasses. They can have both abstract methods (without implementation) and concrete methods.
  • Interfaces define a contract of methods that a class must implement.
  • Abstraction provides a way to define common behavior and establish a hierarchy of classes, where higher-level classes provide a more general abstraction while lower-level classes provide more specific implementations.
  • It allows you to work with objects at a higher level of abstraction, focusing on what an object does rather than how it does it.
  • Abstraction simplifies complex systems by breaking them down into manageable and understandable units.

Encapsulation:

  • Encapsulation is a concept that focuses on bundling data (attributes/fields) and methods that operate on the data within a single unit, i.e., a class.
  • It involves hiding the internal implementation details of a class and exposing only necessary information through methods.
  • Encapsulation provides data hiding, where the internal state of an object is not directly accessible or modifiable from outside the class.
  • It protects the integrity of the data by controlling access to it through methods, allowing the class to enforce rules and validations.
  • Encapsulation helps in achieving modularity, as the internal implementation of a class can be modified without affecting other parts of the code that use the class.
  • It improves code organization, as related data and behavior are encapsulated within a single class, making the code more maintainable and understandable.
  • Encapsulation also facilitates code reuse, as objects can be used as black boxes, interacting with other objects through well-defined interfaces.

Abstraction focuses on representing complex entities as simplified models, while encapsulation focuses on bundling data and methods within a class, controlling access to the data, and hiding the implementation details. Abstraction provides a higher-level view, emphasizing what an object does, while encapsulation provides information hiding and modular code organization. Both concepts are crucial for building robust and maintainable object-oriented programs.

6. What is the diamond problem in inheritance?

In the case of multiple inheritances, suppose class A has two subclasses B and C, and class D has two superclasses B and C. If a method present in A is overridden by both B and C but not by D then from which class D will inherit that method B or C? This problem is known as the diamond problem.

7. Why Java does not support multiple inheritances?

Java was designed to be a simple language and multiple inheritances introduce complexities like the diamond problem. Inheriting states or behaviors from two different types of classes is a case which in reality very rare and it can be achieved easily through an object association.

8. What is Static Binding and Dynamic Binding?

Static or early binding is resolved at compile time. Method overloading is an example of static binding. Static binding is faster than dynamic binding.

Dynamic or late or virtual binding is resolved at run time. Method overriding is an example of dynamic binding. This decision making during runtime makes Dynamic binding slower than static binding.

 

9. What is the meaning of the “IS-A” and “HAS-A” relationship?

“IS-A” relationship implies inheritance. A subclass object is said to have an “IS-A” relationship with the superclass or interface. If class A extends B then A “IS-A” B. It is transitive, that is, if class A extends B and class B extends C then A “IS-A” C. The “instance of” operator in java determines the “IS-A” relationship.

When a class A has a member reference variable of type B then A “HAS-A” B. It is also known as Aggregation.

10. What is an Association?

Association is a relationship between two objects with multiplicity.

11. What is Aggregation?

Aggregation is also known as “HAS-A” relationship. When class Car has a member reference variable of type Wheel then the relationship between the classes Car and Wheel is known as Aggregation. Aggregation can be understood as “whole to its parts” relationship.

Car is the whole and wheel is part. The wheel can exist without the Car. Aggregation is a weak association.

12. What is Composition?

Composition is a special form of Aggregation where the part cannot exist without the whole. Composition is a strong Association. Composition relationship is represented like aggregation with one difference that the diamond shape is filled.

13. What is Dependency?

When one class depends on another because it uses that class at some point in time then this relationship is known as Dependency. One class depends on another if the independent class is a parameter variable or local variable of a method of the dependent class. A Dependency is drawn as a dotted line from the dependent class to the independent class with an open arrowhead pointing to the independent class.

14. What is the difference between Association and Dependency?

The main difference between Association and Dependency is in case of Association one class has an attribute or member variable of the other class type but in case of Dependency a method takes an argument of the other class type or a method has a local variable of the other class type.

 

15. 30 commonly asked interview questions related to Object-Oriented Programming (OOP) in Java

  1. Question: What is the difference between a class and an object in Java? Answer: A class is a blueprint or template that defines the structure and behavior of objects, while an object is an instance of a class. A class represents a general concept, while an object represents a specific instance of that concept.

  2. Question: Explain the concept of inheritance in Java. Answer: Inheritance allows a class to inherit the properties (fields and methods) of another class, known as the superclass or parent class. It promotes code reuse and allows for the creation of specialized classes from a general superclass. Example: A Car class can inherit common properties and methods from a Vehicle class.

  3. Question: What is the difference between method overloading and method overriding? Answer: Method overloading is the process of defining multiple methods with the same name but different parameters within the same class. Method overriding, on the other hand, occurs when a subclass provides a different implementation of a method that is already defined in its superclass.

  4. Question: What is the purpose of the super keyword in Java? Answer: The super keyword is used to refer to the immediate parent class’s members (fields and methods) from within a subclass. It is often used to call the superclass’s constructor or to access overridden methods or hidden fields.

  5. Question: What is the concept of polymorphism in Java? Answer: Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling them to respond to the same method invocation in different ways. Polymorphism is achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).

  6. Question: Explain the concept of encapsulation in Java. Answer: Encapsulation is the process of bundling data (attributes/fields) and methods that operate on the data within a single unit, i.e., a class. It provides data hiding, where the internal implementation details of a class are hidden from the outside world, and access to the data is controlled through methods.

  7. Question: What is an abstract class in Java? How is it different from an interface? Answer: An abstract class is a class that cannot be instantiated but can be used as a base class for subclasses. It can have both abstract methods (without implementation) and concrete methods. An interface, on the other hand, defines a contract of methods that a class must implement. Unlike an abstract class, an interface cannot contain implementation details.

  8. Question: What is the purpose of the final keyword in Java? Answer: The final keyword is used to restrict the behavior of classes, methods, and variables. A final class cannot be subclassed, a final method cannot be overridden, and a final variable cannot be reassigned once initialized.

  9. Question: What is the concept of method overriding in Java? Answer: Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The overridden method in the subclass must have the same signature (name, return type, and parameters) as the method in the superclass.

  10. Question: What is the purpose of the this keyword in Java? Answer: The this keyword refers to the current instance of a class. It is often used to differentiate between instance variables and method parameters or to invoke constructors within a class.

  11. Question: What is the difference between composition and inheritance? Answer: Composition represents a “has-a” relationship, where one class contains references to objects of another class. Inheritance, onContinuing from the previous response, here are more interview questions related to Object-Oriented Programming (OOP) in Java:

  12. Question: What is the concept of method overloading in Java? Answer: Method overloading is the process of defining multiple methods with the same name but different parameters within the same class. The compiler determines which method to invoke based on the number, types, and order of the arguments passed.

  13. Question: What is the difference between abstract classes and interfaces in Java? Answer: Abstract classes can have both abstract and concrete methods, while interfaces can only have abstract methods. A class can implement multiple interfaces, but it can only extend one abstract class.

  14. Question: What is the significance of the static keyword in Java? Answer: The static keyword is used to define class-level members that are shared among all instances of a class. static methods and variables can be accessed without creating an instance of the class.

  15. Question: What is the purpose of the final keyword for variables in Java? Answer: The final keyword for variables makes them constants, meaning their values cannot be changed once assigned. It is used to create immutable variables.

  16. Question: What is the concept of method hiding in Java? Answer: Method hiding occurs when a subclass defines a static method with the same name and signature as a static method in its superclass. The subclass’s static method hides the superclass’s static method.

  17. Question: What is the difference between shallow copy and deep copy? Answer: Shallow copy creates a new object that references the same memory as the original object, while deep copy creates a new object with its own memory, copying all the values of the original object.

  18. Question: How does Java support multiple inheritance? Answer: Java doesn’t support multiple inheritance of classes, but it supports multiple inheritance of interfaces. By implementing multiple interfaces, a class can inherit multiple sets of behavior.

  19. Question: What are access modifiers in Java, and what is their significance? Answer: Access modifiers control the visibility and accessibility of classes, methods, and variables. They include public, protected, private, and default (no modifier). They ensure proper encapsulation and provide control over the accessibility of code.

  20. Question: What is a static initializer block in Java? Answer: A static initializer block is a block of code that is executed when a class is loaded into memory. It is used to initialize static variables or perform one-time setup tasks for the class.

  21. Question: What is the purpose of the instanceof operator in Java? Answer: The instanceof operator is used to check if an object is an instance of a particular class or implements a specific interface. It returns a boolean value indicating the result of the check.

  22. Question: What are accessors and mutators (getters and setters) in Java? Answer: Accessors (getters) are methods used to retrieve the values of private fields, while mutators (setters) are methods used to modify the values of private fields. They ensure controlled access to the object’s state.

  23. Question: What is the purpose of the clone() method in Java? Answer: The clone() method is used to create a copy of an object. It performs a shallow copy by default, but it can be overridden to perform a deep copy if necessary.

  24. Question: What is the equals() method in Java used for? Answer: The equals() method is used to compare the equality of two objects. It is typically overridden to provide a custom implementation for object comparison based on specific criteria.

  25. Question: What is the difference between String,Continuing from the previous response, here are more interview questions related to Object-Oriented Programming (OOP) in Java:

  26. Question: What is the difference between String, StringBuilder, and StringBuffer in Java? Answer:

    • String is an immutable class, meaning its value cannot be changed once created. It is suitable for situations where the value needs to remain constant.
    • StringBuilder and StringBuffer are mutable classes that can be used to manipulate strings. StringBuilder is not thread-safe, while StringBuffer is thread-safe due to its synchronized methods.
  27. Question: What is method hiding in Java, and how does it differ from method overriding? Answer: Method hiding occurs when a subclass defines a static method with the same name and signature as a static method in its superclass. The subclass’s static method hides the superclass’s static method. Method overriding, on the other hand, occurs when a subclass provides a different implementation of a method that is already defined in its superclass.

  28. Question: What is the difference between the throw and throws keywords in Java? Answer:

    • The throw keyword is used to explicitly throw an exception within a method or block of code.
    • The throws keyword is used in a method signature to indicate that the method may throw one or more exceptions. It is used for checked exceptions.
  29. Question: What is the finalize() method in Java used for? Answer: The finalize() method is a method of the Object class that is called by the garbage collector when it determines that there are no more references to the object. It can be overridden to perform cleanup tasks before the object is garbage collected.

  30. Question: What is the difference between the ArrayList and LinkedList classes in Java? Answer:

    • ArrayList is implemented as a dynamic array, providing fast random access and iteration. It is suitable for scenarios where frequent element access and modification are required.
    • LinkedList is implemented as a doubly-linked list, providing fast insertion and deletion at both ends. It is suitable for scenarios where frequent insertions and deletions are required.

 

 

 

 

October 10, 2019