Java Interview Materials

Q1] How to create Immutable Object
Ans:-When we declare all fields final and private.
Don't allow subclasses to oveerride methods.
We can’t add any setter method.

For Immutable Class:-
  • The class must be declared as final so that child classes can’t be created.
  • Data members in the class must be declared private so that direct access is not allowed.
  • Data members in the class must be declared as final so that we can’t change the value of it after object creation.
  • A parameterized constructor should initialize all the fields performing a deep copy so that data members can’t be modified with an object reference.
  • Deep Copy of objects should be performed in the getter methods to return a copy rather than returning the actual object reference)


Q2] Mulitple inhertance is not possible:
  Ans:- In Java, a class cannot extend more than one class. actually The reason behind this is to prevent ambiguity.

Q3] What is mean by Encapsulation?
   Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.
   Technically we say in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of its own class in which it is declared.
   As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is also known as a combination of data-hiding and abstraction.
   Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables

Q4] What is Polymorphism?

  It is means one thing represents in mulitple formate. we have 2 types of polymorphism.
   Method overloading(compile time polymorphism) and method overriding(run time polymorphism)

Q5] What is difference between overloading and overriding in java
  -Overriding means Runtime Polymorphism and Overloading means Compile time polymorphism.
  -The method Overriding occurs between superclass and subclass. Overloading occurs between the methods in the same class.
  -Overriding methods have the same signature i.e. same name and method arguments.
   Overloaded method names are the same but the parameters are different.
  -With Overloading, the method to call is determined at the compile-time. With overriding, the method call is determined at the runtime based
   on the object type.
  -If overriding breaks, it can cause effect will be visible at runtime. Whereas if overloading breaks, the compile-time error will come and it’s easy to fix.

Overloading

Overriding

Overloading means Compile time polymorphism.

Overriding means Runtime Polymorphism

Overloading occurs between the methods in the same class.

The method Overriding occurs between superclass and subclass.

Overloaded method names are the same but the parameters are different.

Overriding methods have the same signature i.e. same name and method arguments.

With Overloading, the method to call is determined at the compile-time

With overriding, the method call is determined at the runtime based on the object type.

Whereas if overloading breaks, the compile-time error will come and it’s easy to fix.

 

If overriding breaks, it can cause effect will be visible at runtime


Q6] Abstract class and Interface difference?

Abstract class

Interface

The abstract keyword is used to declare abstract class.

The interface keyword is used to declare interface.

An abstract class can be extended using keyword "extends".

An interface can be implemented using keyword "implements".

Abstract class can have abstract and non-abstract methods.

Interface can have only abstract methods. from Java 8, it can have default and static methods also.

Abstract class doesn't support multiple inheritance.

Interface supports multiple inheritance.

Abstract class can have final, non-final, static and non-static variables.

Interface has only static and final variables.

An abstract class can extend another Java class and implement multiple Java interfaces.

An interface can extend another Java interface only.

Abstract class can provide the implementation of interface.

Interface can't provide the implementation of abstract class.


Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message.

Q7] Interface with same method:

 If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable.  the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding.

Q8] Can we create constructor in interface and abstract class.

-A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created.
   -Yes! Abstract classes can have constructors!
   -we cannot have a constructor within an interface in Java. You can have only public, static, final variables interface.

Q9] Can we change value of variable in interface.

- we cannot change the variables declared in interface because by default, they are public, static and final.

Q10] **Parcelable vs serializable:
   - Serializale is Java interface and Parcelable is an Android specific interface
   - Parcelable is faster than serializable.
   - parcelable interface takes more time to implement compared to serializable interface.
   - Serializable infterface is easier to implement.
   - Serializable interface creates a lots of temporary objects, So it causes quite a bit of garbage collection. 

Q11] **Comparable and comparator differnce:
   -We can sort the collection on the basis of single element / We can sort the collection on the basis of Mutiple element
   -Comparable afffects the orignal class / Comparator dosent affect the orignal class
   -Comparable provides CompareTo() method to sort element / comaprator provides Compare() method to sort element
   -Comparable is present in java.lang package/ comaprator is present in java.utils package.

Q12] Difference between ArrayList and LinkedList

ArrayList

LinkedList

ArrayList internally uses dynamic array to store the elements

LinkedList internally uses doubly linked list to store the elements.

ArrayList search operation is pretty fast compared to the LinkedList search operation.

LinkedList search operation is slow compared to ArrayList

ArrayList element deletion is slower compared to LinkedList.

LinkedList element deletion is faster compared to ArrayList.

ArrayList element insertion is slower compared to LinkedList.

LinkedList element insertion is faster compared to ArrayList.

Memory consumption is low in ArrayList.

Memory consumption is high in LinkedList.

ArrayList class can act as a list only because it implements List only.

LinkedList class can act as a list and queue both because it implements List and Deque interfaces.

