Sunteți pe pagina 1din 33

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.

Q 2. Can a class be declared as protected?

Ans: A class can't be declared as protected. only methods can be declared as protected.

Q 3. How is final different from finally and finalize?

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

Class Sub extends Super

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.

Abstract class Interface

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.

Q 7. Can an Interface extend another Interface?

Ans: Yes an Interface can inherit another Interface, for that matter an Interface can
extend more than one Interface.

Q 8. What is Serializablity ?Give an example? Explain Transient keyword?

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.

public class Customer implements java.io.Serializable


{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}

import java.io.*;

public class SerializeDemo


{
public static void main(String [] args)
{
Customer c = new Customer();
c.name = "abhay mishra";
c.address = "atal dwar indore";
c.SSN = 11122333;
c.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/customer.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/customer.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Deserializing an Object:

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

public class DeserializeDemo

public static void main(String [] args)


{
Customer e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/customer.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Customer) in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
return;
}
catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);

System.out.println("Number: " + e.number);

}
}

This would produce the following result:


Deserialized Employee...
Name: abhay mishra
Address:atal dwar indore
SSN: 0
Number:101

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)

Q 10. What is an intern() method in the String class?


A pool of Strings is maintained by the String class. When the intern() method is invoked
equals(…) method is invoked to determine if the String already exist in the pool. If it does
then the String from the pool is returned. Otherwise, this String object is added to the pool
and a reference to this object is returned. For any two Strings s1 & s2,
s1.intern() ==s2.intern() only if s1.equals(s2) is true.

Ques-11 what is the difference between ArrayList and LinkedList?

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.

Q. 12)What is the difference between HashTable and HashMap? which is better?

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.

Q. 13)what is the difference Collection and Generics?

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>

Q.14) What is the meaning of Hashing in collections? Explain the process?

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.

Q. 15 What is difference between Path and Classpath?

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.

Q.16) Explain thread?

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 17: Explain different ways of creating a thread? FAQ


Ans : Threads can be used by either :
 Extending the Thread class
 mplementing the Runnable interface.

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.

For eg: main()

Thread t=Thread.currentThread();

Thread1 t1=new Thread1();

T1.start();

T1.join();

Now the main thread will wait until T1 completes.

Q 20. Why synchronization is important?


Ans Without synchronization, it is possible for one thread to modify a shared object while
another thread is in the process of using or updating that object’s value. This often causes
dirty data and leads to significant errors. The disadvantage of synchronization is that it
can cause deadlocks when two threads are waiting on each other to do something. Also
synchronized code has the overhead of acquiring lock, which can adversely affect the
performance.

Q 21. What is a ThreadLocal class?


Ans: ThreadLocal is a handy class for simplifying development of thread-safe concurrent
programs by making the object stored in this class not sharable between threads.
ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-
threaded environment and also allows you to create per-thread-singleton.

Q 22. What is a daemon thread?


Ans : Daemon threads are sometimes called "service" or “background” threads. These are
threads that normally run at a low priority and provide a basic service to a program when
activity on a machine is reduced. An example of a daemon thread that is continuously
running is the garbage collector thread. The JVM exits whenever all nondaemon
threads have completed, which means that all daemon threads are automatically stopped.
To make a thread as a daemon thread in Java 􀃆 myThread.setDaemon(true);
Q.23)Why wait(),wait(int ms,int ns),wait(int ms),notify(),notifyAll() are in object
class where it is used in Thread?

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.

Q.24) garbage collector in java?

Ans:Garbage Collection is essential need for any runtime environment.Where as some


languages provide manual garbage collection like c++,java provides free the users by
providing automatic garbage collection.

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.

Q 25) what is compile time exception?

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{

FileInputStream fis=new FileInputStream(“A.java”);


}
Catch(FileNotFoundException e)
{}
}
Here FileInputStream Constructor throws FileNotFoundException.

Q 26.) how to reverse string w/o using buffer?

Ans- String s=”abc”;

StringBuffer s1=new StringBuffer(s);

S1.reverse();

S=new String(s1);

