0% found this document useful (0 votes)
28 views

Praveen Java Interview Questions

Uploaded by

smart59684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Praveen Java Interview Questions

Uploaded by

smart59684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

1) What is the performance effect of a large number of import statements which

are not used?


Ans: They are ignored if thecorresponding class is not used.
2) Give a scenario where hotspot will optimize your code?
Ans: If we have defined a variable as static and then initialized this variable in a static block
then the Hotspot will merge the variable and the initialization in a single statement and
hence reduce the code.
3) What will happen if an exception is thrown from the finally block?
Ans: The program will exit if the exception is not catched in the finally block.
4) How does decorator design pattern works in I/O classes?
Ans: The various classes like BufferedReader ,BufferedWriterworkk on the underlying
stream classes. Thus Buffered* class will provide a Buffer for Reader/Writer classes.
5) If I give you an assignment to design Shopping cart web application, how will
you define the architecture of this application. You are free to choose any
framework, tool or server?
Ans: Usually I will choose a MVC framework which will make me use other design patterns
like Front Controller, Business Delegate, Service Locater, DAO, DTO, Loose Coupling etc.
Struts 2 is very easy to configure and comes with other plugins like Tiles, Velocity and
Validator etc. The architecture of Struts becomes the architecture of my application with
various actions and corresponding JSP pages in place.
6) What is a deadlock in Java? How will you detect and get rid of deadlocks?
Ans: Deadlock exists when two threads try to get hold of a object which is already held by
another object.
7) Why is it better to use hibernate than JDBC for database interaction in various
Java applications?
Ans: Hibernate provides an OO view of the database by mapping the various classes to the
database tables. This helps in thinking in terms of the OO language then in RDBMS terms
and hence increases productivity.
8) How can one call one constructor from another constructor in a class?
Ans: Use the this() method to refer to constructors.
9) What is the purpose of intern() method in the String class?
Ans: It helps in moving the normal string objects to move to the String literal pool
10) How will you make your web application to use the https protocol?
Ans: This has more to do with the particular server being used than the application itself.
Here is how it can be done on tomcat:
1.What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest.
They are:

 Abstraction

 Polymorphism

 Inheritance

 Encapsulation

(i.e. easily remembered as A-PIE).

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.

4.What is the difference between abstraction and encapsulation?

 Abstraction focuses on the outside view of an object (i.e. the

interface) Encapsulation (information hiding) prevents clients from seeing it’s


inside view, where the behavior of the abstraction is implemented.

 Abstraction solves the problem in the design side while Encapsulation is the
Implementation.

 Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about


grouping up your abstraction to suit the developer needs.

5.What is Inheritance?

 Inheritance is the process by which objects of one class acquire the properties of
objects of another class.

 A class that is inherited is called a superclass.

 The class that does the inheriting is called a subclass.

 Inheritance is done by using the keyword extends.

 The two most common reasons to use inheritance are:

o To promote code
reuse o To use
polymorphism

6.What is Polymorphism?

Polymorphism is briefly described as "one interface, many implementations." Polymorphism


is a characteristic of being able to assign a different meaning or usage to something in
different contexts - specifically, to allow an entity such as a variable, a function, or an
object to have more than one form.

7.How does Java implement polymorphism?

(Inheritance, Overloading and Overriding are used to achieve Polymorphism in


java). Polymorphism manifests itself in Java in the form of multiple methods having
the same name.
 In some cases, multiple methods have the same name, but different formal
argument lists (overloaded methods).

 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.

Note: From a practical programming viewpoint, polymorphism manifests itself in three


distinct forms in Java:

 Method overloading

 Method overriding through inheritance

 Method overriding through the Java interface

9.What is runtime polymorphism or dynamic method dispatch?

In Java, 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 superclass.
The determination of the method to be called is based on the object being referred to by
the reference variable.

10.What is Dynamic Binding?

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.

11.What is method overloading?

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:

 Overloaded methods MUST change the argument list

 Overloaded methods CAN change the return type

 Overloaded methods CAN change the access modifier

 Overloaded methods CAN declare new or broader checked exceptions


 A method can be overloaded in the same class or in a subclass

12.What is method overriding?

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).

 You cannot override a method marked final

 You cannot override a method marked static

13.What are the differences between method overloading and method overriding?

Overrid
Overloaded Method d

Arguments Must change Must not change

Can’t change except for


Return type Can change covar

Can reduce or eliminate.


Exceptions Can change Must
checked exceptions

Must not make more


Access Can change restrictiv
Object type determines
Invocation Reference type determines which overloaded version is which
selected. Happens at compile time. at runtime.

14.Can overloaded methods be override too?

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.

15.Is it possible to override the main method?

NO, because main is a static method. A static method can't be overridden in Java.

16.How to invoke a superclass version of an Overridden method?

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:

 You can only go back one level.

 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.

18.How do you prevent a method from being


overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on
the method declaration, which means "this is the final implementation of this method", the
end of its inheritance hierarchy.

public final void exampleMethod() {

// Method statements

19.What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must


have.

Note:

 You can’t mark an interface as final.

 Interface variables must be static.

 An Interface cannot extend anything but another interfaces.

20.Can we instantiate an interface?

You can’t instantiate an interface directly, but you can instantiate a class that
implements an interface.

21.Can we create an object for an interface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces


cannot be instantiated in their own right, so you must write a class that implements the
interface and fulfill all the methods defined in it.

22.Do interfaces have member variables?

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.

23.What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?

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.

25.What is an abstract class?

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.

 Abstract classes may not be instantiated, and require subclasses to provide


implementations for the abstract methods.

 You can’t mark a class as both abstract and final.


26.Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

27.What are the differences between Interface and Abstract class?

Interfac
Abstract Class es

An abstract class can provide complete, default code and/or just


the An interface cannot provide any code
at all
details that have to be overridden.

In case of abstract class, a class may extend only one abstract A Class may implement several
class. interfaces.

All methods of an Interface are


An abstract class can have non-abstract methods. abstract.

An Interface cannot have instance


An abstract class can have instance variables. variables

An Interface visibility must be public


An abstract class can have any visibility: public, private, protected. (or) no

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 .

Interfaces are slow as it requires extra


indir
Abstract classes are fast.
method in the actual class.

28.When should I use abstract classes and when should I use interfaces?

Use Interfaces when…

 You see that something in your design will change frequently.

 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.

 Abstract classes are an excellent way to create planned inheritance hierarchies.


They're also a good choice for nonleaf classes in class hierarchies.

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.

30.Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

31.What is Constructor?
 A constructor is a special method whose task is to initialize the object of its class.

 It is special because its name is the same as the class name.

 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.

 Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?

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.

33.Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class constructor.

34.What are the differences between Contructors and Methods?

Me
Constructors t

Purpose Create an instance of a class Group Java statements

Cannot be abstract, final, native, static, or Can be abstract, final,


Modifiers synchronized native

Return Type No return type, not even void void or a valid return type

Any name except the


Name Same name as the class (first letter is capitalized by class. M
lowercase letter by
convention) -- usually a noun conventio
action

Refers to another constructor in the same class. If Refers to an instance of


this used, it the o
must be the first line of the constructor static methods.

Calls the constructor of the parent class. If used, must Calls an overridden
super be method in
the first line of the constructor

Inheritance Constructors are not inherited Methods are inherited

35.How are this() and super() used with constructors?


 Constructors use this to refer to another constructor in the same class with a
different parameter list.

 Constructors use super to invoke the superclass's constructor. If a constructor


uses super, it must use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?
Instance
Class Methods Meth

Instance methods on the other hand


require
Class methods are methods which are declared as static. The exist before they can be called, so an
method can insta
be called without creating an instance of the class created by using the new keyword.
Instance methods operate on specific
instan

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

Class methods are methods which are declared as static. The


method can Instance methods are not declared as
static
be called without creating an instance of the class.

37.How are this() and super() used with constructors?

 Constructors use this to refer to another constructor in the same class with a
different parameter list.

 Constructors use super to invoke the superclass's constructor. If a constructor


uses super, it must use it in the first line; otherwise, the compiler will complain.

38.What are Access Specifiers?

One of the techniques in object-oriented programming is encapsulation. It concerns the


hiding of data in a class and making this class available only through methods. Java allows
you to control access to classes, methods, and fields via so-called access specifiers..

39.What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:

 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.

Situation public protected

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.

 final Classes- A final class cannot have subclasses.

 final Variables- A final variable cannot be changed once it is initialized.

 final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?

There are two reasons for marking a method as final:


 Disallowing subclasses to change the meaning of the method.

 Increasing efficiency by allowing the compiler to turn calls to the method into inline
Java code.

42.What is static block?

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.

43.What are static variables?

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.

static type varIdentifier;

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.

44.What is the difference between static and non-static 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.

45.What are static methods?

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.

Note:The use of a static method suffers from the following restrictions:

 A static method can only call other static methods.

 A static method must only access static data.

 A static method cannot reference to the current object using keywords super or
this.

46.What is an Iterator ?

 The Iterator interface is used to step through the elements of a Collection.

 Iterators let you process each element of a Collection.

 Iterators are a generic way to go through all the elements of a Collection no


matter how it is organized.
 Iterator is an Interface implemented a different way for every Collection.

47.How do you traverse through a collection using its Iterator?

To use an iterator to traverse through the contents of a collection, follow these steps:

 Obtain an iterator to the start of the collection by


calling the collection’s iterator() method.
 Set up a loop that makes a call to hasNext(). Have the loop
iterate as long as hasNext() returns true.

 Within the loop, obtain each element by calling next().

48.How do you remove elements during Iteration?

Iterator also has a method remove() when remove is called, the current element in
the iteration is deleted.

49.What is the difference between Enumeration and Iterator?

Enumeration Iterator

Enumeration doesn't have a remove() method Iterator has a remove() method

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

Note: So Enumeration is used whenever we want to make Collection objects as Read-only.

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

51.What is the List interface?

 The List interface provides support for ordered collections of objects.

 Lists may contain duplicate elements.

52.What are the main implementations of the List interface ?

The main implementations of the List interface are as follows :

 ArrayList : Resizable-array implementation of the List interface. The best


all-around implementation of the List interface.

 Vector : Synchronized resizable-array implementation of the List interface with


additional "legacy methods."

 LinkedList : Doubly-linked list implementation of the List interface. May provide


better performance than the ArrayList implementation if elements are frequently
inserted or deleted within the list. Useful for queues and double-ended queues
(deques).
53.What are the advantages of ArrayList over arrays ?

Some of the advantages ArrayList has over arrays are:

 It can grow dynamically

 It provides more powerful insertion and search mechanisms than arrays.

54.Difference between ArrayList and


Vector ?
ArrayList Vector

ArrayList is NOT synchronized by default. Vector List is synchronized by default.

Vector list can use Iterator and


Enumeratio
ArrayList can use only Iterator to access the elements.
elements.

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.

55.How to obtain Array from an ArrayList ?

Array can be obtained from an ArrayList using toArray() method on ArrayList.

List arrayList = new ArrayList();


arrayList.add(…

Object a[] = arrayList.toArray();

56.Why insertion and deletion in ArrayList is slow compared to LinkedList ?

 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.

57.Why are Iterators returned by


ArrayList called Fail Fast ?

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

 Sets do not allow duplicate elements

 Contains no methods other than those inherited from Collection

 It adds the restriction that duplicate elements are prohibited

 Two Set objects are equal if they contain the same elements

60.What are the main Implementations of the Set interface ?

The main implementations of the List interface are as follows:

 HashSet

 TreeSet

 LinkedHashSet

 EnumSet

61.What is a HashSet ?

 A HashSet is an unsorted, unordered Set.

 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.

64.Difference between HashSet and TreeSet ?


HashSet TreeSet

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 ?

 A map is an object that stores associations between keys and values


(key/value pairs).
 Given a key, you can find its value. Both keys and values are objects.

 The keys must be unique, but the values may be duplicated.

 Some maps can accept a null key and null values, others cannot.

66.What are the main Implementations of the Map interface ?

The main implementations of the List interface are as follows:

 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.

69.Difference between HashMap and Hashtable ?


Hashtabl
HashMap e

HashTable does not allows null values


HashMap lets you have null values as well as one null key. as ke

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).

HashMap is unsynchronized. Hashtable is synchronized.

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.

71.What Are the different


Collection Views That Maps
Provide?

Maps Provide Three Collection Views.

 Key Set - allow a map's contents to be viewed as a set of keys.


 Values Collection - allow a map's contents to be viewed as a set of values.

 Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

72.What is a KeySet View ?

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.

73.What is a Values Collection View ?

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.

74.What is an EntrySet View ?

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.

75.How do you sort an ArrayList (or any list) of user-defined objects ?

Create an implementation of the java.lang.Comparable interface that knows how to order


your objects and pass it to java.util.Collections.sort(List, Comparator).

76.What is the Comparable interface ?

The Comparable interface is used to sort collections and arrays of objects using

the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the


class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable<T>

where T is the name of the type parameter.

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)

 If object1 < object2: The value of i returned will be negative.

 If object1 > object2: The value of i returned will be positive.

 If object1 = object2: The value of i returned will be zero.

77.What are the differences between the Comparable and Comparator interfaces ?
Comparable Comparato
It uses the compareTo() method. t uses the compare() method.

int objectOne.compareTo(objectTwo). int compare(ObjOne, ObjTwo)

It is necessary to modify the class whose instance is A separate class can be created
going to be sorted. in order to

Many sort sequences can be


Only one sort sequence can be created. created.

It used by third-party classes to


It is frequently used by the API classes. sort instanc

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

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:
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”);
}
}

//compile by javac .java


//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 do not 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.
17)Does constructor return any value?

Ans:yes, that is current instance (You cannot use return type yet it returns a value).

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,jvmcreats object first then call main() method that will lead to the problem of
extra memory allocation.
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, by static block.


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?

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


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.


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

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

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) methodoverlaoding 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.
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).
48)What is final method?

Final methods can’t be overridden..


49)What is final class?

Final class can’t be inherited.


50) What is blank final variable?

A final variable, not initalized at the time of declaration, is known as blank final variable.
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.
52)Can you declare the main method as final?

Yes, such as, public static final void main(String[] args){}.

Core Java – OOPs Concepts: Polymorphism Interview Questions

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
superclass. 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 hides the data.
Abstraction lets you focus on what the object does instead of how it does it.
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 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?

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?

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.

Core Java : Exception Handling Interview Questions

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?

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?

finally block is a block that is always executed.


78)Can finally block be used without catch?

Yes, by try block. finally must be followed by either try or catch.


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).
80)What is difference between throw and throws?

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.

Core 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,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?

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

Yes, it is known as nested interface.


99)Can an Interface have a class?

Yes, they are static implicitly.

Core Java : Multi Threading Interview Questions

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?

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.
101) 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.
102)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.
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?

No, there is no possibility to start a thread twice. If we does, it throws an exception.


106) 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.
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?

No, if you do so, it will throw IllegalThreadStateException .


109)What is shutdown hook?

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?

Synchronized block is used to lock an object for any shared resource.


Scope of synchronized block is smaller than the method.
113)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.
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.

Garbage Collection Interview Questions

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)Whatan 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.
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 Serializableinterface, 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.

Collection Interview Questions

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?

HashSet contains only values whereas HashMap contains entry(key,value).


140)What is difference between HashMap and TreeMap?

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?

HashSet maintains no order whereas TreeSet maintains ascending order.


142) What is difference between List and Set?

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?

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 SortedSetsynchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMapsynchronizedSortedMap(SortedMap m){}
145) What is difference between Iterator and Enumeration?

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?

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

Miscellaneous Interview Questions

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 develpoment 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.

JDBC Interview Questions

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?

Register the driver class


Creating connection
Creating statement
Executing queries
Closing connection.
168)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.
169)How can we execute stored procedures and functions?

By using Callable statement interface, we can execute procedures and functions.


170)How can we store and retrieve images from the database?

By using PreparedStaement interface, we can store and retrieve images.

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

Q. What if the main method is declared as private?

Answer:

The program compiles properly but at runtime it will give “Main method not public.”
message.

Q. What is meant by pass by reference and pass by value in Java?

Answer:

Pass by reference means, passing the address itself rather than passing the value. Pass
by value means passing a copy of the value.

Q. If you’re overriding the method equals() of an object, which other method


you might also consider?

Answer:

hashCode()

Q. What is Byte Code?


Or

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.

Q. What are the differences between == and .equals() ?

Or

Q. what is difference between == and equals

Or

Q. Difference between == and equals method

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

03 public static void main(String[] args) {

04

05 String s1 = “abc”;

06 String s2 = s1;

07 String s5 = “abc”;

08 String s3 = new String(”abc”);

09 String s4 = new String(”abc”);

10 System.out.println(”== comparison : ” + (s1 == s5));

11 System.out.println(”== comparison : ” + (s1 == s2));

12 System.out.println(”Using equals method : ” + s1.equals(s2));

13 System.out.println(”== comparison : ” + s3 == s4);

14 System.out.println(”Using equals method : ” + s3.equals(s4));

15 }

16 }

Output

1 == comparison : true

2 == comparison : true

3 Using equals method : true

4 false

5 Using equals method : true

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:

Program compiles. But at runtime throws an error “NoSuchMethodError”.


Q. Why oracle Type 4 driver is named as oracle thin driver?

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

Q. What is final, finalize() and finally?

Or

Q. What is finalize() method?

Or

Q. What does it mean that a class or member is final?

Answer:

final – declare constant

finally – handles exception

finalize – helps in garbage collection

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.

Q. What is the Java API?

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.

Q. What is the GregorianCalendar class?

Answer:

The GregorianCalendar provides support for traditional Western calendars.

Q. What is the ResourceBundle class?

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.

Q. Why there are no global variables in Java?

Answer:

Global variables are globally accessible. Java does not support globally accessible
variables due to following reasons:

The global variables breaks the referential transparency

Global variables create collisions in namespace.

Q. How to convert String to Number in java program?

Answer:

The valueOf() function of Integer class is is used to convert string to Number. Here is the
code example:

1 String numString = “1000″;

2 int id=Integer.valueOf(numString).intValue();

Q. What is the SimpleTimeZone class?

Answer:

The SimpleTimeZone class provides support for a Gregorian calendar.

Q. What is the difference between a while statement and a do statement?

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.

Q. What is the Locale class?

Answer:

The Locale class is used to tailor a program output to the conventions of a particular
geographic, political, or cultural region.

Q. Describe the principles of OOPS.

Answer:

There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.

Q. Explain the Inheritance principle.

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

Q. What is implicit casting?

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;

2 long j = i; //Implicit casting

Q. Is sizeof a keyword in java?

Answer:

The sizeof is not a keyword.

Q. What is a native method?

Answer:

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

Q. In System.out.println(), what is System, out and println?

Answer:

System is a predefined final class, out is a PrintStream object and println is a built-in
overloaded method in the out object.

Q. What are Encapsulation, Inheritance and Polymorphism

Or

Q. Explain the Polymorphism principle. Explain the different forms


of Polymorphism.

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.

Polymorphism exists in three distinct forms in Java:

Method overloading

Method overriding through inheritance

Method overriding through the Java interface

Q. What is explicit casting?

Answer:
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.

Example

1 long i = 700.20;

2 int j = (int) i; //Explicit casting

Q. What is the Java Virtual Machine (JVM)?

Answer:

The Java Virtual Machine is software that can be ported onto various hardware-based
platforms

Q. What do you understand by downcasting?

Answer:

The process of Downcasting refers to the casting from a general to a more specific type,
i.e. casting down the hierarchy

Q. What are Java Access Specifiers?

Or

Q. What is the difference between public, private, protected and default Access
Specifiers?

Or

Q. What are different types of access modifiers?

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:

Public: accessible to all classes

Protected: accessible to the classes within the same package and any subclasses.

Private: accessible only to the class to which they belong

Default: accessible to the class to which they belong and to subclasses within the
same package

Q. Which class is the superclass of every class?

Answer:

Object.

Q. Name primitive Java types.

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

Q. What are “class variables”?

Or

Q. What is static in java?

Or

Q. What is a static method?

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.

Non-static variables take on unique values with each object instance.

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.

Q. How does Java handle integer overflows and underflows?

Answer:

It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation.

Q. What if I write static public void instead of public static void?

Answer:

Program compiles and runs properly.

Q. What is the difference between declaring a variable and defining a variable?


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.

Q. What type of parameter passing does Java support?

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.

Q. Explain the Encapsulation principle.

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.

Q. What do you understand by a variable?

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.

Q. What do you understand by numeric promotion?

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.

Q. What is the first argument of the String array in main method?

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.

Q. Can an application have multiple classes having main method?

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.

Q. When is static variable loaded? Is it at compile time or runtime? When


exactly a static block is loaded in Java?

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.

Q. Can I have multiple main methods in the same class?

Answer:

We can have multiple overloaded main methods but there can be only one main
method with the following signature :

1 public static void main(String[] args) {}

No the program fails to compile. The compiler says that the main method is already
defined in the class.

Q. Explain working of Java Virtual Machine (JVM)?

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.

Q. How can I swap two variables without using a third variable?

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:

1 int a=5,b=10;a=a+b; b=a-b; a=a-b;

An other approach to the same question

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;

Q. What is data encapsulation?

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.

Q. What is reflection API? How are they implemented?

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.

Q. What is phantom memory?

Answer:

Phantom memory is false memory. Memory that does not exist in reality.

Q. Can a method be static and synchronized?

Answer:

A static method can be synchronized. If you do so, the JVM will obtain a lock on the
java.lang.

Class instance associated with the object. It is similar to saying:

1 synchronized(XYZ.class) {

2}

Q. What is difference between String and StringTokenizer?


Answer:

A StringTokenizer is utility class used to break up string.

Example:

1 StringTokenizer st = new StringTokenizer(”Hello World”);

2 while (st.hasMoreTokens()) {

3 System.out.println(st.nextToken());

4}

Output:

1 Hello

2 World

Question: What is transient variable?

Answer:

Transient variable can’t be serialize. For example if a variable is declared as transient in


a Serializable class and the class is written to an ObjectStream, the value of the variable
can’t be written to the stream instead when the class is retrieved from the ObjectStream
the value of the variable becomes null.

Note

01 transient

02

03 identifies a variable not to be written out when an

04

05 instance is serialized (It can't be copied to remove

06

07 system)

08

09

10

11 volatile

12
13 indicates that the field is used by synchronized threads

14

15 and that the compiler should not attempt to perform

16

17 optimizations with it.

18

19

20

21 When more than one thread share a (volatile) data it is

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.

Question: What do you understand by Synchronization?

Answer:

Synchronization is a process of controlling the access of shared resources by the multiple


threads in such a manner that only one thread can access one resource at a time. In non
synchronized multithreaded application, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating the object’s value.
Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:

1 public synchronized void Method1 () {

3 // Appropriate method-related code.

5}

E.g. Synchronizing a block of code inside a function:

1 public myFunction (){


2 synchronized (this) {

3 // Synchronized code here.

4 }

5}

Core-Java----1 st round

===================

1.Interface & abstract class ?

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

2.How can u achive Abstraction With Real Time Example(Project) ?

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

3.In your Project Where u are using oops concept..?

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

4.Encapsulation u are using in ur project in which layer. ?

ans: Ya we are using In Model layer (BO,DTO,FORM)

5.To override all the method from super which keyword we have to use.and why

ans: implements keyword coz class+interface== always implements


6.Why abstract class achive less abstraction why not interface.?

ans: Cause Abstract class contain boh concrete and abstract method but it's not
mandatory that

My subclass always override supperclass method so there is no guarentee to achive

fully abstraction

7.Write 5 classes which u r develope in your project with fully qualified name ?

Just mention as below

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:

1.NullPointerException:-Resolve by Remote Debugging

2.DataAccessException:-Enter the Column name properly this exception from DAO

3.ClassCastException:-Mentain Typecast or Generics properly

9.Why u are using Spring-jdbc why not hibernate ?

ans:Coz my project is Intranet Application and it handles huge amount of data for

persist and retrive thats why we are using Spring-Jdbc

10.Which security u are using..?

ans:Simple Authentication by using Spring


11.Level of log(Which one u use in your project)

ans: DEBUG,ERROR,WARN

Second-Round(CoreJava+Spring)

===========================

1.What is abstraction

ans:Hide the implementation Provide only Functionality is called abstraction

2.How to create own immutable class write code

public class MyImmutable {

int no;

public MyImmutable(int no) {

super();

this.no = no;

public MyImmutable modify(int no) {

if (this.no == no) {

return this;

} else {

return new MyImmutable(no);

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

per one class per one jvm.

In my project i didn't use coz we are using Spring so every bean scope is singleton

so we no need to make explicitly singleton.


4.Why List allow duplicate why not Set with internal ?

ans: Coz List internally follw Array Concept so no there is no restriction in

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

Just explain the flow of Map ok if he ask more.....

5.What is Dependency Injection ?

ans:Dependency Injection is a process of inject dependency in Dependant class

automatically we no need create object and no need to map with object .it internally

follow Strategy design pattern

6.Which type of Injection u are using in ur project and why..

ans: We are using both setter and constructor injection both coz some fields we need to
compolsory

inject and some fields are optional for our project

7.What is autoware,Type explain with sample code

ans:Autowire is auto enable dependency Inject

it is 3 type:1)byName 2)byType 3)Constructor

8.Which version Spring u used.. ?

ans:4.x

9.What are the annotation u are using in ur project ?

ans:-
@Componet,@Service,@Controller,@Autowire,@Transactional,@Scope,@ControllerAdvic
e,@ExceptionHandler

@RequestParm,@PathVariable,@ModelAttribute,@PropertyResource

10.Write Spring-transaction configuration

ans:

<aop:config>
<aop:pointcut expression="execution(*
com.dt.service.ManageEmployeeService.*(..))" id="manageEmpPct"/>

<aop:advisor advice-ref="manageEmployeeTxAdvice" pointcut-


ref="manageEmpPct"/>

</aop:config>

<tx:advice id="manageEmployeeTxAdvice">

<tx:attributes>

<tx:method name="new*" read-only="false"


propagation="REQUIRED" />

<tx:method name="*" read-only="true"


propagation="REQUIRED"/>

</tx:attributes>

</tx:advice>

11.Spring-Transaction annotation details with attribute why ?

ans: @Transactional(read-only="false",Isolation="Read-
Commit",Propagation="Required")

12.@Qualifier annotation use with example ?

ans:@Qualifier annotation used to avoid ambiguity error

ex:

<bean id="a1" class="A">

<bean id="a2" class="A">

here class is same but id is different so here my IOC Container confuse due to same
class

found multiple time so here bean id u want mention in @Qualifier("a1") then

IOc will instantiate that bean only

13.@RequestParm and @ModelAttribute where we have to use..

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

like movieName,Time,Location,Nearest hall...etc then choose @ModelAttribute

14.What is ur daily activity in ur working environment

ans:Sensiourly working in service and dao based on user story

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.

Like this few Senario

2. Transaction management support in Spring

We need transaction management to handle multiple resources(Table), means in sort if


my tables are dependent with each other if one of them failing I don't want perform DB
operation with other simply I want to roll back entire transaction

So for that spring provided transaction management with few annotation

@Transactional and here we need to specify few attributes like

Isolation, propagation and read only

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.

Some of the benefits of using Spring Transaction Management are:

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.

c. Support for programmatic transaction management by using TransactionTemplate or


PlatformTransactionManager implementation.

3. What is strategy design pattern ?

Where it used nd why ?

Common interview question

Spring dependency injection which is

Greatest features provided by spring framework. To design this DI they comes under
Strategy design pattern
See programaticall description

class Bank{

private Transaction transaction;

public void setBank(Transaction transaction){

this.transaction=transaction;

public Transaction getBank(){

return transaction;

public void doTransaction(){

/*Approach:1

by using Composition

SBI sbi=new SBI();

sbi.deposite();*/

/*Approach:2

by taking interface

as class level attribute

to avoid tight coupling nd to

achive RuntimePolymorphisim

transaction=new SBI();

transaction.deposite();

transaction=new AXIS();

transaction.deposite();*/

/*Approach:3
Here we get partial couple not fully

tight coupling due to logical

name

transaction=BankTransactionFactory.getInstance("axis");

transaction.deposite();*/

transaction.deposite();

interface Transaction{

public void deposite();

class SBI implements Transaction{

public void deposite(){

System.out.println("Deposit in SBI");

class AXIS implements Transaction{

public void deposite(){

System.out.println("Deposit in AXIS");

class BankTransactionFactory{
public static Transaction getInstance(String type){

if(type.equalsIgnoreCase("Sbi")){

return new SBI();

else if(type.equalsIgnoreCase("Axis")){

return new AXIS();

return null;

class Customer{

public static void main(String[] args){

Bank b=new Bank();

Transaction t=new SBI();

b.setBank(t);

b.doTransaction();

/*See here we do manually setter nd getter

for inject dependency .but in spring frame

work this work is done by IOC container

so completely spring dependency injection

design by follwing this strategy design

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;

public interface Behaviour {

void moveOnCommand();

package com.stratergy.pattern;

public class AgressiveBehaviour implements Behaviour{

@Override

public void moveOnCommand() {

System.out.println("Robot behave : AgressiveBehaviour");

package com.stratergy.pattern;

public class DefensiveBehaviour implements Behaviour{

@Override

public void moveOnCommand() {

System.out.println("Robot behave : DefensiveBehaviour");

package com.stratergy.pattern;

public class NormalBehaviour implements Behaviour{

@Override
public void moveOnCommand() {

System.out.println("Robot behave : NormalBehaviour");

package com.stratergy.pattern;

public class Robot {

Behaviour behaviour;

String name;

public Robot(String name) {

this.name = name;

public void setBehaviour(Behaviour behaviour) {

this.behaviour = behaviour;

public Behaviour getBehaviour() {

return behaviour;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

}
public void move() {

System.out.println("Based on current position the behaviour object decide the next


move");

behaviour.moveOnCommand();

System.out.println("The result returned by behaviour object is sent to the movement


mechanisms for the robot '" + this.name + "'");

package com.stratergy.pattern;

public class MainClass {

public static void main(String[] args) {

Robot r1 = new Robot("Big Robot");

Robot r2 = new Robot("George v.2.1");

Robot r3 = new Robot("R2");

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();

Strategy Design Pattern 1.Favor Composition over Inheritance 2.Always Design to


Interfaces never code to Implementation 3.Code should be open for extension and
closed for modification
4. Which OOP concept is used in import statement?

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?

5.what is difference between maven vs Gradle:

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.

6.How to generate WADL for Rest application

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

7.Why we are using Rest


First try to understand what is Rest ,Rest is an architectural way of desine web services ,
through which you can consume and expose any of your service to other user with
multiple mediaType it can be JSON ,XML ,HTML or PLAIN_TEXT

Assume i have multiple modules as part of my project for example

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

Except Rest we have 2 way

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 .

8.Spring vs Spring boot

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:

simplifies your Spring dependencies, no more version collisions

can be run straight from a command line without an application container

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

9.Why we should go for lamda expressions?

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;

public class LambdaDem {

public static void main(String[] args) {

// without lambda

MyInterface1 interface1 = new MyInterface1() {

@Override

public void test() {

System.out.println("calling 1 without lambda");

};

interface1.test();

// with lambda

MyInterface1 interface2 = () -> {

System.out.println("Calling with lambda");

};

interface2.test();

10. How to create enterprise application project using maven.?

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 .

1.Go to file section

2.Create Maven project

3.choose maven archtype as WebApp

4.specify your group id , artifact id and version

5.finish project

6.add required dependency

7.Start deveopmenet ur application

11.What is maven goals ?


maven goals is nothing it just inform to your maven build tool what exact task will done
by your plugin

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>

12.Maven life cycle?

maven life cycle catagorized in multiple section and each life cycle having specific role.
like

mvn:validate -> helps us to validate pom.xml

mvn:compile - compile the source code of the project

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:test -> will help us to run our junit test case

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

13.How to write test case for your rest api.

To write junit test case for rest api multiple third party is there like mockMvc , power
mock and mockito

As am using mockMvc and it's quite easy to work

assume i have a end point http://localhost:8080/saveEmployee who will take input as


Employee object and will give me some response as it is saving employee object means
it is one POST HTTP method call

steps

1.inject mockMvc in ur test class

2.inject webApplicationContext in your test class

3.Before run your test method just initialize ur mockMvc using @Before annotation

4.write a test method with return type void

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"))

6.mention the mediaType whether it is json or xml or plain text

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)

public class SpringDataJpaApplicationTests {

private MockMvc mockMvc;

private ObjectMapper om = new ObjectMapper();


@Autowired(required = true)

private WebApplicationContext webApplicationContext;

@Before

public void setUp() {

mockMvc =
MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

@Test

public void addUser() throws Exception {

UserRequest request = new UserRequest();

List<User> users = new ArrayList<>();

User user1 = new User();

user1.setName("Basanta");

user1.setAddress("Hyderabad");

User user2 = new User();

user2.setName("Santosh");

user2.setAddress("Bangalore");

users.add(user1);

users.add(user2);

request.setUsers(users);

String requestJson = om.writeValueAsString(request);

MvcResult result = mockMvc

.perform(post("/Services/saveUser").content(requestJson).contentType(MediaTyp
e.APPLICATION_JSON_VALUE))

.andExpect(status().isOk()).andReturn();

String resultContent = result.getResponse().getContentAsString();

UserResponse response = om.readValue(resultContent,


UserResponse.class);

Assert.assertTrue(response.isStatus() == true);

14. What is default mode of autowiring in spring.

As we are using annotation approach so by default it will consider byType


15.Why JMS if we have Already webServices

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?

Static binding : method overloading

dynamic binding : method overriding

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

And static binding max we are implementing in same class.

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

17. If in spring boot application.properties is there then why we need application.yaml

The main reason people are going for yml instead of properties

1.well readability as yml following key value pair structure

2.no boiler plate syntax like

Assume am configuring datasource details in properties file

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

MNC Common Interview Questions

#Core Java ,#Spring and #Hibernate

1.project architecture?

2.spring flow?

3.list out all the annotations in spring?

4.what are all the annotations you used in your project on restful services?

5.in hibernate use of cascade and inverse?

6.first level cache? second level cache in hibernate?

7.waht is diff b/w arraylist and linkedlist?

8.can you explain the internal flow of hashmap?

9.what is the diff b/w hashmap and hashtable?

10.diff b/w array and arraylist?

11.diff b/w arraylist and vector?

12.in your project where you used cuncurrent hashmap?

13.waht is java annoying?

14.diff b/w callable interface adn future interface in concurrent package?


15.class loaders?

16.how can you take list into map?

17.how can you take map into list?

18.when you will get ClassNotFoundException and NoClassDefFoundError?

19.how you implement exception handling in your project?

20.where you implement multi-threading in your project?

21.what are all the design patterens you oberved in spring?

22.which design patters you used in your project?

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?

25.waht is use of intern() in spring?

26.what is diff b/w String str="xyz"; and String str2= new String("xyz");

27.expalin about java architectue?

28.explain about jvm architecture?

29.data base queries?

30.i have a compeny table in remote database. by using rest i need to get the table data

and print into a file?

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?

33.diff b/w rest and web(soap)?

34.agile methodolgy?

35.how to create web-services project and spring project using mavan?

36.what is diff b/w throw and throws?

37.can you tell me java8 features?

38.what are all the contents in wsdl?

4/7/2018 MNC Common Interview Questions

39.refer regular expressions?

40.can i add elements to list , if it is defined as final

ex:final List<String> list= new ArrayList<>();?

41.if you pass duplicate key to map what will happen?


42.diff b/w abstract class and interface?

43.diff b/w comparator and comparable?

44.how to compare two database tables(clue: comparator, compare(), you have to


compare

database objects.)?

45.how to set timeout for the browser?(clue: restful client api.)?

46.what workflow you used in your project?

47.why java? why not c & c++?

48.In written test they are asking sorting programs(bubblesort,quicksort,...)?

49.what is time complexity? if you are going to implement sorting by your own which

sorting you prefer? and why?

50.what is the use of volatile and synchronized?

51.what is serialization? have you implement serialization in your project?

52.programs on io streams?

53.why we are using @qualifier?

54.diff b/w Bean Factory and Application Context?

55.explain about ioc container?

56.programs on string manipulations?(they are expecting solv by using regular

expressions).

57.how you are implemented polymorphism in your project?

58.how you iterate map having key and list<values>?

59.diff b/w Iterator and ListIterator and Enumarator?

60.what are all the collections are supporting ListIterator?

61.how to make non-synchronized map and list as synchronized(by using collection


method)?

62.what is diff b/w collection and collections?

63.write the junit test case for the below senario..

-->read array of elements into list<>.

64.what are all the modifiers we can use inside method?(ans: only final)

65.what is diff b/w spring-jdbc and hibernate?

66.what are all the drawbacks of jdbc over hibernate?

67.what are all the problems with inheritance?


68.what is the use of hinernate session?

69.they given one query in sql and they are asking corresponding criteria api query?

70.why we are using @transient in hibernate?

71.what are all the inputs we are giving to SessionFactory?

72.what we are writing in hibernate-mapping file?

73.what we are writing in hibernate-configuration file?

74.senario: in jsp page with 2 buttons, one for addbook and another is for

showListOfBooks(by using spring and hibernate)?

75.what is use of @ComponentScan?

76.what is use of dispather servlet?

77. What are all the pre-processings tasks done by DispatcherServlet?

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

interact with dao without service?

80.by default servlet container will handle multi-threaded applications , then why you

are implementing multi-threading in your application?

Accenture Interview Question:

1. Where you used polymorphism


2. How to find memory leakage in your application
3. How is use of gc
4. Can we execute GC
5. How to propagate exception between multiple layer
6. What is use of multi catch block
7. When we have to use comparator
8. What is contract between hash code and equal method
9. How to improve performance of application
10. How stream api is working internally
11. What is use of functional interface
12. What is order if creation object (listener, filter, Servlet context, Servlet config)
13. How to pass additional data between multiple web pages
14. How to invalidate session.
15. How to configure error page in Servlet
16. Different between L1 and L2 cache
17. What is DI and IOC
18. Spring bean life cycle
19. Spring MVC flow

Infogain Interview Question:

1. Write the query to find duplicate value in related column.


2. Write the query to give grant for particular table
3. What is difference between primary key and unique key
4. What is DML and DDL
5. What is use of sequence
6. What is Rollback policy?
7. Difference between truncate and delete and drop
8. How to validate form using javascript
9. Write a program based on selection one should be enables and one disabled
10. How to read form value using javascript.
11. Write the program to disable all filed
12. How to send disable form field value to next page
13. Write a program to retrieve a data from controller and display in jsp page
14. What is safe method is rest api
15. Difference between http1 and http2
16. How to implement cache in Rest api.
17. What is use ETAG is rest
18. Difference between BASIC and DIGEST security.
19. How you will provide method level security in rest.
20. How to handle transaction between multiple database
21. Give typical architecture of your project
22. Which SDLC model you are following
23. How you are getting requirement
24. How you can make your rest api as thread safe

Capgemini Interview Question:

1. Online amcat written test( Java, Spring, Hibernate technical question)


2. Write a immutable class without using final keyword
3. Write a program to explain all oops concept
4. What will happen if we store custom object in tree set or tree map.
5. Why string class is immutable not string buffer.
6. Difference b/w IO stream NIO Stream
7. What is disadvantage of IO stream
8. What is service locator design pattern
9. What are design pattern you have used in your project
10. Difference between Factory design pattern and abstract Factory pattern
11. What is proxy design pattern
12. What all are the pattern used by spring
13. What is pull mechanism and push mechanism
14. What is disadvantage of hibernate
15. When we have native sql in hibernate why we have to use jdbc
16. How to call procedure in hibernate
17. How to resolve n+1 problem in hibernate.
18. What is asynchronous and synchronous communication?
19. Difference b/w absolute path and relative path
20. What if order of logging level
21. How to configure connection pool in server. How you get object of that
22. Difference between flat transaction and distributed transaction.
23. What is trace method in http.
24. How to raise a event in your application.
25. When are working multiple environment so how your managing DB credentials in
your application.
26. How to resolve conflict in git.
27. How you are making your war file how you are deploying.
28. What is your rollback policy if deployment got failed?
29. What all are your step to resolve production issue.
30. How you are managing you team.
31. Have you involved in design.
SoftVision Interview questions:

1. How to read session attribute in spring mvc


2. What is difference between request param and path param
3. What is use of @ModelAttribute annotation
4. What is use of @Initbinder annotation
5. Diffrencce between @Rest Controller and @ Controller
6. Difference b/w @Component and @Bean
7. Explain all view resolver and controller in spring
8. What is difference between xml configuration and annotation based configuration
in spring
9. What is difference between request and session scope
10. If depended been have prototype scope if we call getbean method what will
happen.
11. What is aware injection
12. What is dependency pool and dependency lookup
13. What is bean post processor
14. Spring bean life cycle method.
15. What is namaparamer jdbc template and jdbc template.
16. Jdbc template is thred safe or not
17. how to integrate spring with ORM tool write the program
18. how to configure multiple property file in spring.
19. how to execute batch in spring jdbc
20. difference between rowmapper and resultsetextraror
21. what is difference between ref and idref tag
22. How to handle exception in spring mvc
23. Difference between put and post method
24. What is resource class and resource method in rest
25. What is use of @Context annotation in rest
26. What is difference between url and Uri.
27. What is difference between itrate and execute update method in hibernate
28. What is QBC and criterion object in hibernate
29. What is order class and restriction class in hibernate.
30. What happen if we call get uniqueResult() method in hibernate if query giving
multiple result.
31. Difference between merge and update method in hibernate.
32. What of component mapping in hibernate.
33. How to configure composite key In hibernate.
34. What is group id and artifact id in maven
35. Maven life cycle. And maven project architecture
36. Diffrence between mvn clean and maven install
37. How to resolve conflict in maven
38. How to configure your test case in maven
39. What is difference between after class and before class in junit
40. How to test void method in junit.
41. How to test you rest api using junit

Muliti threading Interveiw Questions:


=============================
1) What is multitasking?
2) What is multithreading and explain its application areas?
3) What is advantage of multithreading?
4)When compared with c++ what is the advantage in java with respect to
multithreading?
5) In how many ways we can define a thread?
6)Among extending Thread and implementing Runnable which approach is
recommended?
7) Difference b/w t.start () and t.run ()?
8) Explain about thread Scheduler?
9) If we are not overriding run () what will happen?
10) Is it possible overloading of run ()?
11) Is it possible to override a start () method and what will happen?
12) Explain life cycle of a thread?
13) What is the importance of Thread class start () method?
14) After starting a thread if we try to restart the same Thread once again what will
happen?
15) Explain Thread class constructors?
16) How to get and set name of a thread?
17) Who uses thread priorities?
18) Default priority for main thread?
19) Once we create a new thread what is its priority?
20) How to get priority from thread and set priority to a thread?
21) If we are trying to set priority of thread as 100, what will happen?
22) If two threads having different priority then which thread will get chance first for
execution?
23) If two threads having same priority then which thread will get chance first for
execution?
24) How we can prevent thread from execution?
25) What is yield () and Explain its purpose?
26) Is join is overloaded?
27) Purpose of sleep () method?
28) What is synchronized keyword? Explain its advantages and disadvantages?
29) What is object lock and when it is required?
30) What is a class level lock when it is required?
31) While a thread executing any synchronized method on the given object is it possible
to execute remaining synchronized methods on the same object simultaneously by other
thread?
32) Difference b/w synchronized method and static synchronized method?
33) Advantages of synchronized block over synchronized method?
34) What is synchronized statement?
35) How two threads will communicate with each other?
36) wait (), notify (), notifyAll () are available in which class?
37) Why wait (), notify (), notifyAll () methods are defined in Object instead of thread
class?
38) Without having the lock is it possible to call wait ()?
39) If a waiting thread gets notification then it will enter into which state?
40) In which methods thread can release lock?
41) Explain wait (), notify () & notifyAll ()?
42) Difference between notify () & notifyAll ()?
43) Once a thread gives notification then which waiting thread will get a chance?
44) How a thread can interrupt another thread?
45) What is deadlock? Is it possible to resolve deadlock situation?
46) Which keyword causes deadlock situation?
47) How we can stop a thread explicitly?
48) Explain about suspend () and resume ()?
49) What is starvation and explain difference between deadlock & starvation?
50) What is race condition?
51) What is daemon thread? Give an example purpose of Daemon Thread?
52) How we can check daemon nature of a Thread? Is it possible to change Daemon
nature of a Thread? Is main thread daemon (or) non-daemon?
53) Explain about ThreadGroup?
54) What is ThreadLocal?

1. What is the different between ServletConfig and ServletContext?


Ans=

• ServletConfig available in javax.servlet.*; package


• ServletConfig object is one per servlet class
• Object of ServletConfig will be created during initialization process of the servlet
• This Config object is public to a particular servlet only
• Scope: As long as a servlet is executing, ServletConfig object will be available, it will
be destroyed once the servlet execution is completed.
• We should give request explicitly, in order to create ServletConfig object for the first
time
• In web.xml – <init-param> tag will be appear under <servlet-class> tag
Here's how it looks under web.xml : (Source)
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.stackoverflow.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>
• ServletContext available in javax.servlet.*; package
• ServletContext object is global to entire web application
• Object of ServletContext will be created at the time of web application deployment
• Scope: As long as web application is executing, ServletContext object will be
available, and it will be destroyed once the application is removed from the server.
• ServletContext object will be available even before giving the first request
In web.xml – <context-param> tag will be appear under <web-app> tag
Here's how it looks under web.xml :

<context-param>
<param-name>globalVariable</param-name>
<param-value>com.stackoverflow</param-value>
</context-param>

2. What is jsp include directive?

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).

For Code Reusability purpose.<%@ include file="resourceName" %>

3. What is jsptaglib directive?


The JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag
section we will use this tag so it will be better to learn it in custom tag.
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

4. What is connection polling?


a connection pool is a cache of database connections maintained so that
the connections can be reused when future requests to the database are
required. Connection pools are used to enhance the performance of executing
commands on a database.
5. How to insert query to the data source?
6. What is jsp:useBean?
The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean depending
on the scope. But if object of bean is not created, it instantiates the bean.

Java Bean

A Java Bean is a java class that should follow following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Why use Java Bean?

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object, so we can access this object from multiple
places. Moreover, it provides the easy maintenance.

• 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)

• Is it possible to use @Repository behalf of @Controller? explain.

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.

• What is configuration in hibernate? program


• If I want to connect two database in hibernate , then how I will connect?
• What is dialect in hibernate ?
• How u will show the result in jsp , fetching data from database? program
• What is collection?
• What is map?
• What will be the output if we access private method? program
• How to resolve the OutOfmemory problem.(heap memeory)
• Is it possible to create object in interface and why?
• Exception program .and what will be output?
• Difference between jdbc and hibernate.
• If there are 5 methods in a interface, Is child class implements 2 method from 5
?and why? Program…
• Difference between ArrayList and LinkedLIst?
Design pattern java programming
Java String programming
Matrix java programming.
Get and load method in hibernate
Logic behind the number character occurrence in string.
Sql query logic.
How to find the 3rd largest salary from employee?
What is Hash Map?
Hash map program logic.
How to find number of key value pairs in a map?
How to find the corresponding values of key?
Join of two tables
After joining two salary table and employee table getting 4th highest paid
salary of employee
Abstraction vs interface
Spring mvc concept.
How to change the port no. of server in eclipse.
• Written round and programming…clear..
• WAP occurrence of character in String.
• WAP to Swap two variables without using 3rd variable.
• WAP to for circular linked list.
• WAP for producer consumer relation.
• WAP for String Anagram.
• Different between application object and session object?
• WAP I array to retrieve largest 3 no. from array.
Matrix anti clock wise 90 degree program in java
Spring mvc with rest web service insert, update program
Linked list program(last element of list will come to first and after all are same)
Mathematical solution of permutation combination question.

1. Design current project architecture diagram.


2. Introduction of project.
3. Wap occurrences of character in string.
4. Oops concept.
5. What is abstraction different with interface?
6. What is invert tag in hibernate?
7. Difference between Get and Load method in hibernate?
8. Difference between save and merge method in hibernate?
9. What are new feature in java 1.7?
10. Multiple catch concepts and how it makes convince from previous
version?
11. Difference between ConncurrentHashMap and SynchronisedHashmap.
12. Checked exception program.
13. Can u handle OutOfMemory error? How u resolved this?
14. Difference between sql date and util date?
15. Difference between sterilization and externalization?

• 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:

1st Round: Test:

Written and progrominc test

2st Round: Test:

• Abot project and role responsibity


• Program of overloading
• Difference between hibernate and jdbc
• Can we write query in hibernate?
• What are type of mvc model?
• What are the folder structure of spring mvc?
• Puzzle solve?
• There is table , query for finding all null value of specific coloumn and null of all
table?

IWeen

1st Round: Test:

• Find index of first non-repeated character in a string.


• In an array there are lot of floating –ve and +ve value, find the sum of value
which is equivalent to zero.
Without using any inbuilt function and collection.
• Forgot the question.
• 20 objective.

2st Round:

• about the project..


• about role and responsibility
• difference between throw and throws?
• Customized exception program
• Difference between coucuranthashmap and synchronized hashmap?
• Difference between ArrayList and LinkList?
• Diffence between .equlasnd ==
• T

3st Round:

• How many ways to create Thread with program


• Print 10 tables in child thread class..program
• To sleep all table 5 second ,,program
• Difference between sleep(), wait(), notify()
• Difference between notify(), notifyAll()
• What is Thread Pool
• ThreadPool program havig 10 threads on by one and some criteria
• Input=Iween@Bangalore
Output= Iween
Bangalore write program… without using collection and inbuilt function
• Again add some requirement in above program..
• Difference between soap vs restful
• Difference between get and post?

Altimetric:

1st Round: System Test:

40 objective from java, c++, data structure , java script, sql


2 programing:
• One scenario where there are lot of parents having lot of children. Have to
find the siblings of particular parent .
Example: input1 =5; length of the araay.
int[] input2={1, 3, 5, 6,7}
input3= siblings of particular no.
siblings will consider as n+1 and n+2
here siblings of 5 are 6,7

• 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:

Find index of first non-repeated character in a string.

Technical round

1. Abut the project.


2. Return type of web service
3. Given a scenario to get all customer details to write full program in rest controller
with configuration and all classes.
4. What are the jar u use in restful for json response
5. What is enum?
6. Is enum is singletone?
7. What is Thread pool?
8. What is Executor?
9. What is ExcuteService interface?
10. What are the specifier and modifier are use in Java?
11. Class Test{
Intb ;
Employe e;
} make it immutable calss.
12. Internal working flow of HasMap?
13. HashMap related other question..somepackgerealted.
14. Iterator vs enumeration?
15. HashmapvshashTable?
16.

First round (Core java +spring)

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?

3. Tell me Hash Map implementation

4. Difference between Linked List and Array List

5. How to make a map as synchronized map

6. What is the difference between Collections.synchronizedMap(m) and concurrent hash

map

7. Difference between forEach and iterator

8. Can we instantiate interface if not then why?

9. Difference between classNotFoundException and NoClassDefError in which situation


we

will face this?

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?

Second round(Spring boot)

1. Why we should go for spring boot?

2. What are the main component of spring boot?

3. How to monitor application in different environment?

4. Why we are returning ResponseEntity from controller method why not direct object?

5. How to handle exception using spring boot mvc architecture

6. What @SpringBootApplication annotation does?

4/7/2018 Interview Question Profile: Java and spring boot

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?

9. What are the build tools u r aware?

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

running how can I do

13. What is application. Properties if I will keep different name instead of application will
it
work?

14. How to enable logging in spring boot

15. Difference between soap and rest web services give one example

Interview question with answer

1. List down all the annotation in spring.


Answer: These are the basic annotation presents in spring

• @Component
• @Service
• @Controller
• @Repository
• @Require
• @Autowired
• @Qualifier
• @Configuration
• @Bean
• @ComponentScan
• @Import
• @Dependson
• @Lazy
• @RequestParm
• @PathVariable
• @ModelAttribute
• @RequestMapping
• @Transactional
• @AdviceController
• @ExceptionHandler

2. List out all annotation of rest used in your projects?


Answer: In my project I am using these below annotations

1. @ApplicationPath
2. @Path
3. @Consumes
4. @Produces
5. @POST
6. @GET
7. @PUT
8. @DELETE
9. @FormParm
10. @PathParm
etc…

3. Use of cascade and inverse attributes in Hibernate?


Answer:

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

4. Difference between Level 1 and level 2 cache in Hibernate?

Level-1 cache Level-2 cache

1. Level-1 cache is session scope. 1.Level-2 cache is Session Factory scope

2. By default enable. 2.We need to enable it by using some


configuration
3.level 1 cache data will not available in 3. level 2 cache data will available in entire
entire application cause its scope is session application cause its scope is session
scope and one application can contain factory
multiple session scope
4.It implements SRAM (static random 4.It implements DRAM(Dynamic random
access memory) access memory)

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

5. Difference between ArrayList and LinkedList ?

ArrayList LinkedList

1.For retrieval operation ArrayList is 1.For Middle insertion or middle


preferable modification LinkedList is preferable

2.Memory shifting or Memory management 2.Memory shifting or Memory management


is complicated is not required

3. ArrayList internally uses dynamic 3. LinkedList internally uses doubly linked


array to store the elements. list to store the elements.

6. Internal flow of HashMap ?


Normally HashMap follows below 3 steps

1. hashCode() to find bucket

2. == operator to reference comparison

3. equals () to content comparison


When we are save object in map means map.put(Object,Object) then first hashMap
internally use hashing technique to find the bucket so it find the hashCode of object then
% by initial capacity then bucket number will be get and object will placed on that
specific bucket no Ex: (key.hashCode()%11)

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.

7. Difference between hashMap and hashTable ?

HashMap HashTable

1.HashMap is non-synchronized and non- 1.HashTable is synchronized and thread


thread safe safe

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

5.HashMap is introduced 1.2 version 5.HashTable is introduced in 1.2 so it is


legacy

8. Difference between Array and ArrayList ?


Array ArrayList
1. Array is not Grow able in nature. 1.ArrayList is grow able in nature

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

4.Performance wise Array is best 4.Performance wise ArrayList is preferable


5.Memory wise Array is not good 5.Memory wise ArrayList is not good in
comparison Array

9. Difference between ArrayList and vector ?

ArrayList Vector

1.ArrayList is non-synchronized 1.Vector is synchronized

2.It is Non-Thread safe 2.it is thread safe

3.it Introduced in jdk 1.2 3.Vector is legacy

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

5.Support Iterator 5.Support Enumeration

10.in your project where you used ConcurrentHashMap?


Answer:

As per my project business requirement I didn’t use ConcurrentHashMap that’s why I


don’t have hands on experience on it but I know where we have to use.

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.

NOTE: Normally to avoid ConcurrentModificationException ConcurrentHashMap


introduced in JDK 1.5

13. Difference between Callable and Future interface?


Answer:

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

public Object call() throws Exception {


returnnull;
}
Future I is a general concurrency abstraction, also known as a promise, which promise to
return a result in future. When we are calling service.submit(Pass Thread class Object);
then it instantly computation the result and return back to the future object based on
generics and we can get that results by calling future.get() method

ExecutorService service = Executors.newFixedThreadPool(2);


Future<Object>f = service.submit(Thread class Object);
Object result = f.get();

14. Class loaders?


Answer: Class Loaders helps to load the class in JVM normally there are 3 types of class
loader available i.e. 1. Bootstrap Class Loader 2.Extension Class Loader
3.Application Class Loader

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

15. How can we take list into map?


Example: public Map<List<String>, List<Double>> getData() {

Map<List<String>, List<Double>>dataMap = new HashMap<>();

List<String>l1Key = new ArrayList<>();


l1Key.add("Basant");
l1Key.add("Babul");

List<String>l2Key = new ArrayList<>();


l2Key.add("Manoj");
l2Key.add("Amit");
l2Key.add("Saroj");

List<Double>l1Value = new ArrayList<>();


l1Value.add(50.000);
l1Value.add(40.000);

List<Double>l2Value = new ArrayList<>();


l2Value.add(90.000);
l2Value.add(60.000);
l2Value.add(30.000);

dataMap.put(l1Key, l1Value);
dataMap.put(l2Key, l2Value);
returndataMap;

16. How can we take Map into List?


Example:

public List<Map<String, Integer>> setData() {


List<Map<String, Integer>>listMap = new ArrayList<>();
Map<String, Integer>map = new HashMap<>();
map.put("A", 34);
map.put("D", 90);
map.put("B", 12);
map.put("C", 91);
listMap.add(map);

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.

18. .how you implement exception handling in your project?


Answer:

Normally we are developing Spring based application so in Spring to handle exception


multiple predefined class is there .so simply in my project we are throwing custom
exception from service layer and when my controller call service it will catch that
exception by using Spring-Aop , We have to create a class which should be annoted as
@ControllerAdvice and we have to take one method whose return type is Model And
View and method should be annoted as @ExceptionHandler so in this method we have to
write the logic for map the exception. And return the same view which is return by
controller class at the time of exception raise. And we have to return some user
understandable message by view page.

Note: Both return logical view should be same

19. Where you implement multi-threading in your project?


Answer:

As a 3 year experience developer I didn’t get a chance to work on Multithreading


environment .these part is developed by our senior team members. But I have aware on
multithreading and I know how to work.

20. What are all the design patterns you observed in spring?
Answer:

As I know in spring internally used 4 to 5 annotations to provide better flexibility


to developer

1. Strategy Design Pattern

2. Factory Design Pattern

3. Template Design Pattern

4. Adapter Design Pattern

5. Singleton Design Pattern

6. Facade Design Pattern

21. Which design patters you used in your project?


Answer:
In my project I used Modularization design Pattern,Facade Design Pattern,
Service locator Design pattern.
pattern

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.

24. What is use of intern () in string?


Answer:

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy