Praveen Java Interview Questions
Praveen Java Interview Questions
There are four principle concepts upon which object oriented design and programming rest.
They are:
Abstraction
Polymorphism
Inheritance
Encapsulation
2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the
background details or explanations.
3.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object
and allowing outside access only as appropriate. It prevents other objects from directly
altering or accessing the properties or methods of the encapsulated object.
Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
5.What is Inheritance?
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
o To promote code
reuse o To use
polymorphism
6.What is Polymorphism?
In other cases, multiple methods have the same name, same return type, and
same formal argument list (overridden methods).
8.Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is method overloading.
Runtime time polymorphism is done using inheritance and interface.
Method overloading
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding (also known as late binding) means that the code associated
with a given procedure call is not known until the time of the call at run-time. It is
associated with polymorphism and inheritance.
Method Overloading means to have two or more methods with same name in the same
class with different arguments. The benefit of method overloading is that it allows you to
implement methods that support the same semantic operation but differ by argument
number or type.
Note:
Method overriding occurs when sub class declares a method that has the same type
arguments as a method declared by one of its superclass. The key benefit of overriding is
the ability to define behavior that’s specific to a particular subclass type.
Note:
The overriding method cannot have a more restrictive access modifier than the
method being overridden (Ex: You can’t override a method marked public and
make it protected).
13.What are the differences between method overloading and method overriding?
Overrid
Overloaded Method d
Yes, derived classes still can override the overloaded methods. Polymorphism can still
happen. Compiler will not binding the method calls since it is overloaded, because it might
be overridden now or in the future.
NO, because main is a static method. A static method can't be overridden in Java.
To invoke a superclass method that has been overridden in a subclass, you must either call
the method directly through a superclass instance, or use the super prefix in the subclass
itself. From the point of the view of the subclass, the super prefix provides an explicit
reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();
17.What is super?
super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the method
can refer to the hidden variable through the use of the super keyword. In the same way, if
a method overrides one of the methods in its superclass, the method can invoke the
overridden method through the use of the super keyword.
Note:
In the constructor, if you use super(), it must be the very first code, and you
cannot access any this.xxx variables or methods to compute its parameters.
// Method statements
19.What is an Interface?
Note:
You can’t instantiate an interface directly, but you can instantiate a class that
implements an interface.
Interfaces may have member variables, but these are implicitly public, static, and final- in
other words, interfaces can declare only constants, not instance variables that are
available to all implementations and may be used as key references for method arguments
for example.
Only public and abstract modifiers are allowed for methods in interfaces.
Marker interfaces are those which do not declare any required methods, but signify their
compatibility with certain operations. The java.io.Serializableinterface and Cloneable are
typical marker interfaces. These do not contain any methods, but classes must implement
this interface in order to be serialized and de-serialized.
Abstract classes are classes that contain one or more abstract methods. An abstract
method is a method that is declared, but contains no implementation.
Note:
If even a single method is abstract, the whole class must be declared abstract.
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
Interfac
Abstract Class es
In case of abstract class, a class may extend only one abstract A Class may implement several
class. interfaces.
If we add a new method to an abstract class then we have the If we add a new method to an
option of Interface the
providing default implementation and therefore all the existing the implementations of the interface
code and d
might work properly. new method.
An Interface cannot contain
An abstract class can contain constructors . constructors .
28.When should I use abstract classes and when should I use interfaces?
If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included
in the class, then you go for the interface, which makes it easy to just implement
and make use of the methods defined in the interface.
Use Abstract Class when…
If various implementations are of the same kind and use common behavior or
status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.
29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.
31.What is Constructor?
A constructor is a special method whose task is to initialize the object of its class.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
If a class defined by the code does not have any constructor, compiler will automatically
provide one no-parameter-constructor (default-constructor) for the class in the byte code.
The access modifier (public/private/etc.) of the default constructor is the same as the
class itself.
No, constructor cannot be inherited, though a derived class can call the base class constructor.
Me
Constructors t
Return Type No return type, not even void void or a valid return type
Calls the constructor of the parent class. If used, must Calls an overridden
super be method in
the first line of the constructor
36.What are the differences between Class Methods and Instance Methods?
Instance
Class Methods Meth
Class methods can only operate on class members and not on Instance methods of the class can also
instance not b
method unless they are being called
members as class methods are unaware of instance members. on an i
Constructors use this to refer to another constructor in the same class with a
different parameter list.
Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same
class to which the methods and fields belong, within its subclasses, and within
classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a
class, method, or field will be accessible from inside the same package to which
the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to
which the methods and fields belong. private methods and fields are not visible
within subclasses and are not inherited by subclasses.
Accessible to class
yes yes
from same package?
Accessible to class
yes no, unless it is a subclass
from different package?
40.What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore.
The actual meaning depends on whether it is applied to a class, a variable, or a method.
Increasing efficiency by allowing the compiler to turn calls to the method into inline
Java code.
Static block which exactly executed exactly once when the class is first loaded into JVM.
Before going to the main method the static block will execute.
Variables that have only one copy per class are known as static variables. They are not
attached to a particular instance of a class but rather belong to a class as a whole. They
are declared by using the static keyword as a modifier.
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically
initialized with a default value. The default value depends on the data type of the
variables.
A static variable is associated with the class as a whole rather than with specific instances
of a class. Non-static variables take on unique values with each object instance.
Methods declared with the keyword static as modifier are called static methods or class
methods. They are so called because they affect a class as a whole, not a particular
instance of the class. Static methods are always invoked without reference to a particular
instance of a class.
A static method cannot reference to the current object using keywords super or
this.
46.What is an Iterator ?
To use an iterator to traverse through the contents of a collection, follow these steps:
Iterator also has a method remove() when remove is called, the current element in
the iteration is deleted.
Enumeration Iterator
Enumeration acts as Read-only interface, because it has the Can be abstract, final, native, static, or
methods only sy
to traverse and fetch the objects
50.How is ListIterator?
ListIterator is just like Iterator, except it allows us to access the collection in either the
forward or backward direction and lets us modify an element
The ArrayList increases its array size by 50 percent if it runs out A Vector defaults to doubling the size of
of room. its
ArrayList has no default size. While vector has a default size of 10.
ArrayList internally uses and array to store the elements, when that array gets
filled by inserting elements a new array of roughly 1.5 times the size of the original
array is created and all the data of old array is copied to new array.
During deletion, all elements present in the array after the deleted elements have to
be moved one step back to fill the space created by deletion. In linked list data is
stored in nodes that have reference to the previous node and the next node so
adding element is simple as creating the node an updating the next pointer on the
last node and the previous pointer on the new node. Deletion in linked list is fast
because it involves only updating the next pointer in the node before the deleted
node and updating the previous pointer in the node after the deleted node.
Because, if list is structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator
fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an
undetermined time in the future.
58.How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random access, without inserting or removing elements from any
place other than the end, then ArrayList offers the optimal collection. If, however, you need
to frequently add and remove elements from the middle of the list and only access the list
elements sequentially, then LinkedList offers the better implementation.
59.What is the Set interface ?
The Set interface provides methods for accessing the elements of a finite mathematical set
Two Set objects are equal if they contain the same elements
HashSet
TreeSet
LinkedHashSet
EnumSet
61.What is a HashSet ?
It uses the hashcode of the object being inserted (so the more efficient your
hashcode() implementation the better access performance you’ll get).
Use this class when you want a collection with no duplicates and you don’t care
about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements
are sorted according to the natural order of elements or by the comparator provided at
creation time.
63.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the
EnumSet type that is specified, explicitly or implicitly, when the set is created.
HashSet is under set interface i.e. it does not guarantee for either TreeSet is under set i.e. it provides
sorted elemen
order or sequence order. order).
We can add only similar types
We can add any type of elements to hash set.
of elements to tree set.
65.What is a Map ?
Some maps can accept a null key and null values, others cannot.
HashMap
HashTable
TreeMap
EnumMap
67.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In
a TreeMap the data will be sorted in ascending order of keys according to the natural order
for the key's class, or by the comparator provided at creation time. TreeMap is based on
the Red-Black tree data structure.
68.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap
is your better alternative. Depending upon the size of your collection, it may be faster to
add elements to a HashMap, then convert the map to a TreeMap for sorted key
traversal.
The iterator in the HashMap is fail-safe (If you change the map
while The enumerator for the Hashtable is
not fai
iterating, you’ll know).
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple
keys to be NULL. Nevertheless, it can have multiple NULL values.
70.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map interface. In
a TreeMap the data will be sorted in ascending order of keys according to the natural
order for the key's class, or by the comparator provided at creation time. TreeMap is
based on the Red-Black tree data structure.
KeySet is a set returned by the keySet() method of the Map Interface, It is a set that
contains all the keys present in the Map.
Values Collection View is a collection returned by the values() method of the Map
Interface, It contains all the objects present as values in the map.
Entry Set view is a set that is returned by the entrySet() method in the map and
contains Objects of type Map. Entry each of which has both Key and Value.
The Comparable interface is used to sort collections and arrays of objects using
interface Comparable<T>
All classes implementing the Comparable interface must implement the compareTo()
method that has the return type as an integer. The signature of thecompareTo() method is
as follows:
int i = object1.compareTo(object2)
77.What are the differences between the Comparable and Comparator interfaces ?
Comparable Comparato
It uses the compareTo() method. t uses the compare() method.
It is necessary to modify the class whose instance is A separate class can be created
going to be sorted. in order to
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.
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 and physically
exists.
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:
Class(Method) Area
Heap
Stack
Program Counter Register
Native Method Stack
3)What is JIT compiler?
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:
Runtime Environment
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 platorm 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:
//save by .java only
class A{
public static void main(String args[]){
System.out.println(“Hello java”);
}
}
No.
10)If I do not provide any arguments on the command line, then the String
array of Main method will be empty or null?
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?
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.
17)Does constructor return any value?
Ans:yes, that is current instance (You cannot use return type yet it returns a value).
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?
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
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.
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?
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?
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.
38)Why method overloading is not possible by changing the return type in
java?
Because of ambiguity
39) Can we overload main() method?
Yes, of-course! You can have many main() methods in a class by overloading the main
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.
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.
Core Java – OOPs Concepts: final keyword Interview Questions
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
48)What is final method?
A final variable, not initalized at the time of declaration, is known as blank final variable.
51) Can we intialize blank final variable?
In case of static binding type of object is determined at compile time whereas in dynamic
binding type of object is determined at runtime.
Abstraction hides the implementation details whereas encapsulation hides the data.
Abstraction lets you focus on what the object does instead of how it does it.
58) What is 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?
Interface is a blueprint of a class that have static constants and abstract methods.It can
be used to achive 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?
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?
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?
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 ?
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.
There is given a list of exception handling interview questions with answers. If you know
any exception handling interview question, kindly post it in the comment section.
73) What is Exception Handling?
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?
Yes.
82)Can subclass overriding method declare an exception if parent class method
doesn’t throw an exception ?
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?
Because java uses the concept of string literal. Suppose there are 5 reference
variables,allreferes 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?
String s1=”Welcome”;
String s2=”Welcome”;
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?
We can create immutable class as the String class by defining final class .
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
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 ofcourse! 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?
There is given a list of multi threading interview questions and answers. If you know any
multi threading interview question, kindly post it in the comment section.
100) What is multithreading?
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.
103) 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.
104) What is difference between wait() and sleep() method?
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.
105) Is it possible to start a thread twice?
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.
107) 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.
108)Can we make the user thread as daemon thread if thread is started?
The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down.
So we can use it perform clean up resource.
110)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.
Core Java : Synchronization Interview Questions
The following interview questions are also the part of multi threading interview
questions.
111) What is synchronization?
Synchronization is the capabilility of control the access of multiple threads to any shared
resource.It is used:
To prevent thread interference.
To prevent consistency problem.
112) What is the purpose of Synchronized block?
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.
114) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on
object.
115)What is the difference between notify() and notifyAll()?
notify() is used to unblock one waiting thread whereas notifyAll() method is used to
unblock all the threads in waiting state.
116)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.
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.
125)What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
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
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.
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?
Yes, by changing the runtime behaviour of a class if the class is not secured.
In java, collection interview questions are mostly asked by the interviewers. Here is the
list of mostly asked collection interview questions with answers.
135) What is difference between ArrayList and Vector?
ArrayList Vector
1) ArrayList is not synchronized. 1) Vector is synchronized.
2) ArrayList is not a legacy class. 2) Vector is a legacy class.
3) ArrayList increases its size by 50% of the array size. 3) Vector increases its size by
doubling the array size.
136) What is difference between ArrayList and LinkedList?
ArrayListLinkedList
1) ArrayList uses a dynamic array. 1) LinkedList uses doubly linked list.
2) ArrayList is not efficient for manipulation because a lot of shifting is required. 2)
LinkedList is efficient for manipulation.
137) What is difference between HashMap and Hashtable?
HashMapHashtable
1) HashMap is not synchronized. 1) Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values. 2) Hashtable cannot
contain any null key nor value.
138)What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value. Two different entries will be kept in a
single hash bucket to avoid the collision.
139) What is difference between HashSet and HashMap?
HashMapTreeMap
1) HashMap is can contain one null key. 1) TreeMapconnot contain any null key.
2) HashMap maintains no order. 2) TreeMap maintains ascending order.
141) What is difference between HashSet and TreeSet?
List can contain duplicate elements whereas Set contains only unique elements.
143) What is difference between Iterator and ListIterator?
Iterator traverses the elements in forward direction only whereas ListIterator traverses
the elements in forward and backward direction.
144) Can you make List,Set and Map elements synchronized?
Iterator Enumeration
1) Iterator can traverse legacy and non-legacy elements. 1) Enumeration can traverse
only legacy elements.
2) Iterator is fail-fast. 2) Enumeration is not fail-fast.
3) Iterator is slower than Enumeration. 3) Enumeration is faster than Iterator.
146) What is difference between Comparable and Comparator?
Comparable Comparator
1) Comparable provides only one sort of sequence. 1) Comparator provides multiple sort
of sequences.
2) It provides one method named compareTo(). 2) It provides one method named
compare().
3) It is found in java.lang package. 3) it is found in java.util package.
4) If we implement Comparable interface, actual class is modified. 4) Actual class is not
modified.
147) What is the Dictionary class?
Wrapper classes are classes that allow primitive types to be accessed as objects.
149)What is a native method?
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
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?
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?
161)What is 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 develpoment environment, like JBuilder or
VisualAge for Java.
165)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.
166)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:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver).
167)What are the steps to connect to database in java?
ok.
And don't comments. Just prepare
Today's CTS interview question
Technical Round:-
=============
*Core-java
************
1 .Tell me the internal flow of Set implementation class with one example
ans:-Set Internally use Map so it doesn't allow duplicate
Map<Set<Obj>,String> m=new HashMap<>();
so whatever object u passed in set.add() method it will place in Map as a key as per
above.
2 . In HashMap if hashing collision occure then how to resolve it.
ans:-Hashing collision means if in collection if multiple object having same hashCode()
then it
will definatly placed in same bucket
so to resolve this one we need to override equlas() method it will check content wise if
object
are content wise same then override the value.else just place in same bucket
3 . can we add duplicate in set and map if yes why write one code
ans: yes, we can add if u don't override equlas() and hashCode() then duplicate will be
allow in
set and map also coz there is no element for comparing thats the reason duplicate are
allow..
class Employee{
int id;
String name;
public Employee(int id,String name){
this.id=id;
this.name=name;
}
@Override
//toString() method here
public static void main(String[] args){
Set<Employee> s=new Set<>();
s.add(new Employee(10,"Basant"));
s.add(new Employee(10,"Basant"));
sop(s);
}
}
4 . Read data from file find the duplicate word and count them and sort them in
desending order
public class ReadFileAndCount {
Map<String, Integer> wordMap = null;
String line = null;
public Map<String, Integer> counter(String fileName) throws IOException {
wordMap = new HashMap<String, Integer>();
try (BufferedReader br = new BufferedReader(new FileReader(new File(
fileName)))) {
while ((line = br.readLine()) != null) {
String[] data = line.split(" ");
for (String word : data) {
if (wordMap.containsKey(word)) {
wordMap.put(word, (wordMap.get(word) + 1));
} else {
wordMap.put(word, 1);
}
}
}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap) {
// convert map to set
Set<Entry<String, Integer>> mapSet = wordMap.entrySet();
// add set to list
List<Entry<String, Integer>> mapList = new ArrayList<>(mapSet);
// use utility method
Collections.sort(mapList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
return mapList;
}
public static void main(String[] args) throws IOException {
ReadFileAndCount rfc = new ReadFileAndCount();
Map<String, Integer> value = rfc.counter("info.txt");
List<Entry<String, Integer>> data = rfc.sortByValue(value);
for (Map.Entry<String, Integer> getData : data) {
sop(getData.getKey() + "=>" + getData.getValue());
}
}
}
5 . where to use Comparable and where to use Comparator did you ever used in ur
project
ans: actually we are not using that interface in our project to sorting data..but i have
idea on it
that we have to use Comparable if u want
to sort the object in collection in simple sorting order like assending or desending if u
want
custom sorting then better to choose
Comparator.
6 . what is bubble sort can you write one programme. .?
public class ArraySort {
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
System.out.print(arr[i] + ",");
}
}
}
7 . can I write try block single means without using try-catch or try-finally
ans: yes we can write .in java 1.7 there is one features try-with-resources by which ur
resourse
stream will be closed automatically
8 . what is Executor framework
ans:Executor Framework is interduced in Concurrent package normaly if we want use
thread
pool to achive reusability then we have to choose this one
9 . how many way we can create thread and which one best approach and why
ans:There are 4 way
1 . extends Thread
2 . implements Runnable
3. implements Cloneable
4 . using AnonymousThread
Preferable is 3rd one coz if you implements from Callable then see below
class MyThread implements Callable {
public Object call (){
return obj;
}
Here after execution my thread return something based on requirements u have to
choose
2 nd approach also good
In both cases we can achive fully abstraction and runtime polymorphism nd multiple
inheritance
so 2 nd 3 r best approach
10 . jdk version u r using in ur project and why (be care on that question coz they
indirectly ask
u the advantages of version or latest features added in New version )
We are using jdk 7
Then tell all the advantages
Like 1 . try with resources
2 . multi catch Exp Handler
3 . String Switch case
4 . Diamond Operator
6 . simple way to declare long variable
*Jdbc:-
**********
1 . difference between Statement and PreparedStatement
ans:Statement are use if we want to pass static querry or hardcoded value if we uant to
pass
positional parameter/Runtime value
then better to use PreparedStatement and in Simple Statement there may be a chance
to get
SQL Injection which we can be
Resolve by PreparedStatement
2.they give one db schema and ask me to retrieve data from DB by passing id
table:-
=====
id name
=============
101 Basant
104 Santosh
final String SQL_QRY_FOR_GET_NAME_BY_ID="SELECT NAME FROM EMPLOYEE
WHERE ID=?";
1.class.forName()
2.Connection con=DriverManager.getConnection();
3.PreparedStatement ps=con.preparedStatement(SQL_QRY_FOR_GET_NAME_BY_ID);
4.ps.setParameter(1,101)
5.ResultSet rs=ps.executeQuerry();
6.Itterate
*Spring :-
**********
1.What is RowMapper when we have to use it write sample code not completely just give
sm
hints with flow?
ans:See basically if we want to iterate complete entity from db then we have to use
RowMapper
which are
Provided by Spring-Framework by which it can easily featch the data from db and it
follow call
back
Mechanisim so it gives us Resultse as method parameter that we can simple get the data
by RS
2.what is ResultSet Extractor where exactly we have to use ?
ans: ResultsetExtractor is used if we want to iterate data from db with some specific
range or
partial ,ya i used it in my
project for pagination by assuming display pageNo and size as per SRC
3.if in my Spring bean configuration file I configure same bean with same id 2 times then
what is
the problem and how to resolve it (contender)
ans:we have to use one atribute in Spring-beans configuration file actualy i am not able
to
remebere that word
properly coz we are using eclips id so but it like something Contender ...
4 . Spring Mvc Flow as per your Project
===================
To make webapp
=====================================
??1 .First From browser u forward request to servlet (Dispatcher Servlet) to handel it..
??2.Dispatcher Servlet here act as a controller. Who only manage the request
processing. ..so it
rcv the request and then forward request to HandlerMapping
??3.Handler mapping is framework provide class..Normally in mvc there r several
controller
Bean so HandlerMapping helps to search appropriate controller Bean based on request
url to
perform business operation
??4.and 5 After finding controller Bean it process some operation and return MAV object
..to
Dispatcher Servlet
M:-model
A:-and
V:-view
??6 . Now after processing business operation response will be generated and it should
be
display on browser otherwise how enduser know about response. ..so to find appropriate
view
representer..Dispatcher Servlet call again ViewResolver. .which helps to find appropriate
jsp to
display view
??7 . Then Dispatcher Servlet render data nd call that jsp which is identify by
ViewResolver to
view response on browser. ..
??8. Finally Response will be receive by End user. ..
5.Spring transaction, why nd how to work on it
ans: we are using Annotation Approach
@Transactional(read-only="false",isolation="Read-Commit",propagation="Required")
6. How u handle Exception in ur Project just give some brief idea on it with annotation
ans: ya to handle the exception we are creating separate Controller class annotatted
with
@AdviceController and here we are
writting one method by passing the exception as parameter and annotated with method
@ExceptionHandler then from my controller
i have to pass same logical name which i already return from my adviceController class
*Webservices :-
**************
1 . WSDL ,what are the elements and just explain the role of each section verbally
ans:
WSDL(Web service Description Language) actually it act as contract betwwen provider
and
consumer and basically contain 5 section 1)Defination 2)types 3)Message 4)PortType
5)Binding
6)Service
Defination:-it act as a root element in XML it just specify the name
types:-it talks about each indivisual required input and output to my webservice method
message:-it talks about exactly what my web-service method takes a parameter in
single unit
portType:-it talks about exact structure of your SEI(Service endPoint Interface)
Binding: talks about what is the protocol it used and which Message Exchanging format
it
follows
service: it talks about address
2.what is Rest,
ans: Rest is a new architectureal style of develope the webservice or we can say this one
is the
easyst way to our
complex business logic over the network with distrubuted technology with interorporable
manner
3 . difference between Soap and Rest ?
ans:Both are used to develope webservices only but the basic difference
1.In sopa base web-service we need to depends on Sopa protocol it act as a transport
protocol
who support only Xml for transfer
but in rest it is support not xml it supports XML,JSON,PLAIN_TEXT also
2.Sopa development is complicated in comparision Rest coz we need to depends on
Multiple
3rd party vender
and procudure is varry from one implementation to anothe implementation
3.Sopa is not Message-Represention-Oriented but rest is M-R-O
4.for security and transaction Soap is Preferable..
4.Write one Resource method using Http method Post
5.which Response u provide to presentation layer and how to bind Json Response ?
ans: We are providing JSON Responce and it will bind through Angular js in UI.
6.Difference between @QuerryParm and @PathPatm which one best and where to use. ..
ans: QuerryParm is not mandatory to pass but if u want data is mandatory then
PathParm is
Best
Answer:
The program compiles properly but at runtime it will give “Main method not public.”
message.
Answer:
Pass by reference means, passing the address itself rather than passing the value. Pass
by value means passing a copy of the value.
Answer:
hashCode()
Q. What gives java it’s “write once and run anywhere” nature?
Answer:
All Java programs are compiled into class files that contain bytecodes. These byte codes
can be run in any platform and hence java is said to be platform independent.
Q. Expain the reason for each keyword of public static void main(String
args[])?
Answer:
public – main(..) is the first method called by java environment when a program
is executed so it has to accessible from java environment. Hence the access
specifier has to be public.
static : Java environment should be able to call this method without creating an
instance of the class , so this method must be declared as static.
void : main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line
and arg is an array for string given during command line.
Or
Or
Or
Q. What would you use to compare two String variables – the operator == or
the method equals()?
Or
Q. How is it possible for two String objects with identical values not to be equal
under the == operator?
Answer:
The == operator compares two objects to determine if they are the same object in
memory i.e. present in the same memory location. It is possible for two String objects to
have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which is equivalent
to the equality operator == being used to compare aliases to the object. String, BitSet,
Date, and File override the equals() method. For two String objects, value equality
means that they contain the same character sequence. For the Wrapper classes, value
equality means that the primitive values are equal.
01 public class EqualsTest {
02
04
05 String s1 = “abc”;
06 String s2 = s1;
07 String s5 = “abc”;
15 }
16 }
Output
1 == comparison : true
2 == comparison : true
4 false
Q. What if the static modifier is removed from the signature of the main
method?
Or
Q. What if I do not provide the String array as the argument to the method?
Answer:
Answer:
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver
includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in
Java, so it is platform independent, can be downloaded to a browser at runtime, and
does not require any Oracle software on the client side. This driver requires a TCP/IP
listener on the server side, and the client connection string uses the TCP/IP port address,
not the TNSNAMES entry for the database name.
Q. What is the difference between final, finally and finalize? What do you
understand by the java final keyword?
Or
Or
Or
Answer:
Variables defined in an interface are implicitly final. A final class can’t be extended i.e.,
final class may not be subclassed. This is done for security reasons with basic classes
like String and Integer. It also allows the compiler to make some optimizations, and
makes thread safety a little easier to achieve. A final method can’t be overridden when
its class is inherited. You can’t change value of a final variable (is a constant). finalize()
method is used just before an object is destroyed and garbage collected. finally, a key
word used in exception handling and will be executed whether or not an exception is
thrown. For example, closing of open connections is done in the finally method.
Answer:
The Java API is a large collection of ready-made software components that provide many
useful capabilities, such as graphical user interface (GUI) widgets.
Answer:
Answer:
The ResourceBundle class is used to store locale-specific resources that can be loaded by
a program to tailor the program’s appearance to the particular locale in which it is being
run.
Answer:
Global variables are globally accessible. Java does not support globally accessible
variables due to following reasons:
Answer:
The valueOf() function of Integer class is is used to convert string to Number. Here is the
code example:
2 int id=Integer.valueOf(numString).intValue();
Answer:
Answer:
A while statement (pre test) checks at the beginning of a loop to see whether the next
loop iteration should occur. A do while statement (post test) checks at the end of a loop
to see whether the next iteration of a loop should occur. The do statement will always
execute the loop body at least once.
Answer:
The Locale class is used to tailor a program output to the conventions of a particular
geographic, political, or cultural region.
Answer:
There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.
Answer:
Inheritance is the process by which one object acquires the properties of another object.
Inheritance allows well-tested procedures to be reused and enables changes to make
once and have effect in all relevant places
Answer:
Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds
of transformations and may not work for all scenarios.
Example
1 int i = 1000;
Answer:
Answer:
Answer:
System is a predefined final class, out is a PrintStream object and println is a built-in
overloaded method in the out object.
Or
Answer:
Polymorphism in simple terms means one name many forms. Polymorphism enables one
entity to be used as a general category for different types of actions. The specific action
is determined by the exact nature of the situation.
Method overloading
Answer:
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.
Example
1 long i = 700.20;
Answer:
The Java Virtual Machine is software that can be ported onto various hardware-based
platforms
Answer:
The process of Downcasting refers to the casting from a general to a more specific type,
i.e. casting down the hierarchy
Or
Q. What is the difference between public, private, protected and default Access
Specifiers?
Or
Answer:
Access specifiers are keywords that determine the type of access to the member of a
class. These keywords are for allowing privileges to parts of a program such as functions
and variables. These are:
Protected: accessible to the classes within the same package and any subclasses.
Default: accessible to the class to which they belong and to subclasses within the
same package
Answer:
Object.
Answer:
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
Additional is String.
Q. What is the difference between static and non-static variables?
Or
Or
Or
Answer:
A static variable is associated with the class as a whole rather than with specific
instances of a class. Each object will share a common copy of the static variables i.e.
there is only one copy per class, no matter how many objects are created from it. Class
variables or static variables are declared with the static keyword in a class. These are
declared outside a class and stored in static memory. Class variables are mostly used for
constants. Static variables are always called by the class name. This variable is created
when the program starts and gets destroyed when the programs stops. The scope of the
class variable is same an instance variable. Its initial value is same as instance variable
and gets a default value when it’s not initialized corresponding to the data type.
Similarly, a static method is a method that belongs to the class rather than any object of
the class and doesn’t apply to an object or even require that any objects of the class
have been instantiated. Static methods are implicitly final, because overriding is done
based on the type of the object, and static methods are attached to a class, not an
object. A static method in a superclass can be shadowed by another static method in a
subclass, as long as the original method was not declared final. However, you can’t
override a static method with a non-static method. In other words, you can’t change a
static method into an instance method in a subclass.
Q. What is the difference between the boolean & operator and the && operator?
Answer:
If an expression involving the boolean & operator is evaluated, both operands are
evaluated, whereas the && operator is a short cut operator. When an expression
involving the && operator is evaluated, the first operand is evaluated. If the first operand
returns a value of true then the second operand is evaluated. If the first operand
evaluates to false, the evaluation of the second operand is skipped.
Answer:
It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation.
Answer:
In declaration we only mention the type of the variable and its name without initializing
it. Defining means declaration + initialization. E.g. String s; is just a declaration while
String s = new String (”bob”); Or String s = “bob”; are both definitions.
Answer:
In Java the arguments (primitives and objects) are always passed by value. With
objects, the object reference itself is passed by value and so both the original reference
and parameter copy both refer to the same object.
Answer:
Encapsulation is a process of binding or wrapping the data and the codes that operates
on the data into a single entity. This keeps the data safe from outside interface and
misuse. Objects allow procedures to be encapsulated with their data to reduce potential
interference. One way to think about encapsulation is as a protective wrapper that
prevents code and data from being arbitrarily accessed by other code defined outside the
wrapper.
Answer:
Variable is a named memory location that can be easily referred in the program. The
variable is used to hold the data and it can be changed during the course of the
execution of the program.
Answer:
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric
type, so that integral and floating-point operations may take place. In the numerical
promotion process the byte, char, and short values are converted to int values. The int
values are also converted to long values, if necessary. The long and float values are
converted to double values, as required.
Q. What do you understand by casting in java language? What are the types of
casting?
Answer:
The process of converting one data type to another is called Casting. There are two
types of casting in Java; these are implicit casting and explicit casting.
Answer:
The String array is empty. It does not have any element. This is unlike C/C++ where the
first element by default is the program name. If we do not provide any arguments on the
command line, then the String array of main method will be empty but not null.
Q. How can one prove that the array is not null but empty?
Answer:
Print array.length. It will print 0. That means it is empty. But if it would have been null
then it would have thrown a NullPointerException on attempting to print array.length.
Answer:
Yes. While starting the application we mention the class name to be run. The JVM will
look for the main method only in the class whose name you have mentioned. Hence
there is not conflict amongst the multiple classes having main method.
Answer:
Static variable are loaded when classloader brings the class to the JVM. It is not
necessary that an object has to be created. Static variables will be allocated memory
space when they have been loaded. The code in a static block is loaded/executed only
once i.e. when the class is first initialized. A class can have any number of static blocks.
Static block is not member of a class, they do not have a return statement and they
cannot be called directly. Cannot contain this or super. They are primarily used to
initialize static fields.
Answer:
We can have multiple overloaded main methods but there can be only one main
method with the following signature :
No the program fails to compile. The compiler says that the main method is already
defined in the class.
Answer:
JVM is an abstract computing machine like any other real computing machine which first
converts .java file into .class file by using Compiler (.class is nothing but byte code file.)
and Interpreter reads byte codes.
Answer:
Add two variables and assign the value into First variable. Subtract the Second value
with the result Value. and assign to Second variable. Subtract the Result of First Variable
With Result of Second Variable and Assign to First Variable. Example:
You use an XOR swap. (BEST APPROACH) as in case of using above approach it may
goes over/under flow. For example:
1 int a = 5; int b = 10;
2 a = a ^ b;
3 b = a ^ b;
4 a = a ^ b;
Answer:
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN)
which are used to access the fields of the object. Typically the fields are made private
while the get and set methods are public. Encapsulation can be used to validate the data
that is to be stored, to do calculations on data that is stored in a field or fields, or for use
in introspection (often the case when using javabeans in Struts, for instance). Wrapping
of data and function into a single unit is called as data encapsulation. Encapsulation is
nothing but wrapping up the data and associated methods into a single unit in such a
way that data can be accessed with the help of associated methods. Encapsulation
provides data security. It is nothing but data hiding.
Answer:
Reflection is the process of introspecting the features and state of a class at runtime and
dynamically manipulate at run time. This is supported using Reflection API with built-in
classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API
we can get the class name, by using the getName method.
Q. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap?
Is this the OS heap or the heap maintained by the JVM? Why
Answer:
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but
references to those objects are on the STACK.
Answer:
Phantom memory is false memory. Memory that does not exist in reality.
Answer:
A static method can be synchronized. If you do so, the JVM will obtain a lock on the
java.lang.
1 synchronized(XYZ.class) {
2}
Example:
2 while (st.hasMoreTokens()) {
3 System.out.println(st.nextToken());
4}
Output:
1 Hello
2 World
Answer:
Note
01 transient
02
04
06
07 system)
08
09
10
11 volatile
12
13 indicates that the field is used by synchronized threads
14
16
18
19
20
22
23 checked every time. Every thread keeps the latest value of volatile variable
Question: Name the containers which uses Border Layout as their default
layout?
Answer:
Containers which uses Border Layout as their default are: window, Frame and Dialog
classes.
Answer:
5}
4 }
5}
Core-Java----1 st round
===================
ans:Interface is a special type of class through which we can achive fully abstraction
runtime polymorphisim and multiple inheritance which makes our code completely loose
coupled
but in abstract class also we can achive abstraction and R.P but partially..coz it
contains both abstract method as well as concret method but in abstract class u can't get
multiple inheritance
ans: As per my project what we people are developed that will be hidden from user so
for them it is abstraction otherwise explain Hari sir Bank Atm example
ans: Ya we implement all the concept in our project and Encapsulation we used in
Business Object or Model class
Inheritance and Polymorphisim we implement in Dao and Service Layer to make it loosly
coupled
5.To override all the method from super which keyword we have to use.and why
ans: Cause Abstract class contain boh concrete and abstract method but it's not
mandatory that
fully abstraction
7.Write 5 classes which u r develope in your project with fully qualified name ?
1.MODULE_NAME_DAO---------com.productOwnersortname.module.layer
2.MODULE_NAME_SERVICE
3.MODULE_NAME_CONTROLLER
4.MODULE_NAME_BO
5.MODULE_NAME_DTO
6.MODULE_NAME_MAPPER
.MODULE_NAME_UTIL
8.What are the exception u face in ur project development and how u resolve them
explain ?
ans:
ans:Coz my project is Intranet Application and it handles huge amount of data for
ans: DEBUG,ERROR,WARN
Second-Round(CoreJava+Spring)
===========================
1.What is abstraction
int no;
super();
this.no = no;
if (this.no == no) {
return this;
} else {
3.What is singletone ,In your project did u use singletone ,Where write code ?
ans:Singleton is object creation design pattern by which we can instantiate only one
instance
In my project i didn't use coz we are using Spring so every bean scope is singleton
array to allow duplicate but in case of Set it internally follow Map which object u add in
set it will be placed as key in That internal Map so duplicate not allowed in Set
automatically we no need create object and no need to map with object .it internally
ans: We are using both setter and constructor injection both coz some fields we need to
compolsory
ans:4.x
ans:-
@Componet,@Service,@Controller,@Autowire,@Transactional,@Scope,@ControllerAdvic
e,@ExceptionHandler
@RequestParm,@PathVariable,@ModelAttribute,@PropertyResource
ans:
<aop:config>
<aop:pointcut expression="execution(*
com.dt.service.ManageEmployeeService.*(..))" id="manageEmpPct"/>
</aop:config>
<tx:advice id="manageEmployeeTxAdvice">
<tx:attributes>
</tx:attributes>
</tx:advice>
ans: @Transactional(read-only="false",Isolation="Read-
Commit",Propagation="Required")
ex:
here class is same but id is different so here my IOC Container confuse due to same
class
ans:If from form page or from UI page u want to get more 2 to 3 element then use
@RequestParm
ex:just assume from login page how many element u will get 2 username and pwd use
@RequestParm
if incoming data will be more then bind them in one object by using @ModelAttribute
ex:Suppose u book a ticket then lot of data u have to pass as input
code testing and write junit test case and test it 2 to 3 times
participate in daily-Scrum
1. Can someone answer where have you used Concurrent Hashmap in your project?
If you know what is ConcurrentHashMap and in which situation we should use it. Then u
can find Senario by own.
I used I has one requirement need to iterate list technician and from technician we need
to extract tech id as key of map and skills as value that is String[]
So based on techid I need to check in one more table if the task assign to him is
matched with his skill then remove that tech from map and send notification to
supervisor with details of tech.
Examples :
Assume a payment transaction while purchase something from shopping site like
Amazon or flip kart
Senario :
Suppose I order one product from Amazon and it generate one order ID and based on
Order ID I want to process the payment
Assume my order got booked but payment got failed so that time we should manage the
transaction nd need to roll back this transaction else without payment we will rcv the
order.
So all people will try to book an order with 0 balance account isn't it business loss.
Spring Transaction Management is one of the most widely used and important feature of
Spring framework. Transaction Management is a trivial task in any enterprise
application. Spring provides extensive support for transaction management and help
developers to focus more on business logic rather than worrying about the integrity of
data incase of any system failures.
a. Support for Declarative Transaction Management. In this model, Spring uses AOP over
the transactional methods to provide data integrity. This is the preferred approach and
works in most of the cases.
b. Support for most of the transaction APIs such as JDBC, Hibernate, JPA, JDO, JTA etc.
All we need to do is use proper transaction manager implementation class. For example
org.springframework.jdbc.datasource.DriverManagerDataSource for JDBC transaction
management and org.springframework.orm.hibernate3.HibernateTransactionManager if
we are using Hibernate as ORM tool.
Greatest features provided by spring framework. To design this DI they comes under
Strategy design pattern
See programaticall description
class Bank{
this.transaction=transaction;
return transaction;
/*Approach:1
by using Composition
sbi.deposite();*/
/*Approach:2
by taking interface
achive RuntimePolymorphisim
transaction=new SBI();
transaction.deposite();
transaction=new AXIS();
transaction.deposite();*/
/*Approach:3
Here we get partial couple not fully
name
transaction=BankTransactionFactory.getInstance("axis");
transaction.deposite();*/
transaction.deposite();
interface Transaction{
System.out.println("Deposit in SBI");
System.out.println("Deposit in AXIS");
class BankTransactionFactory{
public static Transaction getInstance(String type){
if(type.equalsIgnoreCase("Sbi")){
else if(type.equalsIgnoreCase("Axis")){
return null;
class Customer{
b.setBank(t);
b.doTransaction();
pattern
*/
There are common situations when classes differ only in their behavior. For this cases is
a good idea to isolate the algorithms in separate classes in order to have the ability to
select different algorithms at runtime.
Example :
package com.stratergy.pattern;
void moveOnCommand();
package com.stratergy.pattern;
@Override
package com.stratergy.pattern;
@Override
package com.stratergy.pattern;
@Override
public void moveOnCommand() {
package com.stratergy.pattern;
Behaviour behaviour;
String name;
this.name = name;
this.behaviour = behaviour;
return behaviour;
return name;
this.name = name;
}
public void move() {
behaviour.moveOnCommand();
package com.stratergy.pattern;
r1.setBehaviour(new AgressiveBehaviour());
r2.setBehaviour(new DefensiveBehaviour());
r3.setBehaviour(new NormalBehaviour());
r1.move();
r2.move();
r3.move();
r1.setBehaviour(new DefensiveBehaviour());
r2.setBehaviour(new AgressiveBehaviour());
r1.move();
r2.move();
r3.move();
If I import java.lang.*;
Then all the child classes must be imported into the class l, however package scope is
restricted to the package declared package level like a private variable scope is
restricted to.the declared class level.
Package declaration has biggest advantage is security and security comes from data
hiding
Second advantage is Modularity. now you guys 're me, which oops concept helps us I
achieving modularity?
Both having main purpose to support dependency management and automated build.
Maven:
1.Maven contains all dependency details in well manner structure inside pom.xml and it
is purely xml based
2.To achive inbuilt functionality we need to add plugin sparetly in maven and we need to
specify specific goal for it which supported by maven build tool
Gradle:
1.One of the first things we can note about Gradle is that it’s not using XML files, unlike
Ant or Maven. cause internally using Groovy script which more technically handy any
technology can intigrate it easily
2.in gradle every build and plugin we need to specify as a task and in one single shot
you can run all the task with out specify separate goal for each
As we compare 2 main points except these 2 all difference just syntatically changed but
having the same features , even if you will mark build.gradle we are specifying there
apply plugin: 'maven' so we can say gradle is just a layer above ant and maven with
much more manageable way if you observe we are following same structure and
command just syntax changed for both.
To generate WADL you need to write separate controller class with All your API details
for better refer below link.
https://javattitude.com/2014/05/26/wadl-generator-for-spring-rest/
As part of our project we are not using WADL cause we are consuming our service only
not any third party so from UI or from Ansible script we are getting the endpoint URL
.which is more easy suppose i developed bunch of end point which i want to provide
other user then only i need to bind up all endpoint and then i need to provide WADL . as
we are only using it for our internal call so WADL structure not required
1.EMS-API
2.HRMS-API
so think from HRMS-API i want to access any of method from EMS-API how can i do that
1)SOAP service
2)JMS right ?
And you know we need to follow lot of steps to develop any of above 2 , so as we know
to access any other service simple i should aware on URL,REQUEST and RESPONSE
that's enough to access any other API so this easy and handy features we are getting
using Rest API
i can use normal spring mvc as well but main problem i can't expose my service and one
more thing we are not developing fully MVC based application which provides by MVC
(MODEL,VIEW AND CONTROLER) , cause MODEL and CONTROLER is enough for us to
expose any service through rest and that view things mapped by separate UI team
through any of third party api like angular or ajax or jquery .
spring Vs Spring Boot , let's compare basic In short, Spring framework helps you build
web applications. It takes care of dependency injection, handles transactions,
implements an MVC framework and provides foundation for the other Spring frameworks
(including Spring Boot)
While you can do everything in Spring without Spring Boot, Spring Boot helps you get
things done faster:
build more with less code - no need for XML, not even web.xml, auto-configuration
useful tools for running in production, database initialization, environment specific config
files, collecting metrics
if you will observe multiple repository it supports with 0 config and lot of inbuilt features
it supports like data caching , it will give us monitor our application in multiple
environment etc..
Lambda expression just simply help us to ignore instantiate annonymous inner class and
it helps us to write code in easy manner with less boiler plate code like below and it
specific for functional interface
if you observe stream api of java 8 maximum utility method using the lambda
expression that's why our code is smooth and readable and faster
package com.acc.dev.Core;
// without lambda
@Override
};
interface1.test();
// with lambda
};
interface2.test();
To develope any enterprise application using maven means we must have instaled
maven and set class path else maven plugin should avilable in our developer IDE .
5.finish project
for example assume i added plugin wsdl2java how maven know what is the role of this
plugin by seeing the goal section and phase section he will identify like below
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/myService.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
maven life cycle catagorized in multiple section and each life cycle having specific role.
like
mvn: clean ->will help us to delete all generated file from target folder
mvn:package - take the compiled code and package it in its distributable format, such as
a JAR.
mvn:verify - run any checks on results of integration tests to ensure quality criteria are
met
mvn: install -> will help us to download all pom.xml dependency and store in m2
repositiry
mvn:generate Source-> helps us to generate source code from plugins like wsdl2java
etc.
mvn:build-> like here u can run any other specific life cycle commands
like this some more phase is there suppose assume am running mvn:install means all
the initial phase will execute first like validate,clean and package and all
To write junit test case for rest api multiple third party is there like mockMvc , power
mock and mockito
steps
3.Before run your test method just initialize ur mockMvc using @Before annotation
5.gather request and convert it to jsonString use either Gson or use ObjectMapper
5.then mention your method type which u r going to perform by passing the appropiate
end point url and pass the request string
like mockMvc.perform(POST("http://localhost:8080/saveEmployee"))
7.it will return us MvcResult as a raw data then map it your appropiateResponse type
8.then pick any boolean value from response and compare with assert
Example:
@RunWith(SpringRunner.class)
@Before
mockMvc =
MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
@Test
user1.setName("Basanta");
user1.setAddress("Hyderabad");
user2.setName("Santosh");
user2.setAddress("Bangalore");
users.add(user1);
users.add(user2);
request.setUsers(users);
.perform(post("/Services/saveUser").content(requestJson).contentType(MediaTyp
e.APPLICATION_JSON_VALUE))
.andExpect(status().isOk()).andReturn();
Assert.assertTrue(response.isStatus() == true);
you will find lot of difference in google , as far as i know there is main 2 reason
1.We should go for JMS if our request payload contains huge data
2.Using JMS u can't achive interoperable nature as it's name it self self explanatory i.e
Java messaging service
and in both the cases u can achive asynchronous and synchronous mechanisim
16.Can any one explain static Binding and Dynamic Binding with an example? In which
scenarios in real time we use this concept?
Dynamic binding we are following in each layer like service and persistence layer cause
we are following interface to design so what ever method we have in our service we
must have to override service implementation
When ever we have same business but only for few condition I need different input that
case we declare same method with different arguments in same class
The main reason people are going for yml instead of properties
Spring.datasource.driver-classname=
Spring.datasource.url=
Spring.datasource.username=
Spring.datasource.password=
Like above we need to write where Spring.datasource is common syntax
If same you will follow in yml means u can optimize ur syntax and it looks sound good
like Below
Spring:
datasource:
driver-class:
url:
username :
password :
See this tree hierarchy where spring is root node then datasource Then all required fields
basically .yaml support most readabilty hirearchy as compared to .proerties and second
yaml support list and map too but properties just string or raw form of data . that's why
yaml is better approach
1.project architecture?
2.spring flow?
4.what are all the annotations you used in your project on restful services?
23.what are all the critial situations you come across in your project?
24.why wait() placed in object class ? why not it is placed in Thread class?
26.what is diff b/w String str="xyz"; and String str2= new String("xyz");
30.i have a compeny table in remote database. by using rest i need to get the table data
31.how to read book pages on online library by using bookid or author id(by using restful
services)?
32.i have a table in remote database, how to update the data in that table using rest?
34.agile methodolgy?
database objects.)?
49.what is time complexity? if you are going to implement sorting by your own which
52.programs on io streams?
expressions).
64.what are all the modifiers we can use inside method?(ans: only final)
69.they given one query in sql and they are asking corresponding criteria api query?
74.senario: in jsp page with 2 buttons, one for addbook and another is for
78. how to render excel and pdf view to the enduser(using poi and itext api's)?
79.How to validate valid username and password in spring?for validating can i directly
80.by default servlet container will handle multi-threaded applications , then why you
<context-param>
<param-name>globalVariable</param-name>
<param-value>com.stackoverflow</param-value>
</context-param>
The include directive is used to include the contents of any resource it may be jsp file,
html file or text file. The include directive includes the original content of the included
resource at page translation time (the jsp page is translated only once so it will be better
to include static resource).
Java Bean
• About project.
• What is method overloading ?
It is one of the concept of polymorphisim. It defines more than one
method have same name but different argument . In method overloading
method resolution takes care by the compiler based on reference type.
• If an exception occurred before coming to the try-catch, then what will
happen and how to resolve?
Abnormal termination.
• Why String is immutable?
For security, efficiency.
• What is Session Factory and difference between Session factory and
Session?
• Difference between merge () and update();
• How many annotation u uses in spring?
• Difference between @Service, @component, @Controller, @Repository.
• @Component | generic stereotype for any Spring-managed component |
• | @Repository| stereotype for persistence layer |
• | @Service | stereotype for service layer |
• | @Controller| stereotype for presentation layer (spring-mvc)
No.
• Internal working of HashMap.
• Difference between hashmap and hashTable?
• What is finally?
Java finally blockis always executed whether exception is handled or not. Java
finally block follows try or catch block.
• Introduction/About project
• What report u use on your project?
• In which format u use jasper report?
• What are the new feature in java 9?
• What are the new feature in java 8 compare with java 7
• What is lambda Expression und uses?
• What is marker interface?
• Where u use marker interface on your project? Example ?
• What is oops and the benefit of oops comparing with other language?
• What is class?
• What is single tone class?
• Single tone class program.
• What is difference between collection and collections?
• What is HashTable?
• Difference between comparable and comparator interface?
• Difference between hashmap and hashtable? Program?
• What type of annotation use in hibernate inheritance?
• Method overloading program.
• What is hashing?
• Singletone design patern?
1. “helloWord” program using spring, json Rest Api(coding).
2. Dao layer program of Spring mvc connectionwithHibernate.
3. How to connect database using hibernate with spring mvc ?
4. How and where u make transcation management in spring mvc with hibernate?
5. What is @RestController?
6. Internal working of HashMap?
7. Alogorthim behind the linkelist?
8. What is concept behind the two objects store in same bucket?
9. What are the methods in object class?
AricentTechnolopgy:
IWeen
2st Round:
3st Round:
Altimetric:
• There are 20 students in a class. Each student having different points for
which they can able stand in a queue according to their points from
highest point to lowest point. If any student having less point who stand
ahead of student who has more point, how to track this things.
Int[] input1, input2
Where I<j and P[i]>p[j] then …
2nd round:
Technical round
1. What are the oop principle, where you used polymorphism in your project?
2. Why we are injecting interface reference in spring framework why not direct
implementation?
map
10. WAP to find number of vowels present and there count from given input String
11. What is serializable? If my business object not implement serializable is there any
problem?
4. Why we are returning ResponseEntity from controller method why not direct object?
7. Without any configuration file how spring boot scan our bean even we are not writing
@Componentscan
8. How to write test case for controller method? Which framework u r using?
10. How to develop soap web service using spring boot without config.
11. I want to enable features in specific environment how can I archive using spring boot
12. Explain Spring batch architecture , suppose I want to do validation while batch job is
13. What is application. Properties if I will keep different name instead of application will
it
work?
15. Difference between soap and rest web services give one example
• @Component
• @Service
• @Controller
• @Repository
• @Require
• @Autowired
• @Qualifier
• @Configuration
• @Bean
• @ComponentScan
• @Import
• @Dependson
• @Lazy
• @RequestParm
• @PathVariable
• @ModelAttribute
• @RequestMapping
• @Transactional
• @AdviceController
• @ExceptionHandler
1. @ApplicationPath
2. @Path
3. @Consumes
4. @Produces
5. @POST
6. @GET
7. @PUT
8. @DELETE
9. @FormParm
10. @PathParm
etc…
Cascade attribute normally used to save child along with parent, simply in One to many
relationship one parent can contain List of child so to save list of child along with parent
we have to mention cascade attribute with value ‘all’
Inverse attribute is used to change the relationship of owner, and default value of
inverse=’false’ if we assign the value is inverse=’true’ then in case of update and save
operation it will not reflect in child it always showing the changes of parent
5.It have less memory 5.It have more memory than Level-1
6.It is Faster than Level-2 6.Process is little bit slow than Level-1
ArrayList LinkedList
After placing object if in same bucket 2 objects are placed then there may be a chance
key collision .to avoid this situation it internally uses == operator so here it will check
whether these 2 objects have same hashCode or not? If hashCode is different then it will
place the object in map else if both have same hashcode then there may be chance
hashing collision.
If hashing collision occurs then to overcome this issue it internally use equals method to
content comparison it check obj1.equals(obj2) if content same then replace the value
else add that object into map.
HashMap HashTable
2.HashMap allow only one null as key and 2.Null insertion is not there in HashTable
multiple null we can take as value
3.we can use Iterator in HashMap 3.Iterator is not support ,here we have to
use Enumeration
4.HashMap is faster and consumes less 4.HashTable is not faster and it consumes
memory than hashTable more memory than HashMap
2.It allow only homogeneous object 2.It allow both homogeneous and
heterogeneous object
3.Inbuilt methods are not there in Array 3.Inbuilt methods are there provided by
utile class
ArrayList Vector
4.ArrayList increments 50% of its current 4.It increment double of its current initial
array size If number of element exceed its capacity
initial capacity
Suppose I have one requirement where multiple thread want to access/modify under
laying DS of map means one thread try to insert element in key and value pair and
another thread try to modify some element at same times then in this situation better to
prefer ConcurrentHashMap instead of HashMap cause ConcurrentHashMap apply lock on
specific entry not in complete map object.
Both are introduced in java.util.concurrent package in 1.5 v and we are using these 2
interfaces in Executor framework.
Callable interface is used for create thread and the main advantages of using Callable is
after completion of thread execution it returns object cause the return type of call
method is Object
These class loader follows 3 principle to load the class see the below description
1. Principle of delegation
2. Principle of visibility
3. Principle of uniqueness
Principle of delegation:
Normally at the time of class loading always control comes to child class loader i.e.
Application Class Loader as per this principle it forward the request to its parent class
loader i.e. extension class loader then again extension class loader forward it to its
parent class loader Bootstrap Class Loader now Bootstrap Class Loader search from his
directory to find the .class file if find then load else next hierarchy class loader i.e.
extension class loader search in his directory if find then it will load by this class loader
else again it goes to next hierarchy class loader i.e. Application class loader if found the
it will be load else we will get ClassNotFoundException.
Principle of visibility:
This principle maintains the parent and child relationship as we know a child can know
the status of parent class but a parent class can’t know the status of its child same here
see the below hierarchy.
Principle of uniqueness:
Principle of uniqueness means if already class is loaded by one class loader it can’t be
again reload by other otherwise ambiguity will be occurs let’s assume suppose I have
one class and I placed this class in JRE/lib/ext folder so then this class will be loaded by
whom ?
As per above two principle first request will be delegate to its corresponding parent so
after 2 search finally control goes to Extension class loader where my .class file is
available so control can’t goes to application class loader that’s why class will be loaded
by Extension class loader. Here already my .class loaded by Ext loader so it never again
load by subclass loader Application Class loader as per Principle of uniqueness
dataMap.put(l1Key, l1Value);
dataMap.put(l2Key, l2Value);
returndataMap;
returnlistMap;
}
17. When you will get ClassNotFoundException and NoClassDefFoundError ?
Answer:
When our class loaded by class loader but it will not found in class path then
ClassNotFoundException will be raised ex: FileNotFoundException, when you are trying
to perform any file operation but your file is not present in project directory then u will
get FileNotFoundException
When class is visible only at compilation time but not available in Jvm/Runtime ,then in
that situation we will get NoClassDefFoundError.
20. What are all the design patterns you observed in spring?
Answer:
22. What are all the critical situations you come across in your project?
23. Why wait () placed in object class? Why not it is placed in Thread class?
Answer:
Very simple reason behind it actually wait () method is used to wait the thread of
execution and it used for inter thread communication to avoid data inconsistency, so first
reason is wait () and notify () method are not specific for single object it can be apply,
second reason is if it will present in thread class then one thread have to
t know the status
of another thread
Example:: Suppose I have 4 thread th1 ,th2 , th3, th4 and th4 so in inter thread
communication lock will be applied on Object by thread so which thread apply lock that
only known to object .simply locking mechanism no way
way related to thread its related to
Object.
Intern () method is used to avoid string duplication. And if you want to get the reference
of string instance from SCPA with the help of heap reference we have to use intern ()
method.
Example:
25. .what is diff b/w String str1="xyz"; and String str2= new String ("xyz");
Answer:
In String str2=new String(“XYZ”); in this statement 2 string object will be created one is
for newkeyword
keyword so it’s reference will be stored
stored in heap and another one is for String
literal “XYZ” and it’s reference will be stored in SCPA
In String str1=”XYZ”; here only one object will be created and reference will be stored in
SCPA if that string object is not available in SCPA before , if it is already exist in SCPA
than simply it will return the same instance.