You are on page 1of 18

What is the purpose of serialization?

Answer: Serialization is the conversion of an object to a series of


bytes, so that the object can be easily saved to persistent storage
or streamed across a communication link. The byte stream can
then be deserialised converted into a replica of the original
object.
Source | Example
What is the difference between JDK and JRE?
Answer: Java Development Kit (JDK) is the most widely used Java
Software Development Kit. Java Runtime Environment (JRE) is an
implementation of the Java Virtual Machine, which executes Java
programs.
Source | JDK Wiki | JVM Wiki
What is the difference between equals() and == ?
Answer: Equals is intended to check logical equality and ==
checks if both references point to same object. (Thanks Sandeep)
a==b;//Comparesreferences,notvalues.
a.equals(b);//Comparesvaluesforequality.

Source
When will you use Comparator and Comparable interfaces?
Answer: java.util.Comparator and java.lang.Comparable
java.util.Comparator compares some other classs
instances, while java.lang.Comparable compares itself with
another object.
Source | Example
What is the wait/notify mechanism?
Answer: This deals with concurrent programming. The wait() and
notify() methods are designed to provide a mechanism to allow a
thread to be block until a specific condition is met.
However, java.util.concurrent should be used instead of wait()
and notify() to reduce complexity.
Source | Java API | Java Technical Article
What is the difference between checked and unchecked
exceptions?

Answer:In general, unchecked exceptions represent defects in the


program (bugs), which are normally Runtime exceptions.
Furthermore, checked exceptions represent invalid conditions in
areas outside the immediate control of the program.
Source
What is the difference between final, finally and finalize?
Answer: A final variable cannot be modified

b. A final method cannot be overridden


c. A final class never participates in Inheritance

finally is a block of code that always executes when the try


block is finished, unless System.exit() was called. finalize() is an
method that is invoked before an object is discarded by the
garbage collector.
Source | Final Usage |Finally Usage | Finalize()
What is the difference between web server and app server?
Answer: A Web server exclusively handles HTTP requests,
whereas an application server serves business logic to application
programs through any number of protocols.
Source
What is the difference between forward and sendredirect?
Answer: Both method calls redirect you to new
resource/page/servlet. The difference between the two is that
sendRedirect always sends a header back to the client/browser,
containing the data in which you wanted to be redirected.
Source
How does a 3 tier application differ from a 2 tier one?
Answer: Tiers are the physical units of separation or deployment,
while layers are the logical units of separation.
Imagine that youre designing an e-commerce website. A 3 tier
architecture would consist of web pages, a web server and a
database, with the corresponding 3 layers being the
Presentation, Business Logic and Database layers.
If you take the database tier and layer out then your have a 2 tier
architecture.
Source
How does the version control process works?
Answer: Initiate, pull, branch, merge, commit, push.

(Init) Make your own repository. (Pull) Download an existing


repository from a url. (Branch / Merge )Make revisions. Commit
then push your modifications.
Git Cheat Sheet
What is the difference between JAR and WAR files?
Answer: JAR files (Java ARchive) allows aggregating many files
into one, it is usually used to hold Java classes in a library.
WAR files (Web Application aRchive) stores XML, java classes, and
JavaServer pages for Web Application purposes.
Source
What is a Left outer join?
Answer: This deals with SQL. Left outer join preserves the
unmatched rows from the first (left) table, joining them with a
NULL row in the shape of the second (right) table.
Source | Joins Wiki
What is the difference between UNION and UNION ALL?
Answer: This deals with SQL. UNION only selects distinct values,
UNION ALL selects all values.
Source | Example
Why main() in java is declared as public static void main?
What if the main method is declared as
private?
Ans : Because, every program start exucution from main
function.The static method can directly call without createing the
object of the class.So, before createing object the main function
runs and then it creates object.
And, public in main method due to access by JVM. If the method
is private then JVM cannot call that function.The program will
compile but never run.It show the message "Main method not
public."
2.What is Externalizable?
Ans : This interface is used for serialization.To save the state of an

object in file. It provides two method


