Q1.What Is Java? Why It Is Needed?
Q1.What Is Java? Why It Is Needed?
Ans:- Java is a programming language and computing platform first released by Sun
Microsystems in 1995.It is used to create desktop as well as web application.Its features
makes it different from other programming Languages .Its features are:
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed.
Ans: A class can't be declared as protected. only methods can be declared as protected.
Ans: final is a modifier which can be applied to a class or a method or a variable. final
class can't be inherited, final method can't be overridden and final variable can't be
changed.
finally is an exception handling code section which gets executed whether an exception is
raised or not by the try block code segment. finalize() is a method of Object class which will
be executed by the JVM just before garbage collecting object to give a final chance for
resource releasing activity.
Q 4. What is Inheritance?
Ans:Inheritance is the feature of Object Oriented programming in which one class acquires
the properties of another class or we can say that one object acquires the properties of
another object.It is also known as the concept of reusability.Class that is inherited is base
class & another is derived class.
class Super
States(variables)+methods(behaviours)
}
Properties of super+sub
Q 5. What is Abstract class and Interface? How it will use by another? Give the
difference between them?
Ans:-A Class in which one or more methods do not have a body is known as abstract class.
Abstract class provides 0 to 100% abstraction.A class which inherits abstract class must
override abstract methods otherwise declares itself as abstract.Abstract class can have
constructors,instance,static variables.It always fall in the hierarchy,it never be a top level
body.
Whereas Interface always found in the top level level body.It contains all the methods as
abstract no constructor,no instance variables.variables declared inside a interface are
default static & final.
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstractmethods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main method
main method and constructor. or constructor.
5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
7) Example: Example:
public class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Q 6. Why there are some interfaces with no defined methods (i.e. marker interfaces) in
Java? FAQ
Ans 13: The interfaces with no defined methods act like markers. They just tell the
compiler that the objects of the classes implementing the interfaces with no defined
methods need to be treated differently.
Example java.io.Serializable java.lang.Cloneable, java.util.EventListener etc. Marker
interfaces are also known as “tag” interfaces since they tag all the derived classes into a
category based on their purpose.
Ans: Yes an Interface can inherit another Interface, for that matter an Interface can
extend more than one Interface.
Ans: To serialize an object means to convert its state to a byte stream so that the byte
stream can be reverted back into a copy of the object. A Java object is serializable if its
class or any of its superclasses implements either the java.io.Serializable interface or its
subinterface, java.io.Externalizable. Deserialization is the process of converting the
serialized form of an object back into a copy of the object.
import java.io.*;
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output:
import java.io.*;
}
}
Look here the variable ssn in class customer it is declared as transient .If you make any
variable as transient then when object is serialized this variable will not convert into byte
format.so that when you recover it or deserialized it SSN is 0.So transient will not allow the
variable to be serialized.
Q 9. What is Externalizable?
Ans: Externalizable is an Interface that extends Serializable Interface. And sends data
into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput
out) and readExternal (ObjectInput in)
Ans:
ArrayList LinkedList
1) ArrayList internally uses dynamic array LinkedList internally uses doubly linked list
to store the elements. to store the elements.
2) ArrayList requires more time to insert or Insertion & deletion requires less time as only nodes
delete element at specified position as more will get Disturbed.
shifting needs to be done.
3) Searching is fast by indexing. Searching will be slow as every element need to be
traversed.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
5)Elements are connected due to contiguous If any link is corrupted data will be loss.
memory allocation.
6)Less memory effective utilization. Memory utilization is Efficient.
Ans:
HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe Hashtable is synchronized. It is thread
and can't be shared between many threads without -safe and can be shared with many
proper synchronization code. threads.
2) HashMap allows one null key and multiple null Hashtable doesn't allow
values. any null key or value.
3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as synchronized by Hashtable is internally synchronized
calling this code and can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
6) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator
and Iterator.
7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not
fail-fast.
8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
Ans: Collection uses the concept of generics as we know generics was added in JDK1.5 to
improve compile time type safety & explicit type conversion problem.So collection uses
generics,because as all we know collection is used to store objects of different- different
classes.So at compile time only we pass the name of class of which object is stored by
collection. For ex:Collection< class name>
Ans.) Hashing is the technique of searching the elements within a group.Hashing makes the
searching faster. The problem at hands is to speed up searching. If the array is not sorted,
the search might require examining each and all elements of the array. If the array is
sorted, we can use the binary search, and therefore reduce the worse-case runtime
complexity to O(log n).
We can search even faster if the arrays is not sorted by help of technique known as Hashing
.In Hashing we create a hash function in which we pass a key as a input & get the address
of location directly .So the best case complexity for that O(1).
Several techniques used to make hash function like division hashing,multiplication hashing
etc.In java collection classes like HashSet,LinkedHashSet,HashMap,Hashtable use the
concept of hashing.
Ans: Path and Classpath are operating system level environment variales. Path is used
define where the system can find the executables(.exe) files and classpath is used to specify
the location .class files.
Ans.) Thread is a object in java, which is used when we want to create multiple threads
running in parallel to produce multiple outputs at a time .We know that multithreading is a
advance form of multitasking (in which multiple process running simultaneously like
Notepad ,Songs ,Browser etc).In java we can create multiple thread objects to create
multiple thread.And to create a object of a thread we have a class known as Thread class in
java.lang package.
We must first register our thread object to thread scheduler by the help of start
method.start() method called only once for a single thread object.
Q. 18 Which would you prefer Either Extends Thread or implement runnable &
why?
Ans: The Runnable interface is preferred, as it does not require your object to inherit a
thread because when you need multiple inheritance, only interfaces can help you. In the
above example we had to extend the Base class so implementing Runnable interface is an
obvious choice. Also note how the threads are started in each of the different cases as
shown in the code sample. In an OO approach you should only extend a class when you
want to make it different from it’s superclass, and change it’s behavior. By implementing a
Runnable interface instead of extending the Thread class, you are telling to the user that
the class Counter that an object of type Counter will run as a thread.
Q. 19 methods of thread?
Ans:Thread class has several methods which can be used to perform multiple actions on a
thread.
Start()-to register a thread under thread scheduler so that it can join ready queue. Sleep(
time in ms)-to send a running thread into sleeping state until time is not over.
Note:Any method which cause a running thread to go in blocked state will throw interrupted
exception which must be catch or throws by programmer because it is checked
exception.For eg-sleep(),wait(),join(),suspend() etc.
Join()-If a running thread wants to wait for a child thread to complete its execution before
its completes It can call join() method join() method will send the caller thread to waiting
state until child completes.
Thread t=Thread.currentThread();
T1.start();
T1.join();
Ans:First we have to understand the used of wait & notify method .Wait method is used
when we want to make a thread wait for a particular resource or method.So in java lock
always exist on Object or we can say if any thread wants control over any resource first of
all it has to acquire a object lock.And it it is not capable of acquiring the object lock then it
executes wait method of object class & goes into waiting state. That why every class has
Wait method because the methods of object are birth right of every object in java.
We need to understand what garbage means garbage is any memory which is allocated
during runtime but now no longer required.For example we create many objects by new
keyword & we know memory created by new is allocated during runtime on heap(used for
dynamic memory allocation).So at runtime memory can recovered also by using garbage
collector .Java provides automatic garbage collection by providing garbage collector thread
which is executed by jre time to time.We can also send request to garbage collector by
calling system.gc() method.
Ans - Exception means runtime error. Whenever error comes at runtime it is considered to
be an exception because the error is not detected by the compiler(Compiler job is to detect
error in source code)& if compiler passes that code & then error comes at runtime it is
considered to be exception.
Some errors which is known to be come at runtime like division by zero is not detected by
compiler at compile time .But we can trained compiler to restrict some type of suspicious
code by using throws keyword.Whenever any method throw any exception & if it comes
under checked category then compiler will force to catch that exception by try-catch or
propogate using throws keyword. For eg:FileNotFoundException,SqlException etc.
void m1()
{
try{
S1.reverse();
S=new String(s1);
Ans: Immutable object means once a object is created it cannot be changed or its content
cannot be changed, it can only available for reading.String is also immutable in java,if you
try to change its contents new object will be created by jre.
s.concat(“Kumar”);
S=s.conact(“kumar”);
System.out.println(s);//NOW RAVIKUMAR
Ans: Map is not a part of a collection framework. But we can obtain collection view of map.
Where as list extends collection interface & can be iterate by the help of iterator which is
available only for the collection classes. Map contains data as key, value pair where list can
only hold values. Map<k,v>||List<t>.Map key will be unique, values can be repeated .To
obtain collection view of map call map.entry method of map interface.
while(itr.hasNext()) {
Map iteration
Map<Integer,Integer>map=newHashMap<Integer,Integer>();
for(Map.Entry<Integer,Integer>entry:map.entrySet()){
Since in method overriding both the classes(base class and child class) have same method,
compile doesn’t figure out which method to call at compile-time. In this case JVM(java
virtual machine) decides which method to call at runtime that’s why it is known as runtime
or dynamic polymorphism.
class X
{
void methodA(int num)
{
System.out.println ("methodA:" + num);
}
void methodA(int num1, int num2)
{
System.out.println ("methodA:" + num1 + "," + num2);
}
double methodA(double num) {
System.out.println("methodA:" + num);
return num;
}
}
class Y
{
public static void main (String args [])
{
X Obj = new X();
double result;
Obj.methodA(20);
Obj.methodA(20, 30);
result = Obj.methodA(5.5);
System.out.println("Answer is:" + result);
}
}
Output:
methodA:20
methodA:20,30
methodA:5.5
Answer is:5.5
Ans: This design pattern proposes that at any time there can only be one instance of a
The class’s default constructor is made private, which prevents the direct instantiation of the
object by others (Other Classes). A static modifier is applied to the instance method that
returns the object as it then makes this method a class level method that can be accessed
without creating an object.
One such scenario where it might prove useful is when we develop the help Module in a
project. Java Help is an extensible, platform-independent help system that enables authors
and developers to incorporate online help into applications.
scenario by using a singleton connection class we can maintain a single connection object
which can be used throughout the application.
public class SingletonObjectDemo {
Fetching Strategies
There are four fetching strategies
1. fetch-“join” = Disable the lazy loading; always load all the collections and entities.
2. fetch-“select” (default) = Lazy load all the collections and entities.
3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
4. fetch-“subselect” = Group its collection into a sub select statement.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
Use of Aggregation:
Code reuse is also best achieved by aggregation when there is no is-a relationship.
Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
Ques-37 What do you mean by IOC and Dependency Injection Give an example?
Ans:- Spring Framework has its Inversion of Control (IOC) container. The IOC container
manages java objects – from instantiation to destruction – through its Bean Factory. Java
components that are instantiated by the IOC container are called beans, and the IOC
container manages a bean's scope, lifecycle events, and any AOP features for which it has
been configured and coded.
The IOC container enforces the dependency injection pattern for your components, leaving
them loosely coupled and allowing you to code to abstractions. This chapter is a tutorial – in
it we will go through the basic steps of creating a bean, configuring it for deployment in
Spring, and then unit testing it.
Dependency Injection (or sometime called wiring) helps in gluing these classes together and
same time keeping them independent.
Lazy fetching means for example in hibernate if we use load() method then load() is lazy
fetching i.e it is not going to touch the database until we write empobject.getString( eno
);So when we write above statement in that instance it touch the database and get all the
data from database. It is called as lazy loading.If we see another example i.e
session.get(...) method is used then at that instance it is going to touch the database and
get the data and place the data in session object it is called as eager loading
The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages
between applications without confronting interoperability issues (interoperability meaning
the platform that a Web service is running on becomes irrelevant). Another protocol that
has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP
ensures that you do not have to worry about what kind of Web server -- whether Apache or
IIS or any other
WSDL is a document that describes a Web service and also tells you how to access and use
its methods. Take a look at a sample WSDL file
The main things to remember about a WSDL file are that it provides::
Ans:- Serialization in java is a mechanism of writing the state of an object into a byte
stream.
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
E.g:-
package javabeat.samples;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class NameStore implements Serializable{
private String firstName;
private transient String middleName;
private String lastName;
public NameStore (String fName,
String mName,
String lName){
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
}
public String toString(){
StringBuffer sb = new StringBuffer(40);
sb.append("First Name : ");
sb.append(this.firstName);
sb.append("Middle Name : ");
sb.append(this.middleName);
sb.append("Last Name : ");
sb.append(this.lastName);
return sb.toString();
}
}
public class TransientExample{
public static void main(String args[]) throws Exception {
NameStore nameStore = new NameStore("Steve",
"Middle","Jobs");
ObjectOutputStream o = new ObjectOutputStream
(new FileOutputStream("nameStore"));
// writing to object
o.writeObject(nameStore);
o.close();
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content
should change.
Ans:-Similarities :-
1. Session Interface: The basic interface for all hibernate applications. The instances are
light weighted and can be created and destroyed without expensive process.
5. Query and Criteria interface: The queries from the user are allowed by this interface
apart from controlling the flow of the query execution.
Ans:-
Ans. Transaction is a single threaded, short lived object used by the application to specify
atomicity. Transaction abstracts your application code from underlying JDBC, JTA or CORBA
transaction. At times a session can span several transactions. A TransactionFactory is a
factory for transaction instances. A ConnectionProvider is a factory for pool of JDBC
connections. A ConnectionProvider abstracts an application from underlying Datasource or
DriverManager.
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setName(“Brian”);
emp.setSalary(1000.00);
session.save(emp);
tx.commit();
//close session
Ans. A filter dynamically intercepts requests and responses to transform or use the
information contained in therequests or responses but typically do not themselves create
responses. Filters can also be used to transform theresponse from the Servlet or JSP before
sending it back to client. Filters improve reusability by placing recurringtasks in the filter as
a reusable unit.A good way to think of Servlet filters is as a chain of steps that a request
and response must go through beforereaching a Servlet, JSP, or static resource such as an
HTML page in a Web application.
Ans. static class loading : Classes are statically loaded with Java’s“new” operator.
E.g.:
class MyClass {
public static void main(String args[])
}}
A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator
(i.e. static loading) but the runtime system cannot find the referenced class.
class.newInstance (); //A non-static method, which creates an instance of a class (i.e.
creates an object).
The Hibernate Session interface provides createCriteria() method which can be used to
create a Criteria object that returns instances of the persistence object's class when your
application executes a criteria query.
Following is the simplest example of a criteria query is one which will simply return every
object that corresponds to the Employee class.
You can use add() method available for Criteria object to add restriction for a criteria
query.
This method takes an integer that represents the first row in your result set, starting with
row 0.
Ques 56:-Explain Spring AOP, Spring DAO, Spring ORM and Spring Web.
Ans:- Spring AOP enhances the Spring middleware support by providing declarative
services. This allows any object managed by Spring framework to be AOP enabled. Spring
AOP provides “declararative transaction management service” similar to transaction services
provided by EJB. So with Spring AOP you can incorporate declarative transaction
management without having to rely on EJB. AOP functionality is also fully integrated into
Spring for logging and various other features.
Spring DAO uses org.springframework.jdbc package to provide all the JDBC related
support required by your application.This abstraction layer offers a meaningful hierarchy for
handling exceptions and errors thrown by different database vendors with the help of
Spring’s SQLExceptionTranslator. So this abstraction layer simplifies error handling and
greatly reduces the amount of exception handling code you need to write. It also handles
opening and closing of connections.
Spring ORM framework is built on top of Spring DAO and it plugs into several object-to-
relational (ORM) mapping tools like Hibernate, JDO, etc. Spring provides very good support
for Hibernate by supporting Hibernate sessions, Hibernate transaction management etc.
Spring Web sits on top of the ApplicationContext module to provide context for Web based
applications. This provides integration with Struts MVC framework. Spring Web module also
assists with binding HTTP request parameters to domain objects and eases the tasks of
handling multipart requests.
The following declaration is thread safe: because the variables declared inside the scriplets
have the local
scope and not shared.
<% int a = 5 %>
Ques 64: How can you prevent the automatic creation of a session in a JSP page?
Ans: automatically create a session for the request if one does not exist. You can prevent
the creation of useless
sessions with the attribute “session” of the page directive.
<%@ page session=”false” %>
Ques 66. How would you invoke a Servlet from a JSP? Or invoke a JSP form
another JSP?
Ans:You can invoke a Servlet from a JSP through the jsp:include and jsp:forward action
tags.
<jsp:include page=”/servlet/MyServlet” flush=”true” />
Ques 67: Explain the life cycle methods of a JSP?
Ans:
Pre-translated: Before the JSP file has been translated and compiled into the
Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls
the jspInit() to initialize the
Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls the _jspService() method
for each request.
Out of service: The Servlet instance is out of service. The container calls the
jspDestroy() method.
Ques 68. How does an HTTP Servlet handle client requests?
Ans: All client requests are handled through the service() method. The service method
dispatches the request to an appropriate method like doGet(), doPost() etc to handle that
request.
Ans: There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger values,
such as double values, to smaller values, such as byte values. Casting between object
references is used to refer to an object by a compatible class, interface, or array type
reference.
Ans: Downcasting is the casting from a general to a more specific type, i.e. casting down
the hierarchy
Ans: A class does not inherit constructors from any of its superclasses.
Q 78: What are the non-final methods in Java Object class, which are meant
primarily for extension?
Ans 78: The non-final methods are equals(), hashCode(), toString(), clone(), and
finalize(). The other methods likewait(), notify(), notifyAll(), getClass() etc are final
methods and therefore cannot be overridden. Let us look at
these non-final methods, which are meant primarily for extension (i.e. inheritance).
Q 79. What is the main difference between a String and a StringBuffer class?
Another important point is that creation of extra strings is not limited to overloaded
mathematical operator “+” but there are several methods like concat(), trim(),
substring(), and replace() in String classes that generate new string instances. So use
StringBuffer or StringBuilder for computation intensive operations, which offer better
performance.
Q 80: What is the main difference between shallow cloning and deep cloning of
objects?
Ans 80: The default behavior of an object’s clone() method automatically yields a shallow
copy. So to achieve a deep copy the classes must be edited or adjusted.
Shallow copy: If a shallow copy is performed on obj-1 as shown in fig. then it is copied but
its contained objectsare not. The contained objects Obj-1 and Obj-2 are affected by changes
to cloned Obj-2. Java supports shallow cloning of objects by default when a class
implements the java.lang.Cloneable interface.
Deep copy: If a deep copy is performed on obj-1 as shown in fig. then not only obj-1 has
been copied but the
objects contained within it have been copied as well. Serialization can be used to achieve
deep cloning. Deep
cloning through serialization is faster to develop and easier to maintain but carries a
performance overhead.
Q 82: What are JDBC Statements? What are different types of statements? How
can you create them? FAQ
A 82: A statement object is responsible for sending the SQL statements to the Database.
Statement objects are created
from the connection object and then executed. CO
Statement stmt = myConnection.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT id, name FROM myTable where id =1245”); //to
read
or
stmt.executeUpdate(“INSERT INTO (field1,field2) values (1,3)”);//to
insert/update/delete/create
The types of statements are:
Statement (regular statement as shown above)
PreparedStatement (more efficient than statement due to pre-compilation of SQL)
CallableStatement (to call stored procedures on the database)
To use prepared statement:
PreparedStatement prepStmt =
myConnection.prepareStatement("SELECT id, name FROM myTable where id = ? ");
prepStmt.setInt(1, 1245);
Callable statements are used for calling stored procedures.
CallableStatement calStmt = myConnection.prepareCall("{call PROC_SHOWMYBOOKS}");
ResultSet rs = cs.executeQuery();
Ans
Ans:
2)Need not be activated or passivated since Need to handle activation and passivation to
the beans are conserve system
pooled and reused. memory since one session bean object per
client.
Q 85: What is the difference between Container Managed Persistence (CMP) and Bean Managed
Persistence (BMP) entity Beans?
Ans:
Container Managed Persistence (CMP) Bean Managed Persistence (BMP)
1)The container is responsible for persisting The bean is responsible for persisting its own
state of the bean. state.
2) Container needs to generate database bean needs to code its own database (SQL)
(SQL) calls. The calls.
3) The bean persistence is independent of its The bean persistence is hard coded and
database (e.g. hence may not be
DB2, Oracle, Sybase etc). So it is portable portable between different databases (e.g.
from one data DB2, Oracle etc).
source to another