All Core Java Interview Question PDF
All Core Java Interview Question PDF
JDK is the java development kit which is required for developing a java application, compiling
a java application, debugging a java application and executing a java application.
JVM along with the required java libraries is known as JRE(Java Runtime Env). clients need JRE
for executing a java application
JVM is the Java Virtual machine is nothing but the collection of programs which are collectively
working to provide complete environment required for the processor to execute byte code.
The JVM performs the following main tasks:
Loads code,Verifies code,Executes code,Provides runtime environment
paridabapun
2. How many types of memory areas are allocated by JVM?
Many types:
Class(Method) Area,Heap,Stack,Program Counter Register, Native Method Stack
3. What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation. Here the term “compiler” refers to a translator from the instruction
set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
4. What is platform?
Operating System and architecture of the processor together known as platform.
5. What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment [Link] (Application Programming Interface)
6. What gives Java its 'write once and run anywhere' nature?
The byte code. Java is compiled to be a byte code which is the intermediate language
between source code and machine code. This byte code is not platform specific and hence
can be fed to any platform.
7. What is class loader?
The class loader is a subsystem of JVM that is used to load classes and interfaces. There are
many types of class loaders e.g.
Bootstrap class loader (JAVA_HOME\jre\lib\[Link])
Extension class loader (JAVA_HOME\jre\lib\ext)
System class loader (class path)
Plug-in class loader etc.
Works on three principles .delegation , uniqueness , visibility
paridabapun
13. What is difference between object oriented programming language and object
based programming language?
Object based programming languages follow all the features of OOPs except Inheritance.
Examples of object based programming languages are JavaScript, VBScript etc.
14. What will be the initial value of an object reference which is defined as an
instance variable?
The object references are all initialized to null in Java
15. What is constructor?
Constructors are the functionalities which would be executed automatically at the time of
creation of object.
16. What is the purpose of default constructor?
The default constructor provides the default values to the objects. The java compiler creates a
default constructor only if there is no constructor in the class.
17. Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a value)
[Link] constructor inherited?
No, constructor is not inherited.
19. Can you make a constructor final?
No, constructor can't be final.
20. What is static variable?
Static variable is used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees, college name of students etc.
Static variable gets memory only once in class area at the time of class loading.
21. What is static method?
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
paridabapun
static is known as instance method.
2. Object is not required to call static method. Object is required to call instance
methods.
3. Non-static (instance) members cannot be accessed in static context (static method, static
block and static nested class) directly. Static and non-static variables both can be accessed in
instance methods.
4. For example: public static int cube (int n){ return n*n*n;} For example: public void msg
(){...}.
paridabapun
created , just reference variable will be created by pointing to the old contained object.
If we perform any changes to the clone object that reflects in the original .So any one come
and clone your application object & he do whatever he like.
Deep Cloning :
The process creates exactly duplicate independent object ,
In deep cloning if main object contains any reference variable then the corresponding object
copy will be created in cloned object .
If we want to do deep cloning we must implement Clonnable Interface by overriding clone
method .
Here if we perform any changes to the clone object than it won’t reflect on the original object.
*Copy Constructor*
paridabapun
type.
47. What is final variable?
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
48. What is final method?
Final methods can't be overridden.
49. What is final class?
Final class can't be inherited
50. What is blank final variable?
A final variable, not initialized at the time of declaration, is known as blank final variable.
51. Can we initialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized
only in the static block.
52. Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}
53. What is Runtime Polymorphism/Dynamic Polymorphism?
The concept of defining multiple methods with the same name and with the same data type of
the parameters associated with the same object is known as Dynamic polymorphism.
Out of multiple methods with the same name and with the same signature which method has
to get executed would be decided dynamically at the run time based on some runtime
condition .
By using method overriding we implement the concept of Dynamic polymorphism.
54. Can you achieve Runtime Polymorphism by data members?
No.
55. What is the difference between static binding(early binding) and dynamic
binding(late binding)?
late binding:: The concept of binding the functionalities to the method declaration dynamically
at the run time is known as late binding
early binding:: The concept of binding the functionalities to the method declaration at the
time of compilation itself or at the design time is known as early binding
In case of static binding type of object is determined at compile time whereas in dynamic
binding type of object is determined at runtime.
56) What is abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstraction lets you focus on what the object does instead of how it does it.
There are two ways to achieve abstraction in java
Abstract class (0 to 100%),Interface (100%)
57. What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation binds the data along with
paridabapun
the related and corresponding functions
58. What is abstract class?
a abstract class is a partially implemented and partially unimplemented structure which
contains both method declaration with bodies and method declaration without bodies...
A class that is declared as abstract is known as abstract [Link] needs to be extended and its
method implemented. It cannot be instantiated.
59. Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
60. Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final
method.
61. Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
62. What is interface?
Interfaces are fully unimplemented structure which contains only method declaration without
any body.
It can be used to achieve fully abstraction and multiple inheritance.
63. Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords
can't be used together.
64. Can an Interface be final?
No, because its implementation is provided by another class.
65. What is marker interface?
All the interfaces using which we explicitly mention and mark certain properties to the object
could be called as Marker interface.
An interface that has no data member and method is known as a marker interface. For
example Serializable, Cloneable,[Link]
66. What is difference between abstract class and interface?
Abstract class Interface
1 . An abstract class can have method body (non-abstract methods).Interface have only
abstract methods.
2 .An abstract class can have instance variables. An interface cannot have instance
variables.
3 .An abstract class can have constructor. Interface cannot have constructor.
4 .An abstract class can have static methods. Interface cannot have static methods.
5 .You can extend one abstract class. You can implement multiple interfaces.
67. Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public.
68. When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the
referenced interface.
paridabapun
69. What is package?
A package is a group of similar type of classes interfaces and sub-packages. It provides access
protection and removes naming collision.
70. Do I need to import [Link] package any time? Why?
No. It is by default loaded internally by the JVM.
71. Can I import same package/class twice? Will the JVM load the package twice at
runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM
complains about it. But the JVM will internally load the class only once no matter how many
times you import the same class.
72. What is static import?
By static import, we can access the static members of a class directly. There is no need to
qualify it by the class name.
73. What is the difference between import and static import?
The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a class
without the class qualification. The import provides accessibility to classes and interface
whereas static import provides accessibility to static members of the class.
[Link] is the difference between path and class path ?
Path is an environment variable which is used by the OS to find the executables. It is required
to access any java development tool such as javac,java,and javap.
Class path is an environment variable which is used by jvm to locate the user define classes
used by class loader to find & load classes in java prog.
75. What is oops concept in java?
oop is an approach that provides a way of modularizing a program by creating partitioned
memory area for both data and methods that can be used as template for creating copies of
such modules on demand.
There are three oops concept or rules that are supposed to be satisfied by a prog. language in
order to call a prog lang. a oop lang.
The three oops concept are Encapsulation, polymorphism, inheritance.
75. What is the state of the object?
The data present in the object at that point of time or that instance of time is known as the
state of object.
Depending on the functionality executed on the object the state of the object changes from
time to tome thus the state of the object is always tentative.
Behavior of the Object:
The functionality associated with the object constitutes the behavior of the object.
paridabapun
2. Final and static methods cannot be overridden.
3. The overriding method must have same argument list.
4. The overriding method must have same return type (or subtype).
5. The overriding method must not have more restrictive access modifier
This rule can be understood as follows:
If the overridden method is has default access, then the overriding one must be default,
protected or public.
If the overridden method is protected, then the overriding one must be protected or public.
If the overridden method is public, then the overriding one must be only public.
In other words, the overriding method may have less restrictive (more relaxed) access
modifier.
6. Abstract methods must be overridden by the first concrete (non-abstract) subclass.
public interface Animal {
void move();
}
----
public abstract class AbstractDog implements Animal {
protected abstract void bark ();}
----
public class BullDog extends AbstractDog {
public void move()
{ // Bulldog moves... }
protected void bark() { // Bulldog barks...} }
77. The synchronized modifier has no effect on the rules of overriding.
Exception Handling with Method Overriding in Java::
If the super class method does not declare an exception, subclass overriding method cannot
Declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception, subclass overridding method can declare
same,
subclass exception or no exception but cannot declare parent exception.
paridabapun
Let's understand the access modifiers by a simple table.
Access Modifier within class within package outside package by subclass only ou
Private Y N N
Default Y Y N
Protected Y Y Y
Public Y Y Y
Exception :
1. What is an Exception ?.
Exceptions are the object which are automatically generated by the jvm for representing run
time [Link] are set of classes which are exclusively design for representing the logical
errors and the runtime errors are known as Exception classes.
* Checked Exception:
All the exception classes which are not the sub class of RuntimeException are known as
Checked Exception.
Any Exception class representing a run-time error or logical error which can't be avoidable in
our program using conditional statements and our own logic would not be the sub class of
RuntimeException,They comes under Checked Exception
[Link],SQLException etc. Checked exceptions are checked at compile-time.
Unchecked Exception:
All the exception classes which are the sub class of RuntimeException are known as
Uncheched Exception.
Any Exception class representing a run-time error or logical error which could be avoidable in
our program using conditional statements and our own logic would be always the sub class of
RuntimeException,They comes under Unchecked Exception
e.g. ArithmeticException, NullPointerException. Unchecked exceptions are not checked at
compile-time.
paridabapun
It is not necessary that each try block must be followed by a catch block.
It should be followed by either a catch block OR a finally block.
And whatever exceptions are likely to be thrown should be declared in the throws clause of
the method.
Using finally blocks we can maintain proper separation between statement belonging to try &
catch blocks that are supposed
to get executed compulsorily irrespective of the exceptions and the statement belonging to
the function.
Using Finally block we can avoid catch,Thus whenever it is required to avoid a catch block
with respect to the try then we would be using finally block.
finally block is a block that is always executed.
finally block will not be executed if program exits(either by calling [Link]() or by causing
a fatal error that causes the process to abort).
The functionality of throws keyword is only explicitely mention that the corresponding
method is proven to trasfer it's unhandled exceptions to the calling place.
Thus throws keyword would not perform any operation. it only provides the information about
the unhandled exception of the functions
the two uses of throws keyword...
Using throws keyword we can explicitly provide the complete information about the
unhandled exception of the function.
Using throws keyword we can avoid try catch with respect to the statement proven to
generate checked exception
paridabapun
11. Can subclass overriding method declare an exception if parent class method
doesn't throw an exception?
Yes but only unchecked exception not checked.
12. What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.
13. what is difference between final ,finally,finailize() ?
Final –: final is modifier applicable on variable and methods and class.
By mentioning a variable as final we define constraints in java,thus the value of final variable
can't change.
By mentioning a class as final we restrict that class getting inherited by other classes.
By defining a method as final the method can't override in the sub class.
Finally – refer.. Q. 5
Finalize(. – Finalize is method of object class, garbage collector always called this method just
before
destroying any object to perform clean up activity.
paridabapun
mention condition is not [Link] have to explicitly enable Assertion at the time of
executing a java application using -ea (java –ea Ajohn 1 3000)
Ans If Object state cannot be changed after it is created then it is called as Immutable Object
Immutable objects are particularly useful in concurrent multithreading applications. As
its state cannot be inconsistent.
Immutable objects are automatically thread-safe.
String and Wrapper classes are by-default Immutable
Immutable objects are good Map keys and Set elements
Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
Ans Immutable object state cannot be modified after construction, any modification should
result in new immutable object.
Make the class as final so that it cannot be sub-classed
Make all fields final and private
Don‟t provide setter methods that modify fields
More sophisticate approach is to make the constructor private and construct instances
in factory method
If the instance fields include references to mutable objects, don't allow those objects to
be changed:
Don’t provide methods that modify the mutable objects
don’t share references to the mutable objects. Never store references to
external, mutable objects passed to the constructor; if necessary, create copies,
and store references to the copies.
3 Write an Immutable class in Java?
Ans: 1. Immutable objects are by default thread safe, can be shared without synchronization in
concurrent environment.
2. Immutable object simplifies development, because its easier to share between
multiple threads without external synchronization.
3. Immutable object boost performance of Java application by reducing synchronization in code
paridabapun
4. Another important benefit of Immutable objects is reusability, you can cache Immutable
object and reuse them, much like String literals and Integers. You can use static factory
methods to provide methods like valueOf(), which can return an existing Immutable object
from cache, instead of creating a new one.
5. It makes good Map keys and Set elements (these objects must not change state while in the
collection)
5 What is String in Java?
String Pool: As String is most used datatype in java application so java designer wanted to
optimize it by storing it in string pool. Goal was to reduce temporary use of string object by
sharing them and inorder to share them they should be immutable.
Security: String has been widely used as parameter for many Java classes, e.g.
for
opening network connection, you can pass host and port as String, for reading files
in Java you can pass path of files and directory as String and for opening
database connection, you can pass database URL as String. If String was not immutable,
a user might have granted to access a particular file in system, but after authentication
he can change the PATH to something else, this could cause serious security issues.
Similarly, while connecting to database or any other machine in network, mutating String
value can pose security threats.
String in Class Loading Mechanism: Another reason for making String final or
Immutable was driven by the fact that it was heavily used in class loading mechanism.
As String been not Immutable, an attacker can take advantage of this fact and a request
to
load standard Java classes e.g. [Link] can be changed to malicious class
[Link]. By keeping String final and immutable, we can at least
be sure that JVM is loading correct classes.
Multithreading Benefits : String is immutable and we just we can share it
between
threads, it result is more readable and clear
code.
Optimization and Performance: Now when you make a class Immutable, you know in
advance that, this class is not going to change once created. This guarantee open path
for many performance optimization e.g. caching. String itself know that, I am not going
to
change, so String cache its hashCode. It even calculate hashCode lazily and once
created, just cache it. In simple world, when you first call hashCode() method of any
String object, it calculate hash code and all subsequent call to hashCode() returns
already calculated,
cached value. This results in good performance gain, given String is heavily used in hash
based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without
making it immutable and final, as it depends upon content of String itself.
7 All Wrapper classes are also immutable and final in java?
Ans yes
paridabapun
8 Why character array is better than String for Storing password in Java?
Ans String is immutable in java and stored in String pool. Once it’s created it stays in the pool
until unless garbage collected, so even though we are done with password it‟s available
in memory for longer duration and there is no way to avoid it. It’s a security risk
because anyone having access to memory dump can find the password as clear text.
If we use char array to store password, we can set it to blank once we are done with it.
So we can control for how long it‟s available in memory that avoids the security threat
with String.
9 Why String immutable and final in java? [short answer]
When we use double quotes to create a String, it first looks for String with same value
in the String pool, if found it just returns the reference else it creates a new String in
the pool and then returns the reference.
However using new operator, we force String class to create a new String object and
then we can use intern() method to put it into the pool or refer to other String object
from pool having same value.
11 What is the use of intern () method?
Ans When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the
pool is returned. Otherwise, this String object is added to the pool and a reference to
this String object is returned.
This method always return a String that has the same contents as this string,
but is guaranteed to be from a pool of unique strings.
12 Does String is thread-safe in Java?
Ans Strings are immutable, so we can‟t change it‟s value in program. Hence it‟s thread-
safe and can be safely used in multi-threaded environment.
paridabapun
equals method.
== operator checks reference of two strings where as equals() checks the
value/containt of two strings equal or not.
String s1 =
"abc"; String
s2 = "abc";
String s3= new String("abc");
[Link]("s1 == s2 ? "+(s1==s2)); //true
[Link]("s1 == s3 ? "+(s1==s3)); //false
[Link]("s1 equals s3 ? "+([Link](s3))); //true
15 How to Split String in java?
Ans String class split(String regex) is the method that we can use to split Strings into
String array.
String line = "I am a java
developer"; String[] words =
[Link](" "); String[] twoWords =
[Link](" ", 2);
[Link]("String split with delimiter:
"+[Link](words)); [Link]("String split into two:
"+[Link](twoWords));
//split string delimited with special
characters String wordsWithNumbers = "I|am|a|java|
developer"; String[] numbers =
[Link]("\\|");
[Link]("String split with special character: "+[Link](numbers));
String split with delimiter: [I, am, a, java,
developer] String split into two: [I, am a java
developer]
String split with special character: [I, am, a, java, developer]
16 Difference between String, StringBuffer and StringBuilder?
Ans String is immutable and final in java, so whenever we do String manipulation, it creates
a new String.
java provides two utility classes for String manipulations – StringBuffer and StringBuilder.
StringBuffer and StringBuilder are mutable classes.
StringBuffer operations are thread-safe and synchronized where StringBuilder
operations are not thread-safe.
when multiple threads are working on same String, we should use StringBuffer but in
single threaded environment we should use StringBuilder.
StringBuilder performance is fast than StringBuffer because of no
overhead of synchronization.
paridabapun
char initial = [Link](0); // first character
String rem = [Link](1); // Full string without first character
Set<String> words = permutationFinder(rem);
for (String strNew : words) {
for (int i = 0;i<=[Link]();i++){
[Link](charInsert(strNew, initial, i));
}
}
return perm;
}
paridabapun
String s = [Link](c);
[Link]("char to String:
"+s);
// char array to string
char
charray[]=[„k‟,‟a‟,‟r‟,‟t‟,‟i‟,‟
k‟], String s1=new
String(charray);
[Link](s1);
24 Write a method that will remove given character from the String?
Ans We can use replaceAll method to replace all the occurance of a String with another String.
[Link]([Link](c), "")
paridabapun
for (int i = 0; i < length / 2; i++) {
In case of first method, substring starts with beginIndex and goes till end of String, while
in case of overloaded method, substring starts from beginIndex and goes till endIndex-
1.
Since String in Java are zero index based, beginIndex can be from 0 to length of String.
Thus if you have a string with 10000 chars and create 100 substrings with 5-10 chars in
each, all 101 objects will have same char array of size 10000 chars. It is memory
wastage without any doubt or memory leak.
Example
import [Link];
paridabapun
import [Link];
[Link](mainString)
;
[Link](subString);
paridabapun
Ans SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
Date date = [Link](dateInString); // String to Date Object
[Link](date); [Link]([Link](date));
// Date Object to String
paridabapun
[Link]=sname;
}
public String toString() {
return "Sid=" + sid + "Sname=" + sname;
}
}
public class Example1 {
public static void main(String[] args) throws
Exception{ Student s1=new
Student(1,"Bhagabata Parida");
OutputStream os=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(os);
// writing object to Byte Stream
[Link](s1);
// deserializing the Object
InputStream is=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(is);
Student s2=(Student)[Link]();
[Link](s2);
}
}
paridabapun
class Student implements Externalizable {
int sid;
String sname;
public Student(){}
public Student(int sid,String sname)
{ [Link]=sid;
[Link]=sname;
}
public void readExternal(ObjectInput oi) throws
IOException,ClassNotFoundException {
int id=[Link]();
String name=(String)[Link]();
[Link]("Id="+id+"Name="+name);
}
public void writeExternal(ObjectOutput out) throws IOException {
paridabapun
[Link](sid);
[Link](sname);
}
}
public class Example1 {
public static void main(String[] args) throws
Exception{ Student s1=new
Student(1,"Bhagabata Parida");
OutputStream os=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(os);
// writing object to Byte Stream
[Link](s1);
// deserializing the Object
InputStream is=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(is);
[Link]();
}
}
35 What is a Serial Version UID (serialVersionUID) and why should I use it? How to
generate one?
Ans The serialVersionUID is used as a version control in a Serializable class. If you do not
explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various
aspects of your Serializable class
SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions
of the class ensuring that the same class was used during Serialization is loaded during
Deserialization.
If a different class is loaded that has a different serialVersionUID than that of the
corresponding class, that is used while Serialization , then deserialization will result in an
InvalidClassException.
A serializable class can declare its own serialVersionUID explicitly by declaring a field
named "serialVersionUID" that must be static, final, and of type long.
paridabapun
written to the stream. readResolve method allows to designate a replacement object for
the object just read from the stream.
37 Rule of Serialization in Inheritance.
Ans In case super class is Serializable than all its subclasses will be serializable by default. No
need to implement serializable interface in subclass explicitly
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. [Super class members will not serialized]
a) If superclass is not Serializable then all values of the instance variables inherited
from super class will be initialized by calling constructor of Non-Serializable Super
class during deserialization process.
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.
class A implements Serializable{ int x=10; }
class B extends A{
paridabapun
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
public class Example2 {
public static void main(String[] args)throws Exception
{ B ob=new B();
OutputStream os=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(os);
[Link](ob);
}
}
39 What would happen if the SerialVersionUID of an object is not defined in your class?
Ans If you don't define serialVersionUID in your serilizable class, Java compiler will make one
by creating a hash code using most of your class attributes and features.
41 What are transient variables? What role do they play in Serialization process?
Ans The transient keyword in Java is used to indicate that a field should not be serialized.
Marking unwanted fields as transient can help you boost the serialization performance.
paridabapun
42 Why does serialization NOT save the value of static class attributes? Why
static variables are not serialized?
Ans 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:-
a) It will make redundant copy of same variable in multiple objects which makes it in-
efficient.
b) The static variable can be modified by any object and a serialized copy would be
stale or not in sync with current value.
paridabapun
Serializing the collection can be costly therefore make sure you serialize only required
data instead of serializing the whole collection.
paridabapun
// deserializing the Object
InputStream is=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(is);
Student s2=(Student)[Link]();
[Link](s2);
}
}
paridabapun
For this, writeObject () and readObject() methods should be implemented in your class so
that a Not Serializable Exception can be thrown by these methods. And, this can be done
by customizing the Java Serialization process.
class MySubClass extends SomeSerializableSuperClass {
private void writeObject([Link] out) throws IOException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObject([Link] in)throws IOException,
ClassNotFoundException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObjectNoData() throws ObjectStreamException; {
throw new NotSerializableException(“Can not serialize this class”);
}
}
46 What changes are compatible and incompatible to the mechanism of java Serialization?
Ans In an already serialized object, the most challenging task is to change the structure of a
class when a new field is added or removed. As per the specifications of Java
Serialization, addition of any method or field is considered to be a compatible change
whereas changing of class hierarchy or non-implementation of Serializable interface is
considered to be a non-compatible change.
If a serialized object need to be compatible with an older version, it is necessary that the
newer version follows some rules for compatible and incompatible changes.
Compatible changes are:
Addition of a new field or class will not affect serialization, since any new data in the
stream is simply ignored by older versions. the newly added field will be set to its default
values when the object of an older version of the class is un marshaled.
The access modifiers change (like private, public, protected or default) is compatible since
they are not reflected in the serialized object stream.
Changing a transient field to a non-transient field is compatible change since it is similar
to adding a field.
Changing a static field to a non-static field is compatible change since it is also similar to
adding a field.
Some incompatible changes are:
Changing implementation from Serializable to Externalizable interface can not be
done since this will result in the creation of an incompatible object stream.
Deleting a existing Serializable fields will cause a problem.
Changing a non-transient field to a transient field is incompatible change since it is similar
to deleting a field.
Changing a non-static field to a static field is incompatible change since it is also similar to
deleting a field.
Changing the type of a attribute within a class would be incompatible, since this would
cause a failure when attempting to read and convert the original field into the new
field.
changing the package of class is incompatible. Since the fully-qualified class name is
written as part of the object byte stream.
paridabapun
1 How Volatile keyword works? Example of volatile keyword in java.
Ans ● The Java volatile keyword is used to mark a Java variable as "being stored in main memory".
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 write to a volatile variable will be written
to main memory, and not just to the CPU cache.
● Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache
value of this variable and always read it from main memory.
● If you want to share any variable in which read and write operation is atomic by
implementation e.g. read and write in int or boolean variable you can declare them as volatile
variable.
● In Java reads and writes are atomic for all variables declared using Java volatile keyword
(including long and double variables).
● Volatile keyword can only be applied to variable, it cannot be applied to class or method. using
volatile keyword along with class and method is compiler error.
if(instance == null){
synchronized([Link]){
if(instance == null)
}
return instance;
If you look at the code carefully you will be able to figure out:
● Any variable which is shared between multiple threads should be made volatile, in
order to ensure that all thread must see latest value of volatile variable.
paridabapun
● You want to save cost of synchronization as volatile variables are less expensive
than synchronization.
● Another place where volatile variable can be used is to fixing double checked locking in
Singleton pattern.
● You can use Volatile variable if you want to read and write long and double variable
atomically. long and double both are 64 bit data type and by default writing of long and
double is not atomic and platform dependence. Many platform perform write in long and
double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see
32 bit from two different write. You can avoid this issue by making long and double variable
volatile in Java.
● Java volatile keyword doesn't means atomic, its common misconception that after declaring
volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive
access using synchronized method or block in Java.
Volatile is not a replacement of synchronized keyword but can be used as an alternative in certain
cases.
● Volatile keyword in Java is a field modifier, while synchronized modifies code blocks and
methods.
● Synchronized obtains and releases lock on monitor’s Java volatile keyword doesn't require that.
● Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the
case with volatile keyword in Java.
● Since volatile keyword in Java only synchronizes the value of one variable between Thread
memory and "main" memory while synchronized synchronizes the value of all variable between
thread memory and "main" memory and locks and releases a monitor. Due to this reason
synchronized keyword in Java is likely to have more overhead than volatile.
● From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and
reading from a volatile field has the same memory effect as a monitor acquire
1. Comparator in Java defined in [Link] package while Comparable interface available in lang
package
2. Comparator interface is used as utility for sort objects where as Comparable is used for natural
paridabapun
sorting.
4. Comparator interface has a method int compare(Object o1,Object o2) which return a negative,
zero, or positive integer as the first argument less than, equal to or greater than the second .
5. While Comparable Interface has int compareTo(Object o) which also return a negative, zero, or
positive integer as the this object less than, equal to or greater than the specified object
6. If any class implements Comparable interface in java then collection of that object can be sorted
using [Link]() or [Link]();
7. Similarly We can create a Object of Comprator by implementing its compare() method which can
be passed as argument to [Link](Collection,Comparator);
Example:
import [Link].*;
int sid;
String sname;
sid=x;sname=y;
return 0;
else
return -1;
paridabapun
}
[Link](e1);[Link](e2);[Link](e3);[Link](e4);
[Link](stdList);
[Link]("Natural Sort="+stdList);
[Link](e1);[Link](e2);[Link](e3);[Link](e4);
[Link](stdList,new IdComparator());
[Link]("Id Comparator="+stdList);
[Link](stdList,new NameComparator());
[Link]("Name Comparator="+stdList);
}
}
return 1;
return 0;
else
return -1;
paridabapun
}
return [Link]([Link]);
● Vector is synchronized and thread-safe while ArrayList is neither Synchronized nor thread-safe.
● Vector is a legacy class (introduced in 1.0) and initially it was not part of Java Collection
Framework. From Java 1.4 Vector was introduced to implement List interface and become part of
Collection Framework.
● Whenever Vector crossed the threshold specified it increases itself by value specified in
capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity ()
method.
● Vector can return enumeration of items it hold by calling elements () method which is not fail-
fast as opposed to Iterator and ListIterator returned by ArrayList.
Similarities
1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume
that you will get the object in the order you have inserted if you iterate over ArrayList or
Vector.
3) Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.
paridabapun
6 Describe the Class hierarchy of Collection API?
paridabapun
How HashMap works? How get/put method of HashMap works in Java?
a. Hash function must return the same hash code every time when it is applied multiple
times over same object. Is two equal object must produce same hash code.
2) Otherwise hashCode() is applied over key object which returns an integer value which
represents bucket number.
3) That hashCode() may return very high or low hashCode value for that again hash() called
which returns a appropriate value within the range of array.
5) Now two unequal object may have same hashCode ie two different object can stored in same
array location [Bucket] so collision may arise to resolve it at each bucket location LinkedList
is maintained.
6) Now HashMap checks whether already the Entry object available by calling [Link](key)
over key object. And this process following for all entry object available in that bucket.
7) If not available then it stored at end of LinkedList otherwise it is overwritten the value if
exist.
paridabapun
How get() method works
1) It first calls hashCode() over key object which returns bucket index number.
2) Then it calls equals() over key objects for all Entry objects available in that bucket
3) If a matching key found then its respective value will returned otherwise returns null.
9 What happens if HashMap size exceeds a given threshold defined by load factor?
● If size of HashMap exceeds a given threshold defined by load-factor then HashMap re-size
itself by creating new bucket array of size twice of previous size and start putting every old
element into new bucket array of HashMap. This process is called as Re-Hashing.
● If loadfactor is .75 then then it will act to re-size the map once it filled 75%.
● Yes there is potential race condition exists while resizing HashMap in java.
● While doing the rehashing internal elements which are stored in a linked list for given
bucket. They get reverse in the order. Suppose there are two threads encounter the
race condition in same time then there are chances of second thread can go in infinite
loop while traversal since the order has been changed.
● Java HashMap doesn’t append the new element at tail instead it append new element
at head to avoid tail traversing.
11 Why string, Integer and other wrapper classes are considered as good keys?
● String and wrapper classes is immutable and final and overrides equals() and hashCode()
methods so it is considered as good key.
● Hash Key object should be immutable and thread safe as no thread can change the key of
HashMap . if hashCode() over key object returns different value at different time then it will
be impossible retrieve data from Hashmap.
● Yes you can use Custom object as key in hashMap. In this case we have to efficiently
override hashCode() and equals() method.
Example:
class Employee {
paridabapun
private int eid;
[Link]=eid;
[Link]=ename;
return eid+"=="+ename;
Employee e1=(Employee)obj;
if([Link]([Link]))
return true;
return false;
}
public class hashmap11 {
[Link](new Employee(100,"Bhagabata"),5000);
[Link](hm);
}}
12
paridabapun
Sort all elements in a HashMap according to empId where hashMap key is a Custom
Object of Employee Type. And sort according to HashMap value.
[Link]=eid;
[Link]=ename;
Employee e1=(Employee)obj;
else return 0;
[Link](new Employee(100,"x"),5000);
paridabapun
[Link](new Employee(50, "y"),2000);
[Link](hm);
// Using another Map which will containg sorted entries. and Comparable
[Link](entryist);
[Link](e1, [Link](e1));
[Link](sortedMap);
new ArrayList<[Link]<Employee,Integer>>([Link]());
[Link](customList,new Comparator<[Link]<Employee, Integer>>(){
Employee e1=[Link]();
Employee e2=[Link]();
if([Link]()>[Link]())return -1;
else return 1;
});
paridabapun
[Link](customList);
● Hashtable is purely synchronized that is whole hashtable will be locked when and
reader/writer access it. Problem occurs when any reader is reading data the hashtable will
locked
● ConcurentHashMap solves above problem which provides better concurrency by locking only
portion of map.
● Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full
map while doing iteration.
● When getting data, a volatile read is used without any synchronization. If the volatile
read results in a miss, then the lock for that segment is obtained and entry is again
searched in synchronized block.
14 What is difference between ConcurentHashMap and synchronizedHashMap? or
Difference between ConcurrentHashMap and [Link]( HashMap )
paridabapun
iteration to complete.
● ConcurrentHashMap do not allow null keys or null values while synchronized HashMap allows
one null keys.
2) HashMap allows null key and null value where as Hashtable doesn’t allows null key and null
value.
● It is better suited for situation where you have multiple readers and one writer or fewer
writers .
● If you have equaled number of reader and writer than ConcurentHashMap will perform in
line of Hashtable or synchronized hashmap.
18 paridabapun
What is difference between fail-fast and fail-safe iterators?
1. Fail fast iterator while iterating through the collection , instantly throws Concurrent
Modification Exception if there is structural modification of the collection .
a. Single Threaded Environment: After the creation of the iterator , structure is modified
at any time by any method other than iterator's own remove method.
3. Iterators returned collection are fail-fast including Vector, ArrayList, HashSet etc
4. Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over
the copied data [Link] structural modification done to the iterator affects the copied
data structure. So , original data structure remains structurally unchanged .Hence , no
ConcurrentModificationException throws by the fail safe iterator.
b. Fail safe iterator does not guarantee that the data being read is the data currently in
the original data structure.
1. Enumeration is a legacy class and not all Collection supports it. Like Vector Supports
Enumeration but ArrayList doesnot.
3. Iterator is more secure and safe as compared to Enumeration because it does not allow
other thread to modify the collection object while some thread is iterating over it and throws
ConcurrentModificationException.
1. Index based access allow access of the element directly on the basis of index. The cursor of
paridabapun
the data structure can directly go to the 'n' location and get the element. It does not
traverse through n-1 elements.
2. In Iterator based access, the cursor has to traverse through each element to get the desired
[Link] to reach the 'n'th element it need to traverse through n-1 elements.
3. Insertion,updation or deletion will be faster for iterator based access if the operations are
performed on elements present in between the datastructure.
4. Insertion,updation or deletion will be faster for index based access if the operations are
performed on elements present at last of the datastructure.
● This method returns a new list. If a user tries to perform add operation on the new list;
UnSupportedOperationException is thrown.
● A null element can be added only if the set contains is on size 1 because when a second
element is added then as per set defination a check is made to check duplicate value and
comparison with null element will throw NullPointerException.
● To sort the elements of the List in the reverse natural order of the strings, get a reverse
Comparator from the Collections class with reverseOrder(). Then, pass the reverse
Comparator to the sort() method.
paridabapun
[Link](list, comp)
● HashSet implements hashmap internally to store the data. The data passed to hashset is
stored as key in hashmap with null as value.
2. List allows retrieval of data to be in same order in the way it is inserted but Set doesn’t
[Link](List list)
[Link](Set set)
[Link](Map map)
[Link](Collection c)
30 What is identityHashMap?
● This class implements Map interface. It is similar to HashMap except that it uses reference
equality when comparing elements.
● It is used only in the rare cases wherein reference-equality semantics are required.
31 What is WeakHashMap?
● More precisely, the presence of a mapping for a given key will not prevent the key from
being discarded by the garbage collector, that is, made finalizable, finalized, and then
reclaimed.
paridabapun
● When a key has been discarded its entry is effectively removed from the map, so this class
behaves somewhat differently than other Map implementations.
● Both null values and the null key are supported. This class has performance characteristics
similar to those of the HashMap class, and has the same efficiency parameters of initial
capacity and load factor.
● This class is not synchronized. A synchronized WeakHashMap may be constructed using the
[Link] method.
● HashSet implements Set interface, it guarantee uniqueness and this is achieved by storing
elements as keys with same value always.
● A call to add(Object) is delegate to put(Key, Value) internally, where Key is the object you
have passed and value is another object, called PRESENT, which is a constant in
[Link] as shown below :
● HashSet doesn't provide any direct method for retrieving object e.g. get(Key key) as
HashMap or get(int index) as List, only way to get object from HashSet is via Iterator
● iterator() method from [Link] class returns iterator for backup Map returned by
[Link]().iterator() method.
return [Link]().iterator();
● Objects stored in HashSet must override equals() and hashCode() method so that we can
check for equality and no duplicate value are stored in our set.
● If you are storing custom objects in HashSet then we have to override hashCode() and
equals() in that Object.
paridabapun
33 How do you sort objects on Collection?
● Sorting is implemented using Comparable and Comparator in Java and when you call
[Link](list) it gets sorted based on natural order specified in comparareTo() method
● To find middle element in LinkedList we can use two pointers ie incrementing one at each
iteration and other at every second iteration.
● When first pointer will point at end of Linked List, second pointer will be pointing at middle
node of Linked List.
● In fact this two pointer approach can solve multiple similar problems e.g. How to find 3rd
element from last in a Linked List in one Iteration or How to find nth element from last in a
Linked List.
class LinkedList{
public LinkedList(){
tail = head;
}
public Node head(){ return head; }
[Link] = node;
tail = node;
paridabapun
private Node next;
paridabapun
int length = 0;
while([Link]() != null){
length++;
if(length%2 ==0){
middle = [Link]();
current = [Link]();
if(length%2 == 1){
middle = [Link]();
35 How do you find if there is any loop in single linked list? How do you find the start of the
loop?
● Two pointers, fast and slow is used while iterating over linked list. Fast pointer moves two
nodes in each iteration, while slow pointer moves to one node.
● If linked list contains loop or cycle than both fast and slow pointer will meet at some point
during iteration. If they don't meet and fast or slow will point to null, then linked list is not
cyclic and it doesn't contain any loop.
paridabapun
while(fast!= null && [Link] != null){
fast = [Link];
slow = [Link];
//if fast and slow pointers are meeting then LinkedList is cyclic
if(fast == slow ){
return true;
return false;
● brute force method which compares each element of Array to all other elements and return
true if it founds duplicates.
● Another quick way of checking if a Java array contains duplicates or not is to convert that
array into Set. Since Set doesn’t allow duplicates size of corresponding Set will be smaller
than original Array if Array contains duplicates otherwise size of both Array and Set will be
same.
● One more way to detect duplication in java array is adding every element of array into
HashSet which is a Set implementation. Since add(Object obj) method of Set returns false if
Set already contains element to be added, it can be used to find out if array contains
duplicates in Java or not.
37 How to find out the frequency of each element in List?
[Link]("x");[Link]("m");[Link]("k");[Link]("k");
[Link]("z");[Link]("z");[Link]("c");[Link]("c");
for(String x: mySet){
paridabapun
}
//Or
for(int i = 0; i<[Link]();i++){
[Link]([Link](i)+"");
for(String x: mySet1){
for(String x: mySet2){
}
39 Sort a Array in Ascending and descending order?
paridabapun
[Link]("x");[Link]("m");[Link]("k");[Link]("k");
[Link]("z");[Link]("z");[Link]("c");[Link]("c");
//How create a Map which will containg each element and their frequency
for(String elm:list1){
if([Link](elm))
[Link](elm, [Link](elm)+1);
else
[Link](elm, 1);
[Link]("Frequency Of "+[Link]()+":"+[Link]());
42 How will you retrieve Value object if two Keys will have same hashcode?
● Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in
both the directions.
● ListIterator inherits from Iterator interface and comes with extra functionalities like adding
an element, replacing an element, getting index position for previous and next elements.
● Set keySet()
● Collection values()
paridabapun
● Set<[Link]<K, V>> entrySet()
45 What is a TreeMap?
● The map is sorted according to the natural ordering of its keys, or by a Comparator provided
at map creation time, depending on which constructor is used.
● This implementation provides guaranteed log(n) time cost for the containsKey, get, put and
remove operations.
46 What is TreeSet?
● The elements are ordered using their natural ordering, or by a Comparator provided at set
creation time, depending on which constructor is used.
● This implementation provides guaranteed log(n) time cost for the basic operations (add,
remove and contains).
● ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.
● Marker interface used by List implementations to indicate that they support fast random
access.
48 What is EnumSet?
● [Link] is Set implementation to use with enum types.
● All of the elements in an enum set must come from a single enum type that is specified,
explicitly or implicitly, when the set is created.
● It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and
complementOf(EnumSet s).
paridabapun
● The Properties class represents a persistent set of properties. The Properties can be saved to
a stream or loaded from a stream. Each key and its corresponding value in the property list
is a string.
[Link]("database", "localhost");
[Link]("dbuser", "mkyong");
[Link]("dbpassword", "password");
[Link](output, null);
// retriving Data
[Link](fis);
[Link]([Link]("database"));
Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can
be used in multi-threaded environment.
53
paridabapun
What is a Collections interface?
● This class contains methods for collection framework algorithms, such as binary search,
sorting, shuffling, reverse, frequency etc.
[Link](k1+":"+[Link](k1));
[Link]([Link]()+":"+[Link]());
Ans 1. Sleep() is available in Thread class where as wait() is available in Object class.
2. Sleep() is used only for inturrupt/blocking a thread where wait() is used for inter thread
communication.
4. Sleep() is a static method on Thread class. It makes the current thread into the "Not
Runnable" state for specified amount of time. During this time, the thread keeps the lock
(monitors) it has acquired. But wait() is a non-static method on Object class. It makes the
current thread into the "Not Runnable" state. Causes the current thread to wait until
another thread invokes the notify() or notifyAll() method for this object.
6. wait() method releases the lock of object on which it has called, it does release other locks
if it holds any while sleep method of Thread class does not release any lock at all.
Ans 1. ‘yield’ means to let go, to give up, to surrender. A yielding thread tells the virtual
machine that it’s willing to let other threads be scheduled in its place.
2. Yield is a Static method and Native too. Yield tells the currently executing thread to give a
chance to the threads that have equal priority in the Thread Pool.
3. It can only make a thread from Running State to Runnable State, not in wait or blocked
state.
4. It simply give a chance to remaining waiting threads of the same priority to execute. If all
waiting threads have lower priority then same thread will continue execution.
Ans 1. [Link]() only pause() execution , as it is a static method it always applied on current
thread.
2. Java has two varient of sleep() method like sleep(millisecond) and sleep(millisecond,
nannosecond)
paridabapun
5. There is a misconception that [Link]() will put thread t to sleep state but as it is a static
method it always put current thread to sleep.
Ans 1. Wait and notify is not just normal methods or synchronization utility, more than that they
are communication mechanism between two threads in Java. So object class is corect place
for them.
2. Locks are made available on per Object basis, which is another reason wait and notify
is declared in Object class rather then Thread class.
3. In Java in order to enter critical section of code, Threads needs lock and they wait for lock,
they don't know which threads holds lock instead they just know the lock is hold by some
thread and they should wait for lock instead of knowing which thread is inside the
synchronized block and asking them to release lock. this analogy fits with wait and notify
being on object class rather than thread in Java.
Ans 1. Runnable interface represents a Task which can be executed by either plain Thread or
Executors or any other means. so logical separation of Task as Runnable than Thread is
good design decision.
2. Java doesn't support multiple inheritance, which means you can only extend one class in
Java so once you extended Thread class you cannot extend any other class , so in that case
we can implement Runnable interface.
3. Inheriting all Thread methods are additional overhead just for representing a Task which
can can be done easily with Runnable.
6 You have thread T1, T2 and T3 , how you will ensure thread thread T2 run after T1 and
thread T3 run after T2?
Ans 1. Using join method, we can make one Thread to wait for another.
2. Primary use of [Link]() is to wait for another thread and start execution once that
Thread has completed execution or died.
3. Join is also a blocking method, which blocks until thread on which join has called die or
specified waiting time is over.
paridabapun
public static void main(String args[]) throws InterruptedException{
try {
[Link](2000);
[Link]();
};
[Link]();
[Link]();
}
Output:
main is Started
Thread-0 is Started
Thread-0 is Completed
main is Completed
7 Why wait (), notify () and notifyAll () must be called from synchronized block or method
in Java
Ans 1. We use wait () and notify () or notifyAll () method mostly for inter-thread communication.
2. One thread is waiting after checking a condition e.g. In Producer Consumer example
paridabapun
3. Producer Thread is waiting if buffer is full and Consumer thread notify Producer thread after
he creates a space in buffer by consuming an element.
5. The lucky thread returns from wait() method after reacquiring the lock and proceed further.
Let’s divide this whole operation in steps to see a possibility of race condition between wait
() and notify () method in Java
a) The Producer thread tests the condition (buffer is full or not) and confirms that it must
wait (after finding buffer is full).
b) The Consumer thread sets the condition after consuming an element from buffer.
c) The Consumer thread calls the notify () method; to issue notification for producer
threads that condition has been changed, and comback to reacquare lock and proceed
further
d) The Consumer thread calls the wait () method and goes into waiting state and leves
lock.
Now let's think how does this potential race condition get resolved?
This race condition is resolved by using synchronized keyword and locking provided by java. In
order to call the wait (), notify () or notifyAll () methods in Java, we must have to obtain the lock for
the object on which we're calling the method.
Since the wait () method in Java also releases the lock prior to waiting we must use this lock to
ensure that checking the condition (buffer is full or not) and setting the condition (taking element
from buffer) is atomic which can be achieved by using synchronized method or block in Java.
8 What is the advantage of new Lock interface over synchronized block in java.
2. Since Lock is an interface, you need to use one of its implementations to use a Lock in your
applications. Example:
[Link]();
//critical section
[Link]();
paridabapun
The main differences between a Lock and a synchronized block are:
● A synchronized block makes no guarantees about the sequence in which threads waiting to
entering it are granted access.
● You cannot pass any parameters to the entry of a synchronized block. Thus, having a
timeout trying to get access to a synchronized block is not possible.
● The synchronized block must be fully contained within a single method. A Lock can have it's
calls to lock() and unlock() in separate methods. ReentrantLock – as you’d expect, a
reentrant Lock implementation. ReentrantReadWriteLock – a reentrant ReadWriteLock
implementation
[Link] = value;
[Link] = doMySlowCalculation(value);
return value;
paridabapun
private int value;
[Link]().lock();
try {
[Link] = value;
[Link] = doMySlowCalculation(value);
} finally {
[Link]().unlock();
[Link]().lock();
try {
return calculatedValue;
} finally {
[Link]().unlock();
}
}
[Link]().lock();
try {
return value;
} finally {
[Link]().unlock();
paridabapun
}
int size = 4;
[Link]();
[Link]();
[Link] = size;
try {
produce(i);
paridabapun
[Link]([Link]()).log([Link], null, ex);
synchronized (sharedQueue) {
[Link]();
synchronized (sharedQueue) {
[Link](i);
[Link]();
}
paridabapun
[Link] = sharedQueue;
[Link] = size;
while (true) {
try {
[Link](50);
while ([Link]()) {
synchronized (sharedQueue) {
synchronized (sharedQueue) {
[Link]();
paridabapun
}
2. BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store
null value in the queue.
4. BlockingQueue interface is part of java collections framework and it’s primarily used for
implementing producer consumer problem. We don’t need to worry about waiting for the
space to be available for producer or object to be available for consumer in BlockingQueue
as it’s handled by implementation classes of BlockingQueue.
● put(E e): This method is used to insert elements to the queue, if the queue is full it waits for
the space to be available.
● E take(): This method retrieves and remove the element from the head of the queue, if
queue is empty it waits for the element to be available.
public class Message {
[Link]=str;
return msg;
paridabapun
public class Producer implements Runnable {
[Link]=q;
//produce messages
try {
[Link](i);
[Link](msg);
[Link]("Produced "+[Link]());
} catch (InterruptedException e) {
[Link]();
try {
[Link](msg);
} catch (InterruptedException e) {
[Link]();
paridabapun
public Consumer(BlockingQueue<Message> q){
[Link]=q;
try{
Message msg;
[Link](10);
[Link]("Consumed "+[Link]());
}catch(InterruptedException e) {
[Link]();
new Thread(producer).start();
new Thread(consumer).start();
11
Ans paridabapun
Write a program which result deadlock? How to fix deadlock in java?
while(true){
synchronized(str1){
synchronized(str2){
[Link](str1 + str2);
}}
};
while(true){
synchronized(str2){
synchronized(str1){
[Link](str2 + str1);
}}
};
[Link]();
[Link]();
paridabapun
}
1. first you can look at code if it is nested synchronized block or calling one synchronized
method from other or trying to get lock on different object then there is good chance of
deadlock if developer is not very careful.
2. Another way is to find it when you actually get locked while running the application , try to
take thread dump , in Linux you can do this by command "kill -3" , this will print status of all
the thread in application log file and you can see which thread is locked on which object.
3. other way is to use jconsole , jconsole will show you exactly which threads are get locked
and on which object.
synchronized([Link]){
synchronized ([Link]) {
synchronized ([Link]) {
paridabapun
● if you have looked above code carefully you may have figured out that real reason for
deadlock is not multiple threads but the way they access lock , if you provide an
ordered access then problem will be resolved
Solved Example
synchronized([Link]){
synchronized ([Link]) {
synchronized([Link]){
synchronized ([Link]) {
}
}}
Ans 1)Think about IllegalMonitorStateException which wait() and notify() methods throw when they get
called from non-synchronized context so I said I would call [Link]() and if this call throws
exception it means thread in java is not holding lock, otherwise thread holds lock.
2)Thread has a static method called holdsLock(Object obj) which returns true or false based on
whether threads holds lock on object passed.
paridabapun
13 What is atomic operation? What are atomic operations in Java?
Ans ● Atomic operations are performed in a single unit of task without interference from other
operations. Atomic operations are necessity in multi-threaded environment to avoid data
inconsistency.
● To make some operation atomic we have to make it synchronized. Here is another example
which makes operation synchronized.
Example:
[Link]();
[Link]();
[Link]();
[Link]();
processSomething(i);
count++;
return [Link];
paridabapun
private void processSomething(int i) {
try {
[Link](i * 1000);
} catch (InterruptedException e) {
[Link]();
Note: If you will run above program, you will notice that count value varies between 5,6,7,8.
The reason is because count++ is not an atomic operation. So by the time one threads read
it’s value and increment it by one, other thread has read the older value leading to wrong
result.
import [Link];
[Link]();
[Link]();
[Link]();
paridabapun
for (int i = 1; i < 5; i++) {
processSomething(i);
[Link]();
return [Link]();
try {
[Link](i * 1000);
} catch (InterruptedException e) {
[Link]();
Note: Benefits of using Atomic Concurrency classes is that we don’t need to worry about
synchronization
14 What is race condition? How will you find and solve race condition?
Ans ● The situation where two threads compete for the same resource, where the sequence in
which the resource is accessed is significant, is called race conditions. A code section that
leads to race conditions is called a critical section.
15 How will you take thread dump in Java? How will you analyze Thread dump?
Ans ● A thread dump can only show the thread status at the time of measurement, so in order to
see the change in thread status, it is recommended to extract them from 5 to 10 times with
5-second intervals.
paridabapun
● In UNIX you can use kill -3 and then thread dump will print on log on windows you can use
"CTRL+Break".
● In JDK 1.6 and higher, it is possible to get a thread dump on MS Windows using jstack.
● In LINUX: Obtain the process pid by using ps -ef command to check the pid of the currently
running Java process. Use the extracted pid as the parameter of kill –SIGQUIT(3) to obtain a
thread dump.
1. daemon threads;
2. non-daemon threads.
● Daemon Threads are service providing thread. Java application creates several threads by
default. Most of them are daemon threads, mainly for processing tasks such as garbage
collection or JMX.
● A thread running the 'static void main(String[] args)’ method is created as a non-daemon
thread, and when this thread stops working, all other daemon threads will stop as well. (The
thread running this main method is called the VM thread in HotSpot VM.)
17 Why we call start() method which in turns calls run() method, why not we directly call
run() method ?
Ans ● when you call start() method it creates new Thread and execute code declared in run() .
● while directly calling run() method doesn’t create any new thread and execute code on
same calling thread.
Ans ● if thread is blocked on IO then I don't think there is a way to interrupt/awake the thread.
● if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt
the thread and it will awake by throwing InterruptedException.
Ans ● Both CyclicBarrier and CountDownLatch are used to implement a scenario where one
paridabapun
Thread waits for one or more Thread to complete there job before starts processing
● you can not reuse same CountDownLatch instance once count reaches to zero and latch is
open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is
broken.
Ans ● Immutable classes are those class, whose object can not be modified once created, it
means any modification on immutable object will result in another immutable object.
● Access to data shared by multiple threads requires synchronization which is often a source
of fragile and hard to maintain code, hard to find bugs, and performance issues.
● Use of immutable data structures is to reduce and localize the need for synchronization.
21 What are some common problems you have faced in multi-threading environment? How
did you resolve it?
Ans ● Memory-interference, race conditions, deadlock, live lock and starvation are example of
some problems comes in multi-threading and concurrent programming.
Ans ● A thread often acts in response to the action of another thread. If the other thread's action
is also a response to the action of another thread, then livelock may result.
● As with deadlock, livelocked threads are unable to make further progress. However, the
threads are not blocked — they are simply too busy responding to each other to resume
work.
● This is comparable to two people attempting to pass each other in a corridor: Alphonse
moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass.
Seeing that they are still blocking each other, Alphone moves to his right, while Gaston
moves to his left. They're still blocking each other, so...
23 What is Stravation?
Ans ● Starvation describes a situation where a thread is unable to gain regular access to shared
resources and is unable to make progress.
● This happens when shared resources are made unavailable for long periods by "greedy"
threads. For example, suppose an object provides a synchronized method that often takes
a long time to return.
24
paridabapun
● If one thread invokes this method frequently, other threads that also need frequent
synchronized access to the same object will often be blocked.
Ans ● The ThreadLocal class in Java 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 a
ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.
● All threads will see the same ThreadLocal instance, but the values set on the
ThreadLocal via its set() method will only be visible to the thread who set the
value. Even if two different threads set different values on the same ThreadLocal
object, they cannot see each other's values.
try {
[Link](2000);
} catch (InterruptedException e) {}
[Link]([Link]());
paridabapun
Thread thread2 = new Thread(sharedRunnableInstance);
[Link]();
[Link]();
2. You can use java synchronized keyword only on synchronized method or synchronized block.
3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it
leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves
synchronized method after completion or due to any Error or Exception.
4. Java Thread acquires an object level lock when it enters into an instance synchronized java method
and acquires a class level lock when it enters into static synchronized java method.
5. Java synchronized keyword is re-entrant in nature it means if a java synchronized method calls
another synchronized method which requires same lock then current thread which is holding lock can
enter into that method without acquiring lock.
6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null
e.g. synchronized (myInstance) will throws [Link] if myInstance is null.
paridabapun
7. One Major disadvantage of Java synchronized keyword is that it doesn't allow concurrent read, which
can potentially limit scalability. By using concept of lock stripping and using different locks for reading
and writing, you can overcome this limitation of synchronized in Java. You will be glad to know that
[Link] provides ready made implementation of
ReadWriteLock in Java.
8. One more limitation of java synchronized keyword is that it can only be used to control access of
shared object within the same JVM. If you have more than one JVM and need to synchronized access to
a shared file system or database, the Java synchronized keyword is not at all sufficient. You need to
implement a kind of global lock for that.
9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and
can degrade performance. So use synchronization in java when it absolutely requires and consider
using java synchronized block for synchronizing critical section only
10. Java synchronized block is better than java synchronized method in Java because by using
synchronized block you can only lock critical section of code and avoid locking whole method which
can possibly degrade performance.
11. Its possible that both static synchronized and non static synchronized method can run simultaneously
or concurrently because they lock on different object.
12. From java 5 after change in Java memory model reads and writes are atomic for all variables declared
using volatile keyword (including long and double variables) and simple atomic variable access is
more efficient instead of accessing these variables via synchronized java code. But it requires more
care and attention from the programmer to avoid memory consistency errors.
13. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if
synchronization is not implemented correctly.
14. According to the Java language specification you can not use Java synchronized keyword with
constructor it’s illegal and result in compilation error. So you can not synchronized constructor
15. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with
method.
16. [Link] extends capability provided by java synchronized keyword for writing more
sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.
17. Do not synchronize on non final field on synchronized block in Java. because reference of non final
field may change any time and then different thread might synchronizing on different objects i.e. no
synchronization at all
18. Its not recommended to use String object as lock in java synchronized block because string is
immutable object and literal string and interned string gets stored in String pool.
19. From Java library Calendar and SimpleDateFormat classes are not thread-safe and requires external
synchronization in Java to be used in multi-threaded environment.
paridabapun
blocking acquirer.
Semaphore mutex = new Semaphore(1);
Semaphore available = new Semaphore(100); // represents number of permits
Example:
Monitor
● A monitor is an instance of a class that can be used safely by several threads. All the methods of
a monitor are executed with mutual exclusion. So at most one thread can execute a method of
the monitor at the same time.
● Monitors have an other feature, the possibility to make a thread waiting for a condition. During
the wait time, the thread temporarily gives up its exclusive access and must reacquire it after the
condition has been met. You can also signal one or more threads that a condition has been met.
● In Java there is no keyword to directly create a monitor. To implement a monitor, you must create
a new class and use Lock and Condition classes. Lock is the interface is ReentrantLock is the
main used implementation. To create a ReentrantLock, you have two constructors, a default
constructor and a constructor with a boolean argument indicating if the lock is fair or not. A fair
lock indicates that the threads will acquire the locks in the order they ask for. Fairness is a little
heavier than default locking strategies. To acquire the lock, you just have to use the
method lock and unlock to release it.
public class SimpleMonitor {
private final Lock lock = new ReentrantLock();
paridabapun
try {
//Some code
} finally {
[Link]();
}
}
public int testB() {
[Link]();
try {
return 1;
} finally {
[Link]();
}
}
}
return value;
return value--;
You can solve the problem using ● This class now works well. But locking is not a
synchronized at method level : lightweight mechanism and have several
disadvantages. When several threads try to
public class SynchronizedCounter {
acquire the same lock, one or more threads will be
paridabapun
private int value;
suspended and they will be resumed later. When
public synchronized int getValue(){ the critical section is little, the overhead is really
heavy especially when the lock is often acquired
return value;
and there is a lot of contention.
}
● Another disadvantage is that the other threads
public synchronized int waiting of the lock cannot do something else
getNextValue(){ during waiting and if the thread who has the lock is
return value++; delayed (due to a page fault or the end of the time
quanta by example), the others threads cannot
}
take their turn.
public synchronized int
getPreviousValue(){
return value--;
● Java 5.0 provides supports for additional atomic operations. This allows to develop algorithm
which are non-blocking algorithm, e.g. which do not require synchronization, but are based on
low-level atomic hardware primitives such as compare-and-swap (CAS). A compare-and-swap
operation check if the variable has a certain value and if it has this value it will perform this
operation.
● Non-blocking algorithm are usually much faster then blocking algorithms as the synchronization
of threads appears on a much finer level (hardware).
Before Java 5.0, this operation was not available directly to developer, but in Java 5.0 several atomic
variables (for int, long, boolean and reference values) were added. The int and long versions also
supports numeric operations. The JVM compiles these classes with the better operations provided by the
hardware machine, CAS or a Java implementation of the operation using a lock. Here are the classes :
● AtomicInteger
● AtomicLong
● AtomicBoolean
● AtomicReference
All these classes supports compare-and-set (via the compareAndSet() method) and other operations
(get(), set() and getAndSet()). The setters operations are implemented using compareAndSet. These
classes supports multi-threaded access and have a better scalability than synchronizing all the
operations.
paridabapun
public class AtomicCounter {
private final AtomicInteger value = new AtomicInteger(0);
public int getValue(){
return [Link]();
}
public int getNextValue(){
return [Link]();
}
public int getPreviousValue(){
return [Link]();
}
}
paridabapun
private final class StringTask implements Callable<String> {
public String call(){
//Long operations
return "Run";
}}
If you want to execute that task 10 times using 4 threads, you can use that code :
ExecutorService pool = [Link](4);
for(int i = 0; i < 10; i++){
[Link](new StringTask());
}
But you must shutdown the thread pool in order to terminate all the threads of the pool :
[Link](); / [Link]();
● Getting result from task that is submitted
● If you submit a Callable object to an Executor the framework returns an object of
type [Link]. ThisFuture object can be used to check the status of a Callable and
to retrieve the result from the Callable.
● On the Executor you can use the method submit to submit a Callable and to get a future. To
retrieve the result of the future use the get() method.
ExecutorService pool = [Link](4);
List<Future<String>> futures = new ArrayList<Future<String>>(10);
for(int i = 0; i < 10; i++){
[Link]([Link](new StringTask()));
}
for(Future<String> future : futures){
String result = [Link]();
paridabapun
}
for(int i = 0; i < 10; i++){
String result = [Link]().get();
//Compute the result
}
[Link]();
JavaConcurrency In Details
Volatile
o If a variable is declared with the volatile keyword then it is guaranteed that any thread that
reads the field will see the most recently written value. The volatile keyword will not perform
any mutual exclusive lock on the variable.
o As of Java 5 write access to a volatile variable will also update non-volatile variables which
were modified by the same thread. This can also be used to update values within a
reference variable, e.g. for a volatile variable person. In this case you must use a temporary
variable person and use the setter to initialize the variable and then assign the temporary
variable to the final variable. This will then make the address changes of this variable and
the values visible to other threads
Atomic operation
o An atomic operation is an operation which is performed as a single unit of work without the
possibility of interference from other operations.
o The Java language specification guarantees that reading or writing a variable is an atomic
operation(unless the variable is of typelong or double). Operations variables of
type long or double are only atomic if they declared with the volatile keyword. .
o Assume i is defined as int. The i++ (increment) operation it not an atomic operation in
Java. This also applies for the other numeric types, e.g. long. etc).
o The i++ operation first reads the value which is currently stored in i (atomic operations)
and then it adds one to it (atomic operation). But between the read and the write the value
of i might have changed.
o Since Java 1.5 the java language provides atomic variables, e.g. AtomicInteger or
AtomicLong which provide methods
likegetAndDecrement(), getAndIncrement() and getAndSet() which are atomic.
Immutability
The simplest way to avoid problems with concurrency is to share only immutable data between
threads. Immutable data is data which cannot changed.
paridabapun
An immutable class may have some mutable data which is uses to manages its state but from the
outside this class nor any attribute of this class can get changed.
Serialization in Java is important because it allows the conversion of an object into a byte stream, enabling the object to be easily saved to a file or transmitted over a network. Its primary use case is to persist the state of an object or to exchange objects between Java Virtual Machines (JVMs) over a network through sockets .
Java ensures thread safety for collection classes like Vector and Hashtable by synchronizing all public methods. This synchronization prevents concurrent modifications, ensuring thread safety when these collections are used in multi-threaded environments. However, this also leads to performance drawbacks, as synchronization can be costly, impacting scalability and efficiency, particularly in scenarios with high contention .
A subclass of a serializable superclass inherently becomes serializable due to inheritance. However, if one wishes to avoid serialization for a subclass, fields specific to the subclass can be marked as transient, which omits them from the serialization process. Additionally, custom serialization logic (using writeObject and readObject methods) can be implemented to skip processes, effectively bypassing serialization for specific fields. This method ensures the superclass's fields remain serializable while excluding the subclass's fields, which can help in controlling sensitive data exposure .
Static variables are not serialized in Java because they belong to the class, not individual instances. This means they are shared across all instances of the class. Serializing static variables would create redundant copies across serialized objects, leading to inefficiency. Additionally, static variables can be modified by any instance, rendering a serialized static variable potentially out-of-date with the current application context .
The Callable interface in Java allows threads to return a value upon completion. This is achieved by specifying a return type through Generics, which the Runnable interface does not support, as Runnable's run method returns void. When using Callable, the submitted task returns a Future object, enabling the calling thread to obtain results and handle potential exceptions, thus offering greater flexibility and functionality over Runnable .
The Externalizable interface differs from the Serializable interface in that it provides more control over the serialization process. Unlike Serializable, which uses default serialization, Externalizable requires the implementation of readExternal and writeExternal methods to explicitly manage serialization and deserialization. This enables customization of the process and can lead to potentially optimized serialization output formats and reduced serialized size, but requires more effort from developers .
Java's synchronized keyword enforces mutual exclusion on the accessing thread, ensuring that only one thread can execute a synchronized block or method at a time on a given object or class. A thread acquires a lock upon entering synchronized code and releases it upon exiting. This prevents race conditions and ensures data integrity but introduces performance overhead due to the blocking nature of lock acquisition, limiting concurrency. It is essential to use synchronized only when necessary to optimize performance and resource management .
Yes, the serialization process can be customized in Java. This is achieved by defining special methods—writeObject and readObject—within the class that needs customized serialization behavior. These methods allow developers to control what gets serialized and deserialized, overriding the default behavior provided by the Serializable interface. This approach provides flexibility to manipulate the serialization process beyond the automatic operations performed by the JVM .
In serializable inheritance, if a superclass is marked as Serializable, all its subclasses automatically become serializable. However, when a class implements Externalizable, inheritance does not automatically provide serialization capabilities to subclasses unless they explicitly implement the Externalizable interface. With Externalizable, all serialization responsibilities are on the implementing class, whereas Serializable defaults to Java's built-in behavior unless overridden by custom methods .
The serialVersionUID in Java acts as a version control mechanism for Serializable classes. It ensures that the serialization-deserialization process is compatible between different versions of a class. If the serialVersionUID does not match between the serialized object and the class, it results in an InvalidClassException. Defining a serialVersionUID prevents such compatibility issues when the class definition changes over time .