Sunday, February 11, 2018

2.Java Interview Questions List For Experienced

How microservice will interact with each other? How will they come to know that particular api exist in other modules.

 New feature of java9.

 restcontroller vs controller annotation.

 Join , leftJoin and inner join.

 New string, string literal difference.

 Spring mvc architecture.

 Hashmap, hashtable difference.

 Arraylist and linkedlist difference.Why we prefer the linkedList for modification?

 Which is better to use hashtable or cuncurrentHashMap.

 Which collection you would prefer for fast fetching of data.

 String, string buffer and string builder differences.

 Reverse the no 12345.

 Javascript validation for space at first index.

 Abstraction and encapsulation difference.

 Spring xml and annotation configuration differences.

 Hibernate architecture.

 Sql queries for create table and left join.

 Set collection how check for uniqness of elements.

 Why we use Hibernate template?

 How to find the Last char in string?

 Prototype object in spring is stateless or statfull?As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

 Difference between a = a + b and a += b ?
 https://stackoverflow.com/questions/26297041/difference-between-a-b-and-a-ab-in-java 

What is upcasting and downcasting?

 There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C)?

 Read more: http://javarevisited.blogspot.com/2015/10/133-java-interview-questions-answers-from-last-5-years.html#ixzz52YB2N64Uhttps://www.javatpoint.com/downcasting-with-instanceof-operator

 ConcurrentHashMap and HashMap Difference?

 Synchronized acquire the lock on whole Map object

 ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.

 Read more: http://www.java67.com/2012/08/difference-between-hashmap-and-concurrentHashMap-java-collection.html#ixzz536Z5ksXA
http://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

 Hibernate first and secong level cache uses?
 https://www.dineshonjava.com/hibernate/cacheing-in-hibernate-first-level-and/ 

Java preparation in half hour
https://www.edureka.co/blog/interview-questions/java-interview-questions/ 

Whats the difference between Abstract class and interface?
 Read More : https://www.javatpoint.com/difference-between-abstract-class-and-interface

Differences between Factory pattern and Abstract Factory pattern?

 Circular dependency and how we can remove the circular dependency?

 PUT and POST method difference?

 How many table will be created in Many-to-Many asssociation in hibernate?

 When a concurrentModificationException is thrown and how we can handle that?

 How we can maintain session in rest web services?

 What is the Handler Mapper in Spring?

 What is dependency Injection in Spring?

 Difference between Final and Immutable object?
 https://www.geeksforgeeks.org/final-vs-immutability-java/ 

Difference between Singleton and Static?

 How we can remove duplicate values from array?

 what is thread pool?

 What is @Transaction annotaion in Spring?

 Can we implement the two different Interface having same method name and arguments in one class?
Read More: https://www.geeksforgeeks.org/two-interfaces-methods-signature-different-return-types/ 

Difference between load() and get() in Hibernate?

What is sessionFactory in hibernate?

Transaction is a Interface, SeesionFactory is a Interface,Session is a Interface.
Configuration is a class in hibernate.

Object class methods?
     List of object class methods:-
1. public Object()
2. public final Class getClass()
3. public int hashCode()
4. public boolean equals(Object obj)
5. protected Object clone() throws CloneNotSupportedException
6. public String toString()
7. public final void notify()
8. public final void notifyAll()
9. public final void wait(long timeout) throws InterruptedException
10. public final void wait(long timeout, int nanoseconds) throws InterruptedException
11. public final void wait() throws InterruptedException
12. protected void finalize() throws Throwable.

Whats the Hibernate Lifecycle Of pojo Class Objects?
Hibernate Object Lifecycle:
Actually our POJO class object having 3 states like
Transient state
Persistent state
Detached state
Transient:One newly created object,with out having any relation with the database, means never persistent,
not associated with any Session object.
Persistent:Having the relation with the database, associated with a unique Session object.
Detached:previously having relation with the database [persistent ], now not associated with any Session.

What is hbm2ddl Auto in hibernate?
http://www.onlinetutorialspoint.com/hibernate/hbm2ddl-auto-example-hibernate-xml-config.html

What is cascading in Hibernate?
Cascade attribute is mandatory, when ever we apply relationship between objects, cascade attribute transfers operations done on one object onto its related child objects If we write cascade = “all” then changes at parent class object will be effected to child class object too.
Read More: https://www.java4s.com/hibernate/hibernate-cascade-options-cascade-attribute-in-hibernate/

How Many table will be created in Many-To-Many Association in hibernate?
Read More : https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html
https://www.journaldev.com/2924/hibernate-one-to-many-mapping-annotation

What is difference between String, StringBuffer and StringBuilder? When to use them?
The main difference between the three most commonly used String classes as follows.
    StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.
    StringBuffer class implementation is synchronized while StringBuilder class is not synchronized.
    Concatenation operator "+" is internally implemented by Java using either StringBuffer or StringBuilder.
Criteria to choose among String, StringBuffer and StringBuilder
    If the Object value will not change in a scenario use String Class because a String object is immutable.
    If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
    If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
http://www.fromdev.com/2012/02/java-interview-question-answer.html


DATETIME and TIMESTAMP difference?
Answer:-
1.The supported range for DATETIME type is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.
The supported range for TIMESTAMP type is ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.
That means if you want to store date which is before the year 1970 or after the year 2038 you will need to use DATETIME.
2.MySQL converts TIMESTAMP values from the current time zone to UTC for storage,
and back from UTC to the current time zone for retrieval.This means, if your application
is such where you want time to stay absolute with respect to GMT, you must use TIMESTAMP,
or else you should use it with DATETIME.
For example, if I am using using forum, I will use TIMESTAMP as I want to capture the time when user have left comments, but if I am using an application where I have to deliver goods as per local time (and my timezone is changing),
I will use DATETIME.
In appie and soaq dona timestamp hi use kiti hai kyuki oh different time zones ch chalde pae a.
http://www.blendinfotech.com/Advance-java-interview-questions-and-answers-for-experienced

How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting.
For example: Object a; Client b; b = (Client) a;

How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super();
in the first line of the subclass's constructor.

What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

What is Collection API?
collection api is the set of classes and interfaces that provide the methods to perform the operations on collections.
Example of classes: HashMap, HashSet , Treeset, TreeMap, LinkedList,Arraylist
Example odf interfaces: List,Set, Map.

How would you make a copy of an entire Java object with its state?
By implementing clonable interface and call its clone() method.(called Deep copy).

What is Object Pool pattern?
Ans:-Object Pool Pattern says that " to reuse the object that are expensive to create".
Basically, an Object pool is a container which contains a specified amount of objects.
When an object is taken from the pool, it is not available in the pool until it is put back.
Objects in the pool have a lifecycle: creation, validation and destroy.
A pool helps to manage available resources in a better way.


