Top Java Interview Question 2023
Core java interview questions
Q: What is the difference between Class and Object in java ?
In Java, a class is a blueprint or a template that describes the properties and behaviours of a particular type of object. It defines the attributes and methods that an object of that class will have. On the other hand, an object is an instance of a class that represents a specific entity or concept in the program.
Here are some key differences between a class and an object:
- Definition: A class is a blueprint that defines the structure and behaviour of an object, whereas an object is an instance of a class.
- Attributes: A class defines the properties and attributes that an object will have, whereas an object represents the values of those attributes.
- Methods: A class defines the methods that an object can use, whereas an object can call those methods to perform operations.
- Memory: A class is stored in memory once and can be used to create multiple objects, whereas each object created from a class takes up its own memory space.
- Static vs. Non-static: A class can have both static and non-static members, whereas an object can only access non-static members of a class.
In summary, a class is a blueprint that defines the structure and behavior of an object, while an object is an instance of a class that represents a specific entity or concept in the program.
Q) OOPS concept in java ?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects". In Java, OOP is implemented through the following key concepts:
Classes: A class is a blueprint for creating objects. It defines the properties (fields) and behaviors (methods) of an object.
Objects: An object is an instance of a class. It has its own state (values of its fields) and behavior (implementation of its methods).
Encapsulation: Encapsulation is the practice of hiding the implementation details of an object from the outside world, and only exposing a public interface for interacting with the object.
Inheritance: Inheritance allows a class to inherit properties and behaviors from another class. The class that is being inherited from is called the superclass or parent class, and the class that is inheriting is called the subclass or child class.
Polymorphism: Polymorphism is the ability of an object to take on many forms. In Java, this is achieved through method overloading and method overriding.
Abstraction: Abstraction is the practice of reducing complex systems to simpler, more manageable components. In Java, this is typically achieved through interfaces and abstract classes.
By using these OOP concepts in Java, programmers can create modular, reusable, and extensible code that is easier to maintain and understand.
Q: What is ClassLoader in Java ?
ClassLoader is an entity responsible for loading classes into the Java Virtual Machine (JVM) during runtime. When a Java program runs, the ClassLoader is utilized by the JVM to identify and load the necessary classes, including those required by the application and its dependencies.
The ClassLoader is a component of the Java Runtime Environment (JRE), and it is structured hierarchically with each class loader having a parent ClassLoader. This structure is known as the "class loading delegation model". Whenever an application requests a class, the ClassLoader first looks in its own cache to determine if the class has already been loaded. If it hasn't, the request is delegated to its parent ClassLoader. This process is repeated until the class is located, or the top-level ClassLoader is reached. If the class is still not found, a ClassNotFoundException is thrown.
Java provides three pre-built ClassLoaders: Bootstrap ClassLoader, Extension ClassLoader, and System ClassLoader.
Every
class loader has a predefined location, from where they loads class files.
1) Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java.
Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null and any code based on that may throw NullPointerException in Java. Bootstrap class
loader is also known as Primordial ClassLoader in Java.
2) Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader.
2) Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader.
3) System or
Application class loader is responsible for loading application specific
classes from CLASSPATH environment variable, -classpath or -cp command
line option, Class-Path attribute of Manifest file
inside JAR. Application class loader is a child of Extension ClassLoader and
its implemented by sun.misc.Launcher$AppClassLoader class. Also, except Bootstrap
class loader, which is implemented in native language mostly in C, all Java class loaders are implemented
using java.lang.ClassLoader.
In short
here is the location from which Bootstrap, Extension and Application
ClassLoader load Class files.
Bootstrap ClassLoader - JRE/lib/rt.jar
Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
Application ClassLoader - CLASSPATH
environment
variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.
How
ClassLoader works in Java
Java
ClassLoader works in three principles : delegation, visibility and uniqueness.
a) Delegation
principles : When a class is loaded and initialized in Java, a
class is loaded in Java, when its needed.
Suppose you have an application
specific class called Abc.class, first request of loading this
class will come to Application ClassLoader which will delegate to its parent
Extension ClassLoader which further delegates to Primordial or Bootstrap class
loader. Primordial will look for that class in rt.jar and since that class is not there, request comes
to Extension class loader which looks on jre/lib/ext directory
and tries to locate this class there, if class is found there than Extension
class loader will load that class and Application class loader will never load
that class but if its not loaded by extension class-loader than Application
class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or
java command.
b) Visibility
Principle
According
to visibility principle, Child ClassLoader can see class loaded by Parent
ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC
explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in
below Example
package test;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClasssLoaderDemo {
public static void main(String args[]) {
try {
//printing ClassLoader of this class
System.out.println("ClasssLoaderDemo.getClass().getClassLoader() : "
+ ClasssLoaderDemo.class.getClassLoader());
//trying to explicitly load this class again using Extension class loader
Class.forName("test.ClasssLoaderDemo", true
, ClasssLoaderDemo.class.getClassLoader().getParent());
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClasssLoaderDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output:
ClasssLoaderDemo.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
16/08/2012 2:43:48 AM test.ClasssLoaderDemo main
SEVERE: null
java.lang.ClassNotFoundException: test.ClasssLoaderDemo
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at test.ClasssLoaderDemo.main(ClasssLoaderDemo.java:29)
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClasssLoaderDemo {
public static void main(String args[]) {
try {
//printing ClassLoader of this class
System.out.println("ClasssLoaderDemo.getClass().getClassLoader() : "
+ ClasssLoaderDemo.class.getClassLoader());
//trying to explicitly load this class again using Extension class loader
Class.forName("test.ClasssLoaderDemo", true
, ClasssLoaderDemo.class.getClassLoader().getParent());
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClasssLoaderDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output:
ClasssLoaderDemo.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
16/08/2012 2:43:48 AM test.ClasssLoaderDemo main
SEVERE: null
java.lang.ClassNotFoundException: test.ClasssLoaderDemo
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at test.ClasssLoaderDemo.main(ClasssLoaderDemo.java:29)
c) Uniqueness
Principle
According
to this principle a class loaded by Parent should not be loaded by Child
ClassLoader again. Though its completely possible to write class loader which
violates Delegation and Uniqueness principles and loads class by itself, its
not something which is beneficial. You should follow all class loader principle while writing your own
ClassLoader.
Q) What is the difference between GC and Finalize ? Which one is used to clean at what time ?
Both are used for cleanup processing. But GC cleanup those object which was created using “new keyword”
Finalize clean
those object which was not created using “new” keyword. you can use
finalize for closing the file , closing the open connection etc before
JVM shutdown.
Q):- Difference between Sleep, wait, join, notify and notifyAll method ?
Sleep:-
Sleep method is used to stop the execution of thread for a specific
time period. In Sleep lock is not release. It is a static method of
thread. It start execution after the specified time elapsed.
wait :- It
is also use for stopping the current thread execution. But it release
lock. It will start execution after the notify, notifyAll called or (if
wait(time) after the specified time elapsed.).
notify :- Wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
notifyAll :- Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
join :- The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
public final void notify()
notifyAll :- Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
join :- The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
Q):- Difference between overloading and overriding?
Overriding :- Its
basically used to provide the specific implementation of the
functionality defined in parent class and you want to give new
functionality in the child class. Then you override the parent class
function in child class.
Requirements :-
- Parent class and child class having the same function signature. i.e. Function name same, return type same , no. of parameter same and type of the parameter are same.
- Both class having the inheritance relationship.
2):- Overloading :- Its
basically used to make your functionality more readable. You can use
your functionality in different way. Like you can overload your function
based on function parameter.
Requirements :-
- Class having the different function signature. i.e. Function name same , no. of parameter different or type of the parameter are different.
Q) Can we declare local inner class as private.?
No, local inner class can not be declared as private or protected or public.
Q) Is an exception occurred in one thread causes other threads to terminate.?
No,
exception is thread wise. Only that thread will terminate in which
exception has occurred. Other threads will continue to execute.
Q) Can array size be negative.?
No,
array size can not be negative. If you specify array size as
negative, there will be no compile time error, but you will get
NegativeArraySizeException at run time.
Q) Can a JVM have multiple object of singleton class?
Yes,a JVM can have multiple singleton object because JVM have different class loader. And a Classloader can have only one object of singleton class. So multiple classloader can have multiple object.Q) Object Class Methods
- Creational methods
Object() :
Default no-argument constructorclone() :
Returns a new instance of the class- Synchronizing methods
notify() :
Sends a signal to a waiting thread (on the current instance)notifyAll() :
Sends a signal to all waiting threads (on the current instance)wait() :
Forces the current thread to wait for a signal (on the current instance)- Equality methods
equals(Object) :
Returns true if this instance is equal to the argumenthashCode() :
Returns a hash code based on the instance data- Other methods
toString() :
Returns a string representation of the objectfinalize() :
Performs garbage-collection dutiesgetClass() :
Returns theClass
object associated with the instance
Q) Is an object garbage collected even after an exception is occurred in the program.?
Yes, Garbage collector ignores any exceptions occurred in the program.
Q). How do you trigger garbage collection from Java code?
- You, as Java programmer, can not force garbage collection in Java;
- it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
Before removing an object from memory garbage collection thread invokes finalize()method of that object and gives an opportunity to perform any sort of cleanup required. You can also invoke this method of an object code, however, there is no guarantee that garbage collection will occur when you call this method.
Additionally, there are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
Q) Is Map of Collection type.?
No,
Map is not a Collection type. Even though Map is included in the
collection framework, it does not inherit from Collection interface.
Q) Can be check two object equity by only overriding equals method.?
Yes, we can but it is better to override hashCode also because if improve the performance
The purpose of the equals() method is to determine whether the argument is equal to the current instance. This method is used in virtually all of the java.util collections classes, and many other low-level libraries (such as RMI (Remote Method Invocation), JDBC (Java Database Connectivity), etc.) implicitly depend on the correct behaviour. The method should return true if the two objects can be considered equal and false otherwise. Of course, what data is considered equal is up to each individual class to define.
Since computing an object's equality is a time-consuming task, Java also provides a quick way of determining if an object is equal or not, using hashCode(). This returns a small number based on the object's internal datastructure; if two objects have different hash codes, then they cannot be equal to each other. (Think of it like searching for two words in a dictionary; if they both begin with "A" then they may be equal; however, if one begins with "A" and the other begins with "B" then they cannot be equal.)
The purpose of the equals() method is to determine whether the argument is equal to the current instance. This method is used in virtually all of the java.util collections classes, and many other low-level libraries (such as RMI (Remote Method Invocation), JDBC (Java Database Connectivity), etc.) implicitly depend on the correct behaviour. The method should return true if the two objects can be considered equal and false otherwise. Of course, what data is considered equal is up to each individual class to define.
Since computing an object's equality is a time-consuming task, Java also provides a quick way of determining if an object is equal or not, using hashCode(). This returns a small number based on the object's internal datastructure; if two objects have different hash codes, then they cannot be equal to each other. (Think of it like searching for two words in a dictionary; if they both begin with "A" then they may be equal; however, if one begins with "A" and the other begins with "B" then they cannot be equal.)
Q)How to read a Large File efficiently in Java?
We can use stream through file and use Scanner to process every line. It will faster.
Avoid to store data into object or creating duplicate object.
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
Or we can use LineIterator
LineIterator it = FileUtils.lineIterator(theFile,
"UTF-8"
);
try
{
while
(it.hasNext()) {
String line = it.nextLine();
// do something with line
}
}
finally
{
LineIterator.closeQuietly(it);
}
Q) How can be store very Big number ?
We can use BigDecimal [for decimal number] and BigInteger [for Integer].
package com.coreBasics;
import java.math.BigInteger;
public class LargeNumberStoreDemo {
public static void main(String args[]) {
BigInteger bigNum = new BigInteger( "3666666666666666666666666666666666666666666666666666666666667777777777777777777736666666666666666666666666666666666666666666666677777777777777777777");
BigInteger bigNum2 = new BigInteger( "3666666666666666666666666666666666666666666666666666666666667777777777777777777736666666666666666666666666666666666666666666666677777777777777777777");
System.out.println(bigNum.multiply(bigNum2));
}
}
import java.math.BigInteger;
public class LargeNumberStoreDemo {
public static void main(String args[]) {
BigInteger bigNum = new BigInteger( "3666666666666666666666666666666666666666666666666666666666667777777777777777777736666666666666666666666666666666666666666666666677777777777777777777");
BigInteger bigNum2 = new BigInteger( "3666666666666666666666666666666666666666666666666666666666667777777777777777777736666666666666666666666666666666666666666666666677777777777777777777");
System.out.println(bigNum.multiply(bigNum2));
}
}
Q) Can a class implement two interfaces having same method.?
Yes,
a class can implement two interfaces having same method but that method
should be implemented only once ( or can be overloaded ) in the class.
Q) Which one will be faster?
- a) for(int i = 0; i < 1000; i++) {}
- b) for(int i = 1000; i > 0; i–) {}
for(int i = 1000; i > 0; i–) {} will be faster
Q) Can we declare interface methods as static.?
No, we can’t declare interface methods as static.
Q) Which one is faster among String, StringBuffer and StringBuilder.?
StringBuilder.
Q) A class can not be declared with synchronized keyword. Then, why we call classes like Vector, StringBuffer are synchronized classes.?
Any
classes which have only synchronized methods and blocks are treated as
synchronized classes. Classes like Vector, StringBuffer have only
synchronized methods. That’s why they are called as synchronized
classes.
Q). Are there any disadvantages of Garbage Collection?
Yes. Whenever the garbage collector runs, it has an effect on the application’s performance. This is because all other threads in the application have to be stopped to allow the garbage collector thread to effectively do its work.Depending on the requirements of the application, this can be a real problem that is unacceptable by the client. However, this problem can be greatly reduced or even eliminated through skillful optimization and garbage collector tuning and using different GC algorithms.
Q):- Why we use marker interface?
Marker interface are blank interface with no method.It is used to do some specific task. When the code is compiled then JVM check whether any marker interface is there or not. And if any marker interface is find then based on the interface defined it do some mechanism.
There are three type of marker interface
- Serializable
- Clonable
- Remotable
Q) ClassNotFoundException Vs NoClassDefFoundError In JavaClassNotFoundException In Java :ClassNotFoundException is a run time exception which is thrown when an application tries to load a class at run time using Class.forName() or loadClass() or findSystemClass() methods and the class with specified name are not found in the classpath. For example, you may have come across this exception when you try to connect to MySQL or Oracle databases and you have not updated the classpath with required JAR files. In most of time, this exception occurs when you try to run an application without updating the classpath with required JAR files.For example, below program will throw ClassNotFoundException if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found in the classpath.
java.lang.ClassNotFoundException:
oracle.jdbc.driver.OracleDriver
at
java.net.URLClassLoader.findClass(Unknown Source)
at
java.lang.ClassLoader.loadClass(Unknown Source)
at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at
java.lang.ClassLoader.loadClass(Unknown Source)
at
java.lang.Class.forName0(Native Method)
at
java.lang.Class.forName(Unknown Source)
at
pack1.MainClass.main(MainClass.java:17)
NoClassDefFoundError In Java :NoClassDefFoundError is an error which is thrown when Java Runtime System tries to load the definition of a class and class definition is no longer available. The required class definition was present at compile time but it was missing at run time. For example, compile the below program.
Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A
at
java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
|
Q):- What is the difference between String and StringBuffer in Java and which one better when lots of manipulation occurs ?
- String is used to manipulate character strings that cannot be changed (read-only and immutable).
- StringBuffer is used to represent characters that can be modified.
- Performance wise, StringBuffer is faster when performing concatenations.
- This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.
- You can also use StringBuilder which is similar to StringBuffer except it is not synchronized.
Q):- Can be called a Java Program without having the main method ?
Main method is the entry point of any java program. So it can be compiled but it can’t be run.Q):- Can be called a non-static method from static method ?
Non-static method is owned by object of a class and have object level scope and in order to call the non-static method from a static block (Like from a static main method), an object of the class needs to be created first. Then using the object reference we can call the non-static method
Q):- Can be used GOTO keyword in java to go to a particular point,
No, In java there is not goto keyword and java doesn’t support this feature of going to a particular labeled point.
Q):- Can we have any other return type than void for Main Method ?
No
Q):- Is it possible to define a method in Java Class but provide its implementation in the code of another lang. like C ?
Yes we can do this by native methods
Q):- Is Runnable interface marker or not?
Runnable interface is not marker because Runnable interface has the public void run() method declared inside it.
Q):- What Marker or Tag interface do in Java
- marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.
- Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM.
- So if JVM sees a Class is Serializable it done some special operation on it,
- similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning.
Cloning:
Q) What are different type of cloning in Java?
Java supports two type of cloning: - Deep and shallow cloning.By default shallow clone is used in Java. Object class has a method clone() which does shallow cloning.
Q) What is Shallow copy?
Shallow clone is a copying the reference pointer to the object, which mean the new object is pointing to the same memory reference of the old object. The memory usage is lower.
When a deep copy of the object is done new references are created.
Q) What is deep copy and how it can be achieved?
In deep copy is the copy of object itself. A new memory is allocated for the object and contents are copied.When a deep copy of the object is done new references are created.
class Subject {
private String name;
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Subject(String s) {
name = s;
}
}
class Student implements Cloneable {
//Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Student(String s, String sub) {
name = s;
subj = new Subject(sub);
}
// public Object clone() {
// //shallow copy
// try {
// return super.clone();
// } catch (CloneNotSupportedException e) {
// return null;
// }
// }
public Object clone() {
//Deep copy
Student s = new Student(name, subj.getName());
return s;
}
}
public class CopyTest {
public static void main(String[] args) {
Student stud = new Student("John", "Algebra");
System.out.println("Original Object: " + stud.getName() + " - " +
stud.getSubj().getName());
//Clone Object
Student clonedStud = (Student) stud.clone();
System.out.println("Cloned Object: " + clonedStud.getName() + " - " +
clonedStud.getSubj().getName());
stud.setName("Dan");
stud.getSubj().setName("Physics");
System.out.println("Original Object after it is updated: " +
stud.getName() + " - " + stud.getSubj().getName());
System.out.println("Cloned Object after updating original object: " +
clonedStud.getName() + " - " + clonedStud.getSubj().getName());
}
}
Q) Difference between Shallow and Deep Copy in Java
In shallow copy main or parent object is copied, but they share same fields or children if fields are modified in one parent object other parent fields have automatic same changes occur, but in deep copy this is not the case.
If our parent object contains only primitive value then shallow copy is good for making clone of any object because in new object value is copied but if parent object contains any other object then only reference value is copied in new parent object and both will point to same object so in that case according to our need we can go for deep copy.
Deep copy is expensive as compare to shallow copy in terms of object creation, because it involves recursive copying of data from other mutable objects, which is part of original object.
Serialization :
Q) Can we serialize static and transient variable
We cannot serialize Static and Transient variable
Q) How serialization behave with Association ?
Serialization with Association
1):- If Employee has a Address as a refrence variable then Address needs to implementing the Serializable else it will throw an exception that
java.io.NotSerializableException
2):- If we are using the List<Department> then Department need to implement the serializable interface else it will throw an exception.
java.io.NotSerializableException error.
3):- If parentClass is not implemented the Serialization but child class implements the serialization then serialization and deserialization is not giving any error. But every member is initialize to its default value
Parent Class è A
Child Class è B implements Serializable
If A obj = new B();
Then if we serialize object “obj” it will serialize with its default value. And if we deserialize it then it will give member variable value with default value.
4):- If parentClass is not implemented the Serialization but child class implements the serialization then serialization and deserialization is not giving any error. But Parent class member is initialize to its default value
Parent Class A
Child Class B implements Serializable
If
B obj = new B();
Then if we serialize object “obj” it will serialize with its default value. And if we deserialize it then it will give member variable value with default value.
Q) How serialization behave with Inheritance ?
Inheritance in Java Serialization
1) If Super class is Serializable
In case super class is Serializable than all its subclasses will be serializable by default. No need to implement serializable interface in subclass explicitly.
2) If Super class is not Serializable but subclass is
In case super class is not Serializable than to serialize the subclass’s object we must implement serializable interface in subclass explicitly. In this case the superclass must have a no-argument constructor in it.
3) If the superclass is serializable but we don’t want the subclass to be serialized.
To prevent subclass from being serialized we must implement writeObject() and readObject() method and need to throw NotSerializableException from these methods.
Q) What is serialVersionUID in Java Serialization ?
- serialVersionUID is used to ensure that during deserialization the same class (that was used during serialize process) is loaded.
- serialVersionUID is a static Final field.
- It is most important for serialization process.
- If you are not specifing any serialversion id in the class then IDE will show you the warning.
- If you are not adding it, JVM will add it at runtime
Class Refactoring with Serialization and serialVersionUID
Serialization in java permits some changes in the java class if they can be ignored. Some of the changes in class that will not affect the deserialization process are:- Adding new variables to the class
- Changing the variables from transient to non-transient, for serialization it’s like having a new field.
- Changing the variable from static to non-static, for serialization it’s like having a new field.
Q) What is the difference between Serializable vs Externalizable ?
- Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization.
- Correct implementation of Externalizable interface can improve performance of application drastically.
Q) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
- It doesn't have any method and also called Marker Interface in Java.
- When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.
Multithreading:
Q) What is Thread Pool ?
- A thread pool manages the pool of worker threads
- it contains a queue that keeps tasks waiting to get executed.
- A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
- java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java.
package com.java.threadpool;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
processCommand();
System.out.println(Thread.currentThread().getName()+' End.');
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
package com.java.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread('' + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println('Finished all threads');
}
}
Output:-
pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
Q) : what is ExecuterService?
package com.multithreading;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ExecuterServiceDemo {
public static void main(String args[]) {
final ExecutorService executerService = Executors.newFixedThreadPool(3);
Thread cacheService = new Thread(new Service1("CacheService", 1000));
Thread alertService = new Thread(new Service1("AlertService", 1000));
Thread validationService = new Thread(new Service1("ValidationService", 1000));
try {
executerService.execute(cacheService);
executerService.execute(alertService);
executerService.execute(validationService);
System.out.println("Before Shutdown");
executerService.shutdown();
System.out.println("After Shutdown");
while (!executerService.isTerminated()) {
}
System.out.println("All services are up, Application is starting now");
} catch (Exception ie) {
ie.printStackTrace();
}
}
}
class Service1 implements Runnable {
private final String name;
private final int timeToStart;
public Service1(String name, int timeToStart) {
this.name = name;
this.timeToStart = timeToStart;
}
@Override
public void run() {
try {
System.out.println(name + " is going to start");
Thread.sleep(timeToStart);
System.out.println(name + " is after sleep");
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(name + " is Up");
}
}
Output:-
Before Shutdown
ValidationService is going to
start
CacheService is going to start
AlertService is going to start
After Shutdown
ValidationService is after sleep
ValidationService is Up
CacheService is after sleep
CacheService is Up
AlertService is after sleep
AlertService is Up
All services are up, Application
is starting now
Q) : Difference Between ExecuterService and ThreadPoolExecuter?
ThreadPoolExecuter is implementation of ExecuterService.ExecuterService internally used ThreadPoolExecuter
public static ExecutorService newFixedThreadPool(int nThreads)
{
return new ThreadPoolExecutor(
nThreads, nThreads,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Q) : what is CountdownLatch ?
CountdownLatch is used when you want to perform some task and you want this functionality will execute when one or more specified thread completes its execution.
We define count while creating object of CountdownLatch
CountDownLatch latch = new CountDownLatch(3)
It decrease count by using countDown()
latch.countDown();
In countdown latch if thread count is down to "0" then we can not reinitialize it.
package com.aaditi.multithreading;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start();
alertService.start();
validationService.start();
try {
latch.await();
System.out.println("All services are up, Application is starting now");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
class Service implements Runnable {
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch) {
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println(name + " is going to start");
Thread.sleep(timeToStart);
System.out.println(name + " is after sleep");
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(name + " is Up");
latch.countDown(); // reduce count of CountDownLatch by 1
}
}
Output:-
AlertService is going to start
ValidationService is going to
start
CacheService is going to start
ValidationService is after sleep
ValidationService is Up
AlertService is after sleep
CacheService is after sleep
CacheService is Up
AlertService is Up
All services are up, Application
is starting now
Q) : what is CyclicBarrier ?
It is just similliar to countDownlatch but in this we can reset the latch count if it goes to 0.
package com.multithreading;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String args[]) throws InterruptedException, BrokenBarrierException {
CyclicBarrier barrier = new CyclicBarrier(4);
Party first = new Party(1000, barrier, "PARTY-1");
Party second = new Party(2000, barrier, "PARTY-2");
Party third = new Party(3000, barrier, "PARTY-3");
Party fourth = new Party(4000, barrier, "PARTY-4");
Party five = new Party(5000, barrier, "PARTY-5");
Party six = new Party(6000, barrier, "PARTY-6");
Party seven = new Party(7000, barrier, "PARTY-7");
Party eight = new Party(8000, barrier, "PARTY-8");
System.out.println(barrier.getNumberWaiting());
first.start();
second.start();
third.start();
fourth.start();
five.start();
six.start();
seven.start();
eight.start(); //total eight thread but barrier is of 4 size
System.out.println(Thread.currentThread().getName() + " has finished");
}
}
class Party extends Thread {
private int duration;
private CyclicBarrier barrier;
public Party(int duration, CyclicBarrier barrier, String name) {
super(name);
this.duration = duration;
this.barrier = barrier;
}
@Override
public void run() {
try {
Thread.sleep(duration);
System.out.println(Thread.currentThread().getName() + " is calling await()");
System.out.println(Thread.currentThread().getName() + " running : barrier Count is : " + barrier.getNumberWaiting() + " before");
barrier.await(); //this will reset the barrier size
System.out.println(Thread.currentThread().getName() + " running : barrier Count is : " + barrier.getNumberWaiting() + " after");
System.out.println(Thread.currentThread().getName() + " has started running again");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
Output:-
0
main has finished
PARTY-1 is calling await()
PARTY-1 running : barrier Count is : 0 before
PARTY-2 is calling await()
PARTY-2 running : barrier Count is : 1 before
PARTY-3 is calling await()
PARTY-3 running : barrier Count is : 2 before
PARTY-4 is calling await()
PARTY-4 running : barrier Count is : 3 before
PARTY-4 running : barrier Count is : 0 after
PARTY-4 has started running again
PARTY-1 running : barrier Count is : 0 after
PARTY-1 has started running again
PARTY-3 running : barrier Count is : 0 after
PARTY-2 running : barrier Count is : 0 after
PARTY-2 has started running again
PARTY-3 has started running again
PARTY-5 is calling await()
PARTY-5 running : barrier Count is : 0 before
PARTY-6 is calling await()
PARTY-6 running : barrier Count is : 1 before
PARTY-7 is calling await()
PARTY-7 running : barrier Count is : 2 before
PARTY-8 is calling await()
PARTY-8 running : barrier Count is : 3 before
PARTY-8 running : barrier Count is : 0 after
PARTY-8 has started running again
PARTY-7 running : barrier Count is : 0 after
PARTY-7 has started running again
PARTY-5 running : barrier Count is : 0 after
PARTY-5 has started running again
PARTY-6 running : barrier Count is : 0 after
PARTY-6 has started running again
Q) Difference between CountdownLatch and CyclicBarrier ?
In case of CountdownLatch once latch count down to "0" it will not increase again.
But by using CyclicBarrierit can be reset again.
Q) Default threadGroup ?
System is a ThreadGroup.Q) Difference between ExecuterService and CountdownLatch?ExecuterService create a threadPool but countdownLatch doesn't create thread pool.
Q):- Can be again Start the dead thread?
In Java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.
Collection :-
Q) What is the Difference between ArrayList and LinkedList ?
-
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes.
-
But there are many differences between ArrayList and LinkedList classes that are given below.
1) Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).
Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.
2) Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element) and O(1) in best case (While removing last element).
Conclusion: LinkedList element deletion is faster compared to ArrayList.
Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbour elements in the list. Hence removal only requires change in the pointer location in the two neighbour nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element.
3) Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. Reason is same as explained for remove.
4) Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively.
Q):- What is the difference between Comparable vs Comparator
Comparable
- Comparable interface is used to sort the objects of user-defined class
- It found in java.lang.
- For this class must implement the comparable interface and override the compareTo method. And you do your custom functionality in compareTo method for comparision.
Ex:- You have User class having the name , id and City.
package com.akshay.Comparable;
public class User implements Comparable<User>
{
private int Id;
private String Name;
private String City;
public User(int Id, String Name, String City)
{
this.Id = Id;
this.Name = Name;
this.City = City;
}
//create setter and getter
//this logic sort the users data based on name as well as city
@Override
public int compareTo(User user)
{
User temp = this;
int i = temp.getName().compareTo(user.getName());
if(i == 0)
{
i = temp.getCity().compareTo(user.getCity());
}
return i;
}
public String toString()
{
return "Id :- " + this.Id + " , Name :- " + this.Name + " , City :- " + this.City;
}
}
package com.akshay.Comparable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ComparableTest {
public static void main(String[] args)
{
List<User> users = new ArrayList<User>();
users.add(new User(1, "Akshay Gupta", "Noida"));
users.add(new User(2, "Sahi. Gupta", "Hyderabad"));
users.add(new User(3, "Karan Gupta", "Noida"));
users.add(new User(4, "Rahul Gupta", "Pune"));
users.add(new User(5, "Akshay Gupta", "Hyderabad"));
Collections.sort(users);
System.out.println(users);
}
}
Output :-
[Id :- 5 , Name :- Akshay Gupta , City :- Hyderabad, Id :- 1 , Name :- Akshay Gupta , City :- Noida, Id :- 3 , Name :- Karan Gupta , City :- Noida, Id :- 4 , Name :- Rahul Gupta , City :- Pune, Id :- 2 , Name :- Sahi. Gupta , City :- Hyderabad]
Comparator
- Comparator interface is used to order the objects of user-defined class.
- It found in java.util package.
- For this class must implement the comparator interface and override the compare method. And you do your custom functionality in compare method for comparision.
- It provide multiple sorting sequence.
- Ex: we can use it in sorting in Grid like name , City, Department basic separately or you can use together.
package com.akshay.Comparator;
import java.util.Comparator;
public class EmployeeNameComparator implements Comparator<Employee>
{
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getName().compareTo(emp2.getName());
}
}
package com.akshay.Comparator;
import java.util.Comparator;
public class EmployeeNameAndCityBothComparator implements Comparator<Employee>
{
@Override
public int compare(Employee emp1, Employee emp2) {
int i = emp1.getName().compareTo(emp2.getName());
if( i == 0 )
{
i = emp1.getCity().compareTo(emp2.getCity());
}
return i;
}
}
package com.akshay.Comparator;
import java.util.Comparator;
public class EmployeeCityComparator implements Comparator<Employee>
{
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getCity().compareTo(emp2.getCity());
}
}
package com.akshay.Comparator;
mport java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ComparatorTest {
public static void main(String[] args)
{
List<Employee> users = new ArrayList<Employee>();
users.add(new Employee(1, "Akshay Gupta", "Noida"));
users.add(new Employee(2, "Sahi. Gupta", "Hyderabad"));
users.add(new Employee(3, "Karan Gupta", "Noida"));
users.add(new Employee(4, "Rahul Gupta", "Pune"));
users.add(new Employee(5, "Akshay Gupta", "Hyderabad"));
System.out.println("Before Sorting");
System.out.println(users);
System.out.println();
Collections.sort(users,new EmployeeNameComparator());
System.out.println(users);
Collections.sort(users,new EmployeeCityComparator());
System.out.println(users);
Collections.sort(users,new EmployeeNameAndCityBothComparator());
System.out.println(users);//Note :- If you want to sort based on Name and City then you can do so.
}
}