readExternal() and writeExternal().
3.What modifiers are allowed for methods in an Interface?
Ans : abstract and public
4.What are the different identifier states of a Thread?
Ans :
R- Running or Runnable
S- Suspended
MS- Thread Suspended on Moniter lock
MW- Thread waiting on moniter
CW- Thread waiting on condition variable
5.What are some alternatives to inheritance?
Ans : Delegation is an alternative to inheritance. Delegation
means that you include an instance of another class as an
instance variable, and forward messages to the instance. It is
often safer than inheritance because it forces you to think about
each message you forward, because the instance is of a known
class, rather than a new class, and because it doesnt force you
to accept all the methods of the super class: you can provide only
the methods that really make sense. On the other hand, it makes
you write more code, and it is harder to re-use (because it is not a
subclass).
6.Why isnt there operator overloading?
Ans : Because C++ has proven by example that operator
overloading makes code almost impossible to maintain.
7.What does it mean that a method or field is static?
Ans : Static method or field are member of class.They do not
need any object for call or access . We can directly call the static
method and fields without using the object.
Q. Is Java Pass by Reference or Pass by Value?

Ans : Its always pass by value .


Q. What is the purpose of garbage collection in Java, and
when is it used?
Ans : Garbage collection is a special feature in java language. It
helps developer to save time and extra mental tension for
handling object allocation in memory. It automatically clean the
unused object from memory which helps to allocate space at
runtime. When there is no reference to an object found, it will
clean that object from memory . You can run the garbage
collection explicitly by using System.gc() .
Q. What is Marker interface? How is it used in Java?
Ans : Marker interface is an interface which help us to notify few
information to JVM/Compiler. The marker interface does not have
any body, its a empty interface. Ex. Cloneable, Serialization, etc.
Q. Can you give few examples of final classes defined in
Java API?
Ans: String, Integer ,Float ,etc. Basically all wrapper classed are
final.
Q. What is the importance of init() method in Servlet?
Ans: init() method is one of the life cycle method of servlet. This
method runs once in total life. After servlet instance created and
before it handles request the init() method will work. Its basically
used for initializing values at the time of application startup.
Q. How to improve Servlet Performance ?
Ans: You need to do few tuning for this achievement. Few points
below :1.
Use init() method for all expensive operation during
initialization (may be static data or cached data ).
2.
Always avoid auto loading of servlet.
3.
Avoid SingleThreadModel.
4.
Use and control HttpSession properly.
Q. How can a servlet refresh automatically if some new
data has entered the database?
Ans : Basically it depends on the scenario , how you can handle.

You need handle this in dao layer, when doing insert operation
you can call an utility method which will load the context
ServletContextListener. Because, servlets are basically used for
handling request and give the response.
Q. How does JSP handle run-time exceptions?
Ans: You can use isErrorPage=true in page attribute.
Q. What is an EJB Context?
Ans: The EJBContext interface provides an instance with access to
the container-provided runtime context of an enterprise bean
instance.
Q1. Why do you want to work in this industry / company?
Ans: First you should try to convince that this company gives
huge opportunity in many aspect i.e. new technologies
implementation, the policy of company suits you like
professionalism. Also you can mention that you are big fan of
this company and its your dream company. Basically show your
all positive attitude towards company.
Q2. Which location do you want to work in and why?
Ans : Give your own choice. Also mention a valid reason for why
you are interested for that location. The reason should be always
positive and clear. Example :- you can support your family from
this location,
Q3. Describe a problem you faced and how you deal with
it ?
Ans : You can describe any issue you faced during your project
work in the organization. And what the solution you have
implemented for that issue.
Q4. What are the types of class loaders in Java?
Ans : As per my knowledge there are basically 3 types of class
loader like bootstarp classloader,extension class loader and
system class loader.

Bootstrap Class LoaderBootstrap class loader loads javas


core classes like java.lang, java.util etc. These are classes
that are part of java runtime environment. Bootstrap class
loader is native implementation and so they may differ
across different JVMs.
Extensions Class LoaderJAVA_HOME/jre/lib/ext contains jar
packages that are extensions of standard core java classes.
Extensions class loader loads classes from this ext folder.
Using the system environment propery java.ext.dirs you can
add ext folders and jar files to be loaded using extensions
class loader
System Class Loader
Java classes that are available in the java classpath
are loaded using System class loader
Q6. How to read and write image from a file ?
Ans : You can use ImageIo.read() and ImageIO.write() method of
javax.imageio package.
Q7. What is difference between static and init block in
java.
Static does not need any object to execute. Before creating any object the
static block can execute as we are using in static method. So, here the
static block is call at the time of JVM execution , means before creating the
object( when first time JVM execute ). But Initialization block is call/loaded
every time when object is created.Whenever the object is created at that
time the Initialization block is loaded.
Q8. How ConcurrentHashMap works?
Ans : The basic design of ConcurrentHashMap is to handling
threading. Basically it locks each of the box (by default 16) which
can be locked independently and thread safe for operation. And it
does not expose the internal lock process.
What is ConcurrentMap and how it works?
Ans Its a Map which providing thread safety and atomicity

