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?
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
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.htmlDATETIME 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