ArrayList is better for storing and accessing data.

LinkedList is better for manipulating data.


Q13] Difference between ArrayList and vector

ArrayList

Vector

ArrayList is not synchronized

Vector is synchronized.

ArrayList increments 50% of current array size if the number of elements exceeds from its capacity.

Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.

ArrayList is not a legacy class. It is introduced in JDK 1.2

Vector is a legacy class.

ArrayList is fast because it is non-synchronized.

Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object.

ArrayList uses the Iterator interface to traverse the elements.

A Vector can use the Iterator interface or Enumeration interface to traverse the elements.

 

 


Q14] Difference between HashMap and HashTable:

HashMap

Hashtable

HashMap is non synchronized.

Hashtable is synchronized.

It is not-thread safe and can't be shared between many threads without proper synchronization code.

It is thread-safe and can be shared with many threads.

HashMap allows one null key and multiple null values.

Hashtable doesn't allow any null key or value.

HashMap is a new class introduced in JDK 1.2.

Hashtable is a legacy class.

HashMap is fast.

Hashtable is slow.

We can make the HashMap as synchronized by calling this code

Map m = Collections.synchronizedMap(hashMap);

Hashtable is internally synchronized and can't be unsynchronized.

HashMap is traversed by Iterator.

Hashtable is traversed by Enumerator and Iterator.

Iterator in HashMap is fail-fast.

Enumerator in Hashtable is not fail-safe.

HashMap inherits AbstractMap class.

Hashtable inherits Dictionary class.


Q15] Difference between HashMap and ConcurrentHashMap

Parameters

HashMap

ConcurrentHashMap

Thread Safe

It is not at all thread-safe.

It always remains thread-safe.

Synchronization

It does not stay synchronized because it is not thread-safe in nature.

It stays synchronized because it is thread-safe in nature.

Null Values

It allows the keys and values to be null.

It never allows a null value or key. In such a case, it will throw the NullPointerException.

Type of Iterator

The iterator in HashMap is fail-fast. In case a modification happens (concurrently) during iteration, the HashMap throws an exception named ConcurrentModificationException.

It is pretty much fail-safe. Thus, a ConcurrentHashMap never throws any such exceptions during its iteration.

Performance

It is comparatively faster in performance than the ConcurrentHashMap.

It is comparatively much slower in performance as compared to the HashMap.

Occurrence since Java version

Version 1.2

Version 1.5


Q16] Difference between ConcurrentHashMap & HashTable

Key

HashTable

ConcurrentHashMap

Basic 

HashTable is a thread-safe legacy class introduced in the Jdk1.1

 ConcurrentHashmap is a class that was introduced in jdk1.5

Locking

It applies lock on the entire collection 

ConcurrentHashMap apply locks only at bucket level called fragment  while adding or updating the map

Performance 

It is slower than  ConcurrentHashMap

It is better than HashTable

Null

It doesn't allow null key and value

It allows null key and value


Q17] Difference between Fail Fast & Fail Safe Iterator

Fail Fast

Fail Safe

It throws a ConcurrentModificationException in modifying the object during the iteration process.

It does not throw Exception.

No clone object is created during the iteration process.

A copy or clone object is created during the iteration process.

It requires low memory during the process.

It requires more memory during the process.

It does not allow modification during iteration.

It allows modification during the iteration process.

It is fast.

It is slightly slower than Fail Fast.

HashMap, ArrayList, Vector, HashSet, etc

CopyOnWriteArrayList, ConcurrentHashMap, etc.

 

 


Q18] Difference between HashMap & HashSet

HashMap

HashSet

Hashmap is the implementation of Map interface.

Hashset on other hand is the implementation of set interface.

Hashmap internally do not implements hashset or any set for its implementation.

Hashset internally uses Hashmap for its implementation.

HashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is required for its retrieval during iteration.

HashSet stores only objects no such key value pairs maintained.

Put method of hash map is used to add element in hashmap.

On other hand add method of hashset is used to add element in hashset.

Hashmap due to its unique key is faster in retrieval of element during its iteration.

HashSet is completely based on object so compared to hashmap is slower.

Single null key and any number of null value can be inserted in hashmap without any restriction.

On other hand Hashset allows only one null value in its collection, after which no null value is allowed to be added.

Q19] Why String is Immutable or Final in Java

In object-oriented programming, the immutable string or objects that cannot be modified once it is created. But we can only change the reference to the object. We restrict to change the object itself. The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it.

The String objects are cached in the String pool, and it makes the String immutable. The cached String literals are accessed by multiple clients. So, there is always a risk, where action performs by one client affects all other clients. For example, if one client performs an action and changes the string value from Pressure to PRESSURE, all remaining clients will also read that value. For the performance reason, caching of String objects was important, so to remove that risk, we have to make the String Immutable.

Q20] What is BlockingQueue in Java

BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element