guarantees. For Memory consistency it works with other


concurrent collections, actions in a thread prior to placing an
object into a ConcurrentMap as a key or value happenbefore actions subsequent to the access or removal of that object
from the ConcurrentMap in another thread.
Q9. Can a static block throw exception?
Ans : Yes. We can throw checked exception.
Q10. What is difference between iterator access and index
access?
Ans : Basically iterator access process the traverse operation
through each element, where index access process access direct
the element by using the index.
Q11. Why character array is better than string for storing
password in java?
Ans : Because, character array stores data in encrypted format
which is not readable by human. But,the string stores the data in
human readable format which is not secure.
Q12. what is daemon thread in java ?
Ans : A daemon thread is normally runs on background. And it
does not prevent the JVM from exiting when the program finishes
but the thread is still running.
Q13. What is Java Reflection API?
Ans : Reflection is one of the most powerful api which help to
work with classes, methods and variables dynamically. Basically
it inspect the class attributes at runtime. Also we can say it
provides a metadata about the class.
Q14. What is the difference between Serializable and
Externalizable interfaces?
Ans : Both interfaces are used for implement serialization. But,
the basic difference is Serializable interface does not have any

method (its a marker interface ) and Externalizable interface


having 2 methods such as readExternal() and writeExternal().
Serializable interface is the super interface for Externalizable
interface.
What is transient variable ?
Ans : Transient variables are not serializable. It helps to avoid a
variable to being serialization.
4) Write the code to initialize the inner class members.
Ans : Code here
public class InnerClassTest {
class innerTest{
private int age;
public void display(){
System.out.println("Age="+age);
}

}
/**
* @param args
*/
public static void main(String[] args) {
InnerClassTest.innerTest innerObj=new
InnerClassTest().new innerTest();
innerObj.age=20;
innerObj.display();
}
}
5) How to retrieve the elements from the collection write
the code ?
Ans : Java provides certain interfaces by using that we can
retrieve the elements from collection.Example Iterator,
ListIterator and Enumeration.

Example :- ArrayList data retrival


public class ArrayListRetrive {
/**
* @param args
*/
public static void main(String[] args) {
ArrayList<String> arList=new ArrayList<String>();
arList.add("Java");
arList.add("is");
arList.add("Powerful!!!");

//Retrive elements from ArrayList using Iterator


Iterator iTer=arList.iterator();
while(iTer.hasNext()){
System.out.println(iTer.next());
}

}
6) What is static and instance variables and methods ?
Ans : Static variables are per class but the instance variables are
per object. All object share a single copy of static variable. In case
of static method , no need of object creation for calling static
method. The static method can directly call by using class name.
Instance method need object for calling.
7) What is dynamic loading and static loading of java class
?
Ans : Dynamic class loading is by Class.forName() , which loads
the class dynamically. Also you can use reflection for dynamic
class loading. But, the static class loading is working by using
new keyword.
8) What type of loading is class.forname() ?
Ans : Its dynamically locate and loads the class.
9) What is Hibenate 3 best benfits ?

Ans : There are many benefits of hibernate. But the most benefits
are below :1.
It reduces the developer effort to writing queries.
2.
Its easy to use with relational object which maps with java
class and database relation.
3.
Query tuning is not required and it implements separates
cache which is reason for better performance.
10) I have 100 tables and fields. I want to find one table
name and column names. Write a quey .
Ans : I have used mySQL database for this below query.
select TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME from
information_schema.COLUMNS where TABLE_NAME='EMPLOYEE';
11) How to define a field name in hibernate using
annotation ?
Ans:- @Column (Its provided by java persistent API).
12) What is Synchronization ?
Ans:- Synchronization is a solution for concurrency issue.
Java provide 'synchronized' keyword for implementing this.
13) The most commonly used classes in collectionsn ?
Ans : ArrayList, LinkedList, HashTable, HashMap and
ConcurrentHashMap, etc.
3. How many types of literals are there in JAVA ?
Ans : The literals means the value you are assigning to variable.
You can specify the below types of literal in java.As per the
primitive data types(int,short,long,float,double,boolean,char ,etc
there is respective literal. Some literal needs to be ended with a
specific character.Read More.
long var=20L; //specify L or l for long literal
int var=20; // If not mentioned any character then its can be

short or int
char var=A;
float var=10.44f; //specify f or F for float literal
double var=10.44;
boolean var=true; //or false
4. What is meant by Garbage collection ?
Ans : Garbage collection is a automatic feature of java for
cleaning the unused object from heap. It helps to developer for
releasing the reserved memory without any extra effort by
developer. It helps developer to save time and extra mental
tension for handling object allocation in memory. When there is
no reference to an object found, it will clean that object from
memory . You can run the garbage collection explicitly by using
System.gc() .
5. Diffference between string s= new string (); and string
s = "Hi Dude"; ?
Ans : Both statements are different to each other. Always new
keyword is used to create object.
String s=new String(); // This statement creates new object in
heap. S is the object here.
String s=Hi Dude ; // This statement do not create object, its
creating reference and its storing in String Constant Pool.S is the
reference here.
6. What is singleton class? where is it used ?
Ans : Singleton design pattern is the most useful pattern in real
time scenario.Singleton pattern will ensure that there is only one
instance of a class is created in the JVM.This implementation
restrict the user to create multiple access point or instance. This
is a creational design pattern. It has many implementation over
java language, but singleton is an anti-pattern or bad
practice.

7. What is the difference between JSP and Servlets ?


Ans : As simple JSP is pre-compiled but Servlets are not. JSP is
specially use for displaying/populating the data on browser. If we
take an example of MVC architecture JSP plays the role of View
(V). But, Servlets are used to handle the request and process the
business logic. In MVC architecture Servlets are knows as
Controller (C) .
8. What is the difference in using
request.getRequestDispatcher() and
context.getRequestDispatcher()?
Ans : Both are taking String parameter, but
request.getRequestDispatcher() will dispatch the request inside
the application. Where as context.getRequestDispatcher() will
dispatch the request outside the context also. If you are using
absolute path for dispatching then both are similar.
9. How the JSP file will be executed on the Server side ?
Ans : First its converted to java file. Then its compiled by java
compiler and creates the .class file.Now once you get the .class
file you can execute it. Internally a JSP converts into respective
servlet.
Conversion => Compilation => Execution

12. What is the difference between the Session and


SessionFactory in hibernate ?
Ans : Session and SessionFactory are playing a prominent role in
hibernate. SessionFactory is used to create Session and its
created once during starting of the application. You can have only
one SessionFactory per application. SessionFactory is also called
2ndlevel cache. But, Session could be many per application.
Session is being created by using SessionFactory object.Session is
called 1st level cache.
13. What is HQL ?

Ans : HQL stands for Hibernate Query Language. Its fully object
oriented and quite similar with SQL.It supports association and
joins for effective entity relationship.
Which Interface is used to make duplicate of Objects ?
Ans Cloneable interface.
Q11) What are some advantages and disadvantages of
Java Sockets?
Ans The main advantage is its flexible and very efficient during
low network bandwidth. Also its helpful for debugging and some
kind of testing. But, security is the most disadvantages. Its
always recommended to be careful when authenticating.
Q12) When can an object reference be cast to an interface
reference?
Ans Yes its possible, when that interface is implemented by that
class.
Example MyInterface obj=new MyClass();
obj.callMethod();
Q13) How does Java allocate stack and heap Memory?
Ans As we know stack memory is not dynamic and its follows
LIFO order. Java provides similar implementation for memory
allocation. Normally all local variables are created in Stack area
(memory) and objects (reference types) are created in heap
memory (heap area) .Even all primitive types allocated in stack
memory. Heap area is dynamic and handled by JVM runtime.
Heap memory is cleaned by garbage collector at runtime.
Q14) What is memory leak in Java?
Ans Usually memory leak leads to waste of memory. In general
memory leak defines the unavailability of referenced memory. It
causes the Garbage collector to fail to collect that object.

Q15) Can we throw exception from finally block in Java?


Ans Yes, but you need to mentioned throws on the method
head.
Example
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
TestInterface2 interObj=new InterfaceObject();
try{
interObj.display();
}catch(Exception e){
System.out.println("Exception handled...");
}finally{
throw new Exception("This is exception");
}
}
Q16) How does Java handle integer overflows and
underflows?
Ans Yes, java handles overflows and underflows very
intelligently. When it overflows it will go to MIN_VALUE (i.e.
and when it underflows to will go to MAX_VALUE (i.e.

-2

31

2 -1) .
31

Q18) What is casting?


Ans Casting means conversion. Basically we need casting to
type cast the type. There are two types of casting by java i.e.
explicit casting and implicit casting.
Q19) What is new in JSP?
Ans As per my knowledge JSP 2.1 has many new functionalities.
It support resource injection via annotation. It has few extended
support for java standard tag library. Also literal expression is
supported by JSP 2.1 EL and many other additional features.
Q20) What do you mean by Java Reflection ?

Ans It provides runtime access to JVM. Reflection is one of the


most powerful API which help to work with classes, methods and
variables dynamically at runtime. Basically it inspects the class
attributes at runtime. Also we can say it provides a metadata
about the class.
Q21) Why does the InputStreamReader class has a
read() ?
Ans Because, an InputStreamReader is a bridge from byte
streams to character streams: It reads bytes and decodes them
into characters using a specified charset. The charset that it
uses may be specified by name or may be given explicitly, or the
platform's default charset may be accepted. It has two
overloaded read() method . Each invocation of one of an
InputStreamReader's read() methods may cause one or more
bytes to be read from the underlying byte-input stream. To enable
the efficient conversion of bytes to characters, more bytes may
be read ahead from the underlying stream than are necessary to
satisfy the current read operation.

Q.1. How you can define an object ? How its related to


real world and it behaves ? With Example.
Ans : As we know object is a real world entity. It has three basic
property i.e. State, Behavior and Identity.
State: what the objects have. Dog have a name, age, color,etc .It
is implemented by variables in java.
Behavior: what the objects do.Dog can bark, bite, run, etc. It is
implemented by methods in java.
Identity: what makes them unique, Dog have id-unique, which is
unique. (this is important when implementing the equals method,
to determine if the objects are different or not) . Every object has
different hash code.
Example - Suppose , there are many dogs. But, you can't say ,

that is an object. You need to take one dog which has name dick,age-8,color -white and it must have a unique identification.
And now we can say dick is a dog object. And this dick can bark,
bite and run. These are the behavior that object can do, and in its
implemented by methods.
Q.2. How many contructor & methods are in Object class ?
Ans: There are only one constructor and nine methods in Object
class. Its available inside java.lang package.
Constructor :public Object()
Methods :clone() - This create and return copy of the same object.
equals() - This is used to compare some other object is equal to
this or not.
toString() - Convert and return a string representation.
finalize() - This is called by garbage collector when there are no
more active reference to that object exist.
getClass() - This returns the runtime class of this object.
hashCode() - Returns an hash code for this object and its unique.
notify() - Wakes up a single thread that is waiting on this object's
monitor.
notifyAll() - Wakes up all thread that is waiting on this object's
monitor.
wait() - This will make object to wait , until any other thread
notify this.
Q.3. Why wait() and notify() method is inside Object class
instead of Thread class ?
Ans : Because, wait() and notify() method works with multithreaded environment. This is inside Object class because, we are
doing the monitoring work over an Object . When ever we are
calling these methods , we are calling over object , not on thread.
Q.4. How many ways we can create object in Java ?
Ans : There are basic four way for creating object in java as below

:By using new keyword Object obj=new Object();


By using class.forName() Dog

dogObj=(Dog)class.forName("jdeveloperguide.lab.Dog").newtInst
ance();
By using deserialization ObjectInputStreaminStream=new
ObjectInputStream(anInputStream);
DogdogObject=(Dog)inStream.readObject();

By using clone() Dog dogObj=new Dog();


Dog dogObj2=dogObj.clone(); //It must implement clonnable
interface.
Q.5. How JVM allocates object in memory ? What is heap
and stack memory ?
Ans : Normally objects are allocated on heap memory. Heap
memory is a dynamic memory which increase and decrease the
size on run time. All primitive types,methods are allocated on
stack memory. All object type and reference types are allocated
on heap area.Every thread creates a stack (call stack ) and when
thread completes the stack is also release the reserve memory.
The stack is faster compare to heap.

You might also like