Skip to main content

Java Interview questions answers

1) What is difference between JDK,JRE and JVM?
JVM
JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.
JVMs are available for many hardware and software platforms (so JVM is platform dependent).
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

2) How many types of memory areas are allocated by JVM?
Many types:
  1. Class(Method) Area
  2. Heap
  3. Stack
  4. Program Counter Register
  5. Native Method Stack

3) What is JIT compiler?
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

4) What is platform?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

5) What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:
  1. Runtime Environment
  2. API(Application Programming Interface)

6) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

7) What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

8) Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let's take a simple example:
1.    //save by .java only  
2.    class A{  
3.    public static void main(String args[]){  
4.    System.out.println("Hello java");  
5.    }  
6.    }  
7.    //compile by javac .java  
8.    //run by     java A  
compile it by javac .java
run it by java A

9) Is delete,next,main,exit or null keyword in java?
No.

10) If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.

11) What if I write static public void instead of public static void?
Program compiles and runs properly.

12) What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.

Core Java - OOPs Concepts: Initial OOPs Interview Questions
There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. But they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions etc. for better understanding.

13) What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
14) What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

15) What is constructor?
  • Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

16) What is the purpose of default constructor?
  • The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.more details...

17) Does constructor return any value?
Ans:yes, that is current instance (You cannot use return type yet it returns a value).more details...

18)Is constructor inherited?
No, constructor is not inherited.

19) Can you make a constructor final?
No, constructor can't be final.

Core Java - OOPs Concepts: static keyword Interview Questions

20) What is static variable?
  • static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • static variable gets memory only once in class area at the time of class loading.

21) What is static method?
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.

22) Why main method is static?
because object is not required to call static method if It were non-static method,jvm creats object first then call main() method that will lead to the problem of extra memory allocation.more details...

23) What is static block?
  • Is used to initialize the static data member.
  • It is excuted before main method at the time of classloading.

24) Can we execute a program without main() method?
Ans) Yes, one of the way is static block.more details...

25) What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

26) What is difference between static (class) method and instance method?
static or class method
instance method
1)A method i.e. declared as static is known as static method.
A method i.e. not declared as static is known as instance method.
2)Object is not required to call static method.
Object is required to call instance methods.
3)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly.
static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;}
For example: public void msg(){...}.

Core Java - OOPs Concepts: Inheritance Interview Questions

27) What is this in java?
It is a keyword that that refers to the current object.more details...

28)What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

29) Which class is the superclass for every class.
Object class.

30) Why multiple inheritance is not supported in java?
  • To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.more details...

31) What is composition?
Holding the reference of the other class within some other class is known as composition.

32) What is difference between aggregation and composition?
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).
33) Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.

34) What is super in java?
It is a keyword that refers to the immediate parent class object.more details...

35) Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.

36)What is object cloning?
The object cloning is used to create the exact copy of an object. more details...

Core Java - OOPs Concepts: Method Overloading Interview Questions

37) What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.more details...

38) Why method overloading is not possible by changing the return type in java?
Becauseof ambiguity.more details...

39) Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method.

Core Java - OOPs Concepts: Method Overriding Interview Questions

40) What is method overriding:
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.more details...

41) Can we override static method?
No, you can't override the static method because they are the part of class not object.

42) Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

43) Can we override the overloaded method?
Yes.

44) Difference between method Overloading and Overriding.
Method Overloading
Method Overriding
1) Method overloading increases the readability of the program.
Method overriding provides the specific implementation of the method that is already provided by its super class.
2) method overlaoding is occurs within the class.
Method overriding occurs in two classes that have IS-A relationship.
3) In this case, parameter must be different.
In this case, parameter must be same.
45) Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.

46) What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. more details...

Core Java - OOPs Concepts: final keyword Interview Questions

47) What is final variable?
If you make any variable as final, you cannot change the value of final variable(It will be constant).more details...

48) What is final method?
Final methods can't be overriden.more details...

49) What is final class?
Final class can't be inherited. more details...

50) What is blank final variable?
A final variable, not initalized at the time of declaration, is known as blank final variable.more details...

51) Can we intialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block.more details...

52) Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}.

53) What is Runtime Polymorphism?

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super class. The determination of the method to be called is based on the object being referred to by the reference variable.

54) Can you achieve Runtime Polymorphism by data members?

No.

55) What is the difference between static binding and dynamic binding?

In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime.

Core Java - OOPs Concepts : Abstraction Interview Questions


56) What is abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it.

57) What is the difference between abstraction and encapsulation?

Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

58) What is abstract class?

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

59) Can there be any abstract method without abstract class?

No, if there is any abstract method in a class, that class must be abstract.

60) Can you use abstract and final both with a method?

No, because abstract method needs to be overridden whereas you can't override final method.

61) Is it possible to instantiate the abstract class?

No, abstract class can never be instantiated.

62) What is interface?

Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance.

63) Can you declare an interface method static?

No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.

64) Can an Interface be final?

No, because its implementation is provided by another class.

65) What is marker interface?

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.

66) What is difference between abstract class and interface?

Abstract class
Interface
1)An abstract class can have method body (non-abstract methods).
Interface have only abstract methods.
2)An abstract class can have instance variables.
An interface cannot have instance variables.
3)An abstract class can have constructor.
Interface cannot have constructor.
4)An abstract class can have static methods.
Interface cannot have static methods.
5)You can extends one abstract class.
You can implement multiple interfaces.

67) Can we define private and protected modifiers for variables in interfaces?

No, they are implicitly public.

68) When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

Core Java - OOPs Concepts : Package Interview Questions


69) What is package?

A package is a group of similar type of classes interfaces and sub-packages. It provides access protection and removes naming collision.

70) Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

71) Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains about it.But the JVM will internally load the class only once no matter how many times you import the same class.

72) What is static import ?

By static import, we can access the static members of a class directly, there is no to qualify it with the class name.

73) What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked exceptions.

74) What is difference between Checked Exception and Unchecked Exception?
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-time.

75) What is the base class for Error and Exception?
Throwable.

76) Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

77) What is finally block?

78) Can finally block be used without catch?
  • Yes, by try block. finally must be followed by either try or catch.more details...

79) Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).more details...

80) What is difference between throw and throws?
throw keyword
throws keyword
1)throw is used to explicitly throw an exception.
throws is used to declare an exception.
2)checked exceptions can not be propagated with throw only.
checked exception can be propagated with throws.
3)throw is followed by an instance.
throws is followed by class.
4)throw is used within the method.
throws is used with the method signature.
5)You cannot throw multiple exception
You can declare multiple exception e.g. public void method()throws IOException,SQLException.

81) Can an exception be rethrown?
Yes.

82) Can subclass overriding method declare an exception if parent class method doesn't throw an exception ?
Yes but only unchecked exception not checked.

83) What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.


Java: String Handling Interview Questions
There is given a list of string handling interview questions with short and pointed answers. If you know any string handling interview question, kindly post it in the comment section.

84) What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.

85) Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

86) How many ways we can create the string object?
There are two ways to create the string object, by string literal and by new keyword.

