0% found this document useful (0 votes)
4 views60 pages

Core Java Interview

The document outlines key concepts of Object-Oriented Programming (OOP) in Java, including polymorphism, inheritance, abstraction, encapsulation, aggregation, composition, and association. It explains the differences between these concepts and their implications, such as method overloading and overriding, as well as the significance of immutability in strings. Additionally, it discusses the advantages of using char arrays over strings for sensitive data like passwords and the memory management of string objects in Java.

Uploaded by

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

Core Java Interview

The document outlines key concepts of Object-Oriented Programming (OOP) in Java, including polymorphism, inheritance, abstraction, encapsulation, aggregation, composition, and association. It explains the differences between these concepts and their implications, such as method overloading and overriding, as well as the significance of immutability in strings. Additionally, it discusses the advantages of using char arrays over strings for sensitive data like passwords and the memory management of string objects in Java.

Uploaded by

shresth000ai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

OOPS :-

1. What are different oops concept in java?

OOPs stands for Object Oriented Programming. The concepts in oops are similar to any
other programming languages. Basically, it is program agnostic.

The different OOps concepts are :

1. Polymorphism

2. Inheritance

3. Abstraction

4. Encapsulation

5. Aggreagation

6. Composition

7. Association

2. What is polymorphism?

The ability to identify a function to run is called Polymorphism. In java, c++ there are two
types of polymorphism: compile time polymorphism (overloading) and runtime
polymorphism (overriding).
Method overriding: Overriding occurs when a class method has the same name and
signature as a method in parent class. When you override methods, JVM determines the
proper methods to call at the program's run time, not at the compile time.

Method Overloading: Overloading is determined at the compile time. It occurs when


several methods have same names with:

1. Different method signature and different number or type of parameters.

2. Same method signature but different number of parameters.

3. Same method signature and same number of parameters but of different type

3. What is inheritance?

Inheritance allows a Child class to inherit properties from its parent class. In Java this is
achieved by using extends keyword. Only properties with access modifier public and
protected can be accessed in child class.

4. What is multiple inheritance and does java support?

If a child class inherits the property from multiple classes is known as multiple
inheritance. Java does not allow to extend multiple classes.

The problem with with multiple inheritance is that if multiple parent classes has a same
method name, the at runtime it becomes diffcult for compiler to decide which method to
execute from the child class.
To overcome this problem it allows to implement multiple Interfaces. The problem is
commonly referred as What is Diamond Problem.

5. What is difference between polymorphism and inheritance?

1. Inheritance defines parent-child relationship between two classes, polymorphism take


advantage of that relationship to add dynamic behaviour in your code.

2. Inheritance helps in code reusability by allowing child class to inherit behavior from the
parent class. On the other hand Polymorphism allows Child to redefine already defined
behaviour inside parent class. Without Polymorphism it's not possible for a Child to
execute its own behaviour while represented by a Parent reference variable, but with
Polymorphism we can do that.

3. Java doesn't allow multiple inheritance of classes, but allows multiple inheritance of
Interface, which is actually require to implement Polymorphism. For example a Class can
be Runnable, Comparator and Serializable at same time, because all three are
interfaces. This makes them to pass around in code e.g. you can pass instance of this
class to a method which accepts Serializable, or to Collections.sort() which accepts a
Comparator.

4. Both Polymorphism and Inheritance allow Object oriented programs to evolve. For
example, by using Inheritance you can define new user types in an Authentication
System and by using Polymorphism you can take advantage of already written
authentication code. Since, Inheritance guarantees minimum base class behaviour, a
method depending upon super class or super interface can still accept object of base
class and can authenticate it.
6. What is an abstraction ?

Abstraction is a way of converting real world objects in terms of class. Its a concept of
defining an idea in terms of classes or interface. For example creating a class Vehicle
and injecting properties into it.

7. What is Encapsulation?

The encapsulation is achieved by combining the methods and attribute into a class. The
class acts like a container encapsulating the properties.

The users are exposed mainly public methods.The idea behind is to hide how thinigs
work and just exposing the requests a user can do.

8. What is Association?

Association is a relationship where all object have their own lifecycle and there is no
owner. Let's take an example of Teacher and Student.

Multiple students can associate with single teacher and single student can associate with
multiple teachers but there is no ownership between the objects and both have their own
lifecycle. Both can create and delete independently.
9. What is Aggregation?

Aggregation is a specialize form of Association where all object have their own lifecycle
but there is ownership and child object can not belongs to another parent object.

Let's take an example of Department and teacher. A single teacher can not belongs to
multiple departments, but if we delete the department teacher object will not destroy. We
can think about "has-a" relationship.

10. What is Composition ?

Composition is again specialize form of Aggregation and we can call this as a "death"
relationship. It is a strong type of Aggregation.

Child object dose not have their lifecycle and if parent object deletes all child object will
also be deleted. Let's take again an example of relationship between House and rooms.

House can contain multiple rooms there is no independent life of room and any room can
not belongs to two different house if we delete the house room will automatically delete.

11. What is method hiding in Java?

When you declare two static methods with same name and signature in both superclass
and subclass then they hide each other i.e. a call to the method in the subclass will call
the static method declared in that class and a call to the same method is superclass is
resolved to the static method declared in the super class.

12. Is Java a pure object oriented language? if not why?

Java is not a pure object-oriented programming language e.g. there are many things you
can do without objects e.g. static methods. Also, primitive variables are not objects in
Java.

13. The difference between method overloading and overriding?

Several differences but the most important one is that method overloading is resolved at
compile time and method overriding is resolved at runtime.

The compiler only used the class information for method overloading, but it needs to
know object to resolved overridden method calls.

14. Can we overload a static method in Java?

Yes, you can overload a static method in Java. You can declare as many static methods
of the same name as you wish provided all of them have different method signatures.
15. Can we override static method in Java?

No, you cannot override a static method because it's not bounded to an object. Instead,
static methods belong to a class and resolved at compile time using the type of reference
variable.

But, Yes, you can declare the same static method in a subclass, that will result in method
hiding i.e. if you use reference variable of type subclass then new method will be called,
but if you use reference variable of superclass than old method will be called.

16. Can we prevent overriding a method without using the final modifier?

Yes, you can prevent the method overriding in Java without using the final modifier. In
fact, there are several ways to accomplish it e.g. you can mark the method private or
static, those cannot be overridden.

17. Can we override a non-static method as static in Java?

Yes, you can override the non-static method in Java, no problem on them but it should
not be private or final.
18. Can we override the final method in Java?

No, you cannot override a final method in Java, final keyword with the method is to
prevent method overriding. You use final when you don't want subclass changing the
logic of your method by overriding it due to security reason.

This is why String class is final in Java.

19. Can we make a class both final and abstract at the same time?

No, you cannot apply both final and abstract keyword at the class same time because
they are exactly opposite of each other. A final class in Java cannot be extended and you
cannot use an abstract class without extending and making it a concrete class.

As per Java specification, the compiler will throw an error if you try to make a class
abstract and final at the same time.

20. Can we overload or override the main method in Java?

No, since main() is a static method, you can only overload it, you cannot override it
because the static method is resolved at compile time without needing object information
hence we cannot override the main method in Java.
21. What is the difference between Polymorphism, Overloading, and
Overriding?

Polymorphism is the real concept behind on both Overloading and Overriding.


Overloading is compile time Polymorphism and Overriding are runtime Polymorphism.

22. What is the difference between Association, Aggregation, and


Composition in OOP?

When an object is related to another object it called association. It has two forms,
aggregation, and composition. the former is the loose form of association where the
related object can survive individual while later is a stronger form of association where a
related object cannot survive individually. For example, the city is an aggregation of
people but is the composition of body parts.

23. What is the difference between Composition and Inheritance in OOP?

This is another great OOPS concept question because it test what matters, both of them
are very important from a class design perspective. Though, both Composition and
Inheritance allows you to reuse code, former is more flexible than later.

Composition allows the class to get an additional feature at runtime, but Inheritance is
static. You can not change the feature at runtime by substitution new implementation.
See the answer for more detailed discussion
24. What is this keywords?

Every instance method in every object in Java receives a reference named this when the
method is invoked. The reference named this is a reference to the object on which the
method was invoked.

It can be used for any purpose for which such a reference is needed.

25. What is super keyword?

The super keyword is a reference variable that is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.

26. What is final keywords?

The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be: variable, method, class.

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable.
It can be initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only.

27. What is the difference between Procedural programming and OOPS?

1. Procedural language is based on functions but object oriented language is based on


real world objects.

2. Procedural language gives importance on the sequence of function execution but


object oriented language gives importance on states and behaviors of the objects.

3. Procedural language exposes the data to the entire program but object oriented
language encapsulates the data.

4. Procedural language follows top down programming paradigm but object oriented
language follows bottom up programming paradigm.

5. Procedural language is complex in nature so it is difficult to modify, extend and


maintain but object oriented language is less complex in nature so it is easier to modify,
extend and maintain.

6. Procedural language provides less scope of code reuse but object oriented language
provides more scope of code reuse.

30. What is the diamond problem in inheritance?

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

31. What is JIT (Just-in-Time) Compilation ?

There are two ways a language can be compiled

1. Compiled Language

2. Interpreted Language

A machine understands only binary language, so finally a source code has to be


compiled in binary format. In compiled way the compiler directly generate the binary file
from source code.While in interpreted way it generate the class file which is then run by
virtual machine.

That means binary file is generated at the run time (compilation is done on need basis)
this type of compilation is called JIT (Just-in-Time) compilation.
String Interview Questions:-

What is string constant pool?

String objects are most used data objects in Java. Hence, java has a special
arrangement to store the string objects. String Constant Pool is one such arrangement.
String Constant Pool is the memory space in heap memory specially allocated to store
the string objects created using string literals. In String Constant Pool, there will be no
two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of
the object to be created. If there exist an object in the string constant pool with the same
content, then it returns the reference of that object. It doesn't create a new object. If the
content is different from the existing objects then only it creates new object

What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can't modify them once they are created.
They are final in nature. Where as mutable objects are concerned, you can perform
modifications to them.
Why String is immutable or final in Java?

There are several benefits of String because it's immutable and final.

(a). String Pool is possible because String is immutable in java.

(b). 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.

(c). Since String is immutable, it's safe to use in multi-threading and we don't need any
synchronization.

(d). Strings are used in java classloader and immutability provides security that correct
class is getting loaded by Classloader.

Where exactly string constant pool is located in the memory?

Inside the heap memory. JVM reserves some part of the heap memory to store string
objects created using string literals.

What are the difference between String, StringBuffer and StringBuilder?

String is immutable and final in java, so whenever we do String manipulation, it creates a


new String. String manipulations are resource consuming, so java provides two utility
classes for String manipulations :-

1. StringBuffer and

2. StringBuilder

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-
safe and synchronized where StringBuilder operations are not thread-safe. So when
multiple threads are working on same String, we should use StringBuffer but in single
threaded environment we should use StringBuilder.

Why String is popular HashMap key in Java?

Since 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 it's
processing is fast than other HashMap key objects. This is why String is mostly used
Object as HashMap keys.

Why Char array is preferred over String for storing password?

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

2.With String there is always a risk of printing plain text in log file or console but if use
Array you won't print contents of array instead its memory location get printed. though
not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown


Character password: [C@110b053

Though using char[] is not just enough you need to erase content to be more secure.

How about comparing the other objects like Integer, Boolean, and
custom objects like "Pet"?

String class is designed with the Flyweight design pattern in mind. Flyweight is all
about re-usability without having to create too many objects in memory. A pool of Strings
is maintained by the String class. When the intern( ) method is invoked, equals() method
is invoked to determine if the String already exist in the pool.

If it does then the String from the pool is returned instead of creating a new object. If not
already in the string pool, a new String object is added to the pool and a reference to this
object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if
s1.equals(s2) is true.

. Are there any other classes whose objects are immutable?

Yes, Classes like Character, Byte, Integer, Float, Double, Long. called 'Wrapper classes'
are created as 'immutable'. Classes like Class BigInteger, BigDecimal are also.

Why Char array is preferred over String for storing password?

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.

Collections Interview Questions:-

What is the difference between Collection and Collections ?

Collection is an interface while Collections is a java class , both are present in java.util
package and part of java collections framework.

What is the difference between List and Set ?

Set contain only unique elements while List can contain duplicate elements. Set is
unordered while List is ordered . List maintains the order in which the objects are added .

What is the difference between Map and Set ?

Map object has unique keys each containing some value, while Set contain only unique
values.

What are the classes implementing List and Set interface ?

Class implementing List interface : ArrayList , Vector , LinkedList , Class implementing


Set interface : HashSet , TreeSet
What is an iterator ?

Iterator is an interface . It is found in java.util package. It provides methods to iterate over


any Collection.Basically List and set collection provides the iterator.You can get Iterator
from ArrayList, LinkedList, and TreeSet etc.

Map implementation such as HashMap doesn't provide Iterator directory but you can get
there keySet or Value Set and can iterator through that collection.

What is Difference between fail-safe and fail-fast Iterator in Java?

fail-fast Iterators in Java

As name suggest fail-fast Iterators fail as soon as they realized that structure of
Collection has been changed since iteration has begun. Structural changes means
adding, removing or updating any element from collection while one thread is Iterating
over that collection.

fail-fast behavior is implemented by keeping a modification count and if iteration thread


realizes the change in modification count it throws ConcurrentModificationException.

fail-safe Iterator in java

Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is
modified structurally while one thread is Iterating over it because they work on clone of
Collection instead of original collection and that's why they are called as fail-safe iterator.

What is difference between HashMap and Hashtable in Java?

Both HashMap and Hashtable implements Map interface. Here are two differences :
1.The HashMap class is roughly equivalent to Hashtable, except that it is non-
synchronized and permits nulls. (HashMap allows null values as key and value whereas
Hashtable doesn't allow nulls).

2. One of the major differences between HashMap and Hashtable is that HashMap is
non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-
safe and can be shared between multiple threads but HashMap can not be shared
between multiple threads without proper synchronization.

Which methods you need to override to use any object as key in


HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode()
method .

What is the difference between java.util.Iterator and java.util.ListIterator?

1. Iterator : Enables you to traverse through a collection in the forward direction only, for
obtaining or removing elements

2. ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows
the modification of elements.

What is the Difference between Enumeration and Iterator interface?

Enumeration and Iterator are the interface available in java.util package. The functionality
of Enumeration interface is duplicated by the Iterator interface. New implementations
should consider using Iterator in preference to Enumeration. Iterators differ from
enumerations in following ways:

1. Enumeration contains 2 methods namely hasMoreElements() and nextElement()


whereas Iterator contains three methods namely hasNext(), next(),remove().

2. Iterator adds an optional remove operation, and has shorter method names. Using
remove() we can delete the objects but Enumeration interface does not support this
feature.

Enumeration interface is used by legacy classes. Vector.elements() and


Hashtable.elements() method returns Enumeration. Iterator is returned by all Java
Collections Framework classes. java.util.Collection.iterator() method returns an instance
of Iterator.

What is the difference between Sorting performance of Arrays.sort() vs


Collections.sort() ? Which one is faster? Which one to use and when?

Many developers are concerned about the performance difference between


java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same
algorithm the only difference is type of input to them. Collections.sort() has a input as List
so it does a translation of List to array and vice versa which is an additional step while
sorting.

So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the
sorting is done directly on the array. So clearly it should be used when you have a array
available with you and you want to sort it.

What is WeakHashMap ?

WeakHashMap :
WeakHashMap is a class present in java.util package similar to IdentityHashMap. It is a
Hashtable based implementation of Map interface with weak keys. An entry in
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.

It permits null keys and null values.

Like most collection classes this class is not synchronized.A synchronized


WeakHashMap may be constructed using the Collections.synchronizedMap() method.
Iterators returned by the iterator() method are fail-fast , hence , will throw
ConcurrentModificationException.

What is Comparable and Comparator interface?

In java. all collection which have feature of automatic sorting, uses compare methods to
ensure the correct sorting of elements. For example classes which use sorting are
TreeSet, TreeMap etc.

To sort the data elements a class needs to implement Comparator or Comparable


interface.That's why all Wrapper classes like Integer,Double and String class implements
Comparable interface.

Comparable helps in preserving default natural sorting, whereas Comparator helps


in sorting the elements in some special required sorting pattern. The instance of
comparator if passed usually as collection's constructor argument in supporting
collections.

Arrays also helps array of objects to convert in collection objects. Arrays also have some
functions which helps in copying or working in part of array objects.
Which collection classes provide random access of it's elements?

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it's


elements.

Difference between Vector and ArrayList?

Lets note down the differences:-

(a). All the methods of Vector is synchronized. But, the methods of ArrayList is not
synchronized.

(b). Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2,
when collection framework was introduced in java.

(c). By default, Vector doubles the size of its array when it is re-sized internally. But,
ArrayList increases by half of its size when it is re-sized.

Difference between TreeSet and SortedSet?

SortedSet is an interface which TreeSet implements.

Difference between ArrayList and LinkedList?

LinkedList store elements within a doubly-linked list data structure. ArrayList store
elements within a dynamically resizing array.

LinkedListallows for constant-time insertions or removals, but only sequential access of


elements. In other words, you can walk the list forwards or backwards, but grabbing an
element in the middle takes time proportional to the size of the list. ArrayLists,on the
other hand, allow random access, so you can grab any element in constant time. But
adding or removing from anywhere but the end requires shifting all the latter elements
over, either to make an opening or fill the gap.

LinkedList has more memory overhead than ArrayList because in ArrayList each index
only holds actual object (data) but in case of LinkedList each node holds both data and
address of next and previous node.

How to decide between HashMap and TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is
your better alternative. Depending upon the size of your collection, it may be faster to add
elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

What are advantages of iterating a collection using iterator?

For loop does not allow updating the collection(add or remove) whereas Iterator does.
Also Iterator can be used where there is no clue what type of collections will be used
because all collections implement Iterator interface.

How do you remove an entry from a Collection? and subsequently what


is the difference between the remove() method of Collection and remove()
method of Iterator, which one you will use while removing elements during
iteration?
Collection interface defines remove(Object obj) method to remove objects from
Collection. List interface adds another method remove(int index), which is used to
remove object at specific index. You can use any of these method to remove an entry
from Collection, while not iterating. Things change, when you iterate.

Suppose you are traversing a List and removing only certain elements based on logic,
then you need to use Iterator's remove() method. This method removes current element
from Iterator's perspective. If you use Collection's or List's remove() method during
iteration then your code will throw ConcurrentModificationException. That's why it's
advised to use Iterator remove() method to remove objects from Collection.

Difference between ArrayList and Vector

ArrayList

1. ArrayList is NOT synchronized by default.

2. ArrayList can use only Iterator to access the elements.

3. The ArrayList increases its array size by 50 percent if it runs out of room.

4. ArrayList has no default size.

Vector

1. Vector List is synchronized by default.

2. Vector list can use Iterator and Enumeration Interface to access the elements.

3. A Vector defaults to doubling the size of its array if it runs out of room.

4. While vector has a default size of 10.

Why are Iterators returned by ArrayList called Fail Fast ?


Because, if list is structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException.

Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather
than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

How do you decide when to use ArrayList and When to use LinkedList?

If you need to support random access, without inserting or removing elements from any
place other than the end, then ArrayList offers the optimal collection.

If, however, you need to frequently add and remove elements from the middle of the list
and only access the list elements sequentially, then LinkedList offers the better
implementation.

What is the Set interface ?

1. The Set interface provides methods for accessing the elements of a finite
mathematical set

2. Sets do not allow duplicate elements

3. Contains no methods other than those inherited from Collection

4. It adds the restriction that duplicate elements are prohibited

5. Two Set objects are equal if they contain the same elements

Difference between HashSet and TreeSet ?


HashSet

1. HashSet is under set interface i.e. it does not guarantee for either sorted order or
sequence order.

2. We can add any type of elements to hash set.

TreeSet

1. TreeSet is under set i.e. it provides elements in a sorted order (acceding order).

2. We can add only similar types of elements to tree set.

What is a Map ?

1. A map is an object that stores associations between keys and values (key/value pairs).

2. Given a key, you can find its value. Both keys and values are objects.

3. The keys must be unique, but the values may be duplicated.

4. Some maps can accept a null key and null values, others cannot.

How do you decide when to use HashMap and when to use TreeMap ?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is
your better alternative.

Depending upon the size of your collection, it may be faster to add elements to a
HashMap, then convert the map to a TreeMap for sorted key traversal.

How does a Hashtable internally maintain the key-value pairs?


TreeMap actually implements the SortedMap interface which extends the Map interface.

In a TreeMap the data will be sorted in ascending order of keys according to the natural
order for the key's class, or by the comparator provided at creation time. TreeMap is
based on the Red-Black tree data structure.

Array Interview Questions:-

What is ArrayStoreException in java? When you will get this exception?

ArrayStoreException is a run time exception which occurs when you try to store non-
compatible element in an array object. The type of the elements must be compatible
with the type of array object.

For example :- you can store only string elements in an array of strings. if you try to
insert integer element in an array of strings, you will get ArrayStoreException at run
time.

How to serialize ArrayList in java?

ArrayList is serializable by default. This means you need not to implement


Serializable interface explicitly in order to serialize an ArrayList.

What is synchronize ArrayList in java?


ArrayList is non-synchronized and should not be used in multi-thread environment
without explicit synchronization.

There are two ways to synchronize explicitly :-

(a). Using Collections.synchronizedList() method

(b).Using thread-safe variant of ArrayList: CopyOnWriteArrayList

Serialization Interview Questions:-

1. What is Serialization in Java ?

Object Serialization in Java is a process used to convert Object into a binary format
which can be persisted into disk or sent over network to any other running Java
virtual machine; the reverse process of creating object from binary stream is called
deserialization in Java.

What is the need of Serialization?

The serialization is used :-

(a). To send state of one or more object's state over the network through a socket.

(b). To save the state of an object in a file

(c). An object's state needs to be manipulated as a stream of bytes.

What is serialVersionUID? What would happen if you don't define this?


SerialVersionUID is an ID which is stamped on object when it get serialized usually
hashcode of object, you can use tool serialver to see serialVersionUID of a serialized
object .

SerialVersionUID is used for version control of object. you can specify


serialVersionUID in your class file also.

Java serialization process relies on correct serialVersionUID for recovering state of


serialized object and throws java.io.InvalidClassException in case of
serialVersionUID mismatch.

Do we need to implement any method of Serializable interface to make


an object serializable?

No. Serializable is a Marker Interface. It does not have any methods.

What happens if the object to be serialized includes the references to


other serializable objects?

If the object to be serialized includes references to the other objects, then all those
object's state also will be saved as the part of the serialized state of the object in
question. The whole object graph of the object to be serialized will be saved during
serialization automatically provided all the objects included in the object's graph are
serializable.

What is a transient variable?


These variables are not included in the process of serialization and are not the part of
the object's serialized state.

Are the static variables saved as the part of serialization?

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

Difference between Externalizable and Serialization interface


(Important)?

SERIALIZABLE:-

(a). It is a marker interface it doesn't have any method.

(b). Serializable provides its own default serialization process, we just need to
implement Serializable interface.

(c). We can customize default serialization process by defining following methods in


our class >readObject() and writeObject() Note: We are not overriding these
methods, we are defining them in our class.

(d). It provides less control over Serialization as it's not mandatory to define
readObject() and writeObject() methods.

(e). Constructor is not called during deSerialization.

EXTERNALIZABLE:-

(a). It's not a marker interface. It has method's called writeExternal() and
readExternal()
(b). we need to override writeExternal() and readExternal() for serialization process
to happen.

(c). Serialization process is completely customized, We need to override


Externalizable interface's writeExternal() and readExternal() methods.

(d). Externalizable provides you great control over serialization process as it is


important to override writeExternal() and readExternal() methods.

(e). Constructor is called during deSerialization.

How can you avoid certain member variables of class from getting
Serialized?

Mark member variables as static or transient, and those member variables will no
more be a part of Serialization.

What are compatible and incompatible changes in Serialization


process?

Compatible Changes:- Compatible changes are those changes which does not
affect the deSerialization process even if class was updated after being serialized
(provided serialVersionUID has been declared)

(a). Adding new fields:- We can add new member variables in class.

(b). Adding writeObject()/readObject() methods:- We may add these methods to


customize serialization process.

(c). Removing writeObject()/readObject() methods:- We may remove these


methods and then default customization process will be used.
(d). Changing access modifier of a field:- The change to access modifiers i.e.
public, default, protected, and private have no effect on the ability of serialization to
assign values to the fields.

(e). Changing a field from static to non static OR changing transient filed to
non transient field:- it's like addition of fields.

InCompatible Changes:- InCompatible changes are those changes which affect


deSerialization process if class was updated after being serialized (provided
serialVersionUID has been declared)

(a). Deletion of fields.

(b). Changing a non-static field to static or non transient field to transient


field:- it's equal to deletion of fields.

(c). Modifying the writeObject() / readObject() method:- we must not modify these
method, though adding or removing them completely is compatible change.

Why does serialization NOT save the value of static class attributes?
Why static variables are not serialized?

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.
How to Serialize a collection in java? How to serialize a ArrayList,
Hashmap or Hashset object in Java?

All standard implementations of collections List, Set and Map interface already
implement java.io.Serializable. All the commonly used collection classes like
java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable,
java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not
really need to write anything specific to serialize collection objects.-

However you should keep following things in mind before you serialize a collection
object - Make sure all the objects added in collection are Serializable. - Serializing
the collection can be costly therefore make sure you serialize only required data
isntead of serializing the whole collection. - In case you are using a custom
implementation of Collection interface then you may need to implement serialization
for it.

What Is the purpose of Java Serialization?

You can use Java serialization to perform the following tasks:-


1. (a). Stashing(store (something) safely in a hidden or secret place)
:- Rather holding a large object in memory, it’s better to cache it to a local file via
serialization. If you attempt to save a non-serializable object, the JVM will fail the
operation with .

(b). Data Transmission:- Java permits to serialize an object over a network using
RMI (Remote Method Invocation), a distributed technology of Java. RMI enables a
Java client object communicates with the instance of a Java server hosted on a
remote system. For example, an ATM center of your locality can interact with a bank
server located in a different country.
(c). Persistence:- If you want to preserve the state of a particular operation to a
database, just serialize it to a byte array, and save to the database for later use.

(d). Deep Cloning:- In Java, it is also known as the deep copy. It causes an object to
copy along with the objects to which it refers. You need to write a customized clone
class to achieve this. Java serialization can save you the trouble of adding a clone
class. Serializing the object into a byte array and then deserializing it to another
object will fulfill the purpose.

(e). Cross JVM Communication:- Serialization works the same across different
JVMs irrespective of the architectures they are running on.

What one should take care of, while serializing the object?

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

What happens to the static fields of a class during serialization?

There are three exceptions in which serialization doesn’t necessarily read and write
to the stream. These are as follows:-

(a). Serialization ignores static fields, because they are not part of any particular
state.

(b). Base class fields are only handled if the base class itself is serializable.

(c). Transient fields.

What are Transient and Volatile Modifiers?


A transient variable is a variable that may not be serialized i.e. the value of the
variable can’t be written to the stream in a Serializable class. If you don’t want some
field to be serialized, you can mark that field transient or static. In such a case when
the class is retrieved from the ObjectStream the value of the variable is null.

Volatile modifier applies to variables only and it tells the compiler that the variable
modified by volatile can be changed unexpectedly by other parts of the program.

What will happen if one of the members in the class doesn't implement
Serializable interface?

One of the easy question about Serialization process in Java. If you try to serialize an
object of a class which implements Serializable, but the object includes a reference
to an non- Serializable class then a ‘NotSerializableException’ will be thrown at
runtime and this is why I always put a SerializableAlert (comment section in my code)
, one of the code comment best practices, to instruct developer to remember this fact
while adding a new field in a Serializable class.

What happens in case of Inheritance where Parent Class is


SERIALIZABLE?

If a class is serializable then all subclasses can also be SERIALIZED.

Either of classes needs not to have default constructor.


Difference between Serialization and Extermalization ?

Serializable is a marker interface therefore you are not forced to implement any

methods, however Externalizable contains two methods readExternal() and

writeExternal() which must be implemented.

Serializable interface provides a default serialization mechanism, on the other hand,

Externalizable interface instead of relying on default Java Serialization provides

flexibility to control this mechanism.

Exception Handling Interview Questions:-

What is an exception in programming?

An exception is an event or error that occurs during the execution of a program and
disrupts the normal flow of instructions. Exception handling is used to gracefully
manage and respond to runtime errors or exceptional situations in a program,
preventing the program from terminating abruptly.

difference between checked and unchecked


exceptions?

Checked exceptions are checked at compile-time and need to be explicitly handled by


the programmer. Unchecked exceptions, on the other hand, are not checked at compile-
time and usually indicate programming errors.
What is the role of try, catch, and finally blocks?

The try block encloses the code that might throw an exception. The catch block
catches and handles the exception if it occurs. The finally block contains code that will
be executed whether an exception is thrown or not.

What is the purpose of the throw statement?

The throw statement is used to explicitly throw an exception in a program.

What is the purpose of the finally block, and when is it executed?

The finally block is used to contain code that must be executed whether an exception is
thrown or not. It is executed after the try block, regardless of whether an exception is
caught or not.

What is the difference between throw and throws


throw is used to throw an exception explicitly, while throws is used in
method signatures to indicate that the method might throw certain types of
exceptions.

How can you handle exceptions in a multithreaded environment?

In a multithreaded environment, each thread should have its own exception


handling mechanism. Global exception handling may not be sufficient due to the
concurrent nature of threads.

Explain the try-with-resources statement in Java.


The try-with-resources statement is used to automatically close resources like
files, sockets, or database connections. It simplifies resource management by
eliminating the need for explicit finally blocks.

Difference between Error and Exception

Error represents serious errors that are typically beyond the control of the
programmer and should not be caught or handled. Exception represents exceptional
conditions that a program should catch and handle.

How does the assert statement relate to exception handling?

The assert statement is used for debugging and testing. If an assert


condition fails, an AssertionError is thrown. It's not intended for regular exception
handling but can be caught like any other exception if desired.

Explain the concept of suppressed exceptions in Java.

Suppressed exceptions are exceptions that are thrown in the finally block of a try-
with-resources statement while another exception is being thrown or propagated.
They can be retrieved using the getSuppressed() method in the Throwable class.

Explain the concept of rethrowing an exception.

Rethrowing an exception involves catching an exception in a catch block


and then throwing the same exception or another exception. It allows for
additional logging or custom processing before propagating the exception further.
How do you create a custom exception class in Java?

To create a custom exception class, you need to extend one of the standard
exception classes (usually Exception or one of its subclasses) and provide any
additional functionality or information needed for your specific exception.

Reflection :-

What is reflection ?

It is the process of examining / modifying the runtime behaviour of an object at


runtime.Using java reflection we can inspect a class, interface, enum, get their
structure, methods and fields information at runtime even though class is not
accessible at compile time. We can also use reflection to instantiate an object, invoke
it's methods, change field values.

** Why is Reflection slower ?

Because it has to inspect the metadata in the bytecode instead of just using pre
compiled addresses and constants.

What is Java Reflection API? Why it's so important to have?

Java Reflection API provides ability to inspect and modify the runtime behavior of
java application. We can inspect a java class, interface, enum and get their methods
and field details. Reflection API is an advanced topic and we should avoid it in
normal programming. Reflection API usage can break the design pattern such as
Singleton pattern by invoking the private constructor i.e violating the rules of access
modifiers.

Even though we don't use Reflection API in normal programming, it's very important
to have. We can't have any frameworks such as Spring, Hibernate or servers such as
Tomcat, JBoss without Reflection API. They invoke the appropriate methods and
instantiate classes through reflection API and use it a lot for other processing.

Can a private variable or method of a class can be accessed?

Yes its possible using reflection.


What are advantages of Using Reflection?

1.* Extensibility Features :- An application may make use of external, user-defined


classes by creating instances of extensibility objects using their fully-qualified names.

2. Debugging and testing tools :- Debuggers use the property of reflection to


examine private members on classes.

What are the Drawbacks of Java Reflection?

1.Performance Overhead :- Reflective operations have slower performance than


their non-reflective counterparts, and should be avoided in sections of code which
are called frequently in performance-sensitive applications.

2. Exposure of Internals :- Reflective code breaks abstractions and therefore may


change behavior with upgrades of the platform.

How can you get the class object from a class name?

Use the Class.forName(className) method. Fully qualified classname may be


required if the class is not in the same package as the caller.

How to get the object of Class class?

There are 3 ways to get the instance of Class class. They are as
follows:

• forName() method of Class class


• getClass() method of Object class
• the .class syntax
Using reflection, how can you tell if a member is public or private?

All the classes that implement the Member interface have a method
called getModifiers(). This gives an integer value. There is a class called Modifier
that exposes a number of static methods to interpret this integer.

Here is an example :-

Member mem;

//.

int mod = mem.getModifiers();

Modifier.isPrivate(mod);

Generics Interview Questions:-

1. What are Generics?

Generics are used to create Generic Classes and Generic methods which can work
with different Types(Classes).it provides compile time type-safety and ensures that
you only insert correct Type in collection and avoids ClassCastException in runtime.
2. How Generics works in Java ? What is type erasure ?

Generics is implemented using Type erasure, compiler erases all type related
information during compile time and no type related information is available during
runtime.

For Example :- List is represented by only List at runtime.This was done to ensure
binary compatibility with the libraries

which were developed prior to Java 5. you don't have access to Type argument at
runtime and Generic type is translated to Raw type by compiler during runtime.

3. What are the restrictions in using generic type that is declared in a


class declaration?

If a generic is declared as part of class declaration, it can be used any where a type
can be used in a class method (return type or argument), member variable etc. For
Example:- See how T is used as a parameter and return type in the class
MyListGeneric.

4. What is Bounded and Unbounded wildcards in Generics?

In generics '?' is known as wildcard and it represents an unknown type.

Types of Wildcard :-

1. Unbounded Wildcard.

2. Bounded Wildcard.

(a). Upper bounded Wildcard.


(b). Lower bounded Wildcard.

1. Unbounded Wildcard :- is used for list of unknown types using '?'(Type is not
bounded).

2. Bounded Wildcard :- is used for unknown bounded types using '?' with extends
or super keyword.

(a). Upper bounded Wildcard :- is used to restrict the unknown type to be a specific
type or a subtype of that type using '?' with extends keyword.

(b). Lower bounded Wildcard :-is used to restrict the unknown type to be a specific
type or a super type of that type using '?' with super keyword.

5. What is difference between List<? extends T> and List <? super T>?

Use extends if you need to read from the collection (i.e.List<? extends T>). This will
ensure that the collection itself contains items which extends A. This is read-only
because there is no way to determine the exact type to add to the collection (the
parameter could be List and there would be no way of ensure the type safety of an
addition).

Use super if you want to write to the collection (i.e.List <? super T>). In this case,
the collection can support addition of A types as we know the specified type of the
collection is a super class of A. Therefore, A typed items can always be added to the
collection.

6. How to write parametrized class in Java using Generics ?


This is an extension of previous Java generics interview question. Instead of asking
to write Generic method Interviewer may ask to write a type safe class using
generics. again key is instead of using raw types you need to used generic types and
always use standard place holder used in JDK.

7. Can we use Generics with Array?

No.This was probably most simple generics interview question in Java, if you know
the fact that Array doesn't support Generics and that's why Joshua Bloch suggested
in Effective Java to prefer List over Array because List can provide compile time
type-safety over Array.

8. What is Generic Methods?

Generic methods are methods that introduce their own type parameters. This is
similar to declaring a generic type, but the type parameter's scope is limited to the
method where it is declared. Static and non-static generic methods are allowed, as
well as generic class constructors.
The syntax for a generic method includes a type parameter, inside angle brackets,
and appears before the method's return type. For static generic methods, the type
parameter section must appear before the method's return type.

9. What is Wildcards and Subtyping?

Generics, Inheritance, and Subtypes, generic classes or interfaces are not related
merely because there is a relationship between their types. However, you can use
wildcards to create a relationship between generic classes or interfaces.

10. What is Upper Bounded Wildcards?

You can use an upper bounded wildcard to relax the restrictions on a variable. For
example, say you want to write a method that works on List(Integer), List(Double),
and List(Number); you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by


the extends keyword, followed by its upper bound. Note that, in this context, extends
is used in a general sense to mean either "extends" (as in classes) or "implements"
(as in interfaces).

11. Why do we need generics in java?

Code that uses generics has many benefits over non-generic code:
1. Stronger type checks at compile time: A Java compiler applies strong type
checking to generic code and issues errors if the code violates type safety. Fixing
compile-time errors is easier than fixing runtime errors, which can be difficult to find.

2. Elimination of casts: If you use generics, then explicit type casting is not
required.

3. Enabling programmers to implement generic algorithms: By using generics,


programmers can implement generic algorithms that work on collections of different
types, can be customized, and are type safe and easier to read.

12. What is Wildcard?

In generics '?' is known as wildcard and it represents an unknown type.

Types of wildcard:

1. Unbounded wildcard.

2. Bounded wildcard.

a. Upper bounded wildcard.

b. Lower bounded wildcard.

1. Unbounded wildcard: is used for list of unknown types using '?'(Type is not
bounded).
2. Bounded wildcard: is used for unknown bounded types using '?' with extends or
super keyword.

a. Upper bounded wildcard: is used to restrict the unknown type to be a specific


type or a subtype of that type using '?' with extends keyword.

b. Lower bounded wildcard: is used to restrict the unknown type to be a specific


type or a super type of that type using '?' with super keyword.

JDBC :-
What is JDBC?

One of the first JDBC interview question in most of interviews. JDBC is java database
connectivity as name implies it's a java API for communicating to relational database,
API has java classes and interfaces using that developer can easily interact with
database.

For this we need database specific JDBC drivers.

1. Load the Driver: First step is to load the database specific driver which
communicates with database.

2. Make Connection: Next step is get connection from the database using
connection object, which is used to send SQL statement also and get result back
from the database.

What is the mean of "dirty read" in database?

As the name itself convey the meaning of dirty read "read the value which may or
may not be correct". in database when one transaction is executing and changing
some field value same time some another transaction comes and read the change
field value before first transaction commit or rollback the value ,which cause invalid
value for that field, this scenario is known as dirty read.

Similarly when any transaction changes multiple database after execution of


transaction it will issue pre commit command on each database and all database
send acknowledgement and according to acknowledgement if all are positive ,
transaction will issue the commit command otherwise rollback is done .
What is connection pooling?

In this mechanism clients are not required every time make new connection and then
interact with database, instead connection objects are stored in connection pool and
client gets it from there. so it's a best way to share a server resources among the
client and enhance the application performance.

How to setup JDBC Connection Pool using Spring in Java

Setting up JDBC Database Connection Pool in Spring framework is easy for any
Java application, just matter of changing few configuration in spring configuration file.

If you are writing core java application and not running on any web or application
server like Tomcat or Weblogic, Managing Database connection pool
using Apache Commons DBCP and Commons Pool along-with Spring framework is
nice choice but if you have luxury of having web server and managed J2EE
Container, consider using Connection pool managed by J2EE server.

What are the locking system in JDBC?

There are 2 types of locking in JDBC by which we can handle multiple user issue
using the record. if two user are reading the same record then there is no issue but
what if users are updating the record , in this case changes done by first user is gone
by second user if he also update the same record .so we need some type of locking
so no lost update.

Optimistic Locking: optimistic locking lock the record only when update take place.
Optimistic locking does not use exclusive locks when reading.

Pessimistic locking: in this record are locked as it selects the row to update.
Threads :-

What is Thread in Java?

The thread is an independent path of execution. It's way to take advantage of


multiple CPU available in a machine. By employing multiple threads you can speed
up CPU bound task. For example, if one thread takes 100 milliseconds to do a job,
you can use 10 thread to reduce that task into 10 milliseconds.

Java provides excellent support for multi-threading at the language level, and it's also
one of the strong selling points.

How do you implement Thread in Java?

At the language level, there are two ways to implement Thread in Java. An instance
of java.lang.Thread represent a thread but it needs a task to execute, which is an
instance of interface java.lang.Runnable.

Since Thread class itself implement Runnable, you can override run() method either
by extending Thread class or just implementing Runnable interface. For detailed
answer and discussion see this article.

What is the difference between start() and run() method of Thread


class?

When you call start() method, main thread internally calls run() method to start newly
created Thread, so run() method is ultimately called by newly created thread.
When you call run() method main thread rather than starting run() method with newly
thread it start run() method by itself.

What is significance of using Volatile keyword?

Java allows threads to access shared variables. As a rule, to ensure that shared
variables are consistently updated, a thread should ensure that it has exclusive use
of such variables by obtaining a lock that enforces mutual exclusion for those shared
variables.

If a field is declared volatile, in that case the Java memory model ensures that all
threads see a consistent value for the variable.

NOTE:- (a). Can we have volatile methods in java?

No, volatile is only a keyword, can be used only with variables.

(b). Can we have synchronized variable in java?

No, synchronized can be used only with methods, i.e. in method declaration.

Can you again start Thread?

We cannot start Thread again, doing so will throw runtimeException


java.lang.IllegalThreadStateException. The reason is once run() method is
executed by Thread, it goes into dead state.

When threads are not lightweight process in java?


Threads are lightweight process only if threads of same process are executing
concurrently. But if threads of different processes are executing concurrently then
threads are heavy weight process.

How can you ensure all threads that started from main must end in
order in which they started and also main should end in last?

We can use join() method to ensure all threads that started from main must end in
order in which they started and also main should end in last.In other words waits for
this thread to die. Calling join() method internally calls join(0);

What is race condition in multi-threading and how can we solve it?

When more than one thread try to access same resource without synchronization
causes race condition.

So we can solve race condition by using either synchronized block or


synchronized method.When no two threads can access same resource at a time
phenomenon is also called as mutual exclusion.

NOTE:- (a). What if two threads try to read same resource without synchronization?

When two threads try to read on same resource without synchronization, it's never
going to create any problem.

(b). What if two threads try to write to same resource without synchronization?

When two threads try to write to same resource without synchronization, it's going to
create synchronization problems.
Why wait(), notify() and notifyAll() are in Object class and not in Thread
class?

1. Every Object has a monitor, acquiring that monitors allow thread to hold lock on
object. But Thread class does not have any monitors.

2. wait(), notify() and notifyAll() are called on objects only, When wait() method is
called on object by thread it waits for another thread on that object to release object
monitor by calling notify() or notifyAll() method on that object.

3. When notify() method is called on object by thread it notifies all the threads which
are waiting for that object monitor that object monitor is available now. So, this shows
that wait(), notify() and notifyAll() are called on objects only.

4. Wait(), notify() and notifyAll() method being in Object class allows all the threads
created on that object to communicate with other. [As multiple threads may exist on
same object].

What are thread priorities?

Thread Priority range is from 1 to 10. Where 1 is minimum priority and 10 is


maximum priority.

Thread class provides variables of final static int type for setting thread priority.

Thread with MAX_PRIORITY is likely to get more CPU as compared to low priority
threads. But occasionally low priority thread might get more CPU. Because thread
scheduler schedules thread on discretion of implementation and thread behaviour is
totally unpredictable.
Thread with MIN_PRIORITY is likely to get less CPU as compared to high priority
threads. But occasionally high priority thread might less CPU. Because thread
scheduler schedules thread on discretion of implementation and thread behaviour is
totally unpredictable.

What is ThreadGroup in java, What is default priority of newly created


threadGroup, mention some important ThreadGroup methods ?

When program starts JVM creates a ThreadGroup named main. Unless specified,
all newly created threads become members of the main thread group.

ThreadGroup is initialized with default priority of 10.

ThreadGroup important methods:-

getName():- name of ThreadGroup.

What do you mean by thread starvation?

In deadlock two threads waits for each other to release lock holded by them on
resources. There both Threads starves away to get CPU.

Can a constructor be synchronized?

No, constructor cannot be synchronized. Because constructor is used for


instantiating object, when we are in constructor object is under creation. So, until
object is not instantiated it does not need any synchronization.
What is the difference between object lock and class lock?

Difference between Object Lock and Class Lock:-

Object Lock:-

1. Thread can acquire object lock by:-

(a). Entering synchronized block or

(b). By entering synchronized methods.

2. Multiple threads may exist on same object but only one thread of that object can
enter synchronized method at a time. Threads on different object can enter same
method at same time.

3. Multiple objects of class may exist and every object has it's own lock.

4. Syntax:- public synchronized void method() {}, As soon as thread entered


Synchronization method, thread acquired object lock. Thread will leave lock when it
exits synchronized method.

Class Lock:-

1. Thread can acquire lock on class's class object by:-

(a). Entering synchronized block or

(b). By entering static synchronized methods.

2. Multiple threads may exist on same or different objects of class but only one
thread can enter static synchronized method at a time.

3. Multiple objects of class may exist but there is always one class's class object lock
available.
4. Syntax:- synchronized MyClass synchronized (MyClass.class) {}, As soon as
thread entered static Synchronization method, thread acquired lock on class's class
object. Thread will leave lock when it exits synchronized method.

Does thread leaves object lock when wait() method is called?

When wait() method is called Thread leaves the object lock and goes from running
to waiting state. Thread waits for other threads on same object to call notify() or
notifyAll() and once any of notify() or notifyAll() is called it goes from waiting to
runnable state and again acquires object lock.

Does thread leaves object lock when sleep() method is called?

When sleep() method is called Thread does not leaves object lock and goes from
running to waiting state. Thread waits for sleep time to over and once sleep time is
up it goes from waiting to runnable state.

What are daemon threads?

Daemon threads are low priority threads which runs intermittently in background for
doing garbage collection.

What is Multi-Threading in Java?

The process of executing multiple threads simultaneously is known as multi-


threading. Java supports multi-threading. The main advantage of multi-threading is
reducing CPU idle time and improving the CPU utilization. This makes the job to be
completed in less time.

What is difference between user thread and Daemon thread?

By default a thread created in a program is always a user thread, however we can


make it daemon by calling setDaemon(true) method, if needed.

A daemon thread runs in a background and it doesn’t prevent JVM from being
shutdown. Once all the user thread gets completed the JVM shutdowns without being
bothered whether a daemon thread is running or not.

What is deadlock?

A deadlock is a condition when two or more threads are in waiting for each other to
release the resources that they need.

For example :-

Thread A holds a resource (resource of A)X and need (resource of B)resource


Y whereas Thread B holds a resource Y and need X, in this case both threads are
waiting for each other to release the resource and are in blocked condition.

What is Multi-Threading in Java?

The process of executing multiple threads simultaneously is known as multi-


threading. Java supports multi-threading. The main advantage of multi-threading is
reducing CPU idle time and improving the CPU utilization. This makes the job to be
completed in less time.
Mislaneous

You might also like