Q21] Internal Working of HashMap?

HashMap uses it's inner class Node<K,V> for storing map entries. HashMap stores entries into multiple singly linked lists, called buckets or bins. Default number of bins is 16 and it's always power of 2. HashMap uses hashCode() and equals() methods on keys for get and put operations.

In Java 8, HashMap replaces the linked list with another useful data structure i.e. binary tree on breaching a certain threshold, which is known as TREEIFY_THRESHOLD. Once this threshold is reached the linked list of Entries is converted to the TreeNodes which reduces the time complexity from O(n) to O(log(n)).

TreeNodes are nothing but the structures supporting the binary trees which have two nodes, smaller node goes to the left and the larger to the right. Whenever we want to search for any key the whole left or right subtree is discarded with a single check. This is how the time complexity is reduced to O(log(n). This change has lead to a significant improvement of HashMap.

Once the number of entries is decreased due to removal or resizing of HashMap, the structure is converted back to the older implementation which is LinkedList.

Q22] What is binary tree and its operations?

A binary tree has a special condition that each node can have a maximum of two children. A binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as fast as in linked list.

 

Q23] What is the internal working of a ConcurrentHashMap?

ConcurrentHashMap: It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance

Q24] Which of the following methods is used to avoid serialization of new class whose super class already implements Serialization?

Explanation: writeObject() and readObject() methods should be implemented to avoid Java serialization.

Q25] Singleton Class

The primary purpose of a Singleton class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection.

The memory space wastage does not occur with the use of the singleton class because it restricts the instance creation. As the object creation will take place only once instead of creating it each time a new request is made.

We can use this single object repeatedly as per the requirements. This is the reason why the multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more.

For example, there is a license with us, and we have only one database connection or suppose if our JDBC driver does not allow us to do multithreading, then Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection.

Q26] Difference between Singleton Class and Normal Class

The main difference between these two classes is an instantiation. To create an instance of a normal class, we use a constructor. On the other hand, to create an instance of a singleton class, we use getInstance() method.

Q27] Difference between String and StringBuffer

String

StringBuffer

The String class is immutable.

The StringBuffer class is mutable.

String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance.

StringBuffer is fast and consumes less memory when we concatenate the strings.

String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.

StringBuffer class doesn't override the equals() method of Object class.

String class is slower while performing concatenation operation.

StringBuffer class is faster while performing concatenation operation.

String class uses String constant pool.

StringBuffer uses Heap memory



Q28] Difference between StringBuffer and StringBuilder

StringBuffer

StringBuilder

StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

StringBuffer is less efficient than StringBuilder.

StringBuilder is more efficient than StringBuffer.

StringBuffer was introduced in Java 1.0

StringBuilder was introduced in Java 1.5


Q29] Types of ClassLoaders in Java

Not all classes are loaded by a single ClassLoader. Depending on the type of class and the path of class, the ClassLoader that loads that particular class is decided. To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException. A Java Classloader is of three types:

  • BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesnt have any parent ClassLoaders. It is also called as the Primordial ClassLoader.
  •  Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs.
  • System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader.




Java 8

 Features of Java 8:

Feature Name

Description

Lambda expression

A function that can be shared or referred to as an object.

Functional Interfaces

Single abstract method interface.

Method References

Uses function as a parameter to invoke a method.

Default method

It provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.

Stream API

Abstract layer that provides pipeline processing of the data.

Date Time API

New improved joda-time inspired APIs to overcome the drawbacks in previous versions

Optional

Wrapper class to check the null values and helps in further processing based on the value.

Nashorn, JavaScript Engine

An improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.




Q1] What are functional or SAM interfaces?

Functional Interfaces are an interface with only one abstract method. Due to which it is also known as the Single Abstract Method (SAM) interface. It is known as a functional interface because it wraps a function as an interface or in other words a function is represented by a single abstract method of the interface.

Functional interfaces can have any number of default, static, and overridden methods. For declaring Functional Interfaces @FunctionalInterface annotation is optional to use. If this annotation is used for interfaces with more than one abstract method, it will generate a compiler error.

2] Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional interface.

interface Parent {
public int parentMethod();
}
@FunctionalInterface
interface Child extends Parent {
public int childMethod();
// It will also extend the abstract method of the Parent Interface
// Hence it will have more than one abstract method
// And will give a compiler error
}

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal methods. For eg:

interface Parent {
public void parentMethod(){
System.out.println("Hello");
}
}
@FunctionalInterface
interface Child extends Parent {
public int childMethod();
}

3] What is the default method, and why is it required?

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. In case a new abstract method is added to the interface, all classes implementing the interface will break and will have to implement the new method. With default methods, there will not be any impact on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.

@FunctionalInterface // Annotation is optional 
public interface Foo() {
// Default Method - Optional can be 0 or more
public default String HelloWorld() {
return "Hello World";
}
// Single Abstract Method
public void bar();
}

