Core Java Interview
Core Java Interview
OOPs stands for Object Oriented Programming. The concepts in oops are similar to any
other programming languages. Basically, it is program agnostic.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
6. Procedural language provides less scope of code reuse but object oriented language
provides more scope of code reuse.
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.
1. Compiled Language
2. Interpreted Language
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:-
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
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.
(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.
Inside the heap memory. JVM reserves some part of the heap memory to store string
objects created using string literals.
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.
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.
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);
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.
Yes, Classes like Character, Byte, Integer, Float, Double, Long. called 'Wrapper classes'
are created as 'immutable'. Classes like Class BigInteger, BigDecimal are also.
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.
Collection is an interface while Collections is a java class , both are present in java.util
package and part of java collections framework.
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 .
Map object has unique keys each containing some value, while Set contain only unique
values.
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.
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.
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.
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.
To use any object as key in HashMap , it needs to implement equals() and hashCode()
method .
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.
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:
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.
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.
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.
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?
(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.
LinkedList store elements within a doubly-linked list data structure. ArrayList store
elements within a dynamically resizing array.
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.
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.
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.
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.
ArrayList
3. The ArrayList increases its array size by 50 percent if it runs out of room.
Vector
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.
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.
1. The Set interface provides methods for accessing the elements of a finite
mathematical set
5. Two Set objects are equal if they contain the same elements
1. HashSet is under set interface i.e. it does not guarantee for either sorted order or
sequence order.
TreeSet
1. TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
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.
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.
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.
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.
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.
(a). To send state of one or more object's state over the network through a socket.
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.
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.
SERIALIZABLE:-
(b). Serializable provides its own default serialization process, we just need to
implement Serializable interface.
(d). It provides less control over Serialization as it's not mandatory to define
readObject() and writeObject() methods.
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.
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.
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.
(e). Changing a field from static to non static OR changing transient filed to
non transient field:- it's like addition 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.
(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.
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.
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.
Serializable is a marker interface therefore you are not forced to implement any
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.
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.
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.
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.
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.
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 ?
Because it has to inspect the metadata in the bytecode instead of just using pre
compiled addresses and constants.
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.
How can you get the class object from a class name?
There are 3 ways to get the instance of Class class. They are as
follows:
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;
//.
Modifier.isPrivate(mod);
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.
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.
Types of Wildcard :-
1. Unbounded Wildcard.
2. 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.
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.
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.
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.
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.
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.
Types of wildcard:
1. Unbounded wildcard.
2. 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.
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.
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.
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.
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.
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.
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 :-
Java provides excellent support for multi-threading at the language level, and it's also
one of the strong selling points.
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.
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.
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.
No, synchronized can be used only with methods, i.e. in method declaration.
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);
When more than one thread try to access same resource without synchronization
causes race condition.
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].
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.
When program starts JVM creates a ThreadGroup named main. Unless specified,
all newly created threads become members of the main thread group.
In deadlock two threads waits for each other to release lock holded by them on
resources. There both Threads starves away to get CPU.
Object Lock:-
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.
Class Lock:-
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.
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.
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.
Daemon threads are low priority threads which runs intermittently in background for
doing garbage collection.
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 :-