Wednesday, December 2, 2020

Interview Question and Programmings


 

 
Thread Interview Questions
  1. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
  1. What is Executors Framework?
  1. What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
  1. What is Callable and Future?
Can we call run() method of a Thread class?
What is volatile keyword in Java
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
2.       public void run(){  
3.         System.out.println("running...");  
4.       }  
5.       public static void main(String args[]){  
6.        TestThreadTwice1 t1=new TestThreadTwice1();  
7.        t1.start();  
8.        t1.start();  
9.       }  
10.  }  
Test it Now
       running
       Exception in thread "main" java.lang.IllegalThreadStateException
 
 
 
RESTful with JAX-RS
 
Java OOPs
What are the main features of OOPs?
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Data Abstraction
What is dynamic polymorphism?
What is method overriding?
What is operator overloading?
Differentiate between overloading and overriding.

Overloading

Overriding

Two or more methods having the same name but different parameters or signature

Child class redefining methods present in the base class with the same parameters/ signature

Resolved during compile-time

Resolved during runtime

 

Method

Description

public final Class getClass()

returns the Class class object of this object. The Class class can further be used to get the metadata of this class.

public int hashCode()

returns the hashcode number for this object.

public boolean equals(Object obj)

compares the given object to this object.

protected Object clone() throws CloneNotSupportedException

creates and returns the exact copy (clone)

of this object.

public String toString()

returns the string representation of this

 object.

public final void notify()

wakes up single thread, waiting on this

object's monitor.

public final void notifyAll()

wakes up all the threads, waiting on this

object's monitor.

public final void wait(long timeout)throws InterruptedException

causes the current thread to wait for the

specified milliseconds, until another

thread notifies (invokes notify() or notifyAll()

method).

public final void wait(long timeout,int nanos)throws InterruptedException

causes the current thread to wait for

the specified milliseconds and nanoseconds,

until another thread notifies (invokes notify()

or notifyAll() method).

public final void wait()throws InterruptedException

causes the current thread to wait, until

another thread notifies (invokes notify() or

 notifyAll() method).

protected void finalize()throws Throwable

is invoked by the garbage collector before

object is being garbage collected.

 
 
 
 
VME : Virtual Machine error
OutOf Memory error
Linkage error
Verify Error
 
Others :
NotSerializableException’
InvalidClassException
 
 
 
ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about method overriding with exception handling. The Rules are as follows:

o    If the superclass method does not declare an exception

o    If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.

o    If the superclass method declares an exception

o    If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

If the superclass method does not declare an exception
Interview questions in java collections
What is the difference between HashSet and TreeSet?
The HashSet and TreeSet, both classes, implement Set interface. The differences between the both are listed below.
  • HashSet maintains no order whereas TreeSet maintains ascending order.
  • HashSet impended by hash table whereas TreeSet implemented by a Tree structure.
  • HashSet performs faster than TreeSet.
  • HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.
 What is the difference between HashMap and Hashtable?

No.

HashMap

Hashtable

1)

HashMap is not synchronized.

Hashtable is synchronized.

2)

HashMap can contain one null key and multiple null values.

Hashtable cannot contain any null key

or null value.

3)

HashMap is not ?thread-safe,? so it is useful for non-threaded applications.

Hashtable is thread-safe, and it can be

shared between various threads.

4)

4) HashMap inherits the AbstractMap class

Hashtable inherits the Dictionary class.

 
What does the hashCode() method?
The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by calling equals() method) are identical.
However, it is possible that two hash code numbers can have different or the same keys.
If two objects do not produce an equal result by using the equals() method, then the hashcode() method will provide the different integer result for both the objects.
19) Why we override equals() method?
The equals method is used to check whether two objects are the same or not. It needs to be overridden if we want to check the objects based on the property.
For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to check the equality of employee object by the salary. Then, we need to override the equals() method.
What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value are known as hash-collision. Two separate entries will be kept in a single hash bucket to avoid the collision. There are two ways to avoid hash-collision.
  • Separate Chaining
  • Open Addressing
 How to remove duplicates from ArrayList?
There are two ways to remove duplicates from the ArrayList.
  • Using HashSet: By using HashSet we can remove the duplicate element from the ArrayList, but it will not then preserve the insertion order.
  • Using LinkedHashSet: We can also maintain the insertion order by using LinkedHashSet instead of HashSet.
The Process to remove duplicate elements from ArrayList using the LinkedHashSet:
  • Copy all the elements of ArrayList to LinkedHashSet.
  • Empty the ArrayList using clear() method, which will remove all the elements from th