System.out.println(s);// output :cba

Q 27.) String immutability in java?

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.

FOR EG- String s=new String(“Ravi”);

s.concat(“Kumar”);

System.out.println(s);//IS STILL RAVI

S=s.conact(“kumar”);

System.out.println(s);//NOW RAVIKUMAR

Means concat method created a new object,which is later hold by variable s.

Q 28.) diff btw map and list in java?

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.

Q 29.) Iterator with list and map ?

Ans: ArrayList al = new ArrayList();


// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

Iterator itr = al.iterator();

while(itr.hasNext()) {

Object element = itr.next();

System.out.print(element + " ");


}

Map iteration

Map<Integer,Integer>map=newHashMap<Integer,Integer>();

for(Map.Entry<Integer,Integer>entry:map.entrySet()){

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());


}

Q.30 types of polymorphism?

Ans: Types of polymorphism in java- Runtime and Compile time polymorphism

Runtime Polymorhism( or Dynamic polymorphism)

Method overriding is a perfect example of runtime polymorphism. In this kind of


polymorphism, reference of class X can hold object of class X or an object of any sub
classes of class X. For e.g. if class Y extends class X then both of the following statements
are valid:

Y obj = new Y();

//Parent class reference can be assigned to child object

X obj = new Y();

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.

Compile time Polymorhism( or Static polymorphism)


Compile time polymorphism is nothing but the method overloading in java. In simple terms
we can say that a class can have more than one methods with same name but with different
number of arguments or different types of arguments or both. To know more about it
refer method overloading in java.

Lets see the below example to understand it better-

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

Q.31 Can you call one constructor from another?


Ans: Yes, by using this() syntax.
E.g.
public Pet(int id) {
this.id = id; // “this” means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // ”this” means this object
}
Q.32 What are static factory methods?
Ans: Some of the above mentioned features like searching, sorting, shuffling, immutability
etc are achieved with
java.util.Collections class and java.util.Arrays utility classes. The great majority of these
implementations are provided via static factory methods in a single, non-instantiable (i.e.
private constrctor) class. Speaking of static factory methods, they are an alternative to
creating objects through constructors. Unlike constructors, static factory methods are not
required to create a new object (i.e. a duplicate object) each time they are invoked (e.g.
immutable instances can be cached) and also they have a more meaningful names like
valueOf, instanceOf, asList etc

Q 33.) Singleton DESIGN PATTERN?

Ans: This design pattern proposes that at any time there can only be one instance of a

singleton (object) created by the JVM.

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.

Singletons can be used to create a Connection Pool. If programmers create a new


connection object in every class that requires it, then its clear waste of resources. In this

scenario by using a singleton connection class we can maintain a single connection object
which can be used throughout the application.
public class SingletonObjectDemo {

private static SingletonObject singletonObject;


// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
public static SingletonObjectDemo getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
return singletonObject;
}
}
Q 34: What is a factory pattern?
A 34: A Factory method pattern (aka Factory pattern) is a creational pattern. The
creational patterns abstract the
object instantiation process by hiding how the objects are created and make the system
independent of the object
creation process. An Abstract factory pattern is one level of abstraction higher than a
factory method pattern,
which means it returns the factory classes.

Ques-35 What is FETCH in hibernate?


Ans:- ibernate has few fetching strategies to optimize the Hibernate generated select
statement, so that it can be as efficient as possible. The fetching strategy is declared in the
mapping relationship to define how Hibernate fetch its related collections and entities.

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.

Ques-36 Explain Aggregation?

Ans: Agregation is a special form of association. It is also a relationship between two


classes like association, however its a directional association, which means it is strictly
a one way association. It represents a Has-A relationship.

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.

Ques-38 What is Lazy Loading and Eager Loading?


Ans:- Lazy setting decides whether to load child objects while loading the
Parent Object.You need to do this setting respective hibernate mapping file of the parent
class.lazy = true (means not to load child)By default the lazy loading of the child objects is
true. This make sure that the child objects are not loaded unless they are explicitly invoked
in the application by calling getChild() method on parent.In this case hibernate issues a
fresh database call to load the child when getChild() is actully called on the Parent
object.But in some cases you do need to load the child objects when parent is loaded. Just
make the lazy=false and hibernate will load the child when parent is loaded from the
database.

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

Ques-39 What are the Web Services?


Ans:- Web services are client and server applications that communicate over the World
Wide Web’s (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide
Web Consortium (W3C), web services provide a standard means of interoperating between
software applications running on a variety of platforms and frameworks. Web services are
characterized by their great interoperability and extensibility, as well as their machine-
processable descriptions, thanks to the use of XML. Web services can be combined in a
loosely coupled way to achieve complex operations. Programs providing simple services can
interact with each other to deliver sophisticated added-value services

Ques-40 What is SOAP and WSDL?

Ans:-. Simple Object Access Protocol (SOAP)

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

Web Services Description Language or WSDL

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

 A description of a Web service


 The methods a Web service uses and the parameters that it takes
 A way to locate Web services
Ques-41 What is Is-A RelationShip?
Ans:- Inheritance represents the IS-A relationship, also known as parent-
child relationship.

Use of inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).

 For Code Reusability.

Ques-42 What is serializable? Explain Transient keyword

Ans:- Serialization in java is a mechanism of writing the state of an object into a byte
stream.

Serializability of a class is enabled by the class implementing the java.io.Serializable


interface. Classes that do not implement this interface will not have any of their state
serialized or deserialized. All subtypes of a serializable class are themselves serializable. The
serialization interface has no methods or fields and serves only to identify the semantics of
being serializable.

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

// reading from object


ObjectInputStream in =new ObjectInputStream(
new FileInputStream("nameStore"));
NameStore nameStore1 = (NameStore)in.readObject();
System.out.println(nameStore1);
}}
// output will be :
First Name : Steve
Middle Name : null
Last Name : Jobs
Ques-43 what is java script? when you use rather than clint validation
Ans:- JavaScript is a programming language commonly used in web development. It was
originally developed by Netscape as a means to add dynamic and interactive elements to
websites JavaScript is a client-side scripting language, which means the source code is
processed by the client's web browser rather than on the web server. This means
JavaScript functions can run after a webpage has loaded without communicating with the
server. For example, a JavaScript function may check a web form before it is submitted to
make sure all the required fields have been filled out. The JavaScript code can produce an
error message before any information is actually transmitted to the server

Ques-44 what is ajax?

Ans: AJAX stands for Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

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.

Que:45 what is the Similarities b/w ArrayList and LinkedList

Ans:-Similarities :-

1. Both ArrayList and LinkedList are implementation of List interface.


2. They both maintain the elements insertion order which means while displaying ArrayList
and LinkedList elements the result set would be having the same order in which the
elements got inserted into the List.
3. Both these classes are non-synchronized and can be made synchronized explicitly by
using Collections.synchronizedList method.
4. The iterator and listIterator returned by these classes are fail-fast (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).
Q 46 What are the core interfaces of Hibernate framework?
Ans:- following are the List of core core interfaces of Hibernate framework

1. Session Interface: The basic interface for all hibernate applications. The instances are
light weighted and can be created and destroyed without expensive process.

2. SessionFactory interface: The delivery of session objects to hibernate applications is


done by this interface. For the whole application, there will be generally one SessionFactory
and can be shared by all the application threads.

3. Configuration Interface: Hibernate bootstrap action is configured by this interface. The


location specification is specified by specific mapping documents, is done by the instance of
this interface.

4. Transaction Interface: This is an optional interface. This interface is used to abstract


the code from a transaction that is implemented such as a JDBC / JTA transaction.

5. Query and Criteria interface: The queries from the user are allowed by this interface
apart from controlling the flow of the query execution.

Q 47 What is servlet context and servlet configuration.

Ans:-

servlet configuration servlet context


 1 ServletConfig object is one per servlet ServletContext object is global to entire web
class. application

 2. Object of ServletConfig will be created Object of ServletContext will be created at


during initialization process of the servlet the time of web application deployment

 3. As long as a servlet is executing, As long as web application is executing,


ServletConfig object will be available, it will ServletContext object will be available, and
be destroyed once the servlet execution is it will be destroyed once the application is
completed. removed from the server.
 4. We should give request explicitly, in ServletContext object will be available even
order to create ServletConfig object for before giving the first request
the first time

 5. In web.xml – <init-param> tag will be In web.xml – <context-param> tag will be


appear under <servlet-class> tag appear under <web-app> tag

Ques 48 Explain Transaction management in spring?

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

Ques 49 What is a filter, and how does it work?

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.

Ques 50. Explain static and. dynamic class loading?

Ans. static class loading : Classes are statically loaded with Java’s“new” operator.

E.g.:
class MyClass {
public static void main(String args[])

Car c = new Car();

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

Dynamic loading is a technique for programmatically invoking the functions of a class


loader at run time. Let us look at how to load classes dynamically.Class.forName (String
className); //static method which returns a Class. The above static method returns the
class object associated with the class name. The string class Name can be supplied
dynamically at run time. Unlike the static loading, the dynamic loading will decide whether
to load the class Car or the class Jeep at runtime based on a properties file and/or other
runtime conditions. Once the class is dynamically loaded the following method returns an
instance of the loaded class. It’s just like creating a class object with no arguments.

class.newInstance (); //A non-static method, which creates an instance of a class (i.e.
creates an object).

Jeep myJeep = null ;


//myClassName should be read from a properties file or Constants interface.

String myClassName = "au.com.Jeep" ;


Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

A ClassNotFoundException is thrown when an application tries to load in a


class through its string name using the following methods but no definition for the
class with the specified name could be found:
 The forName(..) method in class - Class.
 The findSystemClass(..) method in class - ClassLoader.
 The loadClass(..) method in class - ClassLoader.

Ques.51 Explain criteria in hibernate


Ans Hibernate provides alternate ways of manipulating objects and in turn data available
in RDBMS tables. One of the methods is Criteria API which allows you to build up a criteria
query object programmatically where you can apply filtration rules and logical conditions.

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.

Restrictions with Criteria:

You can use add() method available for Criteria object to add restriction for a criteria
query.

Pagination using Criteria:

There are two methods of the Criteria interface for pagination.

1 public Criteria setFirstResult(int firstResult)

This method takes an integer that represents the first row in your result set, starting with
row 0.

2. public Criteria setMaxResults(int maxResults)


This method tells Hibernate to retrieve a fixed numbermaxResults of objects.

Ques 52 Explain projection in hibernate criteria?


Ans:- The Criteria API provides the org.hibernate.criterion.Projections class which can
be used to get average, maximum or minimum of the property values. The Projections class
is similar to the Restrictions class in that it provides several static factory methods for
obtaining Projection instances.

Ques 53:- Give an overview of the Spring framework?


Ans:- The Spring framework is an open source and comprehensive framework for enterprise
Java development. Unlike other frameworks, Spring does not impose itself on the design of
a project due to its modular nature and, it has been divided logically into independent
packages, which can function independently. It includes abstraction layers for transactions,
persistence frameworks, Web development, a JDBC integration framework, an AOP
integration framework, email support, web services support etc. It also provides integration
modules for popular Object-to-Relational (O/R) mapping tools like Hibernate, JDO etc. The
designers of an application can feel free to use just a few Spring packages and leave out the
rest. The other spring packages can be introduced into an existing application in a phased
manner. Spring is based on the IOC pattern (aka Dependency Injection pattern) and also
complements OOP (Object Oriented Programming) with AOP (Aspect Oriented
Programming). You do not have to use AOP if you do not want to and AOP complements
Spring IoC to provide a better middleware solution.

Ques 54:- what is Core Container in the Spring?


Ans:- Core Container provides the essential basic functionality. The basic package in the
spring framework is the org.springframework.beans package. The Spring framework uses
JavaBeans and there are two ways in which clients can use the functionality of Spring
framework -- BeanFactory and ApplicationContext. BeanFactory applies the IOC pattern
and separates an application’s configuration and dependency specification from the actual
application code.

Ques 55: what is Spring Application Context?


Ans;- Spring Application Context is a configuration file that provides context information to
Spring framework. The ApplicationContext builds on top of the BeanFactory and inherits all
the basic features of Spring framework. In addition to basic features, ApplicationContext
provides additional features like event management, internalization support, resource
management, JNDI, EJB, email, and scheduling functionality. BeanFactory is useful in low
memory situations, which does not have the excess baggage an ApplicationContext has.
ApplicationContext assist the user to use Spring in a framework oriented way while the
BeanFactory offers a programmatic approach.

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.

Ques 57 What are annotations?


Ans:- An annotation is a tag which can be added to the source code. Annotations are used
to add special behaviour, suppress warnings or to define Hibernate mappings. It starts with
an @ and can have parameters.
Advantages of annotation mapping over XML mapping files
• Mapping is included directly in the class.
• Less definitions to type, because of well chosen default values.
• Faster to develop
• Careful chosen default values

Ques 58: What is pre-initialization of a Servlet?


Ans: By default the container does not initialize the servlets as soon as it starts up. It
initializes a servlet when it receives a request for the first time for that servlet. This is called
lazy loading. The servlet deployment descriptor (web.xml) defines the <load-on-startup>
element, which can be configured to make the servlet container load and initialize the
servlet as soon as it starts up. The process of loading a servlet before any request comes in
is called pre-loading or pre-initializing a servlet. We can also specify the order in which
the servlets are initialized.

Ques 59: What is a RequestDispatcher?


Ans: A Servlet can obtain its RequestDispatcher object from its ServletContext.
//…inside the doGet() method
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
// forwards the control to another servlet or JSP to generate response. This method allows
one servlet to do preliminary
//processing of a request and another resource to generate the response
rd.forward(request,response);
or
// includes the content of the resource such as Servlet, JSP, HTML, Images etc into the
calling Servlet’s response.
rd.include(request, response);

Ques 60: What are the considerations for servlet clustering?


Ans: The clustering promotes high availability and scalability. The considerations for servlet
clustering are:
Objects stored in a session should be serializable to support in-memory replication of
sessions. Also consider the overhead of serializing very large objects. Test the performance
to make sure it is acceptable.
Design for idempotence. Failure of a request or impatient users clicking again can result
in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate
requests.
Avoid using instance and static variables in read and write mode because different
instances may exist on different JVMs. Any state should be held in an external resource such
as a database.
Avoid storing values in a ServletContext. A ServletContext is not serializable and also
the different instances may exist in different JVMs.
Avoid using java.io.* because the files may not exist on all backend machines.
Instead use getResourceAsStream().

Ques 61: 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 this method for each
request.
 Out of service: The Servlet instance is out of service. The container calls the
jspDestroy() method.

Ques 62: Is JSP variable declaration thread safe?


Ans: No. The declaration of variables in JSP is not thread-safe, because the declared
variables end up in the generated Servlet as an instance variable, not within the body of
the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be
evaluated once when the page is loaded
<%! int a = 5 %>

The following declaration is thread safe: because the variables declared inside the scriplets
have the local
scope and not shared.
<% int a = 5 %>

Ques 63: How will you avoid scriptlet code in JSP?


Ans:- By using JavaBeans or Custom Tags instead.

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 65. How does JSP handle run-time exceptions?


Ans: You can use the attribute “errorPage” of the “page” directive to have your uncaught
RuntimeExceptions
automatically forwarded to an error processing page.
Example:
<%@ page errorPage=”error.jsp” %>

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.

Q 69. Can a Byte object be cast to a double value?

Ans: No, an object cannot be cast to a primitive value.

Q 70. What is casting?

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.

Q 71. What is Downcasting ?

Ans: Downcasting is the casting from a general to a more specific type, i.e. casting down
the hierarchy

Q 72 Does a class inherit the constructors of its superclass?

Ans: A class does not inherit constructors from any of its superclasses.

Q 73) Can you override static method in Java?


No, you cannot override static method in Java because they are resolved at compile time
rather than runtime. Though you can declare and define static method of same name and
signature in child class, this will hide the static method from parent class, that's why it is
also known as method hiding in Java.

Q74) What is difference between synchronize and concurrent Collection in Java?


There was time, before Java 1.5 when you only have synchronized collection if you need
them in a multi-threaded Java program. Those classes were plagued with several issue most
importantly performance because they lock the whole collection or map whenever a thread
reads or writes. To address those issue, Java released couple of Concurrent collection
classes e.g. ConcurrentHashMap, CopyOnWriteArrayList and BlockingQueue to provide more
scalability and performance.

Q 75) What is difference between Iterator and Enumeration in Java?


Main difference is that Iterator was introduced in place of Enumeration. It also allows you to
remove elements from collection while traversing which was not possible with Enumeration.
The methods of Iterator e.g. hasNext() and next() are also more concise then corresponding
methods in Enumeration e.g. hasMoreElements(). You should always use Iterator in your
Java code as Enumeration may get deprecated and removed in future Java release.

Que 76) Can Enum implement interface in Java?


Yes, Enum can implement interface in Java. Since enum is a type, similar to class and
interface, it can implement interface. This gives a lot of flexibility to use Enum as specialized
implementation in some cases

Q 77) Difference between Serializable and Externalizable in Java?


Serializable is a marker interface with no methods defined it but Externalizable interface has
two methods defined on it e.g. readExternal() and writeExternal() which allows you to
control the serialization process. Serializable uses default serialization process which can be
very slow for some application.

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?

String is immutable: you can’t modify a StringBuffer is mutable: use StringBuffer or


string object but can replace it by creating a StringBuilder when you wantto modify the
new instance. Creating a new instance is contents. StringBuilder was added in Java
rather expensive. 5 and it isidentical in all respects to
//Inefficient version using immutable String StringBuffer except that it is not
String output = “Some text” synchronized, which makes it slightly faster
Int count = 100; at the cost of not being thread-safe.
for(int i =0; i<count; i++) { //More efficient version using mutable
output += i; StringBuffer
} StringBuffer output = new
return output; StringBuffer(110);// set an initial size of
The above code would build 99 new String 110
objects, of which 98 would be thrown away output.append(“Some text”);
immediately. Creating new objects is not for(int i =0; i<count; i++) {
efficient. output.append(i);
}
return output.toString();
The above code creates only two new
objects, the StringBuffer and the final String
that is returned. StringBuffer expands as
needed, which is costly however, so it would
be better to initialize the StringBuffer with
the correct size from the start as shown.

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 81: How would you refresh your cache?


Ans: You could say that one of the two following strategies can be used:
1. Timed cache strategy where the cache can be replenished periodically (i.e. every 30
minutes, every
hour etc). This is a simple strategy applicable when it is acceptable to show dirty data at
times and also
the data in the database does not change very frequently.
2. Dirty check strategy where your application is the only one which can mutate (i.e.
modify) the data in
the database. You can set a “isDirty” flag to true when the data is modified in the database
through your
application and consequently your cache can be refreshed based on the “isDirty” flag.

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

Q 83: What is the difference between session and entity beans?

Ans

session beans entity beans


1)Use session beans for application logic. Use entity beans to develop persistent object
model.
2) Use entity beans to develop persistent Insist on reuse of entity beans
object model.
Expect little reuse of session beans.
3)Session beans control the workflow and Domain objects with a unique identity (i.e.-
transactions of a primary key) shared
group of entity beans. by multiple clients.
4)Life is limited to the life of a particular Persist across multiple invocations. Handles
client. Handle database access
database access for a particular client. for multiple clients.
5)Do not survive system shut downs or Do survive system shut downs or server
server crashes. crashes.

Q 84 What is the difference between stateful and stateless session beans?

Ans:

Stateful session beans Stateless session beans


1)Do not have an internal state. Can be Do have an internal state. Reused by the
reused by different same client.
clients.

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

S-ar putea să vă placă și