4] What are static methods in Interfaces?

Static methods, which contains method implementation is owned by the interface and is invoked using the name of the interface, it is suitable for defining the utility methods and cannot be overridden.

5] What are some standard Java pre-defined functional interfaces?

Some of the famous pre-defined functional interfaces from previous Java versions are Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier, Consumer, Predicate, etc.

Runnable: use to execute the instances of a class over another thread with no arguments and no return value.

Callable: use to execute the instances of a class over another thread with no arguments and it either returns a value or throws an exception.

Comparator: use to sort different objects in a user-defined order

Comparable: use to sort objects in the natural sort order

6] What is an Optional class?

Optional is a container type which may or may not contain value i.e. zero(null) or one(not-null) value. It is part of java.util package. There are pre-defined methods like isPresent(), which returns true if the value is present or else false and the method get(), which will return the value if it is present.

static Optional<String> changeCase(String word){
if(name!=null && word.startsWith("A")){
return Optional.of(word.toUpperCase());
}else{
return Optional.ofNullable(word); // someString can be null
}
}

7] What are the advantages of using the Optional class?

 It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks, which results in better, readable, and robust code It acts as a wrapper around the object and returns an object instead of a value, which can be used to avoid run-time NullPointerExceptions

8] What are Java 8 streams?

A stream is an abstraction to express data processing queries in a declarative way.

A Stream, which represents a sequence of data objects & series of operations on that data is a data pipeline that is not related to Java I/O Streams does not hold any data permanently.

The key interface is java.util.stream.Stream<T>. It accepts Functional Interfaces so that lambdas can be passed. Streams support a fluent interface or chaining.


9] What is the difference between findFirst() and findAny()?

findFirst()

findAny()

Returns the first element in the Stream

Return any element from the Stream

Deterministic in nature

Non-deterministic in nature


10] How are Collections different from Stream?

Collections

Streams

Data structure holds all the data elements

No data is stored. Have the capacity to process an infinite number of elements on demand

External Iteration

Internal Iteration

Can be processed any number of times

Traversed only once

Elements are easy to access

No direct way of accessing specific elements

Is a data store

Is an API to process the data

11] Difference between PUT and PATCH Request

PUT

PATCH

PUT is a technique of altering resources when the client transmits data that revamps the whole resource.

PATCH is a technique for transforming the resources when the client transmits partial data that will be updated without changing the whole data.

The PUT HTTP method is known to be unchanged. That means, if you retry a request numerous times, that will be equal to a single request conversion

The PATCH HTTP method is believed to be non-idempotent. That means, if you retry the request multiple times, you will end up having multiple resources with different URIs.

The PUT method has high bandwidth.

Whereas, the PATCH method has comparatively low bandwidth.

PUT handles updates by replacing the entire entity

While PATCH only updates the fields that you give it

if we're not checking before updating anything then PUT should be faster

PATCH is faster than PUT


12] WHAT IS THE REST API means?

representational state transfer architectural style

An API, or application programming interface, is a set of rules that define how applications or devices can connect to and communicate with each other. A REST API is an API that conforms to the design principles of the REST, or representational state transfer architectural style.

13] HTTP Status Codes in the REST API

  •          200 OK. The 200 OK status code indicates the request succeeded. ...
  •          303 See Other. The 303 See Other status code indicates that you are being redirected to another resource via the "Location" response header. ...
  •          400 Bad request. ...
  •          404 Resource not found. ...
  •           500 Internal server error.

14] Difference Between Error and Exception

Error

Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of the Error class.

Exception

The term exception is shorthand for the phrase exception event. It is an event that occurs during the execution of the program and interrupts the normal flow of program instructions. These are the errors that occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by using the try-catch block and throws keyword. There are two types of exceptions i.e. checked and unchecked.

15] Design Pattern in java

Gang of 4 are those kamine who create the design patterns.

In short there are 4 people who invent this .

1] Creational Design Patterns

2]  Structural Design Pattern

3]  Behavioral Design Pattern

4]  Miscellaneous Design Pattern

1. Creational Design Pattern

  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern.

2. Structural Design Pattern

  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

3. Behavioral Design Pattern

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern

4. Miscellaneous Design Patterns

  1.        DAO Design Pattern
  2.       Dependency Injection Pattern
  3.      MVC Pattern 

What are the two types of Exceptions in Java? Which are the differences between them?

Java has two types of exceptions: checked exceptions and unchecked exceptions.

  1. Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause if they can be thrown by the execution of the method or the constructor, and propagate outside the method or constructor boundary.

  2. On the other hand, checked exceptions must be declared in a method or a constructor’s throws clause.













Comments

Popular posts from this blog

JTable Connection with JDBC-MYSQL and Pagination Over JTable

Database connection with mysql in Java