Академический Документы
Профессиональный Документы
Культура Документы
Q) Opps concepts
Polymorphism
Ability to take more than one form, In java we achieve this using Method Overloading (compile time
polymorphism), Method overriding (runtime polymorphism)
Inheritance
Is the process by which one object acquires the properties of another object.
Encapsulation
Wrapping of data and function into a single unit called encapsulation. Ex:- all java programs.
Abstraction
Nothing but representing the essential futures without including background details.
Dynamicbinding
Code associated with a given procedural call is not known until the time of the call at runtime. Dynamic
binding is nothing but late binding.
Q) System.out.println()
println() is a methd of java.io.printWriter.
“out” is an instance variable of java.lang.System class.
Q) Default Values
long -2^63 to 2^63 –1 0L
Int -2^31 to 2^31 –1 0
Short -2^15 to 2^15 –1 0
Byte -2^7 to 2^7 –1 0
char 0 to 2^7 –1 null character (or) ‘\u 0000’
double 0.0d
float 0.0f
Boolean false
Character -> ‘\u0000’
JIT is a part of JVM, it compiles byte code into executable code in real time, will increase the performance
of the interpretations.
Access Specifier
Access Modifiers
Q) Wrapper classes
Primitive data types can be converted into objects by using wrapper classes. These are java.lang.package.
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
We can write “static public void” instead of “public static void” but not “public void static”.
If no arguments on the command line, String array of Main method will be empty of null?
It is empty. But not null.
Variables can have the same name as a method or a class
Q) Constructor
The automatic initialization is performed through the constructor, constructor has same name has class
name. Constructor has no return type not even void. We can pass the parameters to the constructor. this() is used
to invoke a constructor of the same class. Super() is used to invoke a super class constructor. Constructor is
called immediately after the object is created before the new operator completes.
Constructor can use the access modifiers public, protected or private or have no access modifier (package
access)
Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
Constructor can be overloaded, we cannot override.
You cannot use this() and Super() in the same constructor.
Class A(
A(){
System.out.println(“hello”);
}}
Class B extends A {
B(){
System.out.println(“friend”);
}}
Class print {
Public static void main (String args []){
B b = new B();
}
o/p:- Hello
friend
Constructor Method
Use to instance of a class Grouping java statement
No return type Void (or) valid return type
Same name as class name As a name except the class method name, begin
with lower case.
“This” refer to another constructor in the same Refers to instance of class
class
“Super” to invoke the super class constructor Execute an overridden method in the super class
“Inheritance” cannot be inherited Can be inherited
We can overload but we cannot overridden Can be inherited
Will automatically invoke when an object is Method has called explicitly
created
Q) Garbage collection
G.C is also called automatic memory management as JVM automatically removes the unused
variables/objects (value is null) from the memory. User program cann't directly free the object from memory,
instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a
program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage
collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign
null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle
the unused objects, but there is no guarantee when all the objects will garbage collected.
Final: - When we declare a sub class a final the compiler will give error as “cannot subclass final class” Final to
prevent inheritance and method overriding. Once to declare a variable as final it cannot occupy memory per
instance basis.
Using System.exit(); in try block will not allow finally code to execute
Finalize: - some times an object need to perform some actions when it is going to destroy, if an object holding
some non-java resource such as file handle (or) window character font, these resources are freed before the
object is going to destroy.Any cleanup processing before the object is garbage collected.
• Overloaded methods are not required to have the same return type or the list of thrown exceptions.
• Overloading is particularly used while implementing several methods that implement similar behavior but for
different data types.
The access modifier for the overriding method may not be more restrictive than the access modifier of the
superclass method
• If the super class method is public, the overriding method must be public
• If the superclass method is protected, the overriding method may be protected or public
• If the superclass method is package, the overriding method may be packagage, protected, or public
• If the superclass methods is private, it is not inherited and overriding is not an issue
• Methods declared as final cannot be overridden.
The throws clause of the overriding method may only include exceptions that can be thrown by the
superclass method, including it's subclasses
Q) Static
Static variables and methods are instantiated only once per class. In other words they are class variables,
not instance variables. If you change the value of a static variable in a particular object, the value of that variable
changes for all instances of that class. Static methods can be referenced with the name of the class.
When a member is declared a static it can be accessed before any object of its class are created.
Instance variables declared as static are essentially global variables.
If you do not specify an initial value to an instance & Static variable a default value will be assigned
automatically.
Methods declared as static have some restrictions they can access only static data, they can only call other
static data, they cannot refer this or super.
Static methods cant be overriden to non-static methods.
Static methods is called by the static methods only, an ordinary method can call the static methods, but static
methods cannot call ordinary methods.
Static methods are implicitly "final", because overriding is only done based on the type of the objects
They cannot refer “this” or “super” in any way.
Q) Class variable & Instance variable & Instance methods & class methods
Instance variable variables defined inside a class are called instance variables with multiple instance of class,
each instance has a variable stored in separate memory location.
Class variables you want a variable to be common to all classes then we crate class variables. To create a
class variable put the “static” keyword before the variable name.
Class methods we create a class methods to allow us to call a method without creating a instance of the class.
To declare a class method use the “static” key word.
Instance methods we define a method in a class, in order to use that methods we need to first create objects of
the class.
Q) Static block
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to
the main method the static block will execute.
StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means
that its value can be changed. It allocates room for 16 addition character space when no specific length is
specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be
overridden the equals() method.
Q) Conversions
String to Int Conversion :-
int I = integer.valueOf(“24”).intValue();
int x = integer.parseInt(“433”);
float f = float.valueOf(23.9).floatValue();
Q) Super()
Super() always calling the constructor of immediate super class, super() must always be the first
statements executed inside a subclass constructor.
Member classes - Member inner classes are just like other member methods and member variables and access
to the member class is restricted, just like methods and variables. This means a public member class acts
similarly to a nested top-level class. The primary difference between member classes and nested top-level
classes is that member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the
block of their declaration. In order for the class to be useful beyond the declaration block, it would need to
implement a more publicly available interface. Because local classes are not members the modifiers public,
protected, private and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous
classes have no name, you cannot provide a constructor.
Q) Abstract Class
Any class that contain one are more abstract methods must also be declared as an abstract, there can be
no object of an abstract class, we cannot directly instantiate the abstract classes. A.C can contain concrete
methods.
Any sub class of an Abstract class must either implement all the abstract methods in the super class or be
declared itself as Abstract.
class B extends A(
void callme(){
}
}
class AbstractDemo{
public static void main(string args[]){
B b = new B();
b.callme();
b.callmetoo();
}
}
Q) Interface
Interface is similar to class but they lack instance variable, their methods are declared with out any body.
Interfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitly
abstract, even if the abstract modifier is omitted. Interface methods have no implementation;
Interface A
{
final static float pi = 3.14f;
}
class B implements A
{
public float compute(float x, float y)
{
return(x*y);
}
}
class test{
public static void main(String args[])
{
A a = new B();
a.compute();
}
}
Q) Diff Interface & Abstract Class?
Abstract classes may have some executable methods and methods left unimplemented. Interface contains no
implementation code.
An abstract class can have nonabstract methods. All methods of an Interface are abstract.
An abstract class can have instance variables. An Interface cannot.
An abstract class can define constructor. An Interface cannot.
An abstract class can have any visibility: public, private, protected. An Interface visibility must be public (or)
none.
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) Synchronization
Synchronization is a process of controlling the access of shared resources by the multiple threads in
such a manner that only one thread can access one resource at a time. (Or) When 2 are more threads need to
access the shared resources they need to some way ensure that the resources will be used by only one thread at
a time. This process which is achieved is called synchronization.
Q) Monitor
A monitor is a mutex, once a thread enter a monitor , all other threads must wait until that thread exist the
monitor.
URL is to identify a resource in a network, is only used to read something from the network.
URL url = new URL(protocol name, host name, port, url specifier)
Q) Runtime class
Runtime class encapsulate the run-time environment. You cannot instantiate a Runtime object. You can
get a reference to the current Runtime object by calling the static method Runtime.getRuntime()
Runtime r = Runtime.getRuntime()
Long mem1;
Mem1 = r.freeMemory();
Mem1 = r.totalMemory();
Q) System class
System class hold a collection of static methods and variables. The standard input, output, error output of
the java runtime are stored in the in, out, err variables.
Q) Class
Class encapsulate the run-time state of a an object or interface. Methods in this class are
Q) Native Methods
Native methods are used to call subroutine that is written in a language other than java, this subroutine
exist as executable code for the CPU.
Q) Cloneable Interface
Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is
used to indicate that a class allow a bit wise copy of an object to be made.
Q) Clone
Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.
Q) Comparable Interface
Classes that implements comparable contain objects that can be compared in some meaningful manner.
This interface having one method compare the invoking object with the object. For sorting comparable interface
will be used.
Ex:- int compareTo(Object obj)
Q) Class
Encapsulate the run time state of an object (or) interface. You cannot explicitly declare a class object, by
using getClass() method you can do that.
Class a = x.getClass();
Q) java.jlang.Reflect (package)
Reflection is the ability of software to analyse it self, to obtain information about the field, constructor,
methods & modifier of class. You need this information to build software tools that enables you to work with java
beans components.
Q) InstanceOf
Instanceof means by which your program can obtain run time type information about an object.
Ex:- A a = new A();
a.instanceOf A;
Q) java lack pointers how do I implements classic pointer structures like linked list?
A) using object reference.
Q) java.Exe
Micro soft provided sdk for java, which includes “jexegentool”. This converts class file into a “.Exec” form.
Only disadvantage is user needs a M.S java V.M installed.
Q)
Collection classes Collection Interfaces Legacy classes Legacy interface
Abstract collection Collection Dictionary Enumerator
Abstract List List Hash Table
Abstract Set Set Stack
Array List Sorted Set Vector
Linked List Map Properties
Hash set Iterator
Tree Set
Hash Map
Tree Map
Collection Classes
Abstract collection
Abstract List
Abstract Set
Array List Array List extends AbstractList and implements the List interface. ArrayList is a variable length
of array of object references, ArrayList support dynamic array that grow as needed. A.L allow rapid random
access to element but slow for insertion and deletion from the middle of the list.
Linked List Extends AbstactSequentialList and implements List interface. L.L provide optimal sequence
access, in expensive insertion and deletion from the middle of the list, relatively slow for random access.
Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast().
Hash Set HashSet extends AbstractSet implements Set interface, it creates a collection that uses
HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet
Tree Set Extends Abstract Set implements Set interface. Objects are stored in sorted, ascending order.
Access and retrial times are quite fast.
Hash Map Extends Abstract Map and implements Map interface. H.P does not guarantee the order of
elements, so the order in which the elements are added to a H.P is not necessary the order in which they are
ready by the iterate.
Tree Map implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in
sorted order and allow rapid retrieval.
Collection Interfaces
Collection Collection is a group of objects, collection does not allow duplicate elements.
List List will extend collection, list stores a sequence of elements that can contain duplicates, elements
can be accessed their position in the list using a zero based index.
Methods>> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int
indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index).
Set Set will extend collection, Set cannot contain duplicate elements.
Map Map maps unique key to value in a map for every key there is a corresponding value and you will
lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map both the “key” &
“value” are objects.
Iterator Before accessing a collection through an iterator you must obtain one if the collection classes
provide an iterator() method that returns an iterator to the start of the collection. By using iterator object you
can access each element in the collection, one element at a time.
Ex:- ArayList arr = new ArrayList();
Arr.add(“c”);
Iterator itr = arr.iterator();
While(itr.hashNext())
{
Object element = itr.next();
}
List Iterator List Iterator gives the ability to access the collection, either forward/backward direction
Legacy Classes
Dictionary is an abstract class that represent key/value storage repository and operates much like “Map”
once the value is stored you can retrieve it by using key.
Hash Table HashTable stores key/value pairs in hash table, HashTable is Synchronized when using
hash table you have to specify an object that is used as a key, and the value that you want to linked to that
key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored
with the table. Use H.T to store large amount of data, it will search as fast as vector.
Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key),
Object put(Object key, Object value)
Stack is a sub class of vector, stack includes all the methods defined by vector and adds several of its
own.
Vector vector holds any type of objects, it is not fixed length and vector is synchronized. We can store
primitive data types as well as objects. Default length of vector is up to 10.
Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean
removeElementAt(int index), final void removeAllElements().
Properties is a subclass of HashTable, it is used to maintain the list of values in which the “key/value” is
String.
Legacy Interfaces
Enumeration Define methods by which you can enumerate the elements in a collection of objects.
Enumeration is synchronized it having 2 methods hasMoreElements(), nextElement().
Q) Array
Array of fixed length of same data type, we can store primitive data types as well as class objects.
Arrays are initialized to the default value of their type when they are created, not declared, even if they are
local variables
Q) List Iterator
It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of
the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.
Exception Handling
Object
Throwable
Error Exception
ExceptionException are generated by java runtime system (or) by manually. An exception is a abnormal
condition that transfer program execution from a thrower to catcher.
Error Will stop the program execution, Error is a abnormal system condition we cannot handled these.
try This is used to fix up the error, to prevent the program from automatically terminating, try-catch is
used to catching an exception that are thrown by the java runtime system.
Throws A Throws clause list the type of exceptions that a methods might through.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses
also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either
to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the
exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked
exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector is unable to
claim any more free memory.
StackOverFlow --> Signals that a stack O.F in the interpreter.
ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or > or equal
to the array size.
StringIndexOutOfbound --> For accessing character of a string or string buffer with index values <0 or >
or equal to the array size.
Arithmetic Exception --> such as divide by zero.
ArrayStore Exception --> Assignment to an array element of an incompatible types.
ClasscastException --> Invalid casting.
IllegalArgument Exception --> Illegal argument is used to invoke a method.
Nullpointer Exception --> If attempt to made to use a null object.
NumberFormat Exception --> Invalid conversition of string to numeric format.
ClassNotfound Exception --> class not found.
Instantion Exception --> Attempt to create an object of an Abstract class or Interface.
NosuchField Exception --> A request field does not exist.
NosuchMethod Exception --> A request method does not exist.
Q) Methods in Exceptions?
A) getMessage(), toString(), printStackTrace(), getLocalizedMessage(),
All Packages
Q) Thread Class
Methods: -
getName() run()
getPriority() Sleep()
isAlive() Start()
join()
Q) Object class
All other classes are sub classes of object class, Object class is a super class of all other class.
Methods: -
void notify() void notifyAll()
Object Clone() Sting toString()
Boolean equals(Object object) Void wait()
void finalize() void wait(long milliseconds, int
nanoseconds)
Q) throwable class
Methods: -
String getMessage() Void printStackTrace()
String toString() Throwable fillInStackTrace()
Q) Javax.servlet Package
ServletInputStream (C) public int readLine(byte b[], int off, int len)
Q) Javax.servlet.Http Package
Q) java.sql Package
Q) java.lang Package
Q) java.IO Package
SERVLETS Questions
Q) Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are
used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in
memory specially instructed to be destroyed.
First the servlet is constructed and then initialized with the init () method, this will call only once.
Any request from client is handled initially by the service () method before delegating to the doXxx () methods
in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy () method, then garbaged collected and
finalized. This will call only once. When your application is stopped (or) Servlet Container shuts down, your
Servlet's destroy () method will be called. This allows you to free any resources you may have got hold of in your
Servlet's init () method.
Q) Session Tracking
Session tracking is the capability of the server to maintain the single client sequential list.
Q) Servlet chaining
Is a technique in which two are more servlets cooperating in servicing a single client sequential request,
where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet
chain open your browser and give the alias name in URL.
HttpRequest construct a URL string and append a comma delimited list of servlets to the end.
Q) HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub
protocol inside http protocol that is tunneling inside another protocol.
Q) Servlet mapping?
A) <servlet>
<servlet-name>watermelon</servlet-name>
<servlet-class>myservlets.watermelon</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>watermelon</servlet-name>
<url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>
Q) Tag Libraries?
A) <taglib>
<taglib-uri>myTaglib</taglib-uri>
<tablig-location>WEB-INF/myTLD.tld</taglib-location>
</taglib>
Q) How can a servlet refresh automatically if some new data has entered the database?
A) you can use client side refresh are server push
URL Rewriting
URL rewriting is a technique in which the requested URL is modified with the session id.
URL rewriting is another way to support anonymous session tracking. With URL rewriting, every local URL the
user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter
Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that
browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the
server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can
uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP
headers, they should be added to the response before you send any content. Browsers are only required to
accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.
You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method:
Zero means to delete the cookie
+ value is the maximum number of seconds the cookie will live, before it expires
- value means the cookie will not be stored beyond this browser session (deleted on browser close)
This will return the session for this user or create one if one does not already exist.
Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved
using getValueNames(). Values can also be removed using removeValue(String valueName)
User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a
user name and password. Once they are verified the client re-sends the authorisation with requests for
documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a
hashtable can be set up to contain all the data for a particular user. When a user makes another request the user
name can be used to add new items to their cart using the hashtable.
Q) Session
Session is a persistence network connection between client and server that facilitate the exchange of
information between client and server. A session object created for each user persists on the server side, either
until user closes the browser or user remains idle for the session expiration time.
As such there is no limit on the amount of information that can be saved in a Session Object. Only the
RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which
should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary
file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session
exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.
Q) SingleThread model
SingleThreadModel is a tag interface with no methods. In this model no two threads will execute
concurrently the service method of the servlet, to accomplish this each thread uses a free servlet instance from
the servlet pool. So any servlet implementing this can be considered thread safe and it is not required synchronize
access to its variables.
(or)
If a servlet implements this interface, the server ensures that each instance of the servlet handles only
one service request at a time. Servers implement this functionality by maintaining a pool of servlet instances and
dispatching incoming requests to free servlets within the pool. SingleThreadModel provides easy thread safety,
but at the cost of increased resource requirements as more servlet instances are loaded at any given time.
Q) Request Headers
User-agent: - Gives the information about client software, browser name, version and information about the
machine on which it is running.
request.getHeader(“user-agent”);
Threading Questions
Q) What threads will start when you start the java program?
A) Finalizer, Main, Reference Handler, Signal dispatcher.
Q) Thread
Thread is a smallest unit of dispatchable code.
Q) yield( )
Yield method temporarily stop the callers thread and put at the end of queue to wait for another turn to be
executed. It is used to make other threads of the same priority have the chance to run.
-> Thread.sleep(milliseconds);
-> Thread.sleep(milliseconds, nanoseconds);
Q) Multi Threading
Q) Daemon Thread
Daemon thread is one which serves another thread, it has no other role normally a daemon thread carry
some background program. When daemon thread remain the program exist.
Q) Thread Priority
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Q) Thread Priorities
Q) What is the use of start() function in starting a thread? why we do not use the run() method directly to
run the thread?
Start method tell the JVM that it needs to create a system specific thread. After creating the system resources
it passes the runnable object to it to execute the run() method.
calling run() method directly has the thread execute in the same as the calling object, not a separate thread of
execution.
Q) what are the different levels of locking using ‘Synchronize’ key word?
A) class level, method level, object level, block level
JSP Questions
Directives
Page Directive <%@ Page language="java" extends="className" Page directive defines information
import="className" session="true|false" buffer="8KB" that will be globally available for that
autoFlush="true/false" isThreadSafe="true/false" page
info="text" errorPage="jspUrl" isErrorPage="true/false"
contentType="mimeType” %>
Include Directive <%@ include file="relative URL" %> Include JSP are Servlet at compile
time meaning that only once parsed
by the compiler, it will act as a “C”
"#include" pulling in the text of the
included file and compiling it as if it
were part of the including file. We can
also include “Static” files using this
directive.
Taglib Directive <%@ taglib uri="uriToTagLibrary" prefix="prefixString" %> Taglib directive enables you to create
your own custom tags.
Actions
<Jsp: useBean> <Jsp: useBean id="beanInstanceName" scope="page| UseBean tag is used to associate a
request|session|application” class="" java bean with jsp.
type="" bean Name="" type="" </jsp: useBean>
<Jsp: getProperty> <Jsp: getProperty name="beanInstanceName" Gets the value of a bean property so
property="propertyName" /> that you can display it in a result
page.
<Jsp: param> <Jsp: param name="beanInstanceName" value=" It is used to provide other tags with
parameterValue " /> additional information in the form of
name, value pairs. This is used to
conjunction with jsp:include,
jsp:forward, jsp:plugin.
<Jsp: include> <Jsp: include page="relativeURL " flush="true" > Jsp Include includes the JSP are
<Jsp: param name="username" value="jsmith" /> Servlet at request time, it is not
</jsp: include> parsed by the compiler, and it
Includes a static file or sends a
request to a dynamic file.
<Jsp: forward> <Jsp: forward page="{relativeURL|<%=expression %>}" > When ever the client request will
come it will take the request and
<jsp: param name="paramName" value="paramValue"/> process the request and the request
</jsp: forward> to be forward to another page and it
will also forward the http parameters
of the previous page to the destination
page. It will work at server side.
<Jsp: plugin> <Jsp: plugin type="bean/applet" code="classFileName" This action is used to generate client
codebase="classFileDirectoryName" browser specific html tags that
name="instanceName" archive="” align="" height=" " ensures the java plug in software is
width=" " hspace=" " vspace=" </jsp: plugin> available, followed by execution of
applet or java bean component
specified in tag.
Q) Implicit Objects
Q) Declaration
A declaration declares one or more variables or methods for use later in the JSP source file.
Ex: <%! int a, b, c; %>
<%! int accountnumber=2346883; %>
<%! String accountname="Thomas"; %>
<%! private void processAmount () { ... } %>
Q) Expressions
An expression tag contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
Ex: <%= (new java.util.Date ()).toLocaleString() %>
Q) Scriptlet
A scriptlet can contain variable or method declarations, or expressions that are valid in the page scripting
language. Within scriptlet tags, you can
1.Declare variables or methods to use later in the file
2.Write expressions valid in the page scripting language
3.Use any of the JSP implicit objects or any object declared with a <jsp: useBean> tag.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet
produces output, the output is stored in the out object, from which you can display it.
Q) Comments
Html comment Creates a comment that is sent to the client in the viewable page source.
Ex: <! -- comment [ <%= expression %> ] -->
Hidden Comment Documents the JSP file, but is not sent to the client.
Ex: <%-- comment --%>
Q) MVC
Model: - model is a java bean/entity bean that represent the data being transmitted are received.
Controller: - Controller is a servlet that performs necessary manipulations to the model.
View: - is a screen representation of the model.
Major benefits of using the MVC design pattern is separate the view & model this make it is possible to create
are change views with out having to change the model.
1) The browser makes a request to the controller servlet 2) Servlet performs necessary actions to the java
bean model and forward the result to the jsp view. 3) The jsp formats the model for display and send the html
results back top the web browser.
Q) Life-cycle of JSP
jspInit( ) container calls the jspInit() to initialize to servlet instance. It is called before any other method,
and is called only once for a servlet instance.
_jspservice( ) container calls _jspservice() for each request, passing it the request and the response objects.
jspDestroy( ) container calls this when it decides take the instance out of service. It is the last method called n
the servlet instance.
jspInit() & jspDestroy() called only once so we cannot override these methods.
<Jsp: forward> Forwards a client request to an HTML file, JSP file, or servlet for processing. When ever
the client request will come it will take the request and process the request and the request to be forward to
another page, it will also forward the http parameters of the previous page to the destination page. It will execute
at “server side” so the browser unaware of the changes. If page1.jsp redirects to page2.jsp, the browser address
bar will still show page1.jsp.
res.sendRedirect(url) when ever the client request will come just it will take the request and the request
to be forwarded to another page. It cannot forward the http parameters of the previous page. This will work at
client side.
sendRedirect() sends a redirect response back to the client's browser. The browser will normally
interpret this response by initiating a new request to the redirect URL given in the response.
forward() does not involve the client's browser. It just takes browser's current request, and hands it off
to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different
servlet/jsp than they originally called.
For ex, if you want to hide the fact that you're handling the browser request with multiple servlets/jsp, and
all of the servlets/jsp are in the same web application, use forward() or include(). If you want the browser to initiate
a new request to a different servlet/jsp, or if the servlet/jsp you want to forward to is not in the same web
application, use sendRedirect ().
<%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and
compiling it as if it were part of the including file. The included file can be any type (including HTML or text). (Or)
includes a jsp/servlet at compile time meaning only once parsed by the compiler.
<jsp:include page="abc.jsp"> include a jsp/servlet at request time it is not parsed by the compiler.
Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is
almost similar.
In jsp we can easily separate the P.L with B.L, but in servlet both are combined.
One servlet object is communicate with many number of objects, but jsp it is not possible.
processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive:
<%@ page isErrorPage=\"true\" %> .
Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And
Proxy server?
Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or
Synchronization?
A) SingleThreadModel technique is easy to use, and works well for low volume sites. If your users to increase in
the future, you may be better off implementing explicit synchronization for your shared data
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious
issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the
unserviced requests are queued until something becomes free.
Servlet1
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet2”) ;
rd.forward(req, res);
Servlet2
Public void service(servletRequest req, servletResponse res)
{
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet1”) ;
rd.include(req, res);
}
Q) How do I pass values from a list box (with multiple selects) to a Java Bean?
Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:
package foo;
public class MovieBean {
private String[] movies;
public MovieBean() {
String movies[] = new String[0];
}
public String[] getMovies() {
return movies;
}
public void setMovies(String[] m) {
this.movies = m;
}
}
Although a good design pattern would be to have the names of the bean properties match those of the HTML
input form elements, it need not always be the case, as indicated within this example. The JSP code to process
the posted form data is as follows:
<html> <body>
<%! String[] movies; %>
JDBC Questions
Q) JDBC connection
import java.sql.*;
public class JDBCSample {
public static void main(java.lang.String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver Class");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:companydb","", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM EMPLOYEES");
while(rs.next()) {
System.out.println(rs.getString("FIRST_NAME"));
}
rs.close();
stmt.close();
con.close();
}
catch (SQLException se) {
System.out.println("SQL Exception: " + se.getMessage());
}
}
}
class.forName(“oracle.jdbcdriver.oracledriver”);
connection con = driverManager.getConnection(“JDBC:oracle:thin:@hostname:portno:oracleservice”,”uid”,
“pwd”);
Q) JDBC Drivers
Q) Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
A) No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
Q) Statements in JDBC
Statement Does not take any arguments, In this statement it will check syntax error and execute it
every time.
Prepare statement P.S are precompiled statements once we compile the statements and send it to the server
for later use. P.S are partially compiled statements placed at server side with place holders. Before execution of
these statements user has to supply values for place holders, it will increase performance of application.
Callable statement C.S used to retrieve data by invoking stored procedures, stored procedure are program
units placed at data base server side for reusability. These are used by n-number of clients. Stored procedure are
precompiled in RDBMS, so they can run faster than the dynamic sql.
Callable statement will call a single stored procedure, they perform multiple queries and updates without net work
traffic.
Q) Database MetaData
You need some information about the “data base” & “dictionary” we use this .To find out tables, stored procedure
names, columns in a table, primary key of a table we use this, this is the largest interface in java.sql package
Q) Procedure
Procedure is a subprogram will perform some specific action, sub programs are name PL/SQL blocks that
can take parameters to be invoked.
Q) Trigger
Trigger is a stored PL/SQL block associated with a specific database table. Oracle executes triggers
automatically when ever a given SQL operation effects the table, we can associate 12 data base triggers with in a
given table.
Create/Replace trigger before Insert (or) Delete (or) Update on emp for each row
Begin
Insert into table-name values(:empno; :name)
end
Retrieve Image
Statement st = con.CreateStatement();
ResultSet rs = st.executeQuery(“select * from img”);
Rs.next();
InputStream is = rs.getBinaryStream(1);
FileOutPutStream fos = new FileOutPutStream(“g2.gif”);
Int ch;
While((ch=is.read(1))!=!-1)
{
fos.write(ch);
}
Q) Resultset Types
rs.beforeFirst() goto 1st record
rs.afterLast() goto last record
res.absolute(4) will got 4th record in result set.
rs.first(), rs.last()
rs.deleteRow()
rs.updateRow(), rs.updateRow(3,88) value in column 3 of resultset is set to 88.
EJB Questions
Q) SessionBeans
Session beans are not persistence there are short lived beans. S.B can perform database operations but
S.B it self is not a persistence objects. S.B are business process objects they implements business logic,
business rules and workflow.
Statefull session bean is a bean that is designed to service business process that span multiple methods
request/transaction, S.S.B can retain their state on the behalf of individual client. All S.S.B can exposes only a
single ejbCreate() method it does not take any parameters.
Stateless session bean these are single request business process is one that does not require state to be
maintained across method invocation. S.S.B cannot hold the state.
Statefull session bean do not have pooling concept
Stateless session bean instance can be pooled.
If the business process span multiple invocations there by requiring a conversational then S.S.B will be ideal
choice.
If the business last only for a single method call, S.S.B are suitable.
Q) Entity Bean
Entity beans are permanent business entities because their state is saved in permanent data storage. E.B
are persistence objects, E.B contain data related logic. E.B are permanent so if any machine crashes, the E.B can
be reconstructed in memory again by simple reading the data back in from the database.
Q) Object-Relational Mapping
Mapping of objects to relational database is a technology called O.R.M. O.R.M is a persistence
mechanism of persistence objects than simple object serialization.
Q) Deployment Descriptor
D.D contains information for all the beans in the “ejb.jar” file. D.D enables ejb container to provide implicit
services to enterprise bean components, these services can gain your bean with out coding. D.D is a XML file.
Q) ejbCreate()
In stateless session bean can have only one ejbCreate() method it must take no arguments. Remember
that ejbCreate() is essentially analogous to a constructor for ejb; it initializes an instance internal state variable.
Because the stateless session bean has no client specific variables.
- The home interface of a Stateless Session Bean must have a single create() method with no arguments,
while the session bean class must contain exactly one ejbCreate() method, also without arguments.
- Stateful Session Beans can have arguments (more than one create method)
- Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition
SessionContext S.C is your beans gateway to interact with the container, S.C query the container about your
current transactional state, your security state.
ejbCreate()
ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the
bean to some temp storage. The container should release all resources held by the bean. Just before passivating,
the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.
ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the
ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection
ejbRemove() container wants to remove your bean instance it will call this method.
Q) Entity Bean CallBack methods?
public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean
{
public abstract void ejbActivate();
public abstract void ejbLoad();
public abstract void ejbPassivate();
public abstract void ejbRemove();
public abstract void ejbStore();
public abstract void setEntityContext(EntityContext ctx);
public abstract void unsetEntityContext();
}
- Stateful session bean has 3 states Does Not Exist, Method Ready Pool and Passivated states.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- Once a container creates one are more instance of a Stateful Session bean it sets them in a Method
Ready State. In this state it can serve requests from its clients. Like Stateless beans, a new instance is
created(Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created
with the ejbCreate().
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write
the bean to some temp storage. The container should release all resources held by the bean. Just before
passivating, the container calls the ejbPassivate() method. So release all resources here,ie,close socket
connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the
ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket
connection
- A S.S.B has only two states: Does Not Exist and Method Ready Pool.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- When the EJB container needs one are more beans, it creates and set then in the Method Ready Pool
Sate. This happens through the creation of a new instance(Class.newInstance()), then it is set its context
(setSessionContext()) and finally calls the ejbCreate() method.
- The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist
State.
Life cycle of Entity bean
- Bean instance “Dose not exist” state represent entity bean instance that has not been instantiated yet.
- To create a new instance container calls the newInstance() on entity bean class.
- After step 2 E.B is in a pool of other E.Bs. At this point your E>b does not have any E.B data base data
loaded into it and it does not hold any bean specific resources (socket & database connections) .If the
container wants to reduce it’s pool size it can destroy your bean by calling unsetEntityContext() on your
bean.
- When the client wants to create some new data base data it calls a create() method on entity beans
HomeObject. The container grabs the beans instance from the pool and the instance ejbCreate() method
is called.
- E.B to be kicked back to pool, if a client call ejbremove() method.
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write
the bean to some temp storage. The container should release all resources held by the bean. Just before
passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket
connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the
ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket
connection
-
Life cycle of M.D.B
Q) EJB Resources?
<ejb-ref>
<description> text </description>
<ejb-ref-name> name </ejb-ref-name>
<ejb-ref-type> Java type </ejb-ref-type>
<home> mycom.ejb.AccountHome </home>
<remote> mycom.ejb.Account </remote>
<ejb-link> ejb.name </ejb-link>
<run-as> security role </run-as>
</ejb-ref>
Each web application should be contained in a war (web archive) file. War files are nothing but a jar file containing
atleast one descriptor called web.xml. The file structure of war file is:
/--
|
| WEB-INF
| |
| |-- WEB.XML (Deployment descriptor)
| |-- classes (Folder containing servlets and JSPs
|
| META-INF
| |
| |-- MANIFEST.MF
|
| all utility files and resources like error pages etc.
Each enterprise bean is stored in a jar file. The jar file contains all standard files like manifest and atleast one
additional file called ejb-jar.xml. The structure of a jar file is:
/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- ejb-jar.xml
|
| all classes as in a normal jar file.
Both jar and war files are placed inside a ear (enterprise archive) file. The structure of an ear file is
/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- application.xml
|
| jar and war files.
<ejb-jar>
<description>
This Deployment includes all the beans needed to make a reservation:
TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin.
</description>
<enterprise-beans>
<session>
<ejb-name>TravelAgentBean</ejb-name>
<remote>com.titan.travelagent.TravelAgent</remote>
...
</session>
<entity>
<ejb-name>CustomerBean</ejb-name>
<remote>com.titan.customer.Customer</remote>
...
</entity>
<session>
<ejb-name>ProcessPaymentBean</ejb-name>
<remote>com.titan.processpayment.ProcessPayment</remote>
...
</session>
...
</enterprise-beans>
<assembly-descriptor>
...
</assembly-descriptor>
...
</ejb-jar>
Q)
Remote Interface
Home Interface
Bean Class
Client
TRANSACTION_READ_UNCOMMITTED
The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur.
Bean methods with this isolation level can read uncommitted change.
TRANSACTION_READ_COMMITTED
The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be
read. Dirty-reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this
isolation level cannot read uncommitted data.
TRANSACTION_REPEATABLE_READ
The transaction cannot change data that is being read by a different transaction.
Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation
level have the same restrictions as Read Committed and can only execute repeatable reads.
TRANSACTION_SERIALIZABLE
The transaction has exclusive read and update privileges to data; different transactions can neither read nor write
the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the
most restrictive.
Dirty-read When your application reads data from a database that has not been committed to permanent
storage yet.
Un-repeatable read When a component reads some data from a database, but upon reading the data, the
data has been changed. This can arise when another concurrently executing transaction modifies the data being
read.
Phantom-read A phantom is a new set of data that magically appears in a database between two database
read operations.
Q) Transaction Attributes
TX_BEAN_MANAGED Then your bean programmatically controls its own transaction boundaries. When you using
programmatically transaction, you issue the begin, commit & abort statements.
TX_NOT_SUPPORTED If you set this your bean cannot be involved in a transaction at all.
TX_REQUIRED If you want your bean to always run in a transaction. If there is a transaction already running your bean
joins in on that transaction. If there is no transaction running, the container starts one for you.
TX_REQUIRES_NEW If you always want a new transaction to begin when your bean is called we should use this. If there
is a transaction already underway when your bean called, that transaction is suspended during the bean invocation. The
container then launches a new transaction and delegate the call to the bean.
TX_SUPPORTS When a client call this it runs only in a transaction if the client had one running already; it then joins that
transaction. If no transaction =, the bean runs with no transaction at all.
TX_MANDATORY Is a safe transaction attribute to use. It guarantees that your bean should run in a transaction. There is
no way your bean can be called if there is not a transaction already running.
Q) ACID Properties
When you properly use transaction your operations will execute ACID properties.
(i) Atomicity Guarantees that many operations are bundled together and appears as one contiguous unit of
work.
Ex:- When you transfer money from one bank account to another you want to add funds to one account and
remove funds from the other transaction and you want both operations to occur or neither to occur.
(ii) Consistency Guarantees that a transaction will leave the system state to be consistent after a transaction
completes.
Ex:- A bank system state could be consist if the rule “bank account balance must always be +ve”.
(iii) Isolation Protect concurrently executing transaction from seeing each other incomplete results.
Ex:- If you write a bank account data to a database, the transaction may obtain locks on the bank account record
(or) table. The lock guarantee that no other updates can interfere.
(iv) Durability Resources keep a transactional log for resources crashes, the permanent data can be
reconstructed by reapplying the steps in the log.
DOM SAX
1. Tree of nodes 1.Sequence of events
2. Occupies more memory preferred for 2.Does not use any memory preferred for large
small XML documents documents.
3. Slower at runtime 3.Faster at runtime
4. Stored as objects 4.Objects are to be created
5. Programmatically easy, since objects 5.Need to write code for creating objects are to
6. Easy of navigation referred
7. DOM creates a tree structure in memory 6.backward navigation is not possible
Q) Hot deployment
Hot Deployment in Web Logic is he act of deploying, re-deploying and un-deploying EJBs while the server is still
running.
Q) Clustering
In J2ee container can be distributed, a distributed container consist of number of JVM’s running on one
are more host machines. In this setup, application components can be deployed on a number of JVM’s. Subject to
the type of loading strategy and the type of the component the container can distributed the load of incoming
request to one of these JVM’s.
Struts Questions
Q) Diff Struts1.0 & 1.1?
A) 1.RequestProcessor class, 2.Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml, 4. Declarative exception handling, 5.Dynamic ActionForms, 6.Plug-
ins, 7.Multiple Application Modules, 8.Nested Tags, 9.The Struts Validator
Change to the ORO package, 10.Change to Commons logging, 11. Removal of Admin actions, 12.Deprecation of
the GenericDataSource
Q) ActionServlet :-
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the Jakarta Struts
Framework this class plays the role of controller. All the requests to the server goes through the controller.
Controller is responsible for handling all the requests.
Q) Action Class :-
The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action
Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and
overwrite the execute() method. In the Action Class all the database/business processing are done. It is
advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the
parameterized class to Action Form using the execute() method. The return type of the execute method is
ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the
returned ActionForward object.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
Q) Action Form :-
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains
the session state for web application and the ActionForm object is automatically populated on the server side with
data entered from a form on the client side
Q) Reset :-
This is called by the struts framework with each request, purpose of this method is to reset all of the forms
data members and allow the object to be pooled for rescue.
Q) execute :-
is called by the controller when a request is received from a client. The controller creates an instance of
the Action class if one do not already exist. The frame work will create only a single instance of each Action class.
Q) Validate :-
This method is called by the controller after the values from the request has been inserted into the
ActionForm. The ActionForm should perform any input validation that can be done and return any detected errors
to the controller.
Q) Struts-config.xml
<struts-config>
<data-sources>
<data-sources>
<set-property property=”key” value=” ” url=”” maxcount=”” mincount=”” user=”” pwd=”” >
</data-sources>
<data-sources>
<!— to identify the target of an action class when it returns results -- >
<global-forwards>
<forward name="error" path="/error.jsp"/>
</global-forwards>
<plug-in className=””/>
</struts-config>
Q) web.xml :-
Is a configuration file describe the deployment elements.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<taglib>
<taglib-uri>struts/html-el</taglib-uri>
<taglib-location>/WEB-INF/struts-html-el.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>struts/logic-el</taglib-uri>
<taglib-location>/WEB-INF/struts-logic-el.tld</taglib-location>
</taglib>
</web-app>
Service Locator
To access different resources/services, J2EE compatible server binds these resources/services to the
JNDI server so that the clients can lookup those resources/services through JNDI lookup process from anywhere
in the network. The resources/services can be
1. EJBHome objects
2. DataSource objects
3. JMS ConnectionFactory
4. JMS Topic/Queue etc.
EJB Client needs to initially get EJBHome object from JNDI to manage life cycle of EJBObjects. JMS clients need
to get ConnectionFactory and Topic/Queue from JNDI for processing messages. JDBC clients need to get
DataSource object in order to get database connection. All these services need to bind to the JNDI services and
the clients need to lookup JNDI to get those services. Clients have to go through JNDI lookup process every time
to work with these services. JNDI lookup process is expensive because clients need to get network connection to
the JNDI server if the JNDI server is located on a different machine and need to go through lookup process every
time, this is redundant and expensive.
The solution for the redundant and expensive JNDI lookup process problem is to cache those service
objects when the client performs JNDI lookup first time and reuse that service object from the cache second time
onwards for other clients. This technique maintains a cache of service objects and looks up the JNDI only first
time for a service object. This technique reduces redundant and expensive JNDI lookup process thus increasing
performance significantly. Service Locator Pattern implements this technique by having a class to cache service
objects, methods for JNDI lookup and methods for getting service objects from the cache.
The figure below shows the ServiceLocator class intercepting the client request and accessing JNDI once and
only once for a service object.
Here the clients call ServiceLocator class to get a service object rather than calling JNDI directly. ServiceLocator
acts as interceptor between client and JNDI. For source code and different flavors of implementation of this
Pattern, see the following links.
Session Facade
EJB clients (swing, servlets, jsps etc) can access entity beans directly. If EJB clients access entity beans
directly over the network, it takes more network calls and imposes network overhead.
Here the servlet calls multiple entity beans directly to accomplish a business process, thereby increasing the
number of network calls.
The solution for avoiding number of network calls due to directly accessing multiple entity beans is to
wrap entity beans with session bean (Facade). The EJB client accesses session bean (Facade) instead of entity
beans through coarse grained method call to accomplish a business process.
Message Facade
Session bean and entity bean methods execute synchronously that means the method caller has to wait
till a value is returned. In some situations like sending hundred's of mails or firing a batch process or updating
processes, the client does not have to bother about return value. If you use synchronous session and entity beans
in such situations, they take a long time to process methods and clients have to wait till the method returns a
value.
The client has to wait till all the eight synchronous steps complete. This synchronous execution takes a long time
and has an impact on performance when the method process is huge.
To avoid blocking of a client, use asynchronous message driven beans, so that client does not have to
wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but
can continue its flow of execution after sending the message.
Value Object
When a client calls a remote method there will be process of marshalling, network calls and
unmarshalling involved for the remote method invocation. If you choose fine grained approach when calling
methods remotely, there will be a significant network overhead involved. For example if you call fine grained
method like this,
remoteObject.getName();
remoteObject.getCity();
remoteObject.getState();
remoteObject.getZipCode();
Here, there are four network calls from client to the remote object because every method call is remote method
call.
The solution for avoiding many network calls due to fine grained method calls is to use coarse grained approach.
For example :
// create an Value Object and fill that object locally
PersonInfo person = new PersonInfo();
person.setName("Ravi");
person.setCity("Austin");
person.setState("TX");
person.zipCode("78749");
// send Value Object through network
remoteObject.getPersonInfo(person);
Here, there is only one network call instead of three network calls and PersonInfo object is a Value Object. The
following figure illustrates the coarse grained approach that is passing a Value Object through network.
Value Object is an object that is passed over the network rather than passing each attributes separately thus
increasing performance by reducing network calls.
ValueObjectFactory
For a single request, a client might need to access multiple server side components such as different
session beans and entity beans. In such situations the client accesses multiple components over the network,
this increases the network traffic and has an impact on the performance.
To reduce the network traffic due to accessing multiple components by a client for a single request, let
ValueObjectFactory hold different ValueObjects as place holders and respond with a single ValueObject for a
client request. Here ValueObjectFactory holds creation and delegation logic of ValueObjects for different client
requests.
Singleton
There will be only one instance for the entire JVM. You can achieve this by having the private constructor
in the class.
Singleton is probably the most widely used design pattern. Its intent is to ensure that a class has only one
instance, and to provide a global point of access to it. There are many situations in which a singleton object is
necessary: a GUI application must have a single mouse, an active modem needs one and only one telephone
line, an operating system can only have one window manager, and a PC is connected to a single keyboard
Business Delegate
The Business Delegate hides the underlying implementation details of the business service, such as
lookup & access details of the EJB architecture. The business delegates acts as a client-side business
abstraction and hides the implementation of the business services.
The delegate may cache results and references to remote business services. Caching can significantly improve
performance, because it limits unnecessary and potentially costly round trips over the network.
A Business Delegate uses a component called the Lookup Service. The Lookup Service is responsible for hiding
the underlying implementation details of the business service lookup code. The Lookup Service may be written as
part of the Delegate, but we recommend that it be implemented as a separate component, as outlined in the
Service Locator pattern
Figure shows the class diagram representing the Business Delegate pattern. The client requests the
BusinessDelegate to provide access to the underlying business service. The BusinessDelegate uses a
LookupService to locate the required BusinessService component.
Security Questions
Basic Authentication Is a security model in this the client must authenticate itself with user id and password
for each resource to access. In this the user id and password are sent by the client in base-64
encoded string, the server decode the string and looks in the data base for match. If it finds a
match grant access to the requested resource.
Digest Authentication In this the user id and password does not send across the network instead send a
digest representation of password.
Database Questions
DQL select
Q) Normalization
Normalization is the process of simplifying the relationship between data elements in a record.
Q) Normal forms
(i) 1st normal form : - 1st N.F is achieved when all repeating groups are removed, and P.K should be defined.
(ii) 2nd normal form : - Eliminate any non full dependence of data item on record keys.
(iii) 3rd normal form : - Eliminate any transitive dependence of data items on P.K’s.
Foreign key constraint prevents any actions that would destroy link between tables with the corresponding data
values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would
leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are
used to enforce referential integrity.
CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to
enforce domain integrity.
NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to
enforce domain integrity, as the check constraints.
Dropping : (Table structure + Data are deleted), Invalidates the dependent objects, Drops the indexes
Truncating : (Data alone deleted), Performs an automatic commit, Faster than delete
Delete : (Data alone deleted), Doesn’t perform automatic commit
Q) How to find out duplicate rows & delete duplicate rows in a table?
A) MPID EMPNAME EMPSSN
----- ---------- -----------
1 Jack 555-55-5555
2 Mike 555-58-5555
3 Jack 555-55-5555
4 Mike 555-58-5555
SQL> select count (empssn), empssn from employee group by empssn
having count (empssn) > 1;
Q) Oracle/PLSQL: Synonyms?
A) A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other
database objects
Syntax: -
Create [or replace] [public] synonym [schema.] synonym_name for [schema.] object_name;
or replace -- allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym
command.
Public -- means that the synonym is a public synonym and is accessible to all users.
Schema -- is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own
schema.
object_name -- is the name of the object for which you are creating the synonym. It can be one of the following:
Table Package
View materialized view
sequence java class schema object
stored procedure user-defined object
Function Synonym
example:
Create public synonym suppliers for app. suppliers;
Example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference
the table called suppliers without having to prefix the table name with the schema named app. For example:
Select * from suppliers;
If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as
follows:
Create or replace public synonym suppliers for app. suppliers;
Dropping a synonym
It is also possible to drop a synonym.
drop [public] synonym [schema .] synonym_name [force];
public -- phrase allows you to drop a public synonym. If you have specified public, then you don't specify a
schema.
Force -- phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea
to use the force phrase as it can cause invalidation of Oracle objects.
example:
Drop public synonym suppliers;
This drop statement would drop the synonym called suppliers that we defined earlier.
Inner Join: - returns all rows from both tables where there is a match
Outer Join: - outer join includes rows from tables when there are no matching values in the tables.
1st N.F -- the big table is broken into many small tables, such that each table has a primary key.
2nd N.F – Removes partial dependency. Ie The columns in a table which is not completely dependant on the
primary key are taken to a separate table
3rd N.F – Removes Transitive dependency. Ie If X is the primary key in a table. Y & Z are columns in the same
table. Suppose Z depends only on Y and Y depends on X. Then Z does not depend directly on primary key. So
remove Z from the table to a look up table.
Q) What techniques are used to retrieve data from more than one table in a single SQL statement?
A) Joins, unions and nested selects are used to retrieve data.
Q) DISTINCT clause?
A) The DISTINCT clause allows you to remove duplicates from the result set.
> SELECT DISTINCT city FROM supplier;
Q) COUNT function?
A) The COUNT function returns the number of rows in a query
> SELECT COUNT (*) as "No of emps" FROM employees WHERE salary > 25000;
Q) What keyword does an SQL SELECT statement use for a string search?
A) The LIKE keyword allows for string searches. The % sign is used as a wildcard.
Q) What is a NULL value? What are the pros and cons of using NULLS?
A) NULL value takes up one byte of storage and indicates that a value is not present as opposed to a space or
zero value. A NULL in a column means no entry has been made in that column. A data value for the column is
"unknown" or "not available."
Unique Index : -
A unique index means that two rows cannot have the same index value.
>CREATE UNIQUE INDEX index_name ON table_name (column_name)
When the UNIQUE keyword is omitted, duplicate values are allowed. If you want to index the values in a column
in descending order, you can add the reserved word DESC after the column name:
>CREATE INDEX PersonIndex ON Person (LastName DESC)
If you want to index more than one column you can list the column names within the parentheses.
>CREATE INDEX PersonIndex ON Person (LastName, FirstName)
IN The comparison operator is the equality and the logical operation between values is OR.
ANY Allows to check if at least a value of the list satisfies condition.
ALL Allows to check if condition is realized for all the values of the list.
EXISTS If the subquery returns a result, the value returned is True otherwise the value returned is False.