What is Oops?
Ans.Java is built upon the Oops concept. Below is a list of some important OopsConcept.
- Abstraction is hiding implementation and showing only what is required in a class.
- Encapsulation is keeping field private and giving access through Setters and getters.
- Polymorphism is the capacity to take different forms or shapes. Method overloading(Static Binding) is an example of compile-time polymorphism and method overriding(Dynamic Binding) is for run time polymorphism.
- Inheritance in java helps us in getting properties of another class by expending the class.
What is the difference between IsA and HasA relationship in Oops?
Example of classes in java library or in JDK where abstraction is implemented?
Ans.Below are some classes available in jdk which uses abstraction .java.io.InputStream, java.io.OutputStream, java.io.Reader, java.io.Writer, java.lang.Enum, AbstractCollection, AbstractList.
What is access modifier in java?
Ans.Access modifiers or specifier in java are used to set accessibility of a class or method. There is four access modifier in java. They are as below.
- Public : This provides global access.
- Protected: Protected provides access to the classes in the package and if there are child classes outside package also.
- Default : Default modifiers are only for package.
- Private : Private modifiers apply to only inside the class.
What is the difference between Overloading and overriding?
Ans.Overloading | overriding | |
---|---|---|
Method name | No Change | No Change |
Argument List | The argument list must be different | It will no change |
Return Type | We can change | co-variant return type possible. |
Access Specifier | No Restriction | Can not override private methods, also visibility can not be decreased. |
Inheritance | Not needed | Necessary |
static, final and private | We can overload | We can not override. |
Method Resolution | At the time of compilation | At Run time by JVM based on an object reference. |
Other Name | Compile Time polymorphism | Run time Polymorphism |
What is the difference between Abstract class and Interface?
Ans.
Interface | Abstract Class |
---|---|
A class can implement multiple interfaces. | A class can extend only one class. |
An interface can have only abstract methods | Abstract Class can have abstract and nonabstract methods. |
An interface can have only static and final variables. | An abstract class can have a non-static,non-final variable as well. |
Interface members are public by default. | An abstract class can have protected, private and default as well. |
What is immutability and give an example of an immutable class?
Ans.A class whose state cannot be changed is called as an immutable class. String, Big Integer, Big decimal are examples of immutable class in java.
Advantages of immutable class:
Immutable classes are easier to design and implement also more secure.
Immutable objects are thread-safe. They do not need synchronization.
It can be shared.
The only disadvantage is each time a new object is created
Why String is immutable?
Ans.- The string is one of the most used data types in Java, String is stored in String pool and the temporary object can be shared easily.
- Security also can be 1 more concern as URL and paths we store as String, if it is mutable and can be changed by a user, that's a security threat.
- Multithreading Benefits.
How to create a custom immutable class in java?
Ans.- Declare the class as final, so it can not be extended.
- Make all fields private so direct access is not allowed.
- Do not provide setter methods, only getter methods.
- Make all mutable fields as final.
- Initialize all fields via constructor performing the deep copy.
- Perform cloning of objects in the getter methods returning copy rather than returning actual object reference.
Caching Techniques in java?
Ans.Caching is having local data storage, so retrieval is faster.
Below are a few examples of the caching technique.
- Singleton Classes: Cache data as static using Collection API.
- Java Caching APIs: Apis such as jcache.
- Http/s Session :Store in your HTTP session.
- LRU Cache: Least Recent Used is a heavily used caching technique.
What is a Singleton class in java?
Ans.A class having only one instance throughout the application is called a Singleton class. Here are the details about creating singleton class in java.
What is Hashmap? How does it work?
Ans.Hashmap works on the principle of hashing. It is a technique that divides the memory into buckets to improve the searching technique of the set. Requirements of Hashing technique:
We should override hashcode and equals method, which is present in the Object class.
Steps followed by set while adding element:
It will call the hashcode method to determine the bucket location, After getting the bucket location it will call the equals method to determine whether the element is duplicate or not, on the basis of equals methods result in it will decide whether to add an element or not.
For a detailed explanation about hashmap follow this HashMapInterviewQuestions.
What is the difference between Comparable and Comparator?
Ans.Comparable | Comparator |
---|---|
Comparable Interface is present in java.lang package. | Comparator interface is present in java.util package. |
Here we have to implement the compareTo() method in the class. | Here we have to implement a compare method in a separate class. |
Inside the compareTo method, we can write only one sorting criterion. | Here we can write multiple sorting criteria. |
Inside the compareTo method, we can write only one sorting criterion. | Here we can write multiple sorting criteria. |
This is used for the default natural sorting order. | Here we can customize sorting. |
Here we have to override only one method compareTo(). | Here we have to override both compare() and equals() method. |
All wrapper classes and String have implemented Comparable interface. | Java Collator and RuleBasedCollator have implemented compare interface. |
How to take heap dump in Java?
Ans.A Heap dump is a snapshot of all the objects that are in JVM memory. It is generally in binary format and can be analyzed using tools like Memory Analyzer(MAT) in eclipse. Below are some steps for heap dump analyzation.
jmap provides us statistics of memory in a running JVM, it can be used for local as well as remote processes.
Ex command :jmap -dump:live,format=b,file=/tmp/dump.hprof 16368
jcmd is used from the same machine where JVM is used.
jcmd 16368 GC.heap_dump E:\VM\dump.hprof
jVisualVM is a GUI tool that helps in monitor or troubleshoots, you can run in your machine directly by typing jvisualvm.
We can make java automatically collect dump when there is an OutOfMemoryError as below
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath= directory
JMX: As in jvisualvm here also we can type jconsole and get the GUI, where we can connect to the remote system also.
What is the difference between map and flat-map in java Stream?
Ans.Both map and flatMap are part of java 8 stream API, both accept a function as an input
- map() returns a transformed value, whereas flatmap() returns a stream.
- From each element of the function in map() one transformed element will be created whereas in flatmap() multiple elements will be created.
- flatmap() helps flatten a collection (List<List<T>) into a List<T>.
- Example:- If you have Arrays inside an array, map() will return arrays, whereas flatmap() will return all the elements without array inside.
Difference between Fail-fast and Fail-Safe in java?
Ans.Fail-safe: Fail-safe means if something fails on the way you will not get any CopyOnWriteArraylit or SynchronizedHashmap() are fail collection Fail-fast: In Fail-fast iterator, we will get concurrent modification exceptions. Iterator is fail-fast in nature
What is the difference between Factory and Abstract Factory Design Pattern?
Ans.- As the name suggests Abstract Factory provides an abstraction over factory pattern.
- The factory pattern uses inheritance whereas Abstract Factory used composition.
- Abstract Factory may use Factory as well as other design patterns for implementation.
What is the difference between Checked and UnChecked exception?
Checked Exception | Unchecked Exception |
---|---|
This exception gets checked during compilation by compiler. | The unchecked exception will not be checked by the compiler. |
The compiler will allow compiling without handing this exception. | The compiler will not check whether it is handled in code or not. |
A checked exception are child class of exception class. | Unchecked exception is a child of RunTimeException class. |
Example of Checked Exception are Interrupted Exception, ClassNotFoud Exception, IO Exception. | Example of unchecked exception is null pointer exception, Arithmetic Exception, ClassCast Exception, Array Index Out Of Exception. |
Difference between final, finally and finalize?
Ans.Final | Finally | Finalize |
---|---|---|
final is a keyword. | Finally, blocks used with a try, catch. | finalize() is a method. |
the final keyword is used to apply the restriction to a class, method or variable. Which tells that indicating it should not be changed. | Finally block is used after catch block which executes the code irrespective of whether an exception is there or not. | Finalize is used to perform clean up before the object is garbage collected. |
What is transient in java?
Ans.Transient is a keyword in java which marks a variable not to be serialized when it is persisted to a stream of bytes.
Also, it should be noted that a static variable also does not get serialized in java.
What is Marker Interface in java?
Ans.
Marker Interface or Tagged Interface are empty interfaces in java without any method or data member. It is a form of metadata.
Client code can test whether an object is an instance of the marker interface and adapt its (the client's) behaviour accordingly.
A marker interface is a design pattern and we can implement our own marker interface by implementing their behaviour by utility classes.
Ex: Serializable, Clonable
What are Serialization and Externalization?
Serialization and Externalization both are used to convert the object to stream byte for storing in memory.
Serialization | Externalization |
---|---|
Serialization is a marker interface. | Externalization has two abstract methods readExternal and writeExternal.It extends the Serializable interface |
This is used to serialize the whole class. | This is used if we need to customize or serialize part of the object. |
In serialization, JVM ignores transient variable. | In externalization, custom logic is written for externalization. |
JVM uses readObject and writeObject for serialization. | User needs to override readExternal and writeExternal methods. |
What is type erasure in java?
Type erasure is a process in which compiler replaces a generic parameter with the actual class.
This makes sure that there is no runtime overhead for creating those classes again.
What is the use of serialVersionUID and why should I use it?
serialVersionUID facilitates versioning of serialized data. Its value is stored with the data when serializing. When de-serializing, the same version is checked to see how the serialized data matches the current code.
SerialVersionUID is a unique identifier for each class.
ConversionConversion EmoticonEmoticon