How to sort ArrayList in descending order?
To sort the ArrayList in descending order, we can use the reverseOrder method of Collections class. Consider the following example.
  1. import java.util.ArrayList;  
  1. import java.util.Collection;  
  1. import java.util.Collections;  
  1. import java.util.Comparator;  
  1. import java.util.Iterator;  
  1. import java.util.List;  
  1.   
  1. public class ReverseArrayList {  
  1. public static void main(String[] args) {  
  1.      List list = new ArrayList<>();  
  1.      list.add(10);  
  1.      list.add(50);  
  1.      list.add(30);  
  1.      list.add(60);  
  1.      list.add(20);  
  1.      list.add(90);  
  1.        
  1.      Iterator i = list.iterator();  
  1.      System.out.println("printing the list....");  
  1.      while(i.hasNext())  
  1.      {  
  1.          System.out.println(i.next());  
  1.      }  
  1.       
  1.     Comparator cmp = Collections.reverseOrder();  
  1.     Collections.sort(list,cmp);  
  1.      System.out.println("printing list in descending order....");  
  1.      Iterator i2 = list.iterator();  
  1.      while(i2.hasNext())  
  1.      {  
  1.          System.out.println(i2.next());  
  1.      }  
  1.        
  1. }  
  1. }  
Output
printing the list....
10
50
30
60
20
90
printing list in descending order....
90
60
50
30
20
10
 
 

JAVA FULLSTACK EVALUATION FORM

Candidate Name:

Date :

L1 Panel Name -

L2 Panel Name -

*Note: Please mention NE = Not Evaluated if you have not questioned candidate on particular technology.

Rating (Scale 1 :- Poor ; 2:- Average ; 3 :- Good , 4 :- Very Good, 5 :- Excellent)

Technologies

Questions Asked / Topics Covered


 

Core Java

Multithreading

Threads, Concurrent Package, Lock, Thread Pool

 

Collections

HashMap, ArrayList, HashSet, Sorting

 

 

Data Structures

LinkedList, Sorting

 

 

Algorithm

 

 

 

OOPS

Java OOP, Interface

 

 

Unit Testing

Ability to write code and unit test to maximze code coverage

 

 

Unit Testing

Knowledge of tools- Junit, Mockito, TestNG etc. (good hands on any 1-2)

 

 

Design Patterns

 

 

 

Framework

Spring 4.2 / above

IOC, DI, Spring MVC, Rest API, Security

 

 

Hibernate

Caching, Bean Mapping

 

 

Database

Data Base

SQL Server, Oracle

 

 

Web Services

SOAP

 

 

 

REST

 

 

 

UI

HTML, CSS

 

 

 

Javascript, JQUERY

 

 

 

Angular

 

 

 

Additional Skills

Microservices 

 

 

 

CI/CD

 

 

 

Analytical Skills

 

 

 

Problem Solving

 

 

 

Communication

 

 

 

Candidate Explained - module/architecture he has worked on or working on:

 

 

Additional Comments:

 

 

Final Status:

 

 

What is Comparator and Comparable ?
 
Can you use any class as a Map key?
What is the ConcurrentHashMap in Java and do you implement it?
How HashSet work internally ?
--------------------------------------------------------------------------------------------
 
 
Spring
9. What is Spring IOC Container?
What do you mean by Dependency Injection? 
In how many ways can Dependency Injection be done?
In general, dependency injection can be done in three ways, namely :
  • Constructor Injection
  • Setter Injection
  • Interface Injection
 How many types of IOC containers are there in spring?
  1. BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.
  1. ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.
14. Differentiate between BeanFactory and ApplicationContext.
BeanFactory vs ApplicationContext

BeanFactory

ApplicationContext

It is an interface defined in org.springframework.beans.factory.BeanFactory

It is an interface defined in org.springframework.context.ApplicationContext

It uses Lazy initialization

It uses Eager/ Aggressive initialization

It explicitly provides a resource object using the syntax

It creates and manages resource objects on its own

It doesn’t supports internationalization

It supports internationalization 

It doesn’t supports annotation based dependency    

It supports annotation based dependency 

 
 
How many bean scopes are supported by Spring?
The Spring Framework supports five scopes. They are:
  • Singleton: This provides scope for the bean definition to single instance per Spring IoC container.
  • Prototype: This provides scope for a single bean definition to have any number of object instances.
  • Request: This provides scope for a bean definition to an HTTP-request. 
  • Session: This provides scope for a bean definition to an HTTP-session. 
  • Global-session: This provides scope for a bean definition to an Global HTTP-session. 
What do you understand by auto wiring and name the different modes of it?
  1. no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.
  1. byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.
  1. byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file.
  1. constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters.
  1. autodetect: First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.
What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?annotations - Spring Framework Tutorial - Edureka!
@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.
@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.
@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.
·         tailed interview feedback
·         Access to exclusive and curated content
SCHEDULE NOW
 
@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.
 
Hibernate
When do you use merge() and update() in Hibernate?
This is one of the tricky Hibernate Interview Questions asked.
Q42. Difference between get() vs load() method in Hibernate?
This is one of the most frequently asked Hibernate Interview Questions. The key difference between the get() and load() method is:
So sometimes using load() can be faster than the get() method.
Q43. Difference between the first and second level cache in Hibernate? 
The first-level cache is maintained at Session level while the second level cache is maintained at a SessionFactory level and is shared by all sessions.
Q44. Difference between Session and SessionFactory in Hibernate?
This is yet another popular Hibernate Interview Question asked.
  • A Session is a single-threaded, short-lived object. It provides the first-level cache.
  • SessionFactory is immutable and shared by all Session. It also lives until the Hibernate is running. It also provides the second-level cache.
Q45. Difference between save() and saveOrUpdate() method of Hibernate?
Even though save() and saveOrUpdate() method is used to store an object into Database, the key difference between them is that save() can only Insert records but saveOrUpdate() can either Insert or Update records.
Q46. Difference between sorted and ordered collection in Hibernate?
sorted collection sort the data in JVM’s heap memory using Java’s collection framework sorting methods. The ordered collection is sorted using order by clause in the database itself.
Note: A sorted collection is more suited for small dataset but for a large dataset, it’s better to use ordered collection to avoid
Q47. Difference between the transient, persistent and detached state in Hibernate?
Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.
Persistent state: An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it’s not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.
 
Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.
Q48. Difference between managed associations and Hibernate associations?
Managed associations:  Relate to container management persistence and are bi-directional.
Hibernate Associations: These associations are unidirectional.
Q49. What are the best practices that Hibernate recommends for persistent classes?
  • All Java classes that will be persisted need a default constructor.
  • All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.
  • All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.
  • A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.
  • All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.
 
more details...
16) Is SessionFactory a thread-safe object?
Yes, SessionFactory is a thread-safe object, many threads cannot access it simultaneously.
17) What is Session?
It maintains a connection between the hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.
more details...
18) Is Session a thread-safe object?
No, Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads.
What are the different states of a persistent entity?
It may exist in one of the following 3 states:
Transient: This is not associated with the Session and has no representation in the database.
  • Persistent: You can make a transient instance persistent by associating it with a Session.
  • Detached: If you close the Hibernate Session, the persistent instance will become a detached instance.
 
 
 
 
DATABASE

Sr. No.

Key

DELETE

DROP

1

Purpose

DELETE Command, removes some or all tuples/records from a relation/table

DROP Command, removes named elements of schema like relations/table, constraints or entire schema.

2

Language

DELETE is DML.

DROP is DDL.

3

Clause

Where clause is used to add filtering.

No where clause is available.

4

Rollback

Delete command can be rollbacked as it works on data buffer.

Drop command can't be rollbacked as it works directly on data.

5

Memory Space

Table memory space is not free if all records are deleted using Delete Command.

Drop command frees the memory space.

6

Problem

DELETE command may face shortage of memory.

DROP Command may cause memory fragmentation.

6

Interaction

SQL directly interacts with database server.

PL/SQL does not directly interacts with database server.

7

Orientation

SQL is data oriented language.

PL/SQL is application oriented language.

8

Objective

SQL is used to write queries, create and execute DDL and DML statments.

PL/SQL is used to write program blocks, functions, procedures, triggers and packages.

 
 
Q #4) What is the difference between TRUNCATE & DELETE command?
Answer: Both the commands are used to remove data from the database.
The difference between the two include:
·         TRUNCATE is a DDL operation while DELETE is a DML operation.
·         TRUNCATE drops the structure of a database and hence cannot be rolled back while the DELETE command can be rolled back.
·         The TRUNCATE command will free the object storage space while the DELETE command does not.
Q #6) What is meant by Joins? List the types of Joins.
Answer: Joins are used to extract data from multiple tables using some common columns or conditions.
There are various types of Joins as listed below:
·         INNER JOIN
·         OUTER JOIN
·         CROSS JOINS or CARTESIAN PRODUCT
·         EQUI JOIN
·         ANTI JOIN
·         SEMI JOIN
 
Self_Join
 
select e.name, m.name from self_join e , self_join m where e.mid=m.empid;
+------------+---------+
| name       | name    |
+------------+---------+
| Ali        | Krishan |
| neeraj     | sanjeev |
| Krishan    | sanjeev |
| Neha Singh | sanjeev |
| Neha Saini | sanjeev |
+------------+---------+
 
 
 
 
 
 
+-------+------------+------+
| empid | name       | mid  |
+-------+------------+------+
|     1 | Ali        |    3 |
|     2 | neeraj     |    4 |
|     3 | Krishan    |    4 |
|     4 | sanjeev    | NULL |
|     5 | Neha Singh |    4 |
|     6 | Neha Saini |    4 |
1. What is a stored procedure?
    A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of operations or queries to execute on a database server.
 
+-------------+
| MAX(Salary) |
+-------------+
|       95000 |
+-------------+
 
1 row in set (0.07 sec)
 
MariaDB [test]> SELECT Min(Salary) From Perwaiz WHERE Salary > ( SELECT min(Salary) FROM Perwaiz);
+-------------+
| Min(Salary) |
+-------------+
|       75000 |
+-------------+
 
 
 
Remove Duplicate rows

 Core Java


Rest API Interview Question & Answers
HTTP methods supported by REST are:
  • GET: It requests a resource at the request URL. It should not contain a request body as it will be discarded. Maybe it can be cached locally or on the server.
  • POST: It submits information to the service for processing; it should typically return the modified or new resource
  • PUT: At the request URL it update the resource
  • DELETE: At the request URL it removes the resource
  • OPTIONS: It indicates which techniques are supported
  • HEAD: About the request URL it returns meta information
2. Mention whether you can use GET request instead of PUT to create a resource?
No, you are not supposed to use PUT for GET. GET operations should only have view rights, while PUT resource is used for updating a data.
3. Mention what are resources in a REST architecture?
Resources are identified by logical URLs; it is the key element of a RESTful design. Unlike, SOAP web services in REST, you view the product data as a resource and this resource should contain all the required information.

1.    

  public class TestThreadTwice1 extends Thread{  

What is polymorphism?

What is static polymorphism?


Exceptions

Unchecked Exception List

ArrayIndexOutOfBoundsException

ClassCastException

IllegalArgumentException

IllegalStateException

IllegalMonitorStateException

NullPointerException

NumberFormatException

IllegalThreadStateException

Error

AssertionError

ExceptionInInitializerError

StackOverflowError

NoClassDefFoundError

Checked Exception List

Exception

IOException

FileNotFoundException

ParseException

ClassNotFoundException

CloneNotSupportedException

InstantiationException

InterruptedException

NoSuchMethodException

NoSuchFieldException

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.

Different modes of bean auto-wiring are:

update(): If you are sure that the Hibernate Session does not contain an already persistent instance with the same id .

 merge():  Helps in merging your modifications at any time without considering the state of the Session.

load(): It will throw an exception if an object with an ID passed to them is not found.

get():  Will return null.

load(): It can return proxy without hitting the database unless required.

get(): It always goes to the database.


SessionFactory provides the instance of Session. It is a factory of Session. It holds the data of second level cache that is not enabled by default.

+-------+------------+------+




MariaDB [abc]> select m.name, e.name from SJ e , SJ m where m.mid=e.empid;

+---------+---------+

| name    | name    |

+---------+---------+

| Ali     | Krishan |

| Krishan | Sanjeev |

| Sanjeev | DevRaj  |

| DevRaj  | DevRaj  |

+---------+---------+



MariaDB [abc]> select * from SJ;

+-------+---------+------+

| empid | name    | mid  |

+-------+---------+------+

|     1 | Ali     |    4 |

|     4 | Krishan |    3 |

|     3 | Sanjeev |    2 |

What            is         a          Stored Procedure:


They are one or more SQL programs stored in a database as an executable object. They can be called interactively, from within a client application or from another stored procedure and from within triggers. We can pass parameters to and return from stored procedures to increase their usefulness and flexibility. A stored procedure can return a number or result set and a status code.



MariaDB [test]> SELECT MAX(Salary) From Perwaiz WHERE Salary < ( SELECT Max(Salary) FROM Perwaiz);

1. Using rowid

SQL > delete from emp

where rowid not in

(select max(rowid) from emp group by empno);

This technique can be applied to almost scenarios. Group by operation should be on the columns which identify the duplicates.


1. Mention what are the HTTP methods supported by REST?

No comments:

Post a Comment