87) How many objects will be created in the following code?
1.    String s1="Welcome";  
2.    String s2="Welcome";  
3.    String s3="Welcome";  
Only one object.

88) Why java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

89)How many objects will be created in the following code?
1.    String s = new String("Welcome");  
Two objects, one in string constant pool and other in non-pool(heap).

90) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.

91) What is the difference between StringBuffer and StringBuilder ?
StringBuffer is synchronized whereas StringBuilder is not synchronized.

92) How can we create immutable class in java ?
We can create immutable class as the String class by defining final class and

93) What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Core Java : Nested classes and Interfaces Interview Questions

94)What is nested class?
A class which is declared inside another class is known as nested class. There are 4 types of nested class member inner class, local inner class, annonymous inner class and static nested class.

95) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes i.e. inner classes are the part of nested classes.

96) Can we access the non-final local variable, inside the local inner class?
No, local variable must be constant if you want to access it in local inner class.

97) What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by default.

98) Can a class have an interface?
Yes, it is known as nested interface.

99) Can an Interface have a class?
Yes, they are static implicitely.
117) What is Garbage Collection?
Garbage collection is a process of reclaiming the runtime unused objects.It is performed for memory management.
118) What is gc()?
gc() is a daemon thread.gc() method is defined in System class that is used to send request to JVM to perform garbage collection.
119) What is the purpose of finalize() method?
finalize() method is invoked just before the object is garbage collected.It is used to perform cleanup processing.
120) Can an unrefrenced objects be refrenced again?
Yes.
121)What kind of thread is the Garbage collector thread?
Daemon thread.
122)What is difference between final, finally and finalize?
final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, can't override final method, can't inherit final class.
finally: finally block is used in exception handling. finally block is always executed.
finalize():finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.

123)What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
124)How will you invoke any external process in Java?
By Runtime.getRuntime().exec(?) method.

I/O Interview Questions

125)What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
126)What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

Serialization Interview Questions

127) What is serialization?
Serialization is a process of writing the state of an object into a byte stream.It is mainly used to travel object's state on the network.
128) What is Deserialization?
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.
129) What is transient keyword?
If you define any data member as transient,it will not be serialized.more details...
130)What is Externalizable?
Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.
131)What is the difference between Serializalble and Externalizable interface?
Serializable is a marker interface but Externalizable is not a marker interface.When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

Networking Interview Questions

132)How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the IP address.

Reflection Interview Questions

133) What is reflection?
Reflection is the process of examining or modifying the runtime behaviour of a class at runtime.It is used in:
  • IDE (Integreted Development Environment) e.g. Eclipse, MyEclipse, NetBeans.
  • Debugger
  • Test Tools etc.
134) Can you access the private method from outside the class?
Yes, by changing the runtime behaviour of a class if the class is not secured.

148)What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.

149)What is a native method?

A native method is a method that is implemented in a language other than Java.

150)What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

151)What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

152)What is singleton class?

Singleton class means that any given time only one instance of the class is present, in one JVM.

AWT and SWING Interview Questions


153)Which containers use a border layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.

154)Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

155)What are peerless components?

The peerless components are called light weight components.

156)is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

157)What is a lightweight component?

Lightweight components are the one which doesn?t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components.

158)What is a heavyweight component?

For every paint call, there will be a native call to get the graphical units.For Example, AWT.

159)What is an applet?

An applet is a small java program that runs inside the browser and generates dynamic contents.

160)Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

Internationalization Interview Questions


161)What is Locale?

A Locale object represents a specific geographical, political, or cultural region.

162)How will you load a specific locale?

By ResourceBundle.getBundle(?) method.

Java Bean Interview Questions


163)What is a JavaBean?

are reusable software components written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java.

RMI Interview Questions


164)Can RMI and Corba based applications interact?

Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.

1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between process is low.

2) What is thread?
A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.

3)What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

4) What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

5) What is difference between wait() and sleep() method?
wait()
sleep()
1) The wait() method is defined in Object class.
The sleep() method is defined in Thread class.
2) wait() method releases the lock.
The sleep() method doesn't releases the lock.

6) Is it possible to start a thread twice?
No, there is no possibility to start a thread twice. If we does, it throws an exception.

7) Can we call the run() method instead of start()?
yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.

8) What about the daemon threads?
The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads.

9)Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw IllegalThreadStateException

10)What is shutdown hook?
The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.

11)When should we interrupt a thread?
We should interrupt a thread if we want to break out the sleep or wait state of a thread.

12) What is synchronization?
Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used:

  1. To prevent thread interference.
  2. To prevent consistency problem.

13) What is the purpose of Synchronized block?
  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

14)Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

15) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on object. more details...

16)What is the difference between notify() and notifyAll()?
The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

17)What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

20 Java Collections Interview Questions

In java, collection interview questions are mostly asked by the interviewers. Here is the list of mostly asked collections interview questions with answers.

1) What is the difference between ArrayList and Vector?

No.
ArrayList
Vector
1)
ArrayList is not synchronized.
Vector is synchronized.
2)
ArrayList is not a legacy class.
Vector is a legacy class.
3)
ArrayList increases its size by 50% of the array size.
Vector increases its size by doubling the array size.

2) What is the difference between ArrayList and LinkedList?

No.
ArrayList
LinkedList
1)
ArrayList uses a dynamic array.
LinkedList uses doubly linked list.
2)
ArrayList is not efficient for manipulation because a lot of shifting is required.
LinkedList is efficient for manipulation.
3)
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.

3) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.
No.
Iterator
ListIterator
1)
Iterator traverses the elements in forward direction only.
ListIterator traverses the elements in backward and forward directions both.
2)
Iterator can be used in List, Set and Queue.
ListIterator can be used in List only.

4) What is the difference between Iterator and Enumeration?

No.
Iterator
Enumeration
1)
Iterator can traverse legacy and non-legacy elements.
Enumeration can traverse only legacy elements.
2)
Iterator is fail-fast.
Enumeration is not fail-fast.
3)
Iterator is slower than Enumeration.
Enumeration is faster than Iterator.

5) What is the difference between List and Set?

List can contain duplicate elements whereas Set contains only unique elements.

6) What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

7) What is the difference between Set and Map?

Set contains values only whereas Map contains key and values both.

8) What is the difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.

9) What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

10) What is the difference between HashMap and Hashtable?

No.
HashMap
Hashtable
1)
HashMap is not synchronized.
Hashtable is synchronized.
2)
HashMap can contain one null key and multiple null values.
Hashtable cannot contain any null key or null value.

11) What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

12) What is the difference between Comparable and Comparator?

No.
Comparable
Comparator
1)
Comparable provides only one sort of sequence.
Comparator provides multiple sort of sequences.
2)
It provides one method named compareTo().
It provides one method named compare().
3)
It is found in java.lang package.
it is found in java.util package.
4)
If we implement Comparable interface, actual class is modified.
Actual class is not modified.

13) What is the advantage of Properties file?

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

14) What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.
But, it is possible that two hash code numbers can have different or same keys.

15) Why we override equals() method?

The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

16) How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

17) What is the advantage of generic collection?

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

18) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

19) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

20) What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

20 Java Collections Interview Questions

In java, collection interview questions are mostly asked by the interviewers. Here is the list of mostly asked collections interview questions with answers.

1) What is the difference between ArrayList and Vector?

No.
ArrayList
Vector
1)
ArrayList is not synchronized.
Vector is synchronized.
2)
ArrayList is not a legacy class.
Vector is a legacy class.
3)
ArrayList increases its size by 50% of the array size.
Vector increases its size by doubling the array size.

2) What is the difference between ArrayList and LinkedList?

No.
ArrayList
LinkedList
1)
ArrayList uses a dynamic array.
LinkedList uses doubly linked list.
2)
ArrayList is not efficient for manipulation because a lot of shifting is required.
LinkedList is efficient for manipulation.
3)
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.

3) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.
No.
Iterator
ListIterator
1)
Iterator traverses the elements in forward direction only.
ListIterator traverses the elements in backward and forward directions both.
2)
Iterator can be used in List, Set and Queue.
ListIterator can be used in List only.

4) What is the difference between Iterator and Enumeration?

No.
Iterator
Enumeration
1)
Iterator can traverse legacy and non-legacy elements.
Enumeration can traverse only legacy elements.
2)
Iterator is fail-fast.
Enumeration is not fail-fast.
3)
Iterator is slower than Enumeration.
Enumeration is faster than Iterator.

5) What is the difference between List and Set?

List can contain duplicate elements whereas Set contains only unique elements.

6) What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

7) What is the difference between Set and Map?

Set contains values only whereas Map contains key and values both.

8) What is the difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.

9) What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

10) What is the difference between HashMap and Hashtable?

No.
HashMap
Hashtable
1)
HashMap is not synchronized.
Hashtable is synchronized.
2)
HashMap can contain one null key and multiple null values.
Hashtable cannot contain any null key or null value.

11) What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

12) What is the difference between Comparable and Comparator?

No.
Comparable
Comparator
1)
Comparable provides only one sort of sequence.
Comparator provides multiple sort of sequences.
2)
It provides one method named compareTo().
It provides one method named compare().
3)
It is found in java.lang package.
it is found in java.util package.
4)
If we implement Comparable interface, actual class is modified.
Actual class is not modified.

13) What is the advantage of Properties file?

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

14) What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.
But, it is possible that two hash code numbers can have different or same keys.

15) Why we override equals() method?

The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

16) How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

17) What is the advantage of generic collection?

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

18) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

19) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

20) What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
1) How many objects of a servlet is created?
Only one object at the time of first request by servlet or web container.

2) What is the life-cycle of a servlet?
  1. Servlet is loaded
  2. servlet is instantiated
  3. servlet is initialized
  4. service the request
  5. servlet is destroyed

3) What are the life-cycle methods for a servlet?
Method
Description
public void init(ServletConfig config)
It is invoked only once when first request comes for the servlet. It is used to initialize the servlet.
public void service(ServletRequest request,ServletResponse)throws ServletException,IOException
It is invoked at each request.The service() method is used to service the request.
public void destroy()
It is invoked only once when servlet is unloaded.

4) Who is responsible to create the object of servlet?
The web container or servlet container.

5) When servlet object is created?
At the time of first request.

6) What is difference between Get and Post method?
Get
Post
1) Limited amount of data can be sent because data is sent in header.
Large amount of data can be sent because data is sent in body.
2) Not Secured because data is exposed in URL bar.
Secured because data is not exposed in URL bar.
3) Can be bookmarked
Cannot be bookmarked
4) Idempotent
Non-Idempotent
5) It is more efficient and used than Post
It is less efficient and used

7) What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class. The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information.

8) What is difference between GenericServlet and HttpServlet?
The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific. HttpServlet provides additional functionalities such as state management etc.

9) What is servlet collaboration?
When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration:
  • RequestDispacher interface
  • sendRedirect() method etc.

10) What is the purpose of RequestDispatcher Interface?
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interceptor can also be used to include the content of antoher resource.

11) Can you call a jsp from the servlet?
Yes, one of the way is RequestDispatcher interface for example:
1.    RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");  
2.    rd.forward(request,response);  

12) Difference between forward() method and sendRedirect() method ?
forward() method
sendRedirect() method
1) forward() sends the same request to another resource.
1) sendRedirect() method sends new request always because it uses the URL bar of the browser.
2) forward() method works at server side.
2) sendRedirect() method works at client side.
3) forward() method works within the server only.
3) sendRedirect() method works within and outside the server.

13) What is difference between ServletConfig and ServletContext?
The container creates object of ServletConfig for each servlet whereas object of ServletContext is created for each web application.

14) What is Session Tracking?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.

15) What are Cookies?
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

16) What is difference between Cookies and HttpSession?
Cookie works at client side whereas HttpSession works at server side.

17) What is filter?
A filter is an object that is invoked either at the preprocessing or postprocessing of a request. It is pluggable.

18) How can we perform any action at the time of deploying the project?
By the help of ServletContextListener interface.

19) What is the disadvantage of cookies?
It will not work if cookie is disabled from the browser.

20) How can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.

21) What is load-on-startup in servlet?
The load-on-startup element of servlet in web.xml is used to load the servlet at the time of deploying the project or server start. So it saves time for the response of first request.

22) What if we pass negative value in load-on-startup?
It will not affect the container, now servlet will be loaded at first request.

23) What is war file?
A war (web archive) file specifies the web elements. A servlet or jsp project can be converted into a war file. Moving one servlet project from one place to another will be fast as it is combined into a single file.

24) How to create war file?
The war file can be created using jar tool found in jdk/bin directory. If you are using Eclipse or Netbeans IDE, you can export your project as a war file.
To create war file from console, you can write following code.
1.    jar -cvf abc.war *  
Now all the files of current directory will be converted into abc.war file.

25) What are the annotations used in Servlet 3?
There are mainly 3 annotations used for the servlet.
  1. @WebServlet : for servlet class.
  2. @WebListener : for listener class.
  3. @WebFilter : for filter class.

26) Which event is fired at the time of project deployment and undeployment?
ServletContextEvent.

27) Which event is fired at the time of session creation and destroy?
HttpSessionEvent.

28) Which event is fired at the time of setting, getting or removing attribute from application scope?
ServletContextAttributeEvent.

29) What is the use of welcome-file-list?
It is used to specify the welcome file for the project.

30) What is the use of attribute in servlets?
Attribute is a map object that can be used to set, get or remove in request, session or application scope. It is mainly used to share information between one servlet to another.

1) What is Spring?
It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java.

2) What are the advantages of spring framework?
  1. Predefined Templates
  2. Loose Coupling
  3. Easy to test
  4. Lightweight
  5. Fast Development
  6. Powerful Abstraction
  7. Declarative support

3) What are the modules of spring framework?
  1. Test
  2. Spring Core Container
  3. AOP, Aspects and Instrumentation
  4. Data Access/Integration
  5. Web

4) What is IOC and DI?
IOC (Inversion of Control) and DI (Dependency Injection) is a design pattern to provide loose coupling. It removes the dependency from the program.
Let's write a code without following IOC and DI.
1.    public class Employee{  
2.    Address address;  
3.    Employee(){  
4.    address=new Address();//creating instance  
5.    }  
6.    }  
Now, there is dependency between Employee and Address because Employee is forced to use the same address instance.
Let's write the IOC or DI code.
1.    public class Employee{  
2.    Address address;  
3.    Employee(Address address){  
4.    this.address=address;//not creating instance  
5.    }  
6.    }  
Now, there is no dependency between Employee and Address because Employee is not forced to use the same address instance. It can use any address instance.

5) What is the role of IOC container in spring?
IOC container is responsible to:
  • create the instance
  • configure the instance, and
  • assemble the dependencies

6) What are the types of IOC container in spring?
There are two types of IOC containers in spring framework.
  1. BeanFactory
  2. ApplicationContext

7) What is the difference between BeanFactory and ApplicationContext?
BeanFactory is the basic container whereas ApplicationContext is the advanced container. ApplicationContext extends the BeanFactory interface. ApplicationContext provides more facilities than BeanFactory such as integration with spring AOP, message resource handling for i18n etc.

8) What is the difference between constructor injection and setter injection?
No.
Constructor Injection
Setter Injection
1)
No Partial Injection
Partial Injection
2)
Desn't override the setter property
Overrides the constructor property if both are defined.
3)
Creates new instance if any modification occurs
Doesn't create new instance if you change the property value
4)
Better for too many properties
Better for few properties.

9) What is autowiring in spring? What are the autowiring modes?
Autowiring enables the programmer to inject the bean automatically. We don't need to write explicit injection logic.
Let's see the code to inject bean using dependency injection.
1.    <bean id="emp" class="com.javatpoint.Employee" autowire="byName" />  
The autowiring modes are given below:
No.
Mode
Description
1)
no
this is the default mode, it means autowiring is not enabled.
2)
byName
injects the bean based on the property name. It uses setter method.
3)
byType
injects the bean based on the property type. It uses setter method.
4)
constructor
It injects the bean using constructor
The "autodetect" mode is deprecated since spring 3.

10) What are the different bean scopes in spring?
There are 5 bean scopes in spring framework.
No.
Scope
Description
1)
singleton
The bean instance will be only once and same instance will be returned by the IOC container. It is the default scope.
2)
prototype
The bean instance will be created each time when requested.
3)
request
The bean instance will be created per HTTP request.
4)
session
The bean instance will be created per HTTP session.
5)
globalsession
The bean instance will be created per HTTP global session. It can be used in portlet context only.

11) In which scenario, you will use singleton and prototype scope?
Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.

12) What are the transaction management supports provided by spring?
Spring framework provides two type of transaction management supports:
  1. Programmatic Transaction Management: should be used for few transaction operations.
  2. Declarative Transaction Management: should be used for many transaction operations.

» Spring JDBC Interview Questions

13) What are the advantages of JdbcTemplate in spring?
Less code: By using the JdbcTemplate class, you don't need to create connection,statement,start transaction,commit transaction and close connection to execute different queries. You can execute the query directly.

14) What are classes for spring JDBC API?
  1. JdbcTemplate
  2. SimpleJdbcTemplate
  3. NamedParameterJdbcTemplate
  4. SimpleJdbcInsert
  5. SimpleJdbcCall

15) How can you fetch records by spring JdbcTemplate?
You can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
  1. ResultSetExtractor
  2. RowMapper

16) What is the advantage of NamedParameterJdbcTemplate?
NamedParameterJdbcTemplate class is used to pass value to the named parameter. A named parameter is better than ? (question mark of PreparedStatement).
It is better to remember.

17) What is the advantage of SimpleJdbcTemplate?
The SimpleJdbcTemplate supports the feature of var-args and autoboxing.

» Spring AOP Interview Questions

18) What is AOP?
AOP is an acronym for Aspect Oriented Programming. It is a methodology that divides the program logic into pieces or parts or concerns.
It increases the modularity and the key unit is Aspect.

19) What are the advantages of spring AOP?
AOP enables you to dynamically add or remove concern before or after the business logic. It is pluggable and easy to maintain.

20) What are the AOP terminology?
AOP terminologies or concepts are as follows:
  • JoinPoint
  • Advice
  • Pointcut
  • Aspect
  • Introduction
  • Target Object
  • Interceptor
  • AOP Proxy
  • Weaving

21) What is JoinPoint?
JoinPoint is any point in your program such as field access, method execution, exception handling etc.

22) Does spring framework support all JoinPoints?
No, spring framework supports method execution joinpoint only.

23) What is Advice?
Advice represents action taken by aspect.

24) What are the types of advice in AOP?
There are 5 types of advices in spring AOP.
  1. Before Advice
  2. After Advice
  3. After Returning Advice
  4. Throws Advice
  5. Around Advice

25) What is Pointcut?
Pointcut is expression language of Spring AOP.

26) What is Aspect?
Aspect is a class in spring AOP that contains advices and joinpoints.

27) What is Introduction?
Introduction represents introduction of new fields and methods for a type.

28) What is target object?
Target Object is a proxy object that is advised by one or more aspects.

29) What is interceptor?
Interceptor is a class like aspect that contains one advice only.

30) What is weaving?
Weaving is a process of linking aspect with other application.

31) Does spring perform weaving at compile time?
No, spring framework performs weaving at runtime.

32) What are the AOP implementation?
There are 3 AOP implementation.
  1. Spring AOP
  2. Apache AspectJ
  3. JBoss AOP

» Spring MVC Interview Questions

33) What is the front controller class of Spring MVC?
The DispatcherServlet class works as the front controller in Spring MVC.

34) What does @Controller annotation?
The @Controller annotation marks the class as controller class. It is applied on the class.

35) What does @RequestMapping annotation?
The @RequestMapping annotation maps the request with the method. It is applied on the method.

36) What does the ViewResolver class?
The View Resolver class resolves the view component to be invoked for the request. It defines prefix and suffix properties to resolve the view component.

37) Which ViewResolver class is widely used?
The org.springframework.web.servlet.view.InternalResourceViewResolver class is widely used.

38) Does spring MVC provide validation support?
Yes.

1) What is PL/SQL?
PL/SQL stands for procedural language extension to SQL. It supports procedural features of programming language and SQL both. It was developed by Oracle Corporation in early of 90's to enhance the capabilities of SQL.

2) What is the purpose of using PL/SQL?
PL/SQL is an extension of SQL. While SQL is non-procedural, PL/SQL is a procedural language designed by Oracle. It is invented to overcome the limitations of SQL.

3) What are the most important characteristics of PL/SQL?
A list of some notable characteristics:
  • PL/SQL is a block-structured language.
  • It is portable to all environments that support Oracle.
  • PL/SQL is integrated with the Oracle data dictionary.
  • Stored procedures help better sharing of application.

4) What is PL/SQL table? Why it is used?
Objects of type tables are called PL/SQL tables that are modeled as database table. We can also say that PL/SQL tables are a way to providing arrays. Arrays are like temporary tables in memory that are processed very quickly. PL/SQL tables are used to move bulk data. They simplifies moving collections of data.

5) What are the datatypes available in PL/SQL?
There are two types of datatypes in PL/SQL:
  1. Scalar datatypes Example are NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN etc.
  2. Composite datatypes Example are RECORD, TABLE etc.

6) What is the basic structure of PL/SQL?
PL/SQL uses BLOCK structure as its basic structure. Each PL/SQL program consists of SQL and PL/SQL statement which form a PL/SQL block.
PL/SQL block contains 3 sections.
  1. The Declaration Section (optional)
  2. The Execution Section (mandatory)
  3. The Exception handling Section (optional)

7) What is the difference between FUNCTION, PROCEDURE AND PACKAGE in PL/SQL?
Function: The main purpose of a PL/SQL function is generally to compute and return a single value. A function has a return type in its specification and must return a value specified in that type.
Procedure: A procedure does not have a return type and should not return any value but it can have a return statement that simply stops its execution and returns to the caller. A procedure is used to return multiple values otherwise it is generally similar to a function.
Package: A package is schema object which groups logically related PL/SQL types , items and subprograms. You can also say that it is a group of functions, procedure, variables and record type statement. It provides modularity, due to this facility it aids application development. It is used to hide information from unauthorized users.

8) What is exception? What are the types of exceptions?
Exception is an error handling part of PL/SQL. There are two type of exceptions: pre_defined exception and user_defined exception.

9) How to write a single statement that concatenates the words ?Hello? and ?World? and assign it in a variable named Greeting?
Greeting := 'Hello' || 'World';

10) Does PL/SQL support CREATE command?
No. PL/SQL doesn't support the data definition commands like CREATE.

11) Write a unique difference between a function and a stored procedure.
A function returns a value while a stored procedure doesn?t return a value.

12) How exception is different from error?
Whenever an Error occurs Exception arises. Error is a bug whereas exception is a warning or error condition.

13) What is the main reason behind using an index?
Faster access of data blocks in the table.

14) What are PL/SQL exceptions? Tell me any three.
  1. Too_many_rows
  2. No_Data_Found
  3. Value_error
  4. Zero_error etc.

15) How do you declare a user-defined exception?
You can declare the User defined exceptions under the DECLARE section, with the keyword EXCEPTION.
Syntax:
1.    <exception_name> EXCEPTION;  

16) What are some predefined exceptions in PL/SQL?
A list of predefined exceptions in PL/SQL:
  • DUP_VAL_ON_INDEX
  • ZERO_DIVIDE
  • NO_DATA_FOUND
  • TOO_MANY_ROWS
  • CURSOR_ALREADY_OPEN
  • INVALID_NUMBER
  • INVALID_CURSOR
  • PROGRAM_ERROR
  • TIMEOUT _ON_RESOURCE
  • STORAGE_ERROR
  • LOGON_DENIED
  • VALUE_ERROR
  • etc.

17) What is a trigger in PL/SQL?
A trigger is a PL/SQL program which is stored in the database. It is executed immediately before or after the execution of INSERT, UPDATE, and DELETE commands.

18) What is the maximum number of triggers, you can apply on a single table?
12 triggers.

19) How many types of triggers exist in PL/SQL?
There are 12 types of triggers in PL/SQL that contains the combination of BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL keywords.
  • BEFORE ALL ROW INSERT
  • AFTER ALL ROW INSERT
  • BEFORE INSERT
  • AFTER INSERT etc.

20) What is the difference between execution of triggers and stored procedures?
A trigger is automatically executed without any action required by the user, while, a stored procedure is explicitly invoked by the user.

21) What happens when a trigger is associated to a view?
When a trigger is associated to a view, the base table triggers are normally enabled.

22) What is the usage of WHEN clause in trigger?
A WHEN clause specifies the condition that must be true for the trigger to be triggered.

23) How to disable a trigger name update_salary?
ALTER TRIGGER update_salary DISABLE;

24) Which command is used to delete a trigger?
DROP TRIGGER command.

25) what are the two virtual tables available at the time of database trigger execution?
Table columns are referred as THEN.column_name and NOW.column_name.
For INSERT related triggers, NOW.column_name values are available only.
For DELETE related triggers, THEN.column_name values are available only.
For UPDATE related triggers, both Table columns are available.

26) What is stored Procedure?
A stored procedure is a sequence of statement or a named PL/SQL block which performs one or more specific functions. It is similar to a procedure in other programming languages. It is stored in the database and can be repeatedly executed. It is stored as schema object. It can be nested, invoked and parameterized.

27) What are the different schemas objects that can be created using PL/SQL?
  • Stored procedures and functions
  • Packages
  • Triggers
  • Cursors

28) What do you know by PL/SQL Cursors?
Oracle uses workspaces to execute the SQL commands. When Oracle processes a SQL command, it opens an area in the memory called Private SQL Area. This area is identified by the cursor. It allows programmers to name this area and access it?s information.

29) What is the difference between the implicit and explicit cursors?
Implicit cursor is implicitly declared by Oracle. This is a cursor to all the DDL and DML commands that return only one row.
Explicit cursor is created for queries returning multiple rows.

30) What will you get by the cursor attribute SQL%ROWCOUNT?
The cursor attribute SQL%ROWCOUNT will return the number of rows that are processed by a SQL statement.

31) What will you get by the cursor attribute SQL%FOUND?
It returns the Boolean value TRUE if at least one row was processed.

32) What will you get by the cursor attribute SQL%NOTFOUND?
It returns the Boolean value TRUE if no rows were processed.

33) What do you understand by PL/SQL packages?
A PL/SQL package can be specified as a file that groups functions, cursors, stored procedures, and variables in one place.

34) What are the two different parts of the PL/SQL packages?
PL/SQL packages have the following two parts:
Specification part: It specifies the part where the interface to the application is defined.
Body part: This part specifies where the implementation of the specification is defined.

35) Which command is used to delete a package?
The DROP PACKAGE command is used to delete a package.

36) How to execute a stored procedure?
There are two way to execute a stored procedure.
From the SQL prompt, write EXECUTE or EXEC followed by procedure_name.
1.    EXECUTE or [EXEC] procedure_name;  
Simply use the procedure name
1.    procedure_name;  

37) What are the advantages of stored procedure?
Modularity, extensibility, reusability, Maintainability and one time compilation.

38) What are the cursor attributes used in PL/SQL?
%ISOPEN: it checks whether the cursor is open or not.
%ROWCOUNT: returns the number of rows affected by DML operations: INSERT,DELETE,UPDATE,SELECT.
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
%NOTFOUND: it checks whether cursor has fetched any row. If no - TRUE.

39) What is the difference between syntax error and runtime error?
A syntax error can be easily detected by a PL/SQL compiler. For example: incorrect spelling etc. while, a runtime error is handled with the help of exception-handling section in a PL/SQL block. For example: SELECT INTO statement, which does not return any rows.

40) Explain the Commit statement.
Following conditions are true for the Commit statement:
  • Other users can see the data changes made by the transaction.
  • The locks acquired by the transaction are released.
  • The work done by the transaction becomes permanent.

41) Explain the Rollback statement?
The Rollback statement is issued when the transaction ends. Following conditions are true for a Rollback statement:
  • The work done in a transition is undone as if it was never issued.
  • All locks acquired by transaction are released.

42) Explain the SAVEPOINT statement.
With SAVEPOINT, only part of transaction can be undone.

43) What is mutating table error?
Mutating table error is occurred when a trigger tries to update a row that it is currently using. It is fixed by using views or temporary tables.

44) What is consistency?
Consistency simply means that each user sees the consistent view of the data.
Consider an example: there are two users A and B. A transfers money to B's account. Here the changes are updated in A's account (debit) but until it will be updated to B's account (credit), till then other users can't see the debit of A's account. After the debit of A and credit of B, one can see the updates. That?s consistency.

45) What is cursor and why it is required?
A cursor is a temporary work area created in a system memory when an SQL statement is executed.
A cursor contains information on a select statement and the row of data accessed by it. This temporary work area stores the data retrieved from the database and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. Cursor are required to process rows individually for queries.

46) How many types of cursors are available in PL/SQL?
There are two types of cursors in PL/SQL.
  1. Implicit cursor, and
  2. explicit cursor

1) What are the components of physical database structure of Oracle database?
Components of physical database structure are given below.
  • One or more data files.
  • Two or more redo log files.
  • One or more control files.

2) What are the components of logical database structure in Oracle database?
Components of logical database structure.
  • Tablespaces
  • Database's schema objects

3) What is a tablespace?
A database contains Logical Storage Unit called tablespaces. A tablespace is a set of related logical structures. Actually a tablespace groups related logical structures together.

4) What is a SYSTEM tablespace and when it is created?
When the database is created in Oracle database system, it automatically generate a SYSTEM named SYSTEM tablespace. The SYSTEM tablespace contains data dictionary tables for the entire database.

5) What is an Oracle table?
A table is basic unit of data storage in Oracle database. A table contains all the accessible information of a user in rows and columns.

6) In the Oracle version 9.3.0.5.0, what does each number shows?
Oracle version number refers:
  • 9 - Major database release number
  • 3 - Database maintenance release number
  • 0 - Application server release number
  • 5 - Component Specific release number
  • 0 - Platform Specific release number

7) What is bulk copy or BCP in Oracle?
Bulk copy or BCP in Oracle, is used to import or export data from tables and views but it does not copy structure of same data.
The main advantage of BCP is fast mechanism for coping data and you can also take the backup of data easily.

8) What is the relationship among database, tablespace and data file?
An Oracle database contains one or more logical storage units called tablespaces. These tablespaces collectively store whole data of databases and each tablespace in Oracle database consists of one or more files called datafiles. These datafiles are physical structure that confirm with the operating system in which Oracle is running.

9) What is a snapshot in Oracle database?
A snapshot is a replica of a target master table from a single point-in-time. In simple words you can say, snapshot is a copy of a table on a remote database.

10) What is the difference between hot backup and cold backup in Oracle? Tell about their benefits also.
Hot backup (Online Backup): A hot backup is also known as online backup because it is done while the database is active. Some sites can not shut down their database while making a backup copy, they are used for 24 hour a day, 7 days a week.
Cold backup (Offline Backup): A cold backup is also known as offline backup because it is done while the database has been shutdown using the SHUTDOWN normal command. If the database is suddenly shutdown with a uncertain condition it should be restarted with RESTRICT mode and then shutdown with NORMAL option.
For a complete cold backup the following files must be backed up.
All datafiles, All control files, All online redo log files(optional) and the init.ora file (you can recreate it manually).

11) How many memory layers are in the Oracle shared pool?
Oracle shared pools contains two layers:
  1. library cache
  2. data dictionary cache

12) What is save point in Oracle database?
Save points are used to divide a transaction into smaller parts. It allows rolling back of a transaction. Maximum five save points are allowed. It is used to save our data, whenever you encounter an error you can roll back from the point where you save your SAVEPOINT.

13) What is hash cluster in Oracle?
Hash cluster is a technique to store a data in hash table and improve the performance of data retrieval. Hash function is applied on table row's cluster key value and store in hash cluster.

14) What are the various Oracle database objects?
Tables: This is a set of elements organized in vertical and horizontal fashion.
Tablespaces: This is a logical storage unit in Oracle.
Views: It is virtual table derived from one or more tables.
Indexes: This is a performance tuning method to process the records.
Synonyms: This is a name for tables.

15) What is the difference between pre-select and pre-query?
A pre-query trigger fire before the query executes and fire once while you try to query. With the help of this trigger you can modify the where clause part dynamically.
Pre-select query fires during the execute query and count query processing after Oracle forms construct the select statement to be issued, but before the statement is actually issued.
Pre-query trigger fires before Pre-select trigger.

16) What are the different types of modules in Oracle forms?
Following are the different modules in Oracle forms:
  • Form module
  • Menu module
  • Pl/SQL Library module
  • Object Library module

17) What is the usage of ANALYZE command in Oracle?
ANALYZE command is used to perform various functions on index, table, or cluster. The following list specifies the usage of ANALYZE command in Oracle:
  • It is used to identify migrated and chained rows of the table or cluster.
  • It is used to validate the structure of the object.
  • It helps in collecting the statistics about object used by the optimizer. They are then stored in the data dictionary.
  • It helps in deleting statistics used by object from the data dictionary.

18) Can you create a synonym without having a table?
Yes. We can create a synonym without having a base table.

19) What types of joins are used in writing SUBQUERIES?
  • Self join
  • Outer Join
  • Equi-join

20) What is the usage of control file in Oracle?
In Oracle, control file is used for database recovery. The control file is also used to identify the database and redo log files that must be opened for database operation to go ahead, whenever an instance of an ORACLE database begins.

21) What is a synonym?
A synonym is also known as alias for a table, view, sequence or program unit.

22) What are the different types of synonyms?
There are two types of synonyms or alias:
Private: It can only accessed by the owner.
Public: It can be accessed by any database user.

23) What is the usage of synonyms?
  • Synonym can be used to hide the real name and owner of an object.
  • It provides public access to an object.
  • It also provides location transparency for tables, views or program units of a remote database.
  • It simplifies the SQL statements for database users.

24) How do you store pictures in a database?
Yes, you can store pictures in a database using Long Raw Data type. This data type is used to store binary data for 2 gigabytes of length. However, the table can have only one Long Raw data type.

25) What is BLOB data type in Oracle?
BLOB data type is a data type with varying length binary string. It is used to store two gigabytes memory. For BLOB data type, the length needs to be specified in bytes.

26) What is the difference between TRANSLATE and REPLACE in Oracle?
Translate is used to substitute a character by character while Replace is used to substitute a single character with a word.

27) What are the different types of database objects?
A list of different types of database objects:
  • Tables: This is a set of elements organized in vertical and horizontal fashion.
  • Tablespaces: This is a logical storage unit in Oracle.
  • Views: It is virtual table derived from one or more tables.
  • Indexes: This is a performance tuning method to process the records.
  • Synonyms: This is a name for tables.

28) What is the usage of Save Points in Oracle database?
Save Points are used to divide a transaction into smaller phases. It enables rolling back part of a transaction. There are maximum 5 save points allowed in Oracle Database. Whenever an error is encountered, it is possible to rollback from the point where the SAVEPOINT has been saved.

29) What is the difference between post-database commit and post-form commit?
The post-database commit trigger is executed after Oracle forms issue the commit to finalized transaction while, the post-form commit is fired during the post and commit transactions process, after the database commit occurs.

30) What is Logical backup in Oracle?
Logical backup is used to read a set of database records and writing them into a file. An Export utility is used to take the backup while an Import utility is used to recover from the backup.

31) What do you understand by Redo Log file mirroring?
Mirroring is a process of having a copy of Redo log files. It is done by creating group of log files together. This ensures that LGWR automatically writes them to all the members of the current on-line redo log group. If the group fails, the database automatically switches over to the next group. It diminishes the performance.

32) What is the meaning of recursive hints in Oracle?
The number of times a dictionary table is repeatedly called by various processes is known as recursive hint. Recursive hint is occurred because of the small size of data dictionary cache.

33) What are the limitations of CHECK constraint?
The main limitation of CHECK constraint is that the condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain sub queries.

34) What is the use of GRANT option in IMP command?
GRANT is used to import object grants.

35) What is the use of ROWS option in IMP command?
The ROWS option indicates whether the table rows should be imported.

36) What is the use of INDEXES option in IMP command?
The INDEXES option is used to determine whether indexes are imported.

37) What is the use of IGNORE option in IMP command?
The IGNORE option is used to specify how object creation errors should be handled.

38) What is the use of SHOW option in IMP command?
The SHOW option specifies when the value of show=y, the DDL within the export file is displayed.

39) What is the use of FILE param in IMP command?
FILE param is used to specify the name of the export file to import. Multiple files can be listed, separated by commas.

40) How to convert a date to char in Oracle? Give one example.
The to_char() function is used to convert date to character. You can also specify the format in which you want output.
1.    SELECT to_char ( to_date ('12-12-2012''DD-MM-YYYY') , 'YYYY-MM-DD'FROM dual;  
Or,
1.    SELECT to_char ( to_date ('12-12-2012''DD-MM-YYYY') , 'DD-MM-YYYY'FROM dual;  

41) What are actual and formal parameters?
Actual Parameters: Actual parameters are the variables or expressions referenced in the parameter list of a subprogram.
Let's see a procedure call which lists two actual parameters named empno and amt:
1.    raise_sal(empno, amt);  
Formal Parameters: Formal parameters are variables declared in a subprogram specification and referenced in the subprogram body.
Following procedure declares two formal parameters named empid and amt:
1.    PROCEDURE raise_sal(empid INTEGER, amt REALIS current_salary REAL;  

42) What are the extensions used by Oracle reports?
Oracle reports are use to make business enable with the facility to provide information of all level within or outside in a secure way. Oracle report uses REP files and RDF file extensions.

43) How to convert a string to a date in Oracle database?
Syntax: to_date (string , format)
Let us take an example :
1.    to_date ('2012-12-12''YYYY/MM/DD')  
It will return December 12, 2012.

44) How do you find current date and time in Oracle?
The SYSDATE() function is used in Oracle to find the current date and time of operating system on which the database is running.
1.    SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS'"Current_Date" FROM DUAL;  

45) What will be the syntax to find current date and time in format "YYYY-MM-DD"?
1.    SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD HH24:MI:SS'"Current_Date" FROM DUAL;  

73) What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked exceptions.

74) What is difference between Checked Exception and Unchecked Exception?
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-time.

75) What is the base class for Error and Exception?
Throwable.

76) Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

77) What is finally block?

78) Can finally block be used without catch?
  • Yes, by try block. finally must be followed by either try or catch.more details...

79) Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).more details...

80) What is difference between throw and throws?
throw keyword
throws keyword
1)throw is used to explicitly throw an exception.
throws is used to declare an exception.
2)checked exceptions can not be propagated with throw only.
checked exception can be propagated with throws.
3)throw is followed by an instance.
throws is followed by class.
4)throw is used within the method.
throws is used with the method signature.
5)You cannot throw multiple exception
You can declare multiple exception e.g. public void method()throws IOException,SQLException.

81) Can an exception be rethrown?
Yes.

82) Can subclass overriding method declare an exception if parent class method doesn't throw an exception ?
Yes but only unchecked exception not checked.

83) What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.


Java: String Handling Interview Questions
There is given a list of string handling interview questions with short and pointed answers. If you know any string handling interview question, kindly post it in the comment section.

84) What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.

85) Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

86) How many ways we can create the string object?
There are two ways to create the string object, by string literal and by new keyword.

87) How many objects will be created in the following code?
1.    String s1="Welcome";  
2.    String s2="Welcome";  
3.    String s3="Welcome";  
Only one object.

88) Why java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

89)How many objects will be created in the following code?
1.    String s = new String("Welcome");  
Two objects, one in string constant pool and other in non-pool(heap).

90) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.

91) What is the difference between StringBuffer and StringBuilder ?
StringBuffer is synchronized whereas StringBuilder is not synchronized.

92) How can we create immutable class in java ?
We can create immutable class as the String class by defining final class and

93) What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Core Java : Nested classes and Interfaces Interview Questions

94)What is nested class?
A class which is declared inside another class is known as nested class. There are 4 types of nested class member inner class, local inner class, annonymous inner class and static nested class.

95) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes i.e. inner classes are the part of nested classes.

96) Can we access the non-final local variable, inside the local inner class?
No, local variable must be constant if you want to access it in local inner class.

97) What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by default.

98) Can a class have an interface?
Yes, it is known as nested interface.

99) Can an Interface have a class?
Yes, they are static implicitely.
1) What is JDBC?
JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database.

2) What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers:
  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

3) What are the steps to connect to the database in java?
  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

4) What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • DatabaseMetaData
  • CallableStatement etc.
Classes:
  • DriverManager
  • Blob
  • Clob
  • Types
  • SQLException etc.

5) What are the JDBC statements?
There are 3 JDBC statements.
  1. Statement
  2. PreparedStatement
  3. CallableStatement

6) What is the difference between Statement and PreparedStatement interface?
In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.

7) How can we execute stored procedures and functions?
By using Callable statement interface, we can execute procedures and functions.

8) What is the role of JDBC DriverManager class?
The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

9) What does the JDBC Connection interface?
The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

10) What does the JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

11) What does the JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

12) What does the JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

13) Which interface is responsible for transaction management in JDBC?
The Connection interface provides methods for transaction management such as commit(), rollback() etc.

14) What is batch processing and how to perform batch processing in JDBC?
By using batch processing technique in JDBC, we can execute multiple queries. It makes the performance fast.

15) How can we store and retrieve images from the database?
By using PreparedStatement interface, we can store and retrieve images.


1)What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the servlet technology. A JSP page is internally converted into servlet.

2) What are the life-cycle methods for a jsp?
Method
Description
public void jspInit()
It is invoked only once, same as init method of servlet.
public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException
It is invoked at each request, same as service() method of servlet.
public void jspDestroy()
It is invoked only once, same as destroy() method of servlet.

3)What is difference between hide comment and output comment?
The jsp comment is called hide comment whereas html comment is called output comment. If user views the source of the page, the jsp comment will not be shown whereas html comment will be shown.

4)What are the JSP implicit objects ?
JSP provides 9 implicit objects by default. They are as follows:
Object
Type
1) out
JspWriter
2) request
HttpServletRequest
3) response
HttpServletResponse
4) config
ServletConfig
5) session
HttpSession
6) application
ServletContext
7) pageContext
PageContext
8) page
Object
9) exception
Throwable
5)What is difference between include directive and include action?
include directive
include action
1) The include directive includes the content at page translation time.
1) The include action includes the content at request time.
2) The include directive includes the original content of the page so page size increases at runtime.
2) The include action doesn't include the original content rather invokes the include() method of Vendor provided class.
3) It's better for static pages.
3) It's better for dynamic pages.

6) Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

7) How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page.

8) How can I prevent the output of my JSP or Servlet pages from being cached by the browser?
(OR) How to disable caching on back button of the browser?
1.    <%  
2.    response.setHeader("Cache-Control","no-store");   
3.    response.setHeader("Pragma","no-cache");   
4.    response.setHeader ("Expires", "0"); //prevents caching at the proxy server  
5.    %>   

9) How can we handle the exceptions in JSP ?
There are two ways to perform exception handling, one is by the errorPage element of page directive, and second is by the error-page element of web.xml file.

10) What are the two ways to include the result of another page. ?
There are two ways to include the result of another page:

11) How can we forward the request from jsp page to the servlet ?
Yes ofcourse! With the help of forward action tag, but we need to give the url-pattern of the servlet.

12) Can we use the exception implicit object in any jsp page ?
No. The exception implicit object can only be used in the error page which defines it with the isErrorPage attribute of page directive.

13) How is JSP used in the MVC model?
JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

14) What are context initialization parameters?
Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

15) What are the different scope values for the <jsp:useBean> tag?
There are 4 values:
  1. page
  2. request
  3. session
  4. application

16)What is the difference between ServletContext and PageContext?-
ServletContext gives the information about the container whereas PageContext gives the information about the Request.

17)What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
request.getRequestDispatcher(path) is used in order to create it we need to give the relative path of the resource whereas context.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.

18) What is EL in JSP?
The Expression Language(EL) is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session etc.

19)What is basic differences between the JSP custom tags and java beans?
  • Custom tags can manipulate JSP content whereas beans cannot.
  • Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
  • Custom tags require quite a bit more work to set up than do beans.
  • Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

20) Can an interface be implemented in the jsp file ?
No.

21) What is JSTL?
JSP Standard Tag Library is library of predefined tags that ease the development of JSP.

22) How many tags are provided in JSTL?
There are 5 type of JSTL tags.
  1. core tags
  2. sql tags
  3. xml tags
  4. internationalization tags
  5. functions tags

23) Which directive is used in jsp custom tag?
The jsp taglib directive.

24) What are the 3 tags used in JSP bean development?
  1. jsp:useBean
  2. jsp:setProperty
  3. jsp:getProperty

25) How to disable session in JSP?
1.    <%@ page session="false" %>   


1) What is hibernate?
Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate and retrieve data from the database.

2) What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation and data access.

3) Explain hibernate architecture?
Hibernate architecture comprises of many interfaces such as Configuration, SessionFactory, Session, Transaction etc.

4) What are the core interfaces of Hibernate?
The core interfaces of Hibernate framework are:
  • Configuration
  • SessionFactory
  • Session
  • Query
  • Criteria
  • Transaction

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

6) Is SessionFactory a thread-safe object?
Yes, SessionFactory is a thread-safe object, many threads cannot access it simultaneously.

7) What is Session?
It maintains a connection between hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.

8) Is Session a thread-safe object?
No, Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads.

9) What is the difference between session.save() and session.persist() method?
No.
save()
persist()
1)
returns the identifier (Serializable) of the instance.
return nothing because its return type is void.
2)
Syn: public Serializable save(Object o)
Syn: public void persist(Object o)

10) What is the difference between get and load method?
The differences between get() and load() methods are given below.
No.
get()
load()
1)
Returns null if object is not found.
Throws ObjectNotFoundException if object is not found.
2)
get() method always hit the database.
load() method doesn't hit the database.
3)
It returns real object not proxy.
It returns proxy object.
4)
It should be used if you are not sure about the existence of instance.
It should be used if you are sure that instance exists.

11) What is the difference between update and merge method?
The differences between update() and merge() methods are given below.
No.
update() method
merge() method
1)
Update means to edit something.
Merge means to combine something.
2)
update() should be used if session doesn't contain an already persistent state with same id. It means update should be used inside the session only. After closing the session it will throw error.
merge() should be used if you don't know the state of the session, means you want to make modification at any time.
Let's try to understand the difference by the example given below:
1.    ...  
2.    SessionFactory factory = cfg.buildSessionFactory();  
3.    Session session1 = factory.openSession();  
4.       
5.    Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing id of employee  
6.    session1.close();  
7.       
8.    e1.setSalary(70000);  
9.       
10. Session session2 = factory.openSession();  
11. Employee e2 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing same id  
12.   
13. Transaction tx=session2.beginTransaction();  
14. session2.merge(e1);  
15.   
16. tx.commit();  
17. session2.close();  
After closing session1, e1 is in detached state. It will not be in session1 cache. So if you call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee instance. If we call merge in session2, changes of e1 will be merged in e2.

12) What are the states of object in hibernate?
There are 3 states of object (instance) in hibernate.
  1. Transient: The object is in transient state if it is just created but has no primary key (identifier) and not associated with session.
  2. Persistent: The object is in persistent state if session is open, and you just saved the instance in the database or retrieved the instance from the database.
  3. Detached: The object is in detached state if session is closed. After detached state, object comes to persistent state if you call lock() or update() method.

13) What are the inheritance mapping strategies?
There are 3 ways of inheritance mapping in hibernate.
  1. Table per hierarchy
  2. Table per concrete class
  3. Table per subclass

14) How to make a immutable class in hibernate?
If you mark a class as mutable="false", class will be treated as an immutable class. By default, it is mutable="true".

15) What is automatic dirty checking in hibernate?
The automatic dirty checking feature of hibernate, calls update statement automatically on the objects that are modified in a transaction.
Let's understand it by the example given below:
1.    ...  
2.    SessionFactory factory = cfg.buildSessionFactory();  
3.    Session session1 = factory.openSession();  
4.    Transaction tx=session2.beginTransaction();  
5.       
6.    Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));  
7.       
8.    e1.setSalary(70000);  
9.       
10. tx.commit();  
11. session1.close();  
Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In such case, state will be updated automatically. This is known as dirty checking in hibernate.

16) How many types of association mapping are possible in hibernate?
There can be 4 types of association mapping in hibernate.
  1. One to One
  2. One to Many
  3. Many to One
  4. Many to Many

17) Is it possible to perform collection mapping with One-to-One and Many-to-One?
`


Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using m...

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.  ...

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an ar...