How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.

Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the  data (variables) and  code acting on the data (methods) together into a single unit.
This keeps the data safe from outside interface and misuse.e.g. class is the single entity contains the member variables and member functions.

What is user defined exception?
Answer:-
    Extend the Exception class to create your own ecxeption class.
    You don't have to implement anything inside it, no methods are required.
    You can have a Constructor if you want.
    You can override the toString() function, to display customized message.
example:
public class MyOwnExceptionClass extends Exception {
private int price; 
public MyOwnExceptionClass(int price){
        this.price = price; 
}   
public String toString(){
       return "Price should not be in negative, you are entered" +price; 
 } }

public class Client {
public static void main(String[] args)throws Exception
{
   int price = -120;

   if(price < 0)
      throw new MyOwnExceptionClass(price);
   else
      System.out.println("Your age is :"+price);
   }
}


Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly:
* Memory allocation: To hold all instance variables and implementation-specific data of the object and its super classes.
* Initialization: the objects are initialized to their default values.
* Constructor: Constructors call the constructors for its super classes. This process continues until the constructor
for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
* Execution: Before the body of the constructor is executed all instance variable initializes and initialization blocks must get executed.
 Then the body of the constructor is executed.

Transient vs volatile keyboard in java?
transient variables are not serialized during Serialization process in Java while volatile variables are used
to provide alternative synchronization in Java. By using volatile keyword or modifier on fields, signals compiler
that this variable is accessed by multiple thread
1) By making a variable or field transient in a Class prevents it from being Serialized in Java.Along with static
variables, transient variables are not serialized during Serialization and they are initialized with
there default value during deserialization process e.g. an int transient variable is initialized with
zero during deserialization in Java.
2) On the other hand volatile variables are used in Concurrent programming in Java. When we declare a variable volatile,
every thread reads its value from main memory and don't used cached value available in every thread stack.
volatile variable also prevents compiler from doing reordering which can compromise synchronization.
3)Transient variables are used to prevent serialization or a field while volatile variables are used to prevent
reordering and avoid reading cached value of field in multithreaded Java program.
Important point related to volatile keyword in Java
The volatile keyword can only be applied to a variable, it can not be applied to class or method.
using volatile keyword along with class and method is a compiler error.
A volatile is also referred as modifier in Java.
When to use Volatile variable in Java
1) Any variable which is shared between multiple threads should be made variable, in order to ensure
that all thread must see the latest value of the volatile variable.
2) A signal to compiler and JIT to ensure that compiler does not change ordering
or volatile variable and moves them out of synchronized context.

DIFFERENCE BETWEEN ENCAPSULATION AND ABSTRACTION ?
Abstraction and Encapsulation in Java are two important Object oriented programming concept and they are completely different to each other.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity.
This keeps the data safe from outside interface and misuse.We define functions or variables with some access
modifier to control the extent of scope that can be used or accessed by the user.
Common examples are declaring a variable private and giving its access using getter and setter methods or declaring a
method private if it's only use is withing the class.
Abstraction is the concept of hiding irrelevant details.In other words make complex system simple by hiding the
unnecessary detail from the user.
Abstraction is implemented in Java using interface and abstract class while
We achieve data encapsulation in java by using access modifiers - Public,Protected,default,Private.
Encapsulation is combining related logic data (variables and methods) where as Abstraction is hiding internal implementation details and expose only relevant details to the user. In a way you can Abstraction is achieved by Encapsulation.

Why Should an Object Used As the Key should be Immutable?
The short answer to this question is key should be immutable so that hashCode() method  always return the same value.
Since hash code returned by hashCode() method depends upon the content of object i.e.
values of member variables. If an object is mutable than those values can change and so is the hash code.
 If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable.

String inertn() methiod?
Ans:-
To save memory (and speed up testing for equality), Java supports “interning” of Strings.
When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings.
If a String object with the same content is already in the table, a reference to the String in the table
is returned. Otherwise, the String is added to the table and a reference to it is returned.
The result is that after interning, all Strings with the same content will point to the same object.
This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.

Can you override private or static method in Java ?
Ans:- you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.

Instance method and static method? overriding and method hiding?
Instance Methods:-
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
The ability of a subclass to override a method allows a class to inherit from a superclass whose
behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name,number and type of parameters, and return type as the method that it overrides. An overriding method can alsoreturn a subtype of the type returned by the overridden method. This subtype is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one  of the superclasses, then it will generate an error. For more information on @Override, see Annotations.

Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass,
then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
 The version of the overridden instance method that gets invoked is the one in the subclass.
 The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Consider an example that contains two classes.
The first is Animal, which contains one instance method and one static method:
public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }
    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}
The Cat class overrides the instance method in Animal and hides the static method in Animal.
The main method in this class creates an instance of Cat and invokes testClassMethod() on the class
and testInstanceMethod() on the instance.
The output from this program is as follows:
The static method in Animal
The instance method in Cat

Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity.
Let's see how ambiguity may occur:
because there was problem:
    class Calculation3{
      int sum(int a,int b){System.out.println(a+b);}
      double sum(int a,int b){System.out.println(a+b);}
   
      public static void main(String args[]){
      Calculation3 obj=new Calculation3();
      int result=obj.sum(20,20); //Compile Time Error
   
      }
    }

Serialzation:
Writing to an Object Stream
Writing objects and primitives to a stream is a straightforward process. For example:
// Serialize today's date to a file.
    FileOutputStream f = new FileOutputStream("tmp");
    ObjectOutput s = new ObjectOutputStream(f);
    s.writeObject("Today");
    s.writeObject(new Date());
    s.flush();

 Reading an object from a stream, like writing, is straightforward:
// Deserialize a string and date from a file.
    FileInputStream in = new FileInputStream("tmp");
    ObjectInputStream s = new ObjectInputStream(in);
    String today = (String)s.readObject();
    Date date = (Date)s.readObject();

LazyInitialization exception and optimistical locking in hibernate?
ans:Trying to access a lazy property after a session is closed.
Code tries to access a lazy initialized collection and session is closed.
This is the most common reason of “LazyInitializationException: could not initialize proxy”.

How lazy initialization exception comes in Hibernate :
Session s = sessions.openSession();
Transaction tx = s.beginTransaction();
Employee e = (Employee) s.createQuery("from Employee e where e.name=:empName").setString("empName", eName).uniqueResult();
List roles = u.getRoles();
tx.commit();
s.close();
String role = roles.get(0); //  This line will throw error
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
   at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
   at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
   at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
Easy Solution
Use lazy=false in hibernate mapping file.

@respositroy and DAO differneces?
The DAO design pattern keeps all database access functionality in DAO classes.

Spring having bean with private constructor will spring intialize it or not?
Answer:The short answer is that Spring is using reflection to set the constructor's accessibility
to true for the purpose of instantiating it.
cg-lib (code generation lib) used by any framework to override your code.hence private consttuctor override by it.

Is null and main are the keywords in java?
Answer:The null value is not a keyword in java. true and flase are also not keywords in java.
They are reserved words in java language.
Main is not a keyword in Java. When you try to execute a java code using "java" command, the
runtime will load the public class that you are trying to execute and then call the main method
defined in the class. The runtime knows that "main" is the method to look for as it is designed that way.

Exception are checked or unchecked in spring framework?

what is serialversionUID?
Answer:During serialization, Java runtime creates a version number for a class, so that it can de-serialize it later. This version number is known as SerialVersionUID in Java.
If during de-serialization, SerialVersionUID doesn't match than process will fail with InvalidClassException as  Exception in thread "main" java.io.InvalidClassException, also printing class-name and respective SerialVersionUID.
Read more: http://javarevisited.blogspot.com/2014/05/why-use-serialversionuid-inside-serializable-class-in-java.html#ixzz4DnclrRpw
The serialVersionUID have to match during the serialization and deserialization process.
The serialization runtime associates with each serializable class a version number, called a serialVersionUID. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification.

what is Immutable class?

what is intern() method?
Ans: Java's String class has a public method intern() that returns a canonical representation for the string object.

Is session  factory a thead safe?
Ans: yes, SessionFactory is Hibernates concept of a single datastore and is threadsafe so that
 many threads can access it concurrently and request for sessions.
 A SessionFactory is usually only built once at startup.

How to get session factory object?
Ans: Configuration configuration = new Configuration();
   configuration.buildSessionFactory();
   buildSessionFactory() returns the sessionfactory object.

what type of exception are occured in spring?

How to Create bean using annotation in spring?
Ans: @bean anootaion

How to inetgare the hibernate with spring framework?
Ans: HibernateTemplate - Spring provides a class called org.springframework.orm.hibernate3.HibernateTemplate that helps in accessing the database via hibernate.
 LocalSessionFactoryBean - This is a spring factory bean that creates hibernate sessionfactory.
   
What is the difference between JDK and JRE?
Answer: Java Development Kit (JDK) is the most widely used Java Software Development Kit.
Java Runtime Environment (JRE) is an implementation of the Java Virtual Machine which executes Java programs.

What is the difference between web server and app server?
Answer: A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

difference between sendRedirect and forward in jsp servlet?
This method is used to pass the request to another resource for further processing within the same server,
another resource could be any servlet, jsp page any kind of file.
RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
  rd.forward(request, response);

This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
This method is used to redirect client request to some other location for further processing ,
the new location is available on different server or different context.
Read more: http://javarevisited.blogspot.com/2011/09/sendredirect-forward-jsp-servlet.html#ixzz4AUulopIa

What does synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at one point of time.
Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection .
Thus, in the face of concurrent modification, Fail-fast iterator can throw ConcurrentModificationException in two scenarios :
Single Threaded Environment After the creation of the iterator , structure is modified at any time by any method other than iterator's own remove method.
Multiple Threaded Environment
 If one thread is modifying the structure of the collection while other thread is iterating over it .
Fail Safe Iterator :
Fail Safe Iterator makes copy of the internal data structure (object array) and
iterates over the copied data structure.Any structural modification done to the
iterator affects the copied data structure.  So , original data structure remains
structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

How can we make Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
Where will you use Hashtable and where will you use HashMap?
The basic difference between a Hashtable and an HashMap is that,
 Hashtable is synchronized while HashMap is not.
Thus whenever there is a possibility of multiple threads accessing the same instance,
one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap.
Non synchronized data structure will give better performance than the synchronized one.
What is the Difference between Enumeration and Iterator interface?
Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(),
 next(),remove().
Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration
 interface does not support this feature.
Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration.
Iterator is returned by all Java Collections Framework classes.
java.util.Collection.iterator() method returns an instance of Iterator.


What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods.
Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting.So this should be used when you are trying to sort a list.
Arrays.sort is for arrays so the sorting is done directly on the array.
So clearly it should be used when you have a array available with you and you want to sort it.
     ArrayList    LinkedList

Implementation  Resizable Array  Douby-LinkedList

ReverseIterator  No     Yes , descendingIterator()

Initial Capacity 10     Constructs empty list

get(int) operation Fast     Slow in comparision

add(int) operation Slow in comparision Fast
Memory Overhead  No     Yes


When to Use ArrayList and LinkedList :
In real world applications , you will more frequently use ArrayList than LinkedList. But in a very specific situations
LinkedList can be preferred.
1. ArrayList is preferred when there are more get(int) or search operations need to be performed as
every search operation runtime is O(1).
2. If application requires more insert(int) , delete(int) operations than the get(int) operations
then LinkedList is preferred as they do not need to maintain back and forth like arraylist  to preserve continues indices.
String buffer and string builder.
page directives in jsp.
scriptlets in jsp.
volatile and trasient variable java.
Try with multiple catch() Exception
A extends Exception
B extends A
try{}
catch{}
catchA{}
catchB{}
inatsance method and static method and access non-static in static method and vice-versa.

Difference between throw and throws in Java?

Different ways to concatenate Strings in Java7 -
1) String Concatenation using + Operator
2) Using concat() method from java.lang.String
3) Using StringBuffer
4) Using StringBuilder
Performance comparison + Operator vs Concat vs StringBuffer vs StringBuilder
Read more: http://java67.blogspot.com/2015/05/4-ways-to-concatenate-strings-in-java.html#ixzz4AVo2O4Oz

http://www.studytonight.com/java/try-and-catch-block.php
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that exception
sub classes inside catch must come before any of their super classes otherwise it will lead to compile time error.
class Excep
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  }
  catch(Exception e)    //This block handles all Exception
  {
   System.out.println("Generic exception");
  }
  catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
  {
   System.out.println("array index out of bound exception");
  }
 }
}
java is not a pure object oriented programming becoz it support primitive types such as int,short,long etc.

Can we have multiple public classes in java source file?
answer: there can only be one public class per .java file, as public classes must have the same name as the source file.

What is composition in java?
answer: composition is design technique to implement has-a relationship in classes.
example: A emplyoee class contain the object of address object as a variable in employee class means employee has-a relationship with address object.we can use composition for code reuse.

Difference between sorted and ordered collection in hibernate?https://malliktalksjava.com/2013/02/24/difference-between-sorted-and-ordered-collection-in-hibernate/
Sorted : A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.
If your collection is not large, it will be more efficient way to sort it.
Ordered: Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it.

Differecne between Fail-Fast and fail-Safe Iterator?
Fail-Fast Iterators In Java :
All Collection types maintain an internal array of objects ( Object[] ) to store the elements.
Fail-Fast iterators directly fetch the elements from this array. They always consider that this
internal array is not modified while iterating over its elements. To know whether the collection
is modified or not, they use an internal flag called modCount which is updated each time a
collection is modified. Every time when an Iterator calls the next() method, it checks the
modCount. If it finds the modCount has been updated after this Iterator has been created,
it throws ConcurrentModificationException.
The iterators returned by the ArrayList, Vector, HashMap etc are all Fail-Fast in nature.

Fail-Safe Iterators In Java :
Fail-Safe iterators don’t throw any exceptions if the collection is modified while iterating over it.
Because, they iterate on the clone of the collection not on the actual collection. So, any
structural modifications done on the actual collection goes unnoticed by these iterators.
But, these iterators have some drawbacks. One of them is that it is not always guaranteed that
you will get up-to-date data while iterating. Because any modifications to collection after the
iterator has been created is not updated in the iterator. One more disadvantage of these
iterators is that there will be additional overhead of creating the copy of the collection in terms
of both time and memory.
Iterator returned by ConcurrentHashMap is a fail-safe iterator.
http://javaconceptoftheday.com/fail-fast-and-fail-safe-iterators-in-java-with-examples/amp/

Difference between JDBC Statement vs PreparedStatement ?
DDL : Full form of DDL is Data Definition Language. It is used to create and database objects
 in a database.Eg: CREATE, ALTER, DROP.
DML: Full form of DML is Data Manipulation Language.
 It is used to retrieve, store, modify, delete, insert and update data in database.
 Eg: INSERT, UPDATE, DELETE,SELECT
Read More: https://www.journaldev.com/2489/jdbc-statement-vs-preparedstatement-sql-injection-example

What is the difference between implementing runnable and extending thread?
By implementing Runnable, multiple threads can share an instance of your work.
If you extended Thread, you'd have to create a new instance of your work for each thread.

Read More: https://www.quora.com/In-Java-threading-what-is-the-difference-between-implements-Runnable-and-extends-Thread


How do I remove repeated elements from ArrayList?
The easiest way to remove repeated elements is to add the contents to a
Set (which will not allow duplicates) and then add the Set back to the ArrayList:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);
Read More: https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist

How to pass parameters from one jsp page to other jsp page?
There is some way to do this
1.Using Query parameter

 <a href="edit.jsp?userId=${user.id}" />
Then you can read that parameter with on the second page.

 request.getParameter("userId")
2.Using Hidden variable

<form method="update.jsp" action="post"> 

<input type="hidden" name="userId" value="${user.id}">

</form>
3.Using Session object

session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");

List contain the emp name "xyz" mutiple times how we can remove that from list?
Iterate the listadd elements into some other collection except the "xyz" using
 if(!item.equals("xyz"))

inside for loop.


When to use Set and When to use List?
The usage is purely depends on the requirement:If the requirement is to have only unique values then Set is your best bet as any implementation of Set maintains unique values only.

If there is a need to maintain the insertion order irrespective of the duplicity then List is a best option. Both the implementations of List interface – ArrayList and LinkedList sorts the elements in their insertion order.

Difference between Singleton Pattern vs Static Class in Java?

When to use Singltone and static methods?
Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz55viwXhKK
A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance.
A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object.
Static class is a Java class, which only contains static methods, good examples of static class is java.lang.Math,which contains lots of utility methods for various maths function e.g. sqrt(). While Singleton classes are those, which has only one instance during application life cycle like java.lang.Runtime.

Difference between BeanFactory and ApplicationContext?
BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC.
Although BeanFactory and ApplicationContext both are used to get the beans from IOC
container by using method getBean(String beanName). But they have some significant

differences in their implementation which are described as below :
1. BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager
initialization approach.i.e BeanFactory creates a singleton bean only when it is requested
from it but ApplicationContext creates all singleton beans at the time of its own initialization.
2. ApplicationContext creates and manages resources objects on its own whereas
BeanFactory used to be explicitly provided a resource object using the syntax :

<span style="font-size:16px;"><span style="font-family:arial,helvetica,sans-serif;">    ClassPathResource resource = new ClassPathResource("beans.xml"); 
 XmlBeanFactory factory = new XmlBeanFactory(resource);
 // Here resource object is provided explicitly</span></span>

3. ApplicationContext supports internationalization but BeanFactory do not.
4. Annotation based dependency Injection is not supported by BeanFactory whereas
 ApplicationContext supports using annotation @PreDestroy, @Autowired.

Read More: http://www.oodlestechnologies.com/blogs/Difference-between-BeanFactory-and-ApplicationContext

Update and merge difference?
https://www.java4s.com/hibernate/difference-between-merge-and-update-methods-in-hibernate/
Let Us Take An Example
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();
s1.setMarks(97);
Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();
session2.merge(s1);
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();

Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();

s1.setMarks(97);

Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();

session2.merge(s1);
Explanation
See from line numbers 6 – 9, we just loaded one object s1 into session1 cache and closed session1 at line number 9,
 so now object s1 in the session1 cache will be destroyed as session1 cache will expires when ever we say session1.close()
Now s1 object will be in some RAM location, not in the session1 cache
here s1 is in detached state, and at line number 11 we modified that detached object s1,
 now if we call update() method then hibernate will throws an error, because we can update
the object in the session only
So we opened another session [session2] at line number 13,
and again loaded the same student object from the database, but with name s2
so in this session2, we called session2.merge(s1); now into s2 object s1 changes
will be merged and saved into the database
Hope you are clear…, actually update and merge methods will come into picture when ever we
loaded the same object again and again into the database, like above.

What is the difference between save and persist in Hibernate?
Here is the difference between save and persist method:
1. First difference between save and persist is there return type. The return type of persist method is void while return type of save method is Serializable object. But bot of them also INSERT records into database
2. Another difference between persist and save is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.
3. Third difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.
4. Fourth difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
5. Read More: https://www.quora.com/What-is-the-difference-between-save-and-persist-in-Hibernate

What is maven-install and maven-deploy?
https://stackoverflow.com/questions/7531115/whats-the-difference-between-mvndeploy-and-mvninstall-commands

Whats artifact-id and group-id in maven?
artifactId is the name of the jar without version. If you created
it then you can choose whatever name you want with lowercase letters and no
strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.
eg. maven, commons-math
groupId will identify your project uniquely across all projects, so we need to enforce a naming
 schema. It has to follow the package name rules, what means that has to be at least as a
domain name you control, and you can create as many subgroups as you want. Look at More
 information about package names. eg. org.apache.maven, org.apache.commons

What os Covariant return types in Java?

Ambiguous overloaded method call?
http://javabypatel.blogspot.com/2016/05/ambiguous-method-overloading.html

Wednesday, February 7, 2018

3.Java Interview Questions List For Experienced

How do I remove repeated elements from ArrayList?
The easiest way to remove repeated elements is to add the contents to a
Set (which will not allow duplicates) and then add the Set back to the ArrayList:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);
Read More: https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist

 <a href="edit.jsp?userId=${user.id}" />
 request.getParameter("userId")
</form>
int userid = session.getAttribute("userId");

When to use Set and When to use List?
The usage is purely depends on the requirement:If the requirement is to have only unique values then Set is your best bet as any implementation of Set maintains unique values only.

If there is a need to maintain the insertion order irrespective of the duplicity then List is a best option. Both the implementations of List interface – ArrayList and LinkedList sorts the elements in their insertion order.

Difference between Singleton Pattern vs Static Class in Java?

When to use Singltone and static methods?

Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz55viwXhKK

A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance.

A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object.
Static class is a Java class, which only contains static methods, good examples of static class is java.lang.Math,which contains lots of utility methods for various maths function e.g. sqrt(). While Singleton classes are those, which has only one instance during application life cycle like java.lang.Runtime.

<span style="font-size:16px;"><span style="font-family:arial,helvetica,sans-serif;">    ClassPathResource resource = new ClassPathResource("beans.xml"); 
XmlBeanFactory factory = new XmlBeanFactory(resource);
// Here resource object is provided explicitly</span></span>

3. ApplicationContext supports internationalization but BeanFactory do not.
4. Annotation based dependency Injection is not supported by BeanFactory whereas
 ApplicationContext supports using annotation @PreDestroy, @Autowired.

Read More: http://www.oodlestechnologies.com/blogs/Difference-between-BeanFactory-and-ApplicationContext

Update and merge difference?
https://www.java4s.com/hibernate/difference-between-merge-and-update-methods-in-hibernate/

Let Us Take An Example
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();
s1.setMarks(97);
Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();
session2.merge(s1);
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();

Student s1 = null;
Object o = session1.get(Student.class, new Integer(101));
s1 = (Student)o;
session1.close();

s1.setMarks(97);

Session session2 = factory.openSession();
Student s2 = null;
Object o1 = session2.get(Student.class, new Integer(101));
s2 = (Student)o1;
Transaction tx=session2.beginTransaction();

session2.merge(s1);
Explanation
See from line numbers 6 – 9, we just loaded one object s1 into session1 cache and closed session1 at line number 9,
 so now object s1 in the session1 cache will be destroyed as session1 cache will expires when ever we say session1.close()
Now s1 object will be in some RAM location, not in the session1 cache
here s1 is in detached state, and at line number 11 we modified that detached object s1,
 now if we call update() method then hibernate will throws an error, because we can update
the object in the session only
So we opened another session [session2] at line number 13,
and again loaded the same student object from the database, but with name s2
so in this session2, we called session2.merge(s1); now into s2 object s1 changes
will be merged and saved into the database
Hope you are clear…, actually update and merge methods will come into picture when ever we
loaded the same object again and again into the database, like above.

What is the difference between save and persist in Hibernate?

Here is the difference between save and persist method:

1. First difference between save and persist is there return type. The return type of persist method is void while return type of save method is Serializable object. But bot of them also INSERT records into database
2.Another difference between persist and save is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.
3. Third difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.
4.Fourth difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
5. Read More: https://www.quora.com/What-is-the-difference-between-save-and-persist-in-Hibernate

What is maven-install and maven-deploy?
mvn:install copies your packaged Maven module to your local repository (by default, in ~/.m2/repository), to be accessed by other local Maven builds.

mvn:deploy uploads your packaged Maven module to another (usually remote) repository, to be accessed by other, not necessarily local, Maven builds.
https://stackoverflow.com/questions/7531115/whats-the-difference-between-mvndeploy-and-mvninstall-commands

Whats artifact-id and group-id in maven?
artifactId is the name of the jar without version. If you created
it then you can choose whatever name you want with lowercase letters and no
strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.
eg. maven, commons-math

groupId will identify your project uniquely across all projects, so we need to enforce a naming
 schema. It has to follow the package name rules, what means that has to be at least as a
domain name you control, and you can create as many subgroups as you want. Look at More
 information about package names. eg. org.apache.maven, org.apache.commons
@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.
By using that annotation we do two things, first we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup. This latter property is used by web-specific tools and functionalities.
For example, DispatcherServlet will look for @RequestMapping on classes which are annotated using @Controller but not with @Component.
This means @Component and @Controller are same with respect to bean creation and dependency injection but later is a specialized form of former. Even if you replace @Controller annotation with @Compoenent, Spring can automatically detect and register the controller class but it may not work as you expect with respect to request mapping.
By using a specialized annotation we hit two birds with one stone. First, they are treated as Spring bean and second you can put special behavior required by that layer.

Though for that you also need to declare org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor as Spring bean in your application context.This bean post processor adds an advisor to any bean that’s annotated with @Repository so that any platform-specific exceptions are caught and then rethrown as one of Spring’s unchecked data access exceptions.

How to Create an Immutable Class in Java?
Declare the class as final so it can’t be extended.
Make all fields private so that direct access is not allowed.
Don’t provide setter methods for variables
Make all mutable fields final so that it’s value can be assigned only once.
Initialize all the fields via a constructor performing deep copy.
Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
Read More:
https://www.journaldev.com/129/how-to-create-immutable-class-in-java
https://dzone.com/articles/how-to-create-an-immutable-class-in-java

Difference between like and ilike in hibernate criteria?
"ilike" is for case-sensitive,

Criteria cr = session.createCriteria(Employee.class);
"like" is for case-insensitive,
// To get records having fistName starting with zara
cr.add(Restrictions.like("firstName", "zara%"));

// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));

What is Projection in Hibernate?
The projections concept is introduced in hibernate 3.0 and mainly we can do the following 2 operations using the projection.
We can load partial object from the database
We can find the Result of Aggregate functions

Projection is an Interface given in “org.hibernate.criterion” package, Projections is an class given in same package,  actually Projection is an interface, and Projections is an class and is a factory for producing projection objects.
Using criteria, if we want to load partial object from the database, then we need to create a projection object for property that is to be loaded from the database

Example:
Criteria crit = session.createCriteria(Products.class);
crit.setProjection(Projections.proparty("proName"));
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
String s = (String)it.next();
}

If we add multiple projections to criteria then the last projection added will be considered to execute see…
Example:
Criteria crit = session.createCriteria(Products.class);

Projection p1 = Projection.property("proName");
Projection p2 = Projection.property("price");

crit.setProjection(p1):
crit.setProjection(p2):
List l=crit.list();
Read More: https://www.java4s.com/hibernate/working-with-hibernate-projections-in-criteria/
HQL is to perform both select and non-select operations on the data,  but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
Criteria used to take more time to execute then HQL
With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

Named queries in hibernate is a technique to group the HQL statements in single location, and lately refer them by some name whenever need to use them.
NamedQuery is the way you define your query by giving it a name.
They can be accessed and used from several places which increase re-usability.

Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client.
We can also write plain SQl queries in a similar manner as follows:
@NamedNativeQueries({
 @NamedNativeQuery(
 name = "findEmployeeByIdNativeSQL",
 query = "select * from Employee_details where emp_id = :passId",
 resultClass = Employee.class
 )
})
In native SQL, you have to declare the ‘resultClass‘ to let Hibernate know what is the return type, failed to do it will caused the exception. Also notice that we are using actual table and column name in DB here.
Read More:https://djcodes.wordpress.com/databases/hibernate-need-and-setup/hibernate-named-query-and-criteria/
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc.
Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.

Comparable affects the original class i.e. actual class is modified.
Comparator doesn't affect the original class i.e. actual class is not modified.

Comparable provides compareTo() method to sort elements.
Comparator provides compare() method to sort elements.

Comparable is found in java.lang package.
Comparator is found in java.util package.

We can sort the list elements of Comparable type by Collections.sort(List) method.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.

Read More: http://javarevisited.blogspot.in/2011/06/comparator-and-comparable-in-java.html
https://www.journaldev.com/780/comparable-and-comparator-in-java-example

Which is more secured session or cookies in jsp?
Sessions are server-side files that contain user information, while Cookies are client-side files that
contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

"passing it in a URL (which poses a security risk)." actually both approach have security risks (different ones).

SLF4J vs LOG4J Which one to prefer?
SLF4J is basically an abstraction layer. It is not a logging implementation. It means that if you're writing a library and you use SLF4J, you can give that library to someone else to use and they can choose which logging implementation to use with SLF4J e.g. log4j or the Java logging API. It helps prevent projects from being dependent on lots of logging APIs just because they use libraries that are dependent on them.
So, to summarise: SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your library/app.
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.
Read More: https://www.slf4j.org/manual.html

Which annotation is used at time of startup to do something immediately after the bean’s initialization?
The @PostConstruct and @PreDestroy annotation are not belong to Spring, it’s located in the J2ee library – common-annotations.jar.

By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in bean configuration file,

@PostConstruct annotation is same as "init-method" we configure in the bean.xml
@PreDestroy annotation is sam eas "destroy-method" we configure in the bean.xml

<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
  <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
    <property name="message" value="i'm property message" />
  </bean>
</beans>

ReadMore: https://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/

JAVA8 New Features?

Stream API
lambda expressions
Functional interfaces
Interface Default and Static Methods
Method References : Reference to a Static Method, Reference to an Instance Method,  Reference to a Constructor.
Optional<T> class: Before Java 8 developers had to carefully validate values they referred to, because of a possibility of throwing the NullPointerException (NPE). All these checks demanded a pretty annoying and error-prone boilerplate code.
Java 8 Optional<T> class can help to handle situations where there is a possibility of getting the NPE. It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.
Collectors class
Collection API improvements:
Some new methods added in Collection API are:Map replaceAll(), compute(), merge() methods.
forEach() method
Java Nashorn
Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.
You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.
StringJoiner
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc.
Miscellaneous Core API improvements
PermGen memory space has been removed.
Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
min(), max() and sum() methods in Integer, Long and Double wrapper classes.
logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
Several utility methods in Math class.
Read More: 
https://www.javatpoint.com/java-8-features
https://www.journaldev.com/2389/java-8-features-with-examples

What is Predicate in java8?
java.util.function.Predicate is a functional interface that can be used as assignment target for lambda expression. The Predicate interface represents an operation that takes a single input and returns a boolean value.
public class PredicateExample1 {
public static void main(String[] args) {

//Predicate String
Predicate<String> predicateString = s -> {
return s.equals("Hello");
};

System.out.println(predicateString.test("Hello"));
System.out.println(predicateString.test("Hello World"));

//Predicate integer
Predicate<Integer> predicateInt = i -> {
return i > 0;
};

System.out.println(predicateInt.test(5));
System.out.println(predicateInt.test(-5));
}
}
Output:
true
false
true
false
Read More: https://www.boraji.com/java-8-predicate-example

Java program to find the counts of each character in a String?
Solution :
1. First get the string.
2. Create one hashmap with key as ‘character’ and value as ‘integer’ .
 Count of each character will be stored as value with key as the character.
3. Scan the string character by character.
4. Check for each character : if no key equals to the character is available in the hashmap ,
 add one new key as the character and value as 1.
5. If key is available, increment the value by one.

Example:
for (int i=0; i<line.length(); i++){
            if(map.containsKey(line.charAt(i))){
                value = map.get(line.charAt(i));
                value ++;
                map.put(line.charAt(i),value);
            }else{
                map.put(line.charAt(i),1);
            }
        }
       
Read More: http://www.codevscolor.com/2017/08/java-count-character-string/

How set collection check element exist or not?
Adding elements to a Set:
The add()method returns true if the set does not contain the specified element, and returns false if the set already contains the specified element:

Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");

if (names.add("Peter")) {
    System.out.println("Peter is added to the set");
}

if (!names.add("Tom")) {
    System.out.println("Tom is already added to the set");
}


Search Algorithm to find particular element in an array.

https://www.geeksforgeeks.org/linear-search-vs-binary-search/
https://www.geeksforgeeks.org/binary-search-preferred-ternary-search/

Remove Duplicate value from array using array only/
https://www.javatpoint.com/java-program-to-remove-duplicate-element-in-an-array

What is the return type of HashmAp put method?
The method put has a return type same with the value:
@Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }
It returns the previous value associated with key if key exist, or null if key does not exist and then it put the value into map .

How set uses the map internally?
In HashSet add(e) method, the return value of map.put(key,value) method will be checked with null value.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

How rest Api convert the request an response and do the mapping?
@ResponseBody
In Spring MVC, @ResponseBody annotation on a AccoutnController method indicates to Spring that the return Account object of
 the method is serialized to JSON directly to the body of the HTTP Response. It uses “Accept” header to choose the appropriate
 Http Converter to marshall the object.
 header "Accept: application/json"

@RequestBody
In Spring MVC, @RequestBody annotation on the argument of a AccountController method create (@RequestBody Account account)
– it indicates to Spring that the body of the HTTP Request (either in JSON or XML) is deserialized to that Account Java Object.
 It uses “Content-Type” header specified by the REST Client will be used to determine the appropriate converter for this.
 Content-Type: application/json

Example:
@RequestMapping(method=RequestMethod.PUT, value="/foos/{id}")
public @ResponseBody void updateFoo(
  @RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}
Read More: https://www.dineshonjava.com/customizing-httpmessageconverter-with-spring-mvc-in-rest/

The Default Message Converters
By default, the following HttpMessageConverters instances are pre-enabled:
ByteArrayHttpMessageConverter – converts byte arrays
StringHttpMessageConverter – converts Strings
ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
SourceHttpMessageConverter – converts javax.xml.transform.Source
FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)
MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)
Read More : http://www.baeldung.com/spring-httpmessageconverter-rest

Try/Catch example with return value?
Whenever try block executes successfully, then it can return value for this method from try block
Similarly, if any exception is raised then exception gets caught in the catch block & it can also return value (from catch block)
Since, we have finally block returning value therefore returning value from try or catch block will be overridden by return statement in the finally block
Because, on all cases finally block gets executed irrespective of exception is raised or NOT & it is handled or NOT inside catch block. Therefore, overriddes any return value from try-block or catch-block
This is called overridden case
Error: any statement after finally block in this example, will result in compile-time error stating “Unreachable code”

public static int myTestingFuncn(){
  try{
     ....
     return 5;
  }Catch{
  ...
  return 1;
  }
  finally {
     ....
     return 19;
   }
}

This program would return value 19 since the value returned by try/Catch has been overridden by finally.
Read More: http://www.benchresources.net/returning-value-from-method-having-try-catch-finally-blocks-in-java/

which method of preparedstatemrnt is used to store java object?
Ans: void setObject(int parameterIndex, Object x)
Sets the value of the designated parameter using the given object.

Which of the following methods will you use to find the maximum number of connection that a specific driver can obtain?
Database.getMaxConnection
Connection.getMaxConnection
DatabaseMetaData.getMaxConnection
ResultSetMetaData.getMaxConnection
Ans: DatabaseMetaData.getMaxConnection.

what is motivation behind command design pattern?
Motivation. "Sometimes it is necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request."

Registry services such as managing information about service providers, service implementations and service metadata is provided by

WSDL
UDDI
REST
SPARQL
Ans: UDDI

where @ignore  annotation is apply , so that code complies?
which of the following Database driver is used to connect javascript code to RDBMS?

What is a Slowly Changing Dimension?
A Slowly Changing Dimension (SCD) is a dimension that stores and manages both current and historical data over time in a data warehouse. It is considered and implemented as one of the most critical ETL tasks in tracking the history of dimension records.

Difference between "==" and "===" operator ?
is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn't allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type "===" return false, while "==" return true.
Read more: http://www.java67.com/2013/07/difference-between-equality-strict-vs-operator-in-JavaScript-Interview-Question.html#ixzz59by0nn1c

Object and class in java?
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.

‘Null’ in JavaScript
‘Null’ is a keyword in JavaScript that signifies ‘no value’ or nonexistence of any value. If you wish to shred a variable off its assigned value, you can simply assign ‘null’ to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript.
An example of explicit null assignment is –
var some_item= null;
console.log(some_item)
Upon execution, the code will print null.

‘Undefined’ in JavaScript
‘Undefined’ is a global variable that JavaScript creates at run time. This global variable is assigned to an object in one of the following cases –
1. Declared but not defined –
JavaScript assigns ‘undefined’ to any object that has been declared but not initialized or defined. In other words, in a case where no value has been explicitly assigned to the variable, JavaScript calls it ‘undefined’.
2. Array index or object property that does not exist.
3. A function parameter that has not been supplied.
4. The return value of functions that have to but don’t return a value.

Sunday, February 4, 2018

HIbernate Interview Questions List For Experienced

What are the advantages of Hibernate over JDBC? (detailed answer)
Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides following benefits
1) Caching
2) Lazy Loading
3) Relationship management and provides code for mapping an object to the data
4) The developer is free from writing code to load/store data into the database.


Difference between get() vs load() method in Hibernate? (detailed answer)
This is one of the most frequently asked Hibernate interview question, I have seen it several times. The key difference between get() and load() method is that load() will throw an exception if an object with id passed to them is not found, but get() will return null. Another important difference is that load can return proxy without hitting the database unless required (when you access any attribute other than id) but get() always go to the database, so sometimes using load() can be faster than the get() method. It makes sense to use the load() method if you know the object exists but get() method if you are not sure about object's existence.

What is N+1 SELECT problem in Hibernate? (detailed answer)
The N+1 SELECT problem is a result of lazy loading and load on demand fetching strategy. In this case, Hibernate ends up executing N+1 SQL queries to populate a collection of N elements. For example, if you have a List of N Items where each Item has a dependency on a collection of Bid object. Now if you want to find the highest bid for each item then Hibernate will fire 1 query to load all items and N subsequent queries to load Bid for each item. So in order to find the highest bid for each item your application end up firing N+1 queries.  It's one of the important Hibernate interview questions and I suggest to read chapter 13 of Java Persistence with Hibernate to understand this problem in more details.

What are some strategies to solve the N+1 SELECT problem in Hibernate? (detailed answer)
This is the follow-up question of previous Hibernate interview question. If you answer the last query correctly then you would be most likely asked this one. Here are some strategies to solve the N+1 problem:
1) pre-fetching in batches, this will reduce N+1 problem to N/K + 1 problem where  K is size of batch
2) subselect fetching strategy
3) disabling lazy loading


What is the difference between save() and persist() method in Hibernate? (detailed answer)
Main difference between save() and persist() method is that, save returns a Serializable object while return type of persist() method is void, so it doesn't return anything. Here is a nice diagram which explains the state transition in Hibernate:


What is the requirement for a Java object to become Hibernate entity object?
It should not be final and must provide a default, no-argument constructor. Becasue
hibernate uses reflection Class<T>.newInstance() to create a new instance of your classes and reflection requiring a no-arg constructor.


What are different types of caches available in Hibernate? (detailed answer)
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.


What is the difference between first and second level cache in Hibernate? (detailed answer)
This is again follow-up of previous Hibernate interview question. The first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions. You can read these books to learn more about caching in Hibernate.


Does Hibernate Session interface is thread-safe in Java? (detailed answer)
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.


Does SessionFactory is thread-safe in Hibernate? (detailed answer)
SessionFactory is both Immutable and thread-safe and it has just one single instance in Hibernate application. It is used to create Session object and it also provide caching by storing SQL queries stored by multiple session. The second level cache is maintained at SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.


What is different between Session and Sessionfactory in Hibernate? (detailed answer)
This is another popular Hibernate interview question, mostly at a telephonic round of interviews. The main difference between Session and SessionFactory is that former is a single-threaded, short-lived object while later is Immutable and shared by all Session. It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that former provides first level cache while SessionFactory provides the Second level cache.


What is criterion query in hibernate? (detailed answer)
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:

List books = session.createCriteria(Book.class)
.add(Restrictions.like("name", "java%") )
.add(Restrictions.like("published_year", "2015"))
.addOrder(Order.asc("name") )
.list();
This can be a tough question if you are not using Hibernate on a daily basis, I have interviewed several Java developers who have used Hibernate but doesn't know about Criterion query or API.


What are other ORM frameworks? Any alternative of Hibernate?
This is a general question, sometimes asked to start the conversation and other times to finish the interview. EJB and TopLink from Oracle are two of the most popular alternative to Hibernate framework.


What is the difference between save() and saveOrUpdate() method of Hibernate? (detailed answer)
Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.


What is difference between getCurrentSession() and openSession() in Hibernate? (detailed answer)
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance of Session object. I have left this question unanswered for you to answer or find an answer based on your experience.


What is Hibernate Query Language (HQL)? (detailed answer)
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.


When do you use merge() and update() in Hibernate? 
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session. See Java Persistence with Hibernate for more details.

The difference between sorted and ordered collection in Hibernate?
The main difference between sorted and ordered collection is that sorted collection sort the data in JVM's heap memory using Java's collection framework sorting methods while ordered collection is sorted using order by clause in the database itself. A sorted collection is more suited for small dataset but for a large dataset, it's better to use ordered collection to avoid OutOfMemoryError in Java application.

How do you log SQL queries issued by the Hibernate framework in Java application?
You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:

<property name=”show_sql”> true </property>

What are the three states of a Hibernate Persistence object can be? (detailed answer)
The Hibernate persistent or entity object can live in following three states:
1) transient
2) persistent
3) detached

What is the difference between the transient, persistent and detached state in Hibernate? (detailed answer)
New objects created in Java program but not associated with any hibernate Session are said to be in the transient state. On the other hand, 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. Similarly, you can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.

Which cache is used by Session Object in Hibernate? First level or second level cache? (detailed answer)
A Session object uses the first-level cache. As I told before the second level cache is used at SessionFactory level. This is a good question to check if Candidate has been working in hibernate or not. If he has not worked in Hibernate from a long time then he would get confused in this question.

Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:

SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it’s required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.

Name some important annotations used for Hibernate mapping?
Hibernate supports JPA annotations and it has some other annotations in org.hibernate.annotations package. Some of the important JPA and hibernate annotations used are:

javax.persistence.Entity: Used with model classes to specify that they are entity beans.
javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
javax.persistence.Id: Used to define the primary key in the entity bean.
javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
javax.persistence.Column: Used to define the column name in database table.
javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
org.hibernate.annotations.Cascade: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with org.hibernate.annotations.CascadeType
javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with org.hibernate.annotations.GenericGenerator and org.hibernate.annotations.Parameter
Here are two classes showing usage of these annotations.
import org.hibernate.annotations.Cascade;

@Entity
@Table(name = "EMPLOYEE")
@Access(value=AccessType.FIELD)
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private long id;

@Column(name = "emp_name")
private String name;

@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;

//getter setter methods
}
package com.journaldev.hibernate.model;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {

@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
private long id;

@Column(name = "address_line1")
private String addressLine1;

@OneToOne
@PrimaryKeyJoinColumn
private Employee employee;

//getter setter methods
}


What is difference between openSession and getCurrentSession?
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.

<property name="hibernate.current_session_context_class">thread</property>
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.

There is another method openStatelessSession() that returns stateless session,


How to configure Hibernate Second Level Cache using EHCache?
EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.

Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars.
<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.3.5.Final</version>
</dependency>
Add below properties in hibernate configuration file.
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
       
<!-- For singleton factory -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
-->
       
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
Create EHCache configuration file, a sample file myehcache.xml would look like below.
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">

    <diskStore path="java.io.tmpdir/ehcache" />

    <defaultCache maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
        maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU" statistics="true">
        <persistence strategy="localTempSwap" />
    </defaultCache>

    <cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="5" timeToLiveSeconds="10">
        <persistence strategy="localTempSwap" />
    </cache>

    <cache name="org.hibernate.cache.internal.StandardQueryCache"
        maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
        <persistence strategy="localTempSwap" />
    </cache>

    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
        maxEntriesLocalHeap="5000" eternal="true">
        <persistence strategy="localTempSwap" />
    </cache>
</ehcache>
Annotate entity beans with @Cache annotation and caching strategy to use. For example,
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "ADDRESS")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {

}


What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.

Bag
Set
List
Array
Map

Why we should not make Entity Class final?
Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

Can we execute native sql query in hibernate?
Hibernate provide option to execute native SQL queries through the use of SQLQuery object.

For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching. Read more at Hibernate Native SQL Query Example.


What is the benefit of native sql query support in hibernate?
Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.


What is Named SQL Query?
Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL.

Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.


What are the benefits of Named SQL Query?
Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code.
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries.
Hibernate Named Query is global, means once defined it can be used throughout the application.

However one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.


What is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach.

Some of the common usage of Criteria API are:

Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
Criteria API can be used with ProjectionList to fetch selected columns only.
Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
Criteria API provides addOrder() method that we can use for ordering the results.

How transaction management works in Hibernate?
Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session beginTransaction() to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction.

Overall hibernate transaction management is better than JDBC transaction management because we don’t need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.

What is Hibernate proxy?
Mapping of classes can be made into a proxy instead of a table. A proxy is
returned when actually a load is called on a session. The proxy contains
 actual method to load the data. The proxy is created by default by
Hibernate, for mapping a class to a file. The code to invoke JDBC is
contained in this class.

Read More: https://www.journaldev.com/3633/hibernate-interview-questions-and-answers