[Go to site: main page, start]

0% found this document useful (0 votes)
11 views86 pages

All Core Java Interview Question PDF

The document provides a comprehensive overview of Java concepts including the differences between JDK, JRE, and JVM, memory areas allocated by JVM, and the roles of static methods and variables. It explains object-oriented programming principles such as inheritance, encapsulation, and polymorphism, along with method overloading and overriding. Additionally, it covers abstract classes, interfaces, and the significance of packages in Java programming.

Uploaded by

Gopinath Sahu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views86 pages

All Core Java Interview Question PDF

The document provides a comprehensive overview of Java concepts including the differences between JDK, JRE, and JVM, memory areas allocated by JVM, and the roles of static methods and variables. It explains object-oriented programming principles such as inheritance, encapsulation, and polymorphism, along with method overloading and overriding. Additionally, it covers abstract classes, interfaces, and the significance of packages in Java programming.

Uploaded by

Gopinath Sahu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. What is difference between JDK ,JRE and JVM?

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

8. Is Empty .java file name is a valid source file name?


Yes, save your java file by .java only, compile it by javac .java and run by java your class
name
9. Is delete,next,main,exit or null keyword in java?
No.
[Link] I don't provide any arguments on the command line, then the String array of
Main method will be empty or null?
It is empty. But not null.
main(new String[0]); Like this JVM calling the main method by passing object of array of string
with 0 size.

12. What is the default value of the local variables?


The local variables are not initialized to any default value, neither primitives nor object
references.

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.

22. Why main method is static?


Because object is not required to call static method if It were non-static method, JVM creates
object first then call main () method that will lead to the problem of extra memory allocation.
23. What is static block?
Is used to initialize the static data member.
It is executed before main method at the time of class loading.
24. Can we execute a program without main() method?
Yes, one of the way is static block.
25. What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
26. What is difference between static (class) method and instance method?
static or class method instance method
1 .A method i.e. declared as static is known as static method. A method i.e. not declared as

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
(){...}.

27. What is this in java?


It is a keyword that that refers to the current object.
28 .What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behavior of
another object of another class. It represents IS-A relationship. It is used for Code Reusability
and Method Overriding.
30. Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java in case of class..
31. What is composition?
Holding the reference of the other class within some other class is known as composition.
32. What is difference between association, aggregation and composition?
Composition and Aggregation are the two forms of association.
Aggregation represents weak relationship whereas composition represents strong
relationship. For example: bike has an indicator (aggregation) but bike has an engine
(composition).
Composition is strong association and aggregation is weak association
33. Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because
they are unsafe(unsecured) and complex to understand.
34. What is super in java?
It is a keyword that refers to the immediate parent class object.
35. Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
36. What is object cloning?
The object cloning is used to create the exact copy of an object.
protected native Object clone() throws CloneNotSupportedException;
The object cloning is used to create the exact copy of an object.
Shallow cloning :
This is the default implementation in java .By default object class clone method is meant for
shallow cloning .It will create bitwise copy of an object .
If the main object contains any primitive variable exact duplicate copy will be created in
cloned object.
If the main object is contain any reference variable , then the corresponding object won’t be

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*

37. What is method overloading?


The syntax of defining multiple methods with the same name with in the same class by
changing the data type of the parameters and parameters is known as method overloading.
It increases the readability of the program
38. Why method overloading is not possible by changing the return type in java?
Because of ambiguity.
39. Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method
40. What is method overriding?
The concept of defining functionality in the sub class with the same name and same
signature of the super class methods is known as method overriding.
41. Can we override static method?
No, you can't override the static method because they are the part of class not object.
42. Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance
method is bound with object and static gets memory in class area and instance gets memory
in heap.
43. Can we override the overloaded method?
Yes.
44. Difference between method Overloading and Overriding.
Method Overloading Method Overriding
1. Method overloading increases the readability of the program. Method overriding provides
the specific implementation of the method that is already provided by its super class.
2. method overloading is occurs within the class. Method overriding occurs in two classes
that have IS-A relationship.
3. In this case, parameter must be different. In this case, parameter must be same.
45. Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.
46. What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the
return type of the subclass overriding method is subclass type. It is known as covariant return

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.

76. What are the rules of method overriding? (Core java)


Animal is the super class and Dog is the subclass, thus Dog inherits the move () method from
Animal.
The Dog’s move () method is called the overriding method.
The Animal’s move () method is called the overridden method.
1. Only inherited methods can be overridden.

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.

78. Method overloading rules:


1. First and important rule to overload a method in java is to change method signature.
Method signature is made of number of arguments, type of arguments and order of
arguments if they are of different types.
2. Return type of method is never part of method signature, so only changing the return type
of method does not amount to method overloading.
3. Thrown exceptions from methods are also not considered when overloading a method.
So your overloaded method throws the same exception, a different exception or it simply does
no throw any exception;.no effect at all on method loading.

79. Understanding all java access modifiers

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.

2. What is Exception Handling?

It is the mechanism of identifying an exception or a runtime error,catching that exception and


assinging that exception to the reference of corresponding exception class within the same
program
It is mainly used to handle checked exceptions.

3. What is difference between Checked Exception and Unchecked Exception?

* 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.

4. Is it necessary that each try block must be followed by a catch block?

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.

5. What is finally block?

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.

6. Can finally block be used without catch?

Yes, by try block. finally must be followed by either try or catch.

7. Is there any case when finally will not be 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).

8. What is throws Keyword and what is the use of throw keyword ?

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

9. What is difference between throw and throws?


throw keyword throws keyword
.Using throw we explicitly raise an exception based on the user define logical error condition
, thus throw performs an operation.
Using throws explicitly provide information about the unhandled exception of the function. It
does not perform any operation.
1. throw is used to explicitly throw an exception. throws is used to declare an exception.
2. checked exceptions cannot be propagated with throw only. checked exception can be
propagated with throws.
3. throw is followed by an instance. throws is followed by class.
4. throw is used within the method. throws is used with the method signature.
5. You cannot throw multiple exception You can declare multiple exception e.g. public
void method()throws IOException,SQLException.

10. Can an exception be rethrown?


[Link] can re throw an exception from catch block to another class where it can be handled.

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.

[Link] ever it is require to mention the class as final ?


When ever it is required to design a class in such a way that so that always object of the class
has to be created only as the sub most object then we mention the class as final.
[Link] is the need of define the constructor as private & providing a factory
method to provide this object.?
ex-

[Link] which case finally block will not executed ?


There is one solution where the finally block wont be executed if we are using [Link](0)
explicity
then JVM itself will be shutdown and there is no chance of executing the finally block
17. It is possible throw an Error ?
Yes it is possible to throw an error any Throwbale type include Error.
18. Is it Possible throw an object ?
No we can use throw keyword only throwble object otherwise we will get compile time error
Saying Unreachible Statement.
19. What is the difference between Exception and Error ?
Exception : These are caused by our program and are recoverable
Error:-these are not caused by our program mostly caused by lake of system [Link]
are non recoverable.
[Link] is Custom Exception ?
If we are creating our own Exception that is known as custom exception or user-defined
exception.
Java custom exceptions are used to customize the exception
By the help of custom exception,you can have your own exception and message according to
the (user)need.
We can create our own exceptions by extending 'Exception' class
public class InvalidAgeException extends Exception {
public String toString() {
return "InvalidAgeException : SUPPLY AGE CORRECTLY";}
[Link] is Assertion how can we implement ?
This is the machanism of suspending the execution of the function in the middle of the
execution based on user define condition
by explicitely rising the AssertionError object(representing the user define run time errors or
user define logical errors) is known as Assertion.
We can implement the concept of assertion using assert keyword.
The functionality of assert keyword is to explicitly rise an AssertionError object when the

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)

STRING Interview Questions :

1 What are Immutable objects in Java?

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.

2 How to create a Immutable Class in Java?

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 public final class Contacts


{ private final String
name; private final String
mobile;
public Contacts(String name,
String mobile) {
[Link] = name;
[Link] = mobile;
}
public String getName(){ return name; }

public String getMobile(){ return mobile; }


}
4 What are benefits of immutable classes 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?

Ans  String is a sequence of characters


 String is immutable class in java

6 Why String is immutable or final 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]

Ans  String Pool is possible because String is immutable in java.


 It increases security because any hacker can‟t change its value and it’s used for
storing
sensitive information such as database username, password etc.
 Since String is immutable, it’s safe to use in multi-threading and we don’t need any
synchronization.
 Strings are used in java class loader and immutability provides security that
correct class is getting loaded by Class loader.
10 What is String Pool?

Ans  String Pool is a pool of Strings stored in Java heap memory.

 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.

13 Why String is popular HashMap key in Java?


Ans  String is immutable, its hashcode is cached at the time of creation and it doesn‟t need
to be calculated again. This makes it a great candidate for key in a Map and its
processing is fast than other HashMap key objects. This is why String is mostly used
Object as
HashMap keys.
14 How do you check if two Strings are equal in Java?
Ans  There are two ways to check if two Strings are equal or not. using “==” operator or using

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.

17 Write a program to print all permutations of String? [AAB” permutations will be


“AAB”, “ABA” and “BAA”]
Ans public class StringHelper {
public static Set<String> permutationFinder(String str)
{ Set<String> perm = new HashSet<String>();
//Handling error scenarios
if (str == null) {
return null;
} else if ([Link]() == 0) {
[Link]("");
return perm;
}

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;
}

public static String charInsert(String str, char c, int j)


{ String begin = [Link](0, j);
String end = [Link](j);
return begin + c + end;
}
public static void main(String[] args)
{ String s = "AAC";
String s1 = "ABC";
String s2 = "ABCD";
[Link]("\nPermutations for " + s + " are: \n" + permutationFinder(s));
[Link]("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
[Link]("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
}
}

18 Can we use String in switch case?


Ans Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn‟t
support this.

19 How to convert String to byte array and vice versa?


Ans  We can use String getBytes() method to convert String to byte array
 we can use String constructor new String(byte[] arr) to convert byte array to String.
String str = "Bhagabata Parida";
//convert String to byte array
byte[] byteArr = [Link]();
[Link]("String to byte array : "+[Link](byteArr));
//convert byte array to String
String str1 = new String(byteArr);
[Link]("byte array to String : "+str1);

20 How to convert String to char array and vice versa?


Ans String str = "123";
char[] chArr = [Link]();
[Link]("String to char array: "+[Link](chArr));
//String to char char
c = [Link](1);
[Link]("String to char: "+c);
//char to String

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);

21 How to compare two Strings in java program?


Ans  compareTo(String anotherString) and compareToIgnoreCase(String str) can be used
to compare two strings.
 If String object less than the argument passed, it returns negative integer and if String
object greater than the argument String passed, it returns positive integer. It returns
zero when both the String have same value.

22 What is String subSequence method?


Ans

23 How can we make String upper case or lower case?


Ans String class toUpperCase() and toLowerCase() methods to get the String in all upper case
or lower case.

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), "")

25 Write a method to check if input String is


Palindrome?
Ans  String class doesn‟t provide any method to reverse the String but StringBuffer and
StringBuilder class has reverse method that we can use to check if String is
palindrome or not.
private static boolean isPalindrome(String str) {
if (str == null)
return
false;
StringBuilder strBuilder = new StringBuilder(str);
[Link]();
return [Link]().equals(str);
}
private static boolean isPalindromeString(String str) {
if (str == null)
return
false; int length =
[Link]();
[Link](length /
2);

paridabapun
for (int i = 0; i < length / 2; i++) {

if ([Link](i) != [Link](length - i - 1))


return false;
}
return true;
}

26 What are different ways to create String Object?


Ans  We can create String object using new operator like any normal java class or we can
use double quotes to create a String object.
o String str = new String("abc");
o String str1 = "abc";
 When we create a String using double quotes, JVM looks in the String pool to find if
any
other String is stored with same value. If found, it just returns the reference to
that
String object else it creates a new String object with given value and stores it in
the String Pool
 When we use new operator, JVM creates the String object but don’t store it into the String
Pool.

27 How to Convert String to Integer to String in Java?


Ans String to int
 int i = [Link]("123");
[Link]() method will throw NumberFormatException if String provided is not
a proper number.
 int i = [Link]("000000081")
This method also throws NumberFormatException if string provided does not
represent actual number.
Int to String
 String price = "" + 123; It converts integer to String
 String price = [Link](123);
 new StringBuilder().append( "" ).append( 10 ).toString();
 String price = [Link] ("%d", 123);
28 How substring() method works in Java - Memory Leak Fixed in JDK 1.7?
How substring() method of String class creates memory leak?
Ans  Substring method is overloaded in String class,and it has two variants

public String substring(int beginIndex)


public String substring(int beginIndex, int endIndex)

 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];

public class SubStringTest {


public static void main(String[] args) throws Exception
{
//Our main String
String mainString = "i_love_java";
//Substring holds value 'java'
String subString = [Link](7);

[Link](mainString)
;
[Link](subString);

//Lets see what's inside mainString


Field innerCharArray = [Link]("value");
[Link](true);
char[] chars = (char[]) [Link](mainString);
[Link]([Link](chars));

//Now peek inside subString


chars = (char[])
[Link](subString);
[Link]([Link](chars));
}
}
Output i_love_java java
[i, _, l, o, v, e, _, j, a, v, a]
[i, _, l, o, v, e, _, j, a, v, a] Solve
Above Memory leak issue
public class SubStringTest{
public static void main(String[] args) throws Exception {
//Our main String
String mainString = "i_love_java";
//Substring holds value 'java'
String subString = new String([Link](7));
[Link](mainString);
[Link](subString);

//Lets see what's inside mainString


Field innerCharArray = [Link]("value");
[Link](true);
char[] chars = (char[]) [Link](mainString);
[Link]([Link](chars));

//Now peek inside subString


chars = (char[]) [Link](subString);
[Link]([Link](chars));
}
}
29 String to Date Object in java?

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

30 Reverse a String using recursion in java


Ans public static String reverse(String str){
if ([Link]()==0 || [Link]()==1)
return str;
else
return reverse([Link](1))+[Link](0);
}

Serialization Interview Questions

31 What is Serialization in java?


Ans  Storing/writing state of an object into any byte/binary stream is called as Serialization.
 Reading state of an object from byte stream is called De-Serialization.
 Due to Serialization Java objects can be persisted into disk or sent over network to any
other running Java virtual machine.
 When there are two different parties involved, you need a protocol to rebuild the exact
same object again. Java serialization API just provides you that.
 Serialization is used to perform a deep copy.

32 Why Serialization is required? What is the need to Serialize?


Ans  It is required to send the state of an object over a network by means of a socket.
 Using serialization one can also store an object‟s state in a file.
 The core of Java Serialization is the Serializable interface. When Serializable interface is
implemented by any class it provides an indication to the compiler that java Serialization
mechanism needs to be used to serialize the object.

33 What is the process to serialize any object?


Ans  To serialize any object that class must implement Serializable interface.
 Then create ObjectOutputStream object by passing any OutputStream object as argument
to its constructor.
 Then use its writeObject() method to write the object to byte stream.
 Similarly to de-serialize create object of ObjectInputStream by passing any InputStream
as argument to its constructor.
 Then use readObject() method to read the state of the object from byte stream.
class Student implements Serializable {
int sid;
String sname;
public Student(int sid,String sname) {
[Link]=sid;

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);
}
}

34 What is Externizable interface ? Describe with a Example.


Ans  When a class implements Serializable interface, JVM applies the default serialization rules
for the object. That means by implementing the „Serializable‟ interface, you get
automatic serialization capability for the objects of that class.
 JVM uses reflection mechanism to marshal and unmarshal the class objects.
 Externalizable‟ extends the „Serializable‟ interface denoting that the class implementing
it supports serialization. But as „Serializable‟, „Externalizable‟ is not a marker interface
and it
provides 2 methods which needs to be implemented in the class.
 readExternal(ObjectInput in): This method will be invoked in the deserialization
process to restore back the object state.
 writeExternal(ObjectOutput out): This method will be invoked in the serialization
process to save the object state.
 Using Externizable we can customize the process of Serialization operation.
 Externalizable interface is implemented by a class which needs complete control over the
serialization process and format and contents of the stream for the class objects and its
supertypes as well, whereas the class implements „Serializable‟ when the default
serialization process serves the purpose.
 At the time of deserialization process. JVM restores the Serializable objects, by calling
read methods on „ObjectInputStream‟, whereas for the Externalizable objects, first the
object is created by calling public no-arguments constructor and then the readExternal
method is called on the newly created object which takes care of deserialization (object
restoration). So public no-arguments constructor has to be present on the class
implementing „Externalizable‟ interface during deserialization process.

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.

36 Difference between Serializable and Externizable in java?


Ans  Externalizable is an interface that enables you to define custom rules and your own
mechanism for serialization. Serializable defines standard protocol and provides out of the
box serialization capabilities.
 Externalizable extends Serializable.
 To use Externizable implement writeExternal and readExternal methods of the
Externalizable interface and create your own contract/protocol for serialization.
 Saving the state of the supertypes is responsibility of the implementing class.
 In case of Externalizable object must have a public no-argument constructor. But in
Seriablizable it is not mandatory.
 Behaviour of writeReplace and readResolve methods are same for both Serializable and
Externalizable objects. writeReplace allows to nominate a replacement object to be

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);
}
}

38 What are the ways to speed up Object Serialization? How to improve


Serialization performance?
Ans  The serialization process performance heavily depends on the number and size of
attributes you are going to serialize for an object. Below are some tips you can use for
speeding up the marshaling and un-marshaling of objects during Java serialization
process.
a) Mark the unwanted or non Serializable attributes as transient.
b) Save only the state of the object, not the derived attributes.
c) Serialize attributes only with NON-default values. For examples, serializing a int
variable with value zero is just going to take extra space however, choosing not to
serialize it would save you a lot of performance.
d) Use Externalizable interface and implement the readExternal and writeExternal
methods to dynamically identify the attributes to be serialized.

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.

40 What are the alternatives to Serialization? If Serialization is not used, is it possible


to persist or transfer an object using any other approach?
Ans  ORM tools (e.g. hibernate) to save the objects in a database and read them from the
database.
 Xml based data transfer is another popular mechanism
 JSON Data Transfer - is recently popular data transfer format.

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.

43 How to Serialize a collection in java? How to serialize a ArrayList, Hashmap or Hashset


object in Java?
Ans  All standard implementations of collections List, Set and Map interface already implement
[Link].
 This means you do not really need to write anything specific to serialize collection
[Link] ever Make sure all the objects added in collection are Serializable.

paridabapun
 Serializing the collection can be costly therefore make sure you serialize only required
data instead of serializing the whole collection.

44 Is it possible to customize the serialization process? How can we customize the


Serialization process?
Ans  Yes, the serialization process can be customized. When an object is serialized,
[Link] (to save this object) is invoked and when an object is
read, [Link] () is invoked.
 Most people do not know is that Java Virtual Machine provides you with an option to
define these methods as per your needs. Once this is done, these two methods will be
invoked by the JVM instead of the application of the default serialization process. Classes
that require special handling during the serialization and deserialization process must
implement special methods with these exact signatures:
a) private void writeObject([Link] out) throws IOException
b) private void readObject([Link] in) throws IOException,
ClassNotFoundException;
c) private void readObjectNoData() throws ObjectStreamException;
class Student implements Serializable{
int sid;
String sname;
public Student(){ }
public Student(int sid,String sname)
{ [Link]=sid;
[Link]=sname;
}
public String toString() {
return "Sid=" + sid + "Sname=" + sname;
}
private void writeObject(ObjectOutputStream oos) throws IOException
{ [Link]("Write The Object to Stream");
}
private void readObjectNoData() throws
ObjectStreamException{ [Link]("No Data
Exist");
}
private void readObject([Link] in) throws IOException,
ClassNotFoundException{
[Link]("Reading the Object State");
}
}
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);

paridabapun
// deserializing the Object
InputStream is=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(is);
Student s2=(Student)[Link]();
[Link](s2);
}
}

45 How can a sub-class of Serializable super class avoid serialization? If serializable


interface is implemented by the super class of a class, how can the serialization of
the class be avoided?
Ans  if the super class of a class is implementing Serializable interface, it means that it is
already serializable. Since, an interface cannot be unimplemented, it is not possible to
make a class non-serializable. However, the serialization of a new class can be avoided.

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.

5+ years Java Interview Collection

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.

public class Singleton{

private static volatile Singleton instance; //volatile variable

public static Singleton getInstance(){

if(instance == null){

synchronized([Link]){

if(instance == null)

instance = new Singleton();

}
return instance;

If you look at the code carefully you will be able to figure out:

1) We are only creating instance one time

2) We are creating instance lazily at the time of first request comes.

2 When to use volatile keyword in java?

● 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.

3 Difference between synchronized and volatile keyword 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.

● Synchronized method affects performance more than 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

4 Difference between Comparable and Comparator

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.

3. [Link]() method takes both objects explicitly where as [Link]()


takes one object implicitly and second argument explicitly.

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].*;

class Student implements Comparable<Student> {

int sid;

String sname;

public Student(int x,String y) {

sid=x;sname=y;

public int compareTo(Student s1) {

if (sid > [Link])


return 1;

else if (sid == [Link])

return 0;

else

return -1;

public String toString() {

return sid + "-" + sname;

paridabapun
}

public class Example1 {

public static void main(String[] args) {

Student e1=new Student(1,"K");

Student e2=new Student(10,"A");

Student e3=new Student(5,"Z");

Student e4=new Student(2,"X");

List<Student> stdList=new ArrayList<Student>();

[Link](e1);[Link](e2);[Link](e3);[Link](e4);

[Link](stdList);

[Link]("Natural Sort="+stdList);

Set<Student> slist=new TreeSet<Student>();

[Link](e1);[Link](e2);[Link](e3);[Link](e4);

[Link]("Natural Sort Using TreeSet="+slist);

// Using Comparator Utility

[Link](stdList,new IdComparator());

[Link]("Id Comparator="+stdList);

[Link](stdList,new NameComparator());

[Link]("Name Comparator="+stdList);

}
}

class IdComparator implements Comparator<Student>{

public int compare(Student o1, Student o2) {

if ([Link] > [Link])

return 1;

else if ([Link] == [Link])

return 0;

else

return -1;

paridabapun
}

class NameComparator implements Comparator<Student>{

public int compare(Student o1, Student o2) {

return [Link]([Link]);

Natural Sort=[1-K, 2-X, 5-Z, 10-A]

Natural Sort Using TreeSet=[1-K, 2-X, 5-Z, 10-A]

Id Comparator=[1-K, 2-X, 5-Z, 10-A]

Name Comparator=[10-A, 1-K, 2-X, 5-Z]

5 What is Difference between ArrayList and Vector?

● Vector is synchronized and thread-safe while ArrayList is neither Synchronized nor thread-safe.

● Performance - Since vector is thread-safe , the performance is slower than ArrayList.

● 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.

● ArrayList by default increases (*3/2+1) but vector increases double.

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.

4) ArrayList and Vector also allows null and duplicates.

paridabapun
6 Describe the Class hierarchy of Collection API?

7 Explain various class hierarchies in Map?


8

paridabapun
How HashMap works? How get/put method of HashMap works in Java?

1) It works on the principle of Hashing

2) Criteria For Hashing: A true hashing must follow :-

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.

3) HashMap is a array of Entry objects which maps key to value.

How Put() method works

1) If key object is null it stored in table[0] position as hashCode of null is zero.

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.

4) Now indexFor(hash,[Link]) of HashMap is called which returns actual position where


the element will stored.

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%.

10 Do you see any problem with resize of HashMap in java?

● 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.

12 Can you use Custom object as key in 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;

private String ename;

public int getEid() {return eid; }

public String getEname() { return ename;}

Employee(int eid,String ename) {

[Link]=eid;

[Link]=ename;

public String toString() {

return eid+"=="+ename;

public int hashCode() { return eid; }

public boolean equals(Object obj) {

Employee e1=(Employee)obj;

if([Link]([Link]))

return true;

return false;

}
public class hashmap11 {

public static void main(String[] args) {

HashMap<Employee,Integer> hm=new HashMap<Employee, Integer>();

[Link](new Employee(100,"Bhagabata"),5000);

[Link](new Employee(50, "Shasanka"),2000);

[Link](new Employee(510, "Raj"),3000);

[Link](new Employee(230, "Tatullya"),4000);

[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.

class Employee implements Comparable<Employee>{

private int eid;

private String ename;

public int getEid() { return eid; }

public String getEname() { return ename; }

Employee(int eid,String ename) {

[Link]=eid;

[Link]=ename;

public String toString() { return eid+"=="+ename; }

public int hashCode() { return eid; }

public boolean equals(Object obj) {

Employee e1=(Employee)obj;

if([Link]([Link])){ return true;}

else return false;

public int compareTo(Employee o1) {


if(eid>[Link]) return 1;

else if(eid<[Link]) return -1;

else return 0;

public class hashmap11 {

public static void main(String[] args) {

HashMap<Employee,Integer> hm=new HashMap<Employee, Integer>();

[Link](new Employee(100,"x"),5000);

paridabapun
[Link](new Employee(50, "y"),2000);

[Link](new Employee(510, "p"),3000);

[Link](new Employee(230, "d"),7000);

[Link](new Employee(230, "b"),2000);

[Link](new Employee(230, "a"),4000);

[Link](hm);

// Using another Map which will containg sorted entries. and Comparable

List<Employee> entryist=new ArrayList<Employee>([Link]());

[Link](entryist);

Map<Employee,Integer> sortedMap=new LinkedHashMap<Employee, Integer>();

for(Employee e1: entryist){

[Link](e1, [Link](e1));

[Link](sortedMap);

// Sorting using Comparator

List<[Link]<Employee, Integer>> customList=

new ArrayList<[Link]<Employee,Integer>>([Link]());
[Link](customList,new Comparator<[Link]<Employee, Integer>>(){

public int compare(Entry<Employee, Integer> o1,Entry<Employee, Integer> o2) {

Employee e1=[Link]();

Employee e2=[Link]();

if([Link]()>[Link]())return -1;

else if([Link]()==[Link]()) return 0;

else return 1;

});

paridabapun
[Link](customList);

13 Can you use ConcurentHashMap over Hashtable?

● 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.

● Hashtable provides stronger thread-safety than ConcurentHashMap but in certain cases it


degrades performance. So ConcurentHashMap can be used in place of Hashtable.

● Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full
map while doing iteration.

● ConcurrentHashMap is divided into number of segments [default 16] on initialization.


ConcurrentHashMap allows similar number (16) of threads to access these segments
concurrently so that each thread work on a specific segment during high concurrency.

● ConcurrentHashMap uses a multitude of locks, each lock controls one segment of


the map. When setting data in a particular segment, the lock for that segment is obtained.
So essentially update operations are synchronized.

● 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 )

● The synchronized collections classes like Hashtable,Vector, synchronized wrapper classes,


[Link]() and [Link](), provide a basic
conditionally thread-safe implementation of Map and List which provides single collection
wide lock. So it affects performance.

● ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher


concurrency while preserving thread safety.

● ConcurrentHashMap introduced concept of segmentation, it only locks part of the Map to


provide thread safety so many other readers can still access map without waiting for

paridabapun
iteration to complete.

● ConcurrentHashMap do not allow null keys or null values while synchronized HashMap allows
one null keys.

● ConcurrentHashMap is consist of internal segments which can be viewed as independent


HashMaps, conceptually. All such segments can be locked by separate threads in high
concurrent executions. In this way, multiple threads can get/put key-value pairs from
ConcurrentHashMap without blocking/waiting for each other.

● In [Link](), we get a synchronized version of HashMap and it is


accessed in blocking manner. This means if multiple threads try to access synchronizedMap
at same time, they will be allowed to get/put key-value pairs one at a time in synchronized
manner.

15 Difference between HashMap and Hashtable?

1) The HashMap class is roughly equivalent to Hashtable, except Hashtable is synchronized

2) HashMap allows null key and null value where as Hashtable doesn’t allows null key and null
value.

3) Hashtable is synchronized so Hashtable is thread-safe and can be shared between multiple


threads. but HashMap cannot be shared between multiple threads without proper
synchronization

4) Iterator in the HashMap is a fail-fast iterator and throw ConcurrentModificationException if


any other Thread modifies the map structurally by adding or removing any element except
Iterator's own remove() method. But the enumerator for the Hashtable is not ie it is fail-safe
iterator.
5) Hashtable is much slower than HashMap if used in Single threaded environment.

HashMap can be synchronized by using [Link](hashMap)

16 When do you use ConcurentHashMap in Java?

● 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.

17 What is Concurrent Modification ?

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 .

2. Fail fast iterators happen in two situations

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.

b. Multiple Threaded Environment: If one thread is modifying the structure of the


collection while other thread is iterating over it .

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.

5. Two issues associated with Fail Safe Iterator are:

a. Overhead of maintaining the copied data structure i.e memory.

b. Fail safe iterator does not guarantee that the data being read is the data currently in
the original data structure.

6. Example of Fail Safe iterator: Iterator of CopyOnWriteArrayList, iterator on


ConcurrentHashMap keySet
19 What is difference between Iterator and Enumeration?

1. Enumeration is a legacy class and not all Collection supports it. Like Vector Supports
Enumeration but ArrayList doesnot.

2. Iterator has a remove() method while Enumeration doesn't.

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.

21 What is difference between iterator access and index access?

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.

5. Traversal or search in index based datastructure is faster.

6. ArrayList is index access and LinkedList is iterator access.

22 How to make a List (ArrayList,Vector,LinkedList) read only?

● A list implemenation can be made read only using [Link](list).

● This method returns a new list. If a user tries to perform add operation on the new list;
UnSupportedOperationException is thrown.

● For any Collections we can use [Link](Collection c)

23 How to sort list of strings - case insensitive?

using [Link](list, String.CASE_INSENSITIVE_ORDER);

24 Can a null element be added to a Treeset or HashSet?

● 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.

● HashSet is based on hashMap and can contain null element.

25 How to sort list in reverse order?

● 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.

List list = new ArrayList();

Comparator comp = [Link]();

paridabapun
[Link](list, comp)

26 Which data structure HashSet implements?

● HashSet implements hashmap internally to store the data. The data passed to hashset is
stored as key in hashmap with null as value.

27 Arrange in the order of speed - HashMap,HashTable,


[Link],concurrentHashmap

HashMap is fastest, ConcurrentHashMap, [Link], HashTable.

28 What is difference between List and Set?

1. List can contain duplicate values but Set doesn't allow.

2. List allows retrieval of data to be in same order in the way it is inserted but Set doesn’t

29 How can Arraylist be synchronized without using Vector?

[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?

● A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will


automatically be removed when its key is no longer in ordinary use.

● 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.

32 How HashSet works internally?

● 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 :

private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map

private static final Object PRESENT = new Object();

public boolean add(E e) {

return [Link](e, PRESENT)==null;

● 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.

public Iterator<E> iterator() {

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

● [Link](list,Comparator) will sort objects based on compare() method of


Comparator.

34 How do you find middle element of a linked list in single pass?

● 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{

private Node head;

private Node tail;

public LinkedList(){

[Link] = new Node("head");

tail = head;

}
public Node head(){ return head; }

public void add(Node node){

[Link] = node;

tail = node;

public static class Node{

paridabapun
private Node next;

private String data;

public Node(String data){ [Link] = data; }

public String data() { return data; }

public void setData(String data) { [Link] = data; }

public Node next() { return next; }

public void setNext(Node next) { [Link] = next; }

public String toString(){ return [Link]; }

public class LinkedListTest {

public static void main(String args[]) {


LinkedList linkedList = new LinkedList();

[Link] head = [Link]();

[Link]( new [Link]("1"));

[Link]( new [Link]("2"));

[Link]( new [Link]("3"));

[Link]( new [Link]("4"));

//finding middle element of LinkedList in single pass

[Link] current = head;

paridabapun
int length = 0;

[Link] middle = head;

while([Link]() != null){

length++;

if(length%2 ==0){

middle = [Link]();

current = [Link]();

if(length%2 == 1){

middle = [Link]();

[Link]("length of LinkedList: " + length);

[Link]("middle element of LinkedList : " + middle);

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.

public boolean isCyclic(){

Node fast = head;

Node slow = head;

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;

36 How to check duplicate elements in Array in Java?

● 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?

List<String> list1=new ArrayList<String>();

[Link]("x");[Link]("m");[Link]("k");[Link]("k");

[Link]("z");[Link]("z");[Link]("c");[Link]("c");

//Now make a Remove all duplicate elements

Set<String> mySet=new HashSet<String>(list1);

for(String x: mySet){

[Link]("Frequency Of "+x+":"+[Link](list1, x));

paridabapun
}

38 How to find out frequency of each character in a String?

String s="java is a programming language which is very power";

List<String> myList1 = new ArrayList<String>([Link]([Link]("")));

//Or

List<String> myList2 = new ArrayList<String>();

for(int i = 0; i<[Link]();i++){

[Link]([Link](i)+"");

//Now Remove Duplicate Elements from List

Set<String> mySet1=new HashSet<String>(myList1);

Set<String> mySet2=new HashSet<String>(myList2);

// Now finding frequence of each Character

for(String x: mySet1){

[Link]("Frequency Of "+x+":"+[Link](myList1, x));

for(String x: mySet2){

[Link]("Frequency Of "+x+":"+[Link](myList2, x));

}
39 Sort a Array in Ascending and descending order?

String[] companies = { "Google", "Apple", "Sony",’Sears’,’Capgemini’ };

Ascending Order:- [Link](companies);

Descending Order:- [Link](companies, [Link]());

Sorting Part Of Array: [Link](companies, 0, 3);

40 Find frequency of each element in List using Hashing implementation?

List<String> list1=new ArrayList<String>();

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

Map<String,Integer> map=new HashMap<String, Integer>();

for(String elm:list1){

if([Link](elm))

[Link](elm, [Link](elm)+1);

else

[Link](elm, 1);

for([Link]<String, Integer> x: [Link]()){

[Link]("Frequency Of "+[Link]()+":"+[Link]());

41 What will happen if two different objects have same hashcode?

Solve by yourself[refer use of hashCode and equals method]

42 How will you retrieve Value object if two Keys will have same hashcode?

Solve by yourself[refer use of hashCode and equals method]

43 What is different between Iterator and ListIterator?


● We can use Iterator to traverse Set and List collections whereas ListIterator can be used with
Lists only.

● 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.

44 What are different Collection views provided by Map interface?

● Set keySet()

● Collection values()

paridabapun
● Set<[Link]<K, V>> entrySet()

45 What is a TreeMap?

● A Red-Black tree based NavigableMap implementation.

● 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?

● A NavigableSet implementation based on a TreeMap.

● 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).

47 Which collection classes provide random access of it’s elements?

● 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.

● EnumSet is not synchronized and null elements are not allowed.

● It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and
complementOf(EnumSet s).

49 How to work with Properties file?

● Java properties file is used to store project configuration data or settings.

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.

● Properties inherits from Hashtable

Properties prop = new Properties();

OutputStream output = new FileOutputStream("[Link]");

// set the properties value

[Link]("database", "localhost");

[Link]("dbuser", "mkyong");

[Link]("dbpassword", "password");

[Link](output, null);

// retriving Data

Properties prop1 = new Properties();

InputStream fis=new FileInputStream("[Link]");

[Link](fis);

[Link]([Link]("database"));

50 Which collection classes are thread-safe?

Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can
be used in multi-threaded environment.

51 What are concurrent Collection Classes?


CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

52 What is Queue and Stack specify their differences?

● [Link] is an interface whose implementation classes are present in java concurrent


package. Queue allows retrieval of element in First-In-First-Out (FIFO) order but it’s not
always the case. There is also Deque interface that allows elements to be retrieved from
both end of the queue.

● Stack is similar to queue except that it allows elements to be retrieved in Last-In-First-Out


(LIFO) order.

● Stack is a class that extends Vector whereas Queue is an interface.

53

paridabapun
What is a Collections interface?

● [Link] is a utility class consists exclusively of static methods

● This class contains methods for collection framework algorithms, such as binary search,
sorting, shuffling, reverse, frequency etc.

54 How to traverse or loop over Map in java?

Map<Integer, String> map=new HashMap<Integer, String>();

[Link](1, "x");[Link](2, "y");[Link](3, "p");[Link](5, "z");

for(Integer k1: [Link]()){

[Link](k1+":"+[Link](k1));

for([Link]<Integer, String> en : [Link]()){

[Link]([Link]()+":"+[Link]());

Real Senario of HashMap


paridabapun
Multithreading Questions
1 What is difference between sleep() and wait() method?

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.

3. Both method thows InterruptedException which is a checked exception

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.

5. Wait method called from synchronized block otherwise it will throw


IllegalMonitorStateException where as sleep can be called without synchronized block.

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.

2 What is yield() in thread?

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.

3 Some Important points about sleep()

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)

3. Sleep() method doesnot relinquish the lock it has accuired.

4. It always throws checked exception InterruptedException.

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.

4 Why wait and notify available in Object class?

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.

5 What is difference between Thread and Runnable?

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.

Example to Understand Join

public class JoinExample {

paridabapun
public static void main(String args[]) throws InterruptedException{

[Link]([Link]().getName() + " is Started");

Thread exampleThread = new Thread(){

public void run(){

try {

[Link]([Link]().getName() + " is Started");

[Link](2000);

[Link]([Link]().getName() + " is Completed");

} catch (InterruptedException ex) {

[Link]();

};

[Link]();

[Link]();

[Link]([Link]().getName() + " is Completed");

}
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.

4. calling notify() or notifyAll() issues a notification to a single or multiple thread that a


condition has changed and once notification thread leaves synchronized block , all the
threads which are waiting fight for object lock on which they are waiting

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.

Ans 1. A [Link] is a thread synchronization mechanism just like


synchronized blocks. A Lock is, however, more flexible and more sophisticated than a
synchronized block.

2. Since Lock is an interface, you need to use one of its implementations to use a Lock in your
applications. Example:

Lock lock = new ReentrantLock();

[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

public class Calculator {

private int calculatedValue;

private int value;

public synchronized void calculate(int value) {

[Link] = value;

[Link] = doMySlowCalculation(value);

public synchronized int getCalculatedValue() {


return calculatedValue;

public synchronized int getValue() {

return value;

public class Calculator {

private int calculatedValue;

paridabapun
private int value;

private ReadWriteLock lock = new ReentrantReadWriteLock();

public void calculate(int value) {

[Link]().lock();

try {

[Link] = value;

[Link] = doMySlowCalculation(value);

} finally {

[Link]().unlock();

public int getCalculatedValue() {

[Link]().lock();

try {

return calculatedValue;

} finally {

[Link]().unlock();

}
}

public int getValue() {

[Link]().lock();

try {

return value;

} finally {

[Link]().unlock();

paridabapun
}

9 How to solve producer and consumer problen in java?Example.

Ans public class ProducerConsumerSolution {

public static void main(String args[]) {

Vector sharedQueue = new Vector();

int size = 4;

Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");

Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer");

[Link]();

[Link]();

class Producer implements Runnable {

private final Vector sharedQueue;

private final int SIZE;

public Producer(Vector sharedQueue, int size) {


[Link] = sharedQueue;

[Link] = size;

public void run() {

for (int i = 0; i < 7; i++) {

[Link]("Produced: " + i);

try {

produce(i);

} catch (InterruptedException ex) {

paridabapun
[Link]([Link]()).log([Link], null, ex);

private void produce(int i) throws InterruptedException {

//wait if queue is full

while ([Link]() == SIZE) {

synchronized (sharedQueue) {

[Link]("Queue is full " + [Link]().getName()

+ " is waiting , size: " + [Link]());

[Link]();

//producing element and notify consumers

synchronized (sharedQueue) {

[Link](i);

[Link]();
}

class Consumer implements Runnable {

private final Vector sharedQueue;

private final int SIZE;

public Consumer(Vector sharedQueue, int size) {

paridabapun
[Link] = sharedQueue;

[Link] = size;

public void run() {

while (true) {

try {

[Link]("Consumed: " + consume());

[Link](50);

} catch (InterruptedException ex) {

[Link]([Link]()).log([Link], null, ex);

private int consume() throws InterruptedException {

//wait if queue is empty

while ([Link]()) {

synchronized (sharedQueue) {

[Link]("Queue is empty " + [Link]().getName()

+ " is waiting , size: " + [Link]());


[Link]();

//Otherwise consume element and notify waiting producer

synchronized (sharedQueue) {

[Link]();

return (Integer) [Link](0);

paridabapun
}

10 Write code to Implement blocking queue in java?

Ans 1. [Link] is a Queue that supports operations that wait for


the queue to become non-empty when retrieving and removing an element, and wait for
space to become available in the queue when adding an element.

2. BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store
null value in the queue.

3. BlockingQueue implementations are thread-safe. All queuing methods are atomic in


nature and use internal locks or other forms of concurrency control.

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.

5. Java provides several BlockingQueue implementations such as ArrayBlockingQueue,


LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

6. While implementing producer consumer problem, we will use ArrayBlockingQueue


implementation and following methods are important to know.

● 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 {

private String msg;

public Message(String str){

[Link]=str;

public String getMsg() {

return msg;

paridabapun
public class Producer implements Runnable {

private BlockingQueue<Message> queue;

public Producer(BlockingQueue<Message> q){

[Link]=q;

public void run() {

//produce messages

for(int i=0; i<100; i++){

Message msg = new Message(""+i);

try {

[Link](i);

[Link](msg);

[Link]("Produced "+[Link]());

} catch (InterruptedException e) {

[Link]();

//adding exit message

Message msg = new Message("exit");

try {
[Link](msg);

} catch (InterruptedException e) {

[Link]();

public class Consumer implements Runnable{

private BlockingQueue<Message> queue;

paridabapun
public Consumer(BlockingQueue<Message> q){

[Link]=q;

public void run() {

try{

Message msg;

//consuming messages until exit message is received

while((msg = [Link]()).getMsg() !="exit"){

[Link](10);

[Link]("Consumed "+[Link]());

}catch(InterruptedException e) {

[Link]();

public class ProducerConsumerService {

public static void main(String[] args) {

//Creating BlockingQueue of size 10

BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);


Producer producer = new Producer(queue);

Consumer consumer = new Consumer(queue);

//starting producer to produce messages in queue

new Thread(producer).start();

//starting consumer to consume messages from queue

new Thread(consumer).start();

[Link]("Producer and Consumer has been started");

11

Ans paridabapun
Write a program which result deadlock? How to fix deadlock in java?

public class MyDeadlock {

String str1 = "Java";

String str2 = "UNIX";

Thread trd1 = new Thread("My Thread 1"){

public void run(){

while(true){

synchronized(str1){

synchronized(str2){

[Link](str1 + str2);

}}

};

Thread trd2 = new Thread("My Thread 2"){

public void run(){

while(true){

synchronized(str2){

synchronized(str1){
[Link](str2 + str1);

}}

};

public static void main(String a[]){

MyDeadlock mdl = new MyDeadlock();

[Link]();

[Link]();

paridabapun
}

How do you detect deadlock in Java ?

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.

Another example of Deadlock

public void method1(){

synchronized([Link]){

[Link]("Aquired lock on [Link] object");

synchronized ([Link]) {

[Link]("Aquired lock on [Link] object");

public void method2(){


synchronized([Link]){

[Link]("Aquired lock on [Link] object");

synchronized ([Link]) {

[Link]("Aquired lock on [Link] object");

How to fix deadlock ?

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

public void method1(){

synchronized([Link]){

[Link]("Aquired lock on [Link] object");

synchronized ([Link]) {

[Link]("Aquired lock on [Link] object");

public void method2(){

synchronized([Link]){

[Link]("Aquired lock on [Link] object");

synchronized ([Link]) {

[Link]("Aquired lock on [Link] object");

}
}}

12 How to check if a thread holds lock on a particular object in Java

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:

public class JavaAtomic {

public static void main(String[] args) throws InterruptedException {

ProcessingThread pt = new ProcessingThread();

Thread t1 = new Thread(pt, "t1");

[Link]();

Thread t2 = new Thread(pt, "t2");

[Link]();

[Link]();

[Link]();

[Link]("Processing count=" + [Link]());

class ProcessingThread implements Runnable {

private int count;


public void run() {

for (int i = 1; i < 5; i++) {

processSomething(i);

count++;

public int getCount() {

return [Link];

paridabapun
private void processSomething(int i) {

// processing some job

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];

public class JavaAtomic {

public static void main(String[] args) throws InterruptedException {

ProcessingThread pt = new ProcessingThread();

Thread t1 = new Thread(pt, "t1");

[Link]();

Thread t2 = new Thread(pt, "t2");


[Link]();

[Link]();

[Link]();

[Link]("Processing count=" + [Link]());

class ProcessingThread implements Runnable {

private AtomicInteger count = new AtomicInteger();

public void run() {

paridabapun
for (int i = 1; i < 5; i++) {

processSomething(i);

[Link]();

public int getCount() {

return [Link]();

private void processSomething(int i) {

// processing some job

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.

● Race conditions can be avoided by proper thread synchronization in critical sections.

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.

● Generate a thread dump by using a program such as jVisualVM.

● 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.

16 Discuss different types of Threads?

Ans Java threads can be divided into two:

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.

18 How will you awake a blocked thread in java?

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.

19 What is difference between CyclicBarriar and CountdownLatch in Java ?

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.

20 What is immutable object? How does it help on writing concurrent application?

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.

22 What is live lock?

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.

What is ThreadLocal ? whay it is used?

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.

● private ThreadLocal myThreadLocal = new ThreadLocal();

● 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.

● To Set value: [Link]("A thread local value");

● Get value: String threadLocalValue = (String) [Link]();

public static class MyRunnable implements Runnable {

private ThreadLocal<Integer> threadLocal =new ThreadLocal<Integer>();

public void run() {

[Link]( (int) ([Link]() * 100D) );

try {
[Link](2000);

} catch (InterruptedException e) {}

[Link]([Link]());

public static void main(String[] args) {

MyRunnable sharedRunnableInstance = new MyRunnable();

Thread thread1 = new Thread(sharedRunnableInstance);

paridabapun
Thread thread2 = new Thread(sharedRunnableInstance);

[Link]();

[Link]();

25 What are different way to create threads ?

Ans ● You know this?

25 What is difference between process and thread?

Ans ● You know this?

25 How a thread will return value in java?

Ans ● Java 5 introduced [Link] interface in concurrency


package that is similar to Runnable interface but it can return any Object and able
to throw Exception.

● Callable interface use Generic to define the return type of Object.

● Executors class provide useful methods to execute Callable in a thread pool.

● Callable tasks return [Link] object. Using Future we can


find out the status of the Callable task and get the returned Object.

25 Some Important Points about Java MultiThreading?


Ans 1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with
multiple threads in Java. Synchronization in Java guarantees that, no two threads can execute a
synchronized method which requires same lock simultaneously or concurrently.

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.

Concurency API in JAVA


Semaphore [ [Link]]
● Semaphore is a Mutex variable which controls multiple access to shared resources. Semaphores
are often used to restrict the number of threads than can access some (physical or logical)
resource.
● Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a
permit is available, and then takes it. Each release() adds a permit, potentially releasing a

paridabapun
blocking acquirer.
Semaphore mutex = new Semaphore(1);
Semaphore available = new Semaphore(100); // represents number of permits

Example:

public class Example {


private int value = 0;
private final Semaphore mutex = new Semaphore(1)
public int getNextValue() throws InterruptedException {
try {
[Link]();
return value++;
} finally {
[Link]();
}
}
}

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();

public void testA() {


[Link]();

paridabapun
try {
//Some code
} finally {
[Link]();
}
}
public int testB() {
[Link]();
try {
return 1;
} finally {
[Link]();
}
}
}

Atomic Variables / Nonblocking algorithms


● When a data (typically a variable) can be accessed by several threads, you must synchronize
the access to the data to ensure visibility and correctness.
public class Counter { This class works really well in single-threaded
environment, but don't work at all when several threads
private int value;
access the same Counter instance.
public int getValue(){

return value;

public int getNextValue(){


return value++;

public int getPreviousValue(){

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--;

● So how to do to avoid this disadvantages ? We must use non-blocking algorithms. It affects


scalablity and performance. These algorithms use low-level machine instructions which are
atomic to ensure the atomicity of higher-level operations.

● 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]();
}
}

Executors and thread pools


● If you want to load threads in parralel and then wait for the completion of all the tasks, it's a little
bit harder to code and if you want to get the return value of all the tasks it becomes really
difficult to keep a good code. Solution is the Executors. This simple class allows you to create
thread pools and thread factories.
● A thread pool is represented by an instance of the class ExecutorService. With an
ExecutorService, you can submit task that will be completed in the future. Here are the type of
thread pools you can create with the Executors class :
✔ Single Thread Executor : A thread pool with only one thread. So all the submitted task
will be executed sequentially. Method :[Link]()
✔ Cached Thread Pool : A thread pool that create as many threads it needs to execute the
task in parralel. The old available threads will be reused for the new tasks. If a thread is
not used during 60 seconds, it will be terminated and removed from the pool.
Method : [Link]()
✔ Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not
available for the task, the task is put in queue waiting for an other task to ends.
Method : [Link]()
✔ Scheduled Thread Pool : A thread pool made to schedule future task.
Method : [Link]()
✔ Single Thread Scheduled Pool : A thread pool with only one thread to schedule future
task. Method : [Link]()
● Once you have a thread pool, you can submit task to it using the different submit methods. You
can submit a Runnable or a Callableto the thread pool. The method return a Future representing
the future state of the task. If you submitted a Runnable, the Future object return null once the
task finished.

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]();

//Compute the result


}
[Link]();
Above steps are little bit complicated , there is a disadvantage. If the first task takes a long time to
compute and all the other tasks ends before the first, the current thread cannot compute the result
before the first task ends. Once again, Java has the solution for you, CompletionService.
A CompletionService is a service that make easier to wait for result of submitted task to an executor.
The implementation is ExecutorCompletionService who's based on an ExecutorService to work. So let's
try :
ExecutorService threadPool = [Link](4);
CompletionService<String> pool = new ExecutorCompletionService<String>(threadPool);

for(int i = 0; i < 10; i++){


[Link](new StringTask());

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.

To make a class immutable make


● all its fields final
● the class declared as final
● the this reference is not allowed to escape during construction
● Any fields which refer to mutable data objects are
o private
o have no setter method
o they are never directly returned of otherwise exposed to a caller
o if they are changed internally in the class this change is not visible and has no effect
outside of the class

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.

Interview Questions on Java Concurency

1. Difference between Runnable and Callable in Java?


Both Runnable and Callable represent task which is intended to be executed in separate thread.
Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these
two is that Callable's call() method can return value and throw Exception, which was not possible
with Runnable's run() method. Callable return Future object, which can hold result of computation
2. Difference between CyclicBarrier and CountDownLatch in Java?
Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events,
main difference between them is that you can not re-use CountDownLatch once count reaches to
zero, but you can reuse same CyclicBarrier even after barrier is broken.
3. What is Java Memory model?
a. Each action in a thread happens-before every action in that thread that comes later in the
program order, this is known as program order rule.
b. An unlock on a monitor lock happens-before every subsequent lock on that same monitor
lock, also known as Monitor lock rule.
c. A write to a volatile field happens-before every subsequent read of that same field, known as
Volatile variable rule.
d. A call to [Link] on a thread happens-before any other thread detects that thread has
terminated, either by successfully return from [Link]() or by [Link]() returning
false, also known as Thread start rule.
e. A thread calling interrupt on another thread happens-before the interrupted thread detects
the interrupt( either by having InterruptedException thrown, or invoking isInterrupted or
interrupted), popularly known as Thread Interruption rule.
f. The end of a constructor for an object happens-before the start of the finalizer for that object,
known as Finalizer rule.
g. If A happens-before B, and B happens-before C, then A happens-before C, which means
happens-before guarantees Transitivity.
paridabapun

Common questions

Powered by AI

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 .

You might also like