final java faqs

147
Java Technoloies Java Technoloies Nazar Babu Nazar Babu 1

Upload: harikrishnam2008gmailcom

Post on 16-Apr-2015

55 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Final Java Faqs

Java TechnoloiesJava Technoloies

Nazar BabuNazar Babu 1

Page 2: Final Java Faqs

Java TechnoloiesJava Technoloies

Nazar BabuNazar Babu 2

Page 3: Final Java Faqs

Java TechnoloiesJava Technoloies

CONTENTS

Core Java 4

Exception Handling 20

Multi Threading 23

Collection Framework 26

JDBC Concept 33

All Packages 41

Servlets 47

JSP 68

Struts 80

Hibernate FAQs 89

EJB Concept 116

Design Patterns Concept 133

Database Concept 141

Security Concept 149

Nazar BabuNazar Babu 3

Page 4: Final Java Faqs

Java TechnoloiesJava Technoloies

CORE JAVACORE JAVA

Q) What is difference between Java and C++?A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in Java. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions that result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore, Java does not have global variables or global functions. (v) Java does not support multiple inheritance.Java does not support destructors, but rather, add the finalize() function. (vi) Java does not have the delete operator. (vii) The << and >> are not overloaded for I/O operations

Q) Opps concepts

PolymorphismAbility to take more than one form, in java we achieve this using Method Overloading (compile time polymorphism), Method overriding (runtime polymorphism)

InheritanceIs the process by which one object acquires the properties of another object. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

EncapsulationWrapping of data and function into a single unit called encapsulation. Ex:- all java programs.(Or)Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

AbstractionNothing but representing the essential futures without including background details.

DynamicbindingCode 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) class & object? class class is a blue print of an object Object instance of class.

Q) Object creation? Object is constructed either on a memory heap or on a stack.

Memory heapgenerally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory allocated to the object is eligible to be back on the heap.

Nazar BabuNazar Babu 4

Page 5: Final Java Faqs

Java TechnoloiesJava Technoloies

Stack During method calls, objects are created for method arguments and method variables. These objects are created on stack.

Q) System.out.println() println() is a methd of java.io.printWriter. “out” is an instance variable of java.lang.System class.

Q) Transient & volatileTransient --> The transient modifier applies to variables only, the object are variable will not persist. Transient variables are not serialized.

Volatile --> value will be changed unexpectedly by the other part of the program, "it tells the compiler a variable may change asynchronously due to threads"

Q) Access Specifiers & Access modifiers?Access Specifiers A.S gives access privileges to outside of application (or) others, they are Public, Protected, Private, Defaults.Access Modifiers A.M which gives additional meaning to data, methods and classes, final cannot be modified at any point of time.

Private Public Protected No modifier

Same class No Yes Yes YesSame package Subclass No Yes Yes YesSame package non-subclass No Yes Yes YesDifferent package subclass No Yes Yes NoDifferent package non-subclass

No Yes No No

Q) Default Values

long -2^63 to 2^63 –1 0L

double 0.0d

Int -2^31 to 2^31 –1 0

float 0.0f

Short -2^15 to 2^15 –1 0

Boolean false

Byte -2^7 to 2^7 –1 0

char 0 to 2^7 –1 null character (or) ‘\u 0000’

Q) Byte code & JIT compiler & JVM & JRE & JDK Byte code is a highly optimized set of instructions. JVM is an interpreter for byte code. Translating a java program into byte code helps makes it much easier to run a program in a wide variety of environment.

JVM is an interpreter for byte code JIT (Just In Time) is a part of JVM, it compiles byte code into executable code in real time, will increase the performance of the interpretations. JRE is an implementation of the Java Virtual Machine, which actually executes Java programs.

Nazar BabuNazar Babu 5

Page 6: Final Java Faqs

Java TechnoloiesJava Technoloies

JDK is bundle of software that you can use to develop Java based software, Tools provided by JDK is(i) javac – compiler (ii) java – interpretor(iii) jdb – debugger (iv) javap - Disassembles(v) appletviewer – Applets (vi) javadoc - documentation generator (vii) javah - 'C' header file generator

Q) Wrapper classesPrimitive data types can be converted into objects by using wrapper classes. These are java.lang.package.

Q) Does Java pass method arguments by value or by reference?

Java passes all arguments by value, not by reference

Q) Arguments & ParametersWhile defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Q) Public static void main (String [] args) We can overLoad the main() method. What if the main method is declared as “Private”? The program compiles properly but at runtime it will give "Main method not public." Message 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”. Protected static void main(), static void main(), private static void main() are also valid. If I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError". If no arguments on the command line, String array of Main method will be empty or null? It is empty. But not null. Variables can have the same name as a method or a class

Q) Can an application have multiple classes having main() method?A) Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q) Can I have multiple main methods in the same class?A) No the program fails to compile. The compiler says that the main method is already defined in the class.

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

Nazar BabuNazar Babu 6

Page 7: Final Java Faqs

Java TechnoloiesJava Technoloies

Constructor can use the access modifiers public, protected, private or have no access modifier 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

Q) Diff Constructor & Method

Constructor MethodUse to instance of a class Grouping java statementNo return type Void (or) valid return typeSame name as class name As a name except the class

method name, begin with lower case.

“This” refer to another constructor in the same class

Refers to instance of class

“Super” to invoke the super class constructor

Execute an overridden method in the super class

“Inheritance” cannot be inherited Can be inheritedWe can “overload” but we cannot “overridden”

Can be inherited

Will automatically invoke when an object is created

Method has called explicitly

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

Nazar BabuNazar Babu 7

Page 8: Final Java Faqs

Java TechnoloiesJava Technoloies

variable when no more in use, 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. Garbage collection is a low-priority thread.

G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do garbage collection if it is running short of memory. The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.

Q) How an object becomes eligible for Garbage Collection?A) An object is eligible for garbage collection when no object refers to it, An object also becomes eligible when its reference is set to null. The objects referred by method variables or local variables are eligible for garbage collection when they go out of scope.

Integer i = new Integer(7);i = null;

Q) Final, Finally, FinalizeFinal: - 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. Final class cannot have static methods Final class cannot have abstract methods (Because of final class never allows any class to inherit it) Final class can have a final method.

Finally: - Finally create a block of code that will be executed after try catch block has completed. Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.

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.

Q) Can we declare abstract method in final class?A) It indicates an error to declare abstract method in final class. Because of final class never allows any class to inherit it.

Q) Can we declare final method in abstract class?A) If a method is defined as final then we can’t provide the reimplementation for that final method in its derived classes i.e. overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract too, then there is no used to declare like that.

Nazar BabuNazar Babu 8

Page 9: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Superclass & SubclassA super class is a class that is inherited whereas subclass is a class that does

the inheriting

Q) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in java?

A) Polymorphism – overloading and overriding Multiple inheritances – interfaces. Multilevel inheritance – extending class.

Q) Overloading & Overriding?

Overloading (Compile time polymorphism) Define two or more methods within the same class (or) subclass that share

the same name and their number of parameter, order of parameter & return type are different then the methods are said to be overloaded. • Overloaded methods do not have any restrictions on what return type of Method (Return type are different) (or) exceptions can be thrown. That is something to worry about with overriding. • Overloading is used while implementing several methods that implement similar behavior but for different data types.

Overriding (Runtime polymorphism)When a method in a subclass has the same name, return type &

parameters as the method in the super class then the method in the subclass is override the method in the super class.

The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method.

• If the superclass 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 its subclasses.

Only member method can be overriden, not member variable

class Parent{ int i = 0; void amethod(){

System.out.println("in Parent"); } }

class Child extends Parent{ int i = 10; void amethod(){

Nazar BabuNazar Babu 9

Page 10: Final Java Faqs

Java TechnoloiesJava Technoloies

System.out.println("in Child"); } } class Test{ public static void main(String[] args){ Parent p = new Child(); Child c = new Child(); System.out.print("i="+p.i+" "); p.amethod (); System.out.print("i="+c.i+" "); c.amethod(); } }

o/p: - i=0 in Child i=10 in Child

Q) Final variableOnce to declare a variable as final it cannot occupy memory per instance

basis.

Q) Static blockStatic 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.

Q) Static variable & Static methodStatic variables & 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. It may not access the instance variables of that class, only its static variables. Further it may not invoke instance (non-static) methods of that class unless it provides them with some object.

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” are “super” in any way.

Q) Class variable & Instance variable & Instance methods & class methodsInstance 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.

Nazar BabuNazar Babu 10

Page 11: Final Java Faqs

Java TechnoloiesJava Technoloies

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 class methods to allow us to call a method without creating 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 methods cannot access instance variables why? Static methods can be invoked before the object is created; Instance

variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables. Instance variables are called called as non-static variables.

Q) String & StringBufferString is a fixed length of sequence of characters, String is immutable.

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

Int to String Conversion :- String arg = String.valueOf(10);

Q) Super()Super() always calling the constructor of immediate super class, super() must

always be the first statements executed inside a subclass constructor.

Q) What are different types of inner classes?

A) Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

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

Nazar BabuNazar Babu 11

Page 12: Final Java Faqs

Java TechnoloiesJava Technoloies

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.

Inner class inside method cannot have static members or blocks

Q) Which circumstances you use Abstract Class & Interface?--> If you need to change your design make it an interface.--> Abstract class provide some default behaviour, A.C are excellent candidates inside of application framework. A.C allow single inheritance model, which should be very faster.

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.

Compile time error occur if an attempt to create an instance of an Abstract class.

You cannot declare “abstract constructor” and “abstract static method”.

An “abstract method” also declared private, native, final, synchronized,

strictfp, protected.

Abstract class can have static, final method (but there is no use).

Abstract class have visibility public, private, protected.

By default the methods & variables will take the access modifiers is <default>,

which is accessibility as package.

An abstract method declared in a non-abstract class.

An abstract class can have instance methods that implement a default behavior.

A class can be declared abstract even if it does not actually have any abstract

methods. Declaring such a class abstract indicates that the implementation is

somehow incomplete and is meant to serve as a super class for one or more

subclasses that will complete the implementation.

A class with an abstract method. Again note that the class itself is declared

abstract, otherwise a compile time error would have occurred.

Nazar BabuNazar Babu 12

Page 13: Final Java Faqs

Java TechnoloiesJava Technoloies

Abstract class A{Public abstract callme();Void callmetoo(){}

}

class B extends A(void callme(){}

}

class AbstractDemo{public static void main(string args[]){

B b = new B();b.callme();b.callmetoo();

}}

Q) When we use Abstract class?A) Let us take the behaviour of animals, animals are capable of doing different things like flying, digging, Walking. But these are some common operations performed by all animals, but in a different way as well. When an operation is performed in a different way it is a good candidate for an abstract method.

Public Abstarctclass Animal{ Public void eat(food food) { } public void sleep(int hours) { } public abstract void makeNoise() {}

public Dog extends Animal { public void makeNoise() { System.out.println(“Bark! Bark”); }}public Cow extends Animal { public void makeNoise() { System.out.println(“moo! moo”); }}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;

Nazar BabuNazar Babu 13

Page 14: Final Java Faqs

Java TechnoloiesJava Technoloies

Interfaces are useful for?

a) eclaring methods that one or more classes are expected to implementb) Capturing similarities between unrelated classes without forcing a class relationship.c) Determining an object's programming interface without revealing the actual body of the class.

Why Interfaces?

“ one interface multiple methods “ signifies the polymorphism concept.

Interface has visibility public. Interface can be extended & implemented. An interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces. All methods of an interface are implicitly Abstract, Public, even if the public modifier is omitted. An interface methods cannot be declared protected, private, strictfp, native or synchronized. All Variables are implicitly final, public, static fields. A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces. An Interface can only declare constants and instance methods, but cannot implement default behavior. top-level interfaces may only be declared public, inner interfaces may be declared private and protected but only if they are defined in a class.

A class can only extend one other class. A class may implements more than one interface. Interface can extend more than one interface.

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

}}

Nazar BabuNazar Babu 14

Page 15: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Diff Interface & Abstract Class? A.C may have some executable methods and methods left unimplemented. Interface contains no implementation code. An A.C can have nonabstract methods. All methods of an Interface are abstract. An A.C can have instance variables. An Interface cannot. An A.C must have subclasses whereas interface can't have subclasses An A.C can define constructor. An Interface cannot. An A.C can have any visibility: public, private, protected. An Interface visibility must be public (or) none. An A.C can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q) What is the difference between Interface and class? A class has instance variable and an Interface has no instance variables. Objects can be created for classes where as objects cannot be created for interfaces. All methods defined inside class are concrete. Methods declared inside interface are without any body.

Q) What is the difference between Abstract class and Class?

Classes are fully defined. Abstract classes are not fully defined (incomplete class) Objects can be created for classes, there can be no objects of an abstract class.

Q) What are some alternatives to inheritance? A) Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Q) Serializable & ExternalizableSerializable --> is an interface that extends serializable interface and sends

data into streams in compressed format. It has 2 methods writeExternal(objectOutput out), readExternal(objectInput in).

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) Internalisation & LocalizationInternalisation -- Making a programme to flexible to run in any locale called

internalisation.Localization -- Making a programme to flexible to run in a specific locale

called Localization.

Nazar BabuNazar Babu 15

Page 16: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) SerializationSerialization is the process of writing the state of the object to a byte stream,

this is useful when ever you want to save the state of your programme to a persistence storage area.

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.

(i) Ex: - Synchronizing a function:public synchronized void Method1 () {}

(i) Ex: - Synchronizing a block of code inside a function:public myFunction (){ synchronized (this) { }}

(iii) Ex: - public Synchronized void main(String args[]) But this is not the right approach because it means servlet can handle one request at a time.

(iv) Ex: - public Synchronized void service() Servlet handle one request at a time in a serialized manner

Q) Different level of locking using Synchronization?A) Class level, Object level, Method level, Block level

Q) MonitorA monitor is a mutex, once a thread enter a monitor, all other threads must

wait until that thread exist the monitor.

Q) Diff = = and .equals()?

A) == Compare object references whether they refer to the sane instance are not. equals () method compare the characters in the string object.

StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String s1 = "Amit"; String s2 = "Amit"; String s3 = new String("abcd"); String s4 = new String("abcd"); String ss1 = "Amit";

Nazar BabuNazar Babu 16

Page 17: Final Java Faqs

Java TechnoloiesJava Technoloies

(sb1==sb2); F (s1.equals(s2)); T(sb1.equals(sb2)); F ((s1==s2)); T(sb1.equals(ss1)); F (s3.equals(s4)); T

((s3==s4)); F

String s1 = "abc"; String s2 = new String("abc"); s1 == s2 F s1.equals(s2)) T Q) Marker Interfaces (or) Tagged Interfaces :-

An Interface with no methods. Is called marker Interfaces, eg. Serializable, SingleThread Model, Cloneable.

Q) URL Encoding & URL Decoding URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and URL Decoding is the reverse process converting all Hex Characters back their normal form.

Q) URL & URLConnection

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)

URLConnection can establish communication between two programs in the network.URL hp = new URL(“www.yahoo.com”);URLConnection con = hp.openConnection();

Q) Runtime classRuntime 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) Execute other programsYou can use java to execute other heavy weight process on your multi tasking

operating system, several form of exec() method allow you to name the programme you want to run.

Runtime r = Runtime.getRuntime();Process p = null;Try{

p = r.exce(“notepad”);p.waiFor()

}

Nazar BabuNazar Babu 17

Page 18: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) System classSystem 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) Native MethodsNative 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 InterfaceAny 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 InterfaceClasses 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) ClassClass encapsulate the run-time state of an object or interface. Methods in this

class are

static Class forName(String name) throws ClassNotFoundException

getClass()

getClassLoader() getConstructor()getField() getDeclaredFields()getMethods() getDeclearedMethods()getInterface() getSuperClass()

Q) java.lang.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) InstanceOfInstanceof means by which your program can obtain run time type

information about an object.Ex:- A a = new A(); a.instanceOf A;

Q) Java pass arguments by value are by reference?A) By value

Nazar BabuNazar Babu 18

Page 19: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Java lack pointers how do I implements classic pointer structures like linked list?A) Using object reference.

Q) java. ExeMicro 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) Bin & Lib in jdk?Bin contains all tools such as javac, appletviewer and awt tool.Lib contains API and all packages.

Nazar BabuNazar Babu 19

Page 20: Final Java Faqs

Java TechnoloiesJava Technoloies

ExceptionException Handling Handling

Object

Throwable

Error Exception

AWT Error Virtual Machine Error

Compile time.Ex Runtime Exception

(checked) (Unchecked)

OutOfMemory.E StackOverFlow.E EOF.E FilenotFound.E Arithmetic.E

NullPointer.E Indexoutof

Bound.E

ArrayIndexoutOfBound.E StirngIndexoutOfBound

Q) Diff Exception & Error Exception and Error both are subclasses of the Throwable class. ExceptionException is 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 handle these.

Q) Can an exception be rethrown?A) Yes, an exception can be rethrown.

Q) try, catch, throw, throwstry 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. Throw is used to throw an exception explicitly.Throws A Throws clause list the type of exceptions that a methods might through.

Q) What happens if an exception is not caught?A) An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

Nazar BabuNazar Babu 20

Page 21: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

Q) Checked & UnChecked Exception :-Checked exception is some subclass of Exception. Making an exception

checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·

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.

Checked Exceptions Un checked exceptionClassNotFoundException ArithmeticExceptionNoSuchMethodException ArrayIndexOutOfBoundExceptionNoSuchFieldException ClasscastExceptionInterruptedException IllegalArgumentException IllegalAccessException IllegalMonitorSateExceptionCloneNotSupportedException IllegalThreadStateException

IndexOutOfBoundExceptionNullPointerExceptionNumberFormatExceptionStringIndexOutOfBounds

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.

Nazar BabuNazar Babu 21

Page 22: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Methods in Exceptions?A) getMessage(), toString(), printStackTrace(), getLocalizedMessage(),

Q) What is exception chaining?A) An exception chain is a list of all the exceptions generated in response to a single root exception. As each exception is caught and converted to a higher-level exception for rethrowing, it's added to the chain. This provides a complete record of how an exception is handled The chained exception API was introduced in 1.4. Two methods and two constructors were added to Throwable.Throwable getCause()Throwable initCause(Throwable)Throwable(String, Throwable)Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause returns the current exception.

Q) Primitive multi tasking If the threads of different priorities shifting the control depend on the priority i.e.; a thread with higher priority is executed first than the thread with lower priority. This process of shifting control is known as primitive multi tasking.

Q) Http Status CodesTo inform the client of a problem at the server end, you call the “sendError”

method. This causes the server to respond with status line, with protocol version and a success or error code.The first digit of the status code defines the class of response, while the last two digits do not have categories Numbe

rType Description

1xx Informational Requested received, continuing to process2xx Success The action was successfully received, understood, and

accepted3xx Redirection Further action must be taken in order to complete the

request4xx Client Error The request contains bad syntax or cannot be fulfilled5xx Server Error The server failed to fulfil valid request

Nazar BabuNazar Babu 22

Page 23: Final Java Faqs

Java TechnoloiesJava Technoloies

Multi Multi Threading Threading

Q) What threads will start when you start the java program?A) Finalizer, Main, Reference Handler, Signal dispatcher.

Q) ThreadThread is a smallest unit of dispatchable code.

Q) Diff process and threads? A) Thread is a smallest unit of dispatchable code, Process is a sub program will perform some specific actions. (I) Process is a heavy weight task and is more cost. (ii) Thread is a lightweight task, which is of low cost. (iii) A Program can contain more than one thread. (v) A program under execution is called as process.

Q) Sleep(), wait(), notify(), notifyAll(), stop(), suspend(), resume()

sleep sleep for a thread until some specific amount of time.wait wait for a thread until some specific condition occurs (Or) Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().notify( ) wakes up the first thread that called wait() on the same object.notifyAll( ) wakes up all the threads that called wait() on the same object, the highest priority thread will run first.stop( ) The thread move to dead state.suspend( ) & resume( ) To pass and restart the execution of a thread. In case of suspend, thread will be suspended by calling the lock on the object. Resume will restart from where it is suspended. join( ) wait for a thread to terminate.

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 ThreadingMultithreading is the mechanism in which more than one thread run

independent of each other within the process.

Q) Daemon ThreadDaemon thread is one which serves another thread, it has no other role

normally a daemon thread carry some background program. When daemon thread remains the program exist.

Q) Thread Priority

Nazar BabuNazar Babu 23

Page 24: Final Java Faqs

Java TechnoloiesJava Technoloies

MIN_PRIORITY = 1NORM_PRIORITY = 5MAX_PRIORITY = 10

Q) Can I restart a stopped thread?A) Once a thread is stopped, it cannot be restarted. Keep in mind though that the use of the stop() method of Thread is deprecated and should be avoided.

Q) Thread Priorities

Class A implements Runnable{Thread t;Public clicker(int p){

T = new Thread(this)t.setPriority(p);

}public void run(){}public void stop(){}public void start(){t.start();}try{

thread.sleep(1000); }lo.stop();hi.stop();try{

hi.t.join();lo.t.join();

}class HiLo{public static void main(Stirng args[]){Thread.currentThread().setPriority(Thread.MAX_PRIORITY);Clicker hi = new Clicker(Thread.NORM_PRIORITY+2);Clicker lo = new Clicker(Thread.NORM_PRIORITY-2);Lo.start();Hi.start();

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

Nazar BabuNazar Babu 24

Page 25: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Which attribute are thread safe?

ObjectiveMulti Threaded Model

Single threaded Model

Local variables Y YInstance variables N YClass variables N NRequest attributes Y YSession attributes N NContext attributes N N

Nazar BabuNazar Babu 25

Page 26: Final Java Faqs

Java TechnoloiesJava Technoloies

Collections Collections Frame Work Frame Work

Q)Collection classes

Collection Interfaces

Legacy classes

Legacy interface

Abstract collection Collection Dictionary EnumeratorAbstract List List Hash TableAbstract Set Set StackArray List Sorted Set VectorLinked List Map PropertiesHash set IteratorTree SetHash MapTree MapAbstract Sequential List

Collection Classes

Abstract collection Implements most of the collection interfaces.

Abstract List Extends Abstract collection & Implements List Interface. A.L allow “random access”.

Methods>> void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), Iterator iterator().

Abstract Set Extends Abstract collection & Implements Set interface.

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. It will allow duplicate elements. Searching is very faster.A.L internal node traversal from the start to the end of the collection is significantly faster than Linked List traversal. A.L is a replacement for Vector.

Methods>>void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexOf(Object element), int latIndexOf(Object element), int size(), Object [] toArray().

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. When ever there is a lot of insertion & deletion we have to go for L.L. L.L is accessed via a reference to the

Nazar BabuNazar Babu 26

Page 27: Final Java Faqs

Java TechnoloiesJava Technoloies

first node of the list. Each subsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via the link-reference number stored in the previous node.

Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexOf(Object element), int latIndexOf(Object element), int size(), Object [] toArray().

Hash Set 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. It will not allow duplicate elements

Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int size().

Tree Set Extends Abstract Set & Implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast. It will not allow duplicate elements

Methods>> boolean add(Object o), boolean addAll(Collection c), Object first(), Object last(), Iterator iterator(), boolean remove(Object o).

Hash Map Extends Abstract Map and implements Map interface. H.M does not guarantee the order of elements, so the order in which the elements are added to a H.M is not necessary the order in which they are ready by the iterate. H.M permits only one null values in it while H.T does not

HashMap is similar to Hashtable.

Tree Map implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allow rapid retrieval.

Abstract Sequential List Extends Abstract collection; use sequential access

of its elements.

Collection Interfaces

Collection Collection is a group of objects, collection does not allow duplicate elements.

Methods >> boolean add(Object obj), boolean addAll(c), int Size(), Object[] toArray(), Boolean isEmpty(), Object [] toArray(), void clear().Collection c), Iterator iterator(), boolean remove(Object obj), boolean removeAll(CollectionExceptions >> UnSupportedPointerException, ClassCastException.

List List will extend Collection Interface, list stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index, (it can access objects by index).

Nazar BabuNazar Babu 27

Page 28: Final Java Faqs

Java TechnoloiesJava Technoloies

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), Object removeAll(Collection c), Object set(int index, Object obj).

Set Set will extend Collection Interface, Set cannot contain duplicate elements. Set stored elements in an unordered way. (it can access objects by value).

Sorted Set Extends Set to handle sorted sets, Sorted Set elements will be in ascending order.

Methods >> Object last(), Object first(), compactor compactor(). Exceptions >> NullPointerException, ClassCastException, NoSuchElementException.

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.

Methods >> Object get(Object k), Object put(Object k, Object v), int size(), remove(Object object), boolean isEmpty()

Iterator Iterator makes it easier to traverse through the elements of a collection. It also has an extra feature not present in the older Enumeration interface - the ability to remove elements. This makes it easy to perform a search through a collection, and strip out unwanted entries.

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.

Methods >> boolean hasNext(), object next(),void remove()

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.

Nazar BabuNazar Babu 28

Page 29: Final Java Faqs

Java TechnoloiesJava Technoloies

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. H.T store the data in sequential order.

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.

Methods>> hasMoreElements(),Object nextElement().

Q) Which is the preferred collection class to use for storing database result sets?

A) LinkedList is the best one, benefits include: 1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created. 4. Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

ResultSet result = stmt.executeQuery("...");List list = new LinkedList();while(result.next()) {

list.add(result.getString("col")); }

If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

Q) Efficiency of HashTable - If hash table is so fast, why don't we use it for everything? A) One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a

Nazar BabuNazar Babu 29

Page 30: Final Java Faqs

Java TechnoloiesJava Technoloies

certain application, the time and space cost is even higher than other data structures (array, linked list, or tree).

Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.

If many entries are to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

Q) How does a Hashtable internally maintain the key-value pairs?A) The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

Q) ArrayArray 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) Diff Iterator & Enumeration & List IteratorIterator is not synchronized and enumeration is synchronized. Both are

interface, Iterator is collection interface that extends from ‘List’ interface. Enumeration is a legacy interface, Enumeration having 2 methods ‘Boolean hasMoreElements()’ & ‘Object NextElement()’. Iterator having 3 methods ‘boolean hasNext()’, ‘object next()’, ‘void remove()’. Iterator also has an extra feature not present in the older Enumeration interface - the ability to remove elements there is one method “void remove()”.

List IteratorIt is an interface, List Iterator extends Iterator to allow bi-directional traversal

of a list and modification of the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.

Q) Diff HashTable & HashMap Both provide key/value to access the data. The H.T is one of the collection original collection classes in java. H.P is part of new collection framework. H.T is synchronized and H.M is not. H.M permits null values in it while H.T does not. Iterator in the H.P is fail-safe while the enumerator for the H.T is not.

Q) Converting from a Collection to an array - and back again?The collection interface define the toArray() method, which returns an array of objects. If you want to convert back to a collection implementation, you could manually traverse each element of the array and add it using the add(Object) method.

// Convert from a collection to an arrayObject[] array = c.toArray();

Nazar BabuNazar Babu 30

Page 31: Final Java Faqs

Java TechnoloiesJava Technoloies

// Convert back to a collectionCollection c2 = new HashSet();for(int i = 0; i < array.length; i++) { c2.add(array[i]); }

Q) How do I look through each element of a HashMap?A) <select id="swf" name="swf" onChange="showStandardWF()" style="width:175px;">

<option value="">&lt;Select Standard WorkFlow&gt;</option><%

hmap =(HashMap)request.getAttribute("stdwf");if( hmap.size() != 0){

int len = hmap.size();Set set = hmap.keySet();Iterator it = set.iterator();while(it.hasNext()){

Integer key = (Integer)it.next();%>

<option value="<%=key%>"><%=(String)hmap.get(key)%></option>

<%}}

%></select>

Q) Retrieving data from a collection?public class IteratorDemo { public static void main(String args[]) { Collection c = new ArrayList();

// Add every parameter to our array list for (int indx = 0; indx < args.length; indx++) { c.add(args[indx]); }

// Examine only those parameters that start with - Iterator i = c.iterator();

// PRE : Collection has all parameters while (i.hasNext()) { String param = (String) i.next();

// Use the remove method of iterator if (! param.startsWith("-") ) i.remove();

Nazar BabuNazar Babu 31

Page 32: Final Java Faqs

Java TechnoloiesJava Technoloies

} // POST: Collection only has parameters that start with -

// Demonstrate by dumping collection contents Iterator i2 = c.iterator(); while (i2.hasNext()) { System.out.println ("Param : " + i2.next()); } }}

Q) How do I sort an array?A) Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly:Arrays.sort(theArray);If, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.Arrays.sort(theArray, theComparator);

Nazar BabuNazar Babu 32

Page 33: Final Java Faqs

Java TechnoloiesJava Technoloies

J D B C J D B C

Q) What Class.forName will do while loading drivers?A) Will create an instance of the driver and register with the DriverManager.

Q) JDBC 3.0 new features?A) 1. Transaction Savepoint support: - Added the Savepoint interface, which

contains new methods to set, release, or roll back a transaction to designated

savepoints.

2. Reuse of prepared statements by connection pools: - to control how prepared

statements are pooled and reused by connections.

3. Connection pool configuration :- Defined a number of properties for the

ConnectionPoolDataSource interface.

These properties can be used to describe how PooledConnection objects created by

DataSource objects should be pooled.

4. Retrieval of parameter metadata: - Added the interface ParameterMetaData,

which describes the number, type

and properties of parameters to prepared statements.

5. Retrieval of auto-generated keys: - Added a means of retrieving values from

columns containing automatically

generated values.

6. Multiple open ResultSet objects: - Added the new method getMoreResults(int).

7. Passing parameters to CallableStatement objects by name: - Added methods to

allow a string to identify the parameter to be set for a CallableStatement object.

8. Holdable cursor support: - Added the ability to specify the of holdability of a

ResultSet object.

9. BOOLEAN data type: - Added the data type java.sql.Types.BOOLEAN. BOOLEAN is

logically equivalent to BIT.

10. Making internal updates to the data in Blob and Clob objects: - Added methods

to allow the data contained in Blob and Clob objects to be altered.

11. Retrieving and updating the object referenced by a Ref object: - Added methods

to retrieve the object referenced by a Ref object. Also added the ability to update a

referenced object through the Ref object.

12. Updating of columns containing BLOB, CLOB, ARRAY and REF types: - Added of

the updateBlob, updateClob, updateArray, and updateRef methods to the ResultSet

interface.

Nazar BabuNazar Babu 33

Page 34: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) JDBC Drivers

o JDBC-ODBC Bridge Driver o Native API - Partly Java Driver o Network protocol - All Java Driver o Native Protocol - Pure Java Driver

Tier Driver mechanism Description

Two JDBC-ODBC

JDBC access via most ODBC drivers, some ODBC binary code and client code must be loaded on each client machine. This driver is commonly used for prototyping. The JDBC-ODBC Bridge is JDBC driver which implements JDBC operations by translating them to ODBC operations.

TwoNative API - Partly Java driver

This driver converts JDBC calls to database specific native calls. Client requires database specific libraries.

ThreeNetwork protocol - All Java Driver

This driver converts JDBC calls into DBMS independent network protocol that is sent to the middleware server. This will translate this DBMS independent network protocol into DBMS specific protocol, which is sent to a particular database. The results are again rooted back to middleware server and sent back to client.

Two Native protocol - All - Java driver

They are pure java driver, they communicate directly with the vendor database.

Q) JDBC connectionimport 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(); }

Nazar BabuNazar Babu 34

Page 35: Final Java Faqs

Java TechnoloiesJava Technoloies

catch (SQLException se) { System.out.println("SQL Exception: " + se.getMessage()); } } }

Q) 4 th type driver class.forName(“oracle.jdbcdriver.oracledriver”);connection con = driverManager.getConnection(“JDBC:oracle:thin:@hostname:portno:oracleservice”,”uid”, “pwd”);

Q) Steps to connect to JDBC?A) 1. First thing is using jdbc you have to establish a connection to the data base this is 2 steps process (i) you must load the jdbc driver (ii) then make a connection, to do this we can call the getConnection() method of driver manager class.2. To execute any sql commands using jdbc connection you must first create a statement object to create this call statement st = con.createSteatement().This is done by calling the createStatement() method in connection interface. Once the statement is created you can executed it by calling execute() method of the statement interface.

Q) Resultset Types rs.beforeFirst() goto 1st record rs.afterLast() goto last record isFirst() / isLast() res.absolute(4) will got 4th record in result set. rs.deleteRow() rs.updateRow(3,88) value in column 3 of resultset is set to 88. rs.updateFloat() rs.relative(2)

Q) Transactional Savepoints Statement stmt = conn.createStatement (); Int rowcount = stmt.executeUpdate ("insert into etable (event) values ('TMM')"); Int rowcount = stmt.executeUpdate ("insert into costs (cost) values (45.0)"); Savepoint sv1 = conn.setSavePoint ("svpoint1"); // create save point for inserts Int rowcount = stmt.executeUpdate ("delete from employees"); Conn.rollback (sv1); // discard the delete statement but keep the inserts Conn.commit; // inserts are now permanent

Q) Updating BLOB & CLOB Data Types

rs.next(); Blob data = rs.getClob (1); Rs.close(); // now let's insert this history into another table stmt.setClob (1, data); // data is the Clob object we retrieved from the history table int InsertCount = stmt.executeUpdate("insert into EscalatedIncidents (IncidentID, CaseHistory, Owner)"

+ " Values (71164, ?, 'Goodson') ");

Nazar BabuNazar Babu 35

Page 36: Final Java Faqs

Java TechnoloiesJava Technoloies

Q Retreiving / Storing / Updating Array of Objects Array a = rs.getArray(1); Pstmt.setArray(2, member_array); Rs.updateArray(“last_num”,num);

Q) How to execute no of queries at one go?A) By using a batchUpdate's (i.e. throw addBatch() and executeBatch()) in java.sql.Statement interface or by using procedures.

Q) Batch Updates CallableStatement stmt = con.prepareCall(“{call employeeInfo (?)}”);stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");// submit a batch of update commands for executionint[] updateCounts = stmt.executeBatch();

Q) Multiple ResultsetA) The methods getMoreResults, getUpdateCount, and getResultSet can be used to retrieve all the results.CallableStatement cstmt = connection.prepareCall(procCall);boolean retval = cstmt.execute();if (retval == false) {} else { ResultSet rs1 = cstmt.getResultSet();

retval = cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT); if (retval == true) { ResultSet rs2 = cstmt.getResultSet(); rs2.next(); rs1.next(); }}

CLOSE_ALL_RESULTS All previously opened ResultSet objects should be closed when calling getMoreResults().

CLOSE_CURRENT_RESULT The current ResultSet object should be closed when calling getMoreResults().

KEEP_CURRENT_RESULT The current ResultSet object should not be closed when calling getMoreResults().

Q) Diff execute() ,executeUpdate() and executeQuery() ? A) execute() returns a boolean value, which may return multiple results. executeUpdate() is used for nonfetching queries, which returns int value and tell how many rows will be affected. executeQuery() is used for fetching queries, which returns single ResulSet object and never return Null value. Q) How to move the cursor in scrollable resultset? Type of a ResultSet object:- TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE,

CONCUR_READ_ONLY and CONCUR_UPDATABLE.

Nazar BabuNazar Babu 36

Page 37: Final Java Faqs

Java TechnoloiesJava Technoloies

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM TABLE_NAME"); rs.afterLast(); while (srs.previous()) { String name = rs.getString("COLUMN_1"); float salary = rs.getFloat("COLUMN_2"); rs.absolute(4); // cursor is on the fourth row int rowNum = rs.getRow(); // rowNum should be 4 rs.relative(-3); int rowNum = rs.getRow(); // rowNum should be 1 rs.relative(2); int rowNum = rs.getRow(); // rowNum should be 3 //... }

Q) How to “Update” & “Delete” a resultset programmatically? Update: - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM TABLE_NAME"); uprs.last(); uprs.updateFloat("COLUMN_2", 25.55);//update last row's data uprs.updateRow();//don't miss this method, otherwise, the data will be lost. Delete: - uprs.absolute(5); uprs.deleteRow(); // will delete row 5.

Q) JDBC connection pool When you are going to caret a pool of connection to the database. This will give access to a collection of already opened data base connections, which will reduce the time it takes to service the request and you can service “n” number of request at once.

Q) Why you need JDBC if ODBC is available?A) ODBC is purely written in “c” so we cannot directly connect with java. JDBC is a low level pure java API used to execute SQL statements. (i) ODBC is not appropriate for direct use from java because it uses “c” interfaces. Calls from java to native “c” code have number of drawbacks in the security, implementation and robustness.

Q) Can we establish the connection with ODBC itself?A) Yes, using java native classes we have to write a program.

Q) What is necessity of JDBC in JDBC-ODBC bridge?A) The purpose of JDBC is to link java API to the ODBC, ODBC return high level “c” API so the JDBC converts “c” level API to java API.

Nazar BabuNazar Babu 37

Page 38: Final Java Faqs

Java TechnoloiesJava Technoloies

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) Is the JDBC-ODBC Bridge multi-threaded?A) No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC

Q) Dynamically creating Tables Statement st = con.cretaeStatement ();Int n = st.executeUpdate (“create table “+ uname+ “(sno int, sentby varchar

(10), subject varchar (15)”);

Q) Statements in JDBC

Statement Does not take any arguments; In this statement it will check syntax error and execute it every time (it will parse every time).

Prepare statement P.S is 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 placeholders? Before execution of these statements user has to supply values for place holders, it will increase performance of application.

PreparedStatement PST = con.prepareStatement ("SELECT * FROM EMP WHERE deptno=?");DataInputStream dis = new DataInputStream (“System.in”);Int dno = Integer.ParseInt (dis.readLine ());pst.setInt (1, dno);ResultSet rs = pst.executeQuery ();

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 is 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 network traffic.

CallableStatement CST = con.prepareCall (“{CALL procedure-name (??)}”);DataInputStream dis = new DataInputStream (“System.in”);Int enum = Integer.ParseInt (dis.readLine ());cst.setInt (1, enum);cst.registerOutParameter (2, types.VARCHAR)Resultset rs = cst.execute ();

In used to send information to the procedure.Out used to retrieve information from data base.InOut both.

Nazar BabuNazar Babu 38

Page 39: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) In which interface the methods commit() & rollback() savepoint() defined ?

A) Java.sql.Connection interface

Q) Retrieving very large values from database?

A) getASSCIISteram() read values which are character in nature. GetBinaryStream() used to read images.

Q) ResultSetMetaDataIt is used to find out the information of a table in a data base. ResultSet rs = stmt.executeQuery("SELECT * FROM "+ table); ResultSetMetaData rsmd = rs.getMetaData();

Methods getColumnCount(), getColumnName(), getColumnLabel(), getColumnType(), getTableName(),

Q) Database MetaDataYou 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

Connection con = DriverManager.getConnection(jdbcURL, "", "");DatabaseMetaData dbmd = con.getMetaData();ResultSet rs= dbmd.getxxx();

Methods getColumns(), getTableTypes(), getTables(), getDriverName(), getMajorVersion(), get MinorVersion(), getProcedures(), getProcedureColumns(), getTables().

Q) SQL WarningsWarnings may be retrieved from Connection, Statement, and ResultSet objects. Trying to retrieve a warning on a connection after it has been closed will cause an exception to be thrown. Similarly, trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an exception to be thrown. Note that closing a statement also closes a result set that it might have produced.

Connection.getWarnings()Statement.getWarnings(), ResultSet.getWarnings(), Serialized Form

SQLWarning warning = stmt.getWarnings();if (warning != null){

while (warning != null){

System.out.println("Message: " + warning.getMessage());

System.out.println("SQLState: " + warning.getSQLState());

System.out.print("Vendor error code: ");

Nazar BabuNazar Babu 39

Page 40: Final Java Faqs

Java TechnoloiesJava Technoloies

System.out.println(warning.getErrorCode());warning = warning.getNextWarning();

}}

Q) ProcedureProcedure is a subprogram will perform some specific action; sub programs

are naming PL/SQL blocks that can take parameters to be invoked.

create (or) replace procedure procedure-name (id IN INTEGER , bal IN OUT FLOAT) IS BEGIN

select balance into bal from accounts where account_id = id; Bal: = bal + bal * 0.03; Update accounts set balance = bal where account_id = id; END;

Q) TriggerTrigger 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 rowBegin

Insert into table-name values(:empno; :name)end

Q) Stored Images into a table Public class img { Public static void main(String args[]){ Class.forName(); Connection con = DriverManager.getConnection(); Preparestatement pst = con.prepareStatement(“insert into image value(?)); FileInputStream fis = new FileInputStream(“a.gif”); Pst.setBinaryStream(1, fis, fis.available); Int I = pst.executeUpadate();}

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

Nazar BabuNazar Babu 40

Page 41: Final Java Faqs

Java TechnoloiesJava Technoloies

All PackagesAll Packages

Q) Thread ClassMethods: -

getName() run()getPriority() Sleep()isAlive() Start()join()

Q) Object classAll 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)

int hashcode()

Q) throwable classMethods: -

String getMessage() Void printStackTrace()String toString() Throwable fillInStackTrace()

Q) Javax.servlet PackageInterfaces Classes ExceptionsServlet GenericServlet ServletExceptio

nServletConfig ServletInputStream UnavaliableExc

eptionServletContext ServletOutputStreamServletRequest ServletContextAttribut

eEventServletResponseSingleThreadModelServletContextListenerServletContextAttributeList

enerServletContextInitialization

parametersServletRequestAttributeList

enerServletRequestListnerFilterFilterChainFilterConfigRequestDispatcher

Nazar BabuNazar Babu 41

Page 42: Final Java Faqs

Java TechnoloiesJava Technoloies

GenericServlet (C) public void destroy();public String getInitParameter(String name);public Enumeration getInitParameterNames();public ServletConfig getServletConfig();public ServletContext getServletContext();public String getServletInfo();public void init(ServletConfig config) throws ServletException;public void log(String msg);public abstract void service(ServletRequest req, ServletResponse

res)

ServletInputStream (C) public int readLine(byte b[], int off, int len)

ServletOutputStream (C) public void print(String s) throws IOException; public void println() throws IOException;

ServletContextAttributeEvent (C) public void attributeAdded(ServletContextAttributeEvent scab) public void attributeRemoved(ServletContextAttributeEvent scab)

public void attributeReplaced(ServletContextAttributeEvent scab)

Servlet (I) public abstract void destroy(); public abstract ServletConfig getServletConfig(); public abstract String getServletInfo(); public abstract void init(ServletConfig config) throws ServletException; public abstract void service(ServletRequest req, ServletResponse res)

ServletConfig (I) public abstract String getInitParameter(String name); public abstract Enumeration getInitParameterNames();

public abstract ServletContext getServletContext();

ServletContext (I) public abstract Object getAttribute(String name);public abstract String getRealPath(String path);public abstract String getServerInfo();public abstract Servlet getServlet(String name) throws

ServletException;public abstract Enumeration getServletNames(); public abstract Enumeration getServlets(); public abstract void log(Exception exception, String msg);

ServletRequest (I) public abstract Object getAttribute(String name); public abstract String getParameter(String name); public abstract Enumeration getParameterNames(); public abstract String[] getParameterValues(String name); public abstract String getRealPath(String path); public abstract String getRemoteAddr(); public abstract String getRemoteHost(); public abstract String getServerName(); public abstract int getServerPort();

Nazar BabuNazar Babu 42

Page 43: Final Java Faqs

Java TechnoloiesJava Technoloies

RequestDispatcher getRequestDispatcher(String path); public int getLocalPort(); // servlet 2.4 public int getRemotePort(); // servlet 2.4 public String getLocalName(); // servlet 2.4 public String getLocalAddr(); // servlet 2.4

ServletResponse (I) public abstract String getCharacterEncoding(); public abstract PrintWriter getWriter() throws IOException; public abstract void setContentLength(int len); public abstract void setContentType(String type);

Q) Javax.servlet.Http PackageInterfaces Classes ExceptionsHttpServletRequest Cookies ServletExceptionHttpServletResponse HttpServlet (Abstarct

Class)UnavaliableException

HttpSession HttpUtilsHttpSessionListener HttpSessionBindingEven

tHttpSessionActivationListenerHttpSessionAttributeListenerHttpSessionBindingListenerHttpSessionContext (deprecated)Filter

ServletContextListener (I) public void contextInitialized(ServletContextEvent event)

public void contextDestroyed(ServletContextEvent event)

ServletContextAttributeListener (I) public void attributeAdded(ServletContextAttributeEvent scab)

public void attributeRemoved(ServletContextAttributeEvent scab)

public void attributeReplaced(ServletContextAttributeEvent scab)

ServletContextInitilazation parameters

Cookies (C) public Object clone();public int getMaxAge();public String getName();public String getPath();public String getValue();public int getVersion();

Nazar BabuNazar Babu 43

Page 44: Final Java Faqs

Java TechnoloiesJava Technoloies

public void setMaxAge(int expiry);public void setPath(String uri);public void setValue(String newValue);public void setVersion(int v);

HttpServlet (C) public void service(ServletRequest req, ServletResponse res) protected void doDelete (HttpServletRequest req, HttpServletResponse res) protected void doGet (HttpServletRequest req, HttpServletResponse res) protected void doOptions(HttpServletRequest req, HttpServletResponse res) protected void doPost(HttpServletRequest req, HttpServletResponse res) protected void doPut(HttpServletRequest req, HttpServletResponse res) protected void doTrace(HttpServletRequest req, HttpServletResponse res) protected long getLastModified(HttpServletRequest req); protected void service(HttpServletRequest req, HttpServletResponse res)

HttpSessionbindingEvent (C) public String getName(); public HttpSession getSession();

HttpServletRequest (I) public abstract Cookie[] getCookies(); public abstract String getHeader(String name); public abstract Enumeration getHeaderNames(); public abstract String getQueryString(); public abstract String getRemoteUser(); public abstract String getRequestedSessionId(); public abstract String getRequestURI(); public abstract String getServletPath(); public abstract HttpSession getSession(boolean create); public abstract boolean isRequestedSessionIdFromCookie(); public abstract boolean isRequestedSessionIdFromUrl(); public abstract boolean isRequestedSessionIdValid();

HttpServletResponse (I) public abstract void addCookie(Cookie cookie); public abstract String encodeRedirectUrl(String url); public abstract String encodeUrl(String url); public abstract void sendError(int sc, String msg) throws

IOException; public abstract void sendRedirect(String location) throws

IOException; public abstract void addIntHeader(String header, int

value); public abstract void addDateHeader(String header,

long value); public abstract void setHeader(String name, String value); public abstract void setIntHeader(String header, int

value);

Nazar BabuNazar Babu 44

Page 45: Final Java Faqs

Java TechnoloiesJava Technoloies

public abstract void setDateHeader(String header, long value);

public void setStatus();HttpSession (I) public abstract long getCreationTime();

public abstract String getId(); public setAttribute(String name, Object value); public getAttribute(String name, Object value); public remove Attribute(String name, Object value); public abstract long getLastAccessedTime(); public abstract HttpSessionContext getSessionContext(); public abstract Object getValue(String name); public abstract String[] getValueNames(); public abstract void invalidate(); public abstract boolean isNew(); public abstract void putValue(String name, Object value); public abstract void removeValue(String name); public setMaxInactiveIntervel();

HttpSessionListener (I) public void sessionCreated(HttpSessionEvent event) public void sessionDestroyed(HttpSessionEvent event)

HttpSessionAttributeListener (I) public void attributeAdded(ServletContextAttributeEvent scab)

public void attributeRemoved(ServletContextAttributeEvent scab)

public void attributeReplaced(ServletContextAttributeEvent scab)

HttpSessionBindingListener (I) public void

HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)public void

HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)

HttpSessionActivationListener (I) public void sessionDidActivate(HttpSessionEvent event)public void sessionWillpassivate(HttpSessionEvent event)

Filter (i)

public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) public FilterConfig getFilterConfig() public void setFilterConfig (FilterConfig filterConfig)

Q) java.sql Package

Interfaces Classes ExceptionsConnection DriverManagerCallableStatement Date ClassNotFoundExceptionDriver TimeStamp Instantiation Exception

Nazar BabuNazar Babu 45

Page 46: Final Java Faqs

Java TechnoloiesJava Technoloies

PreparedStatement TimeResultSet TypesResultSetMetaData SQL Exception, SQL

WarningsStatement DatabaseMetaDataArrayParameterMetaDataClob, BlobSQLInput, SQLOutput, SQLPermissionSavepoint

Q) javax.sql Package

Interfaces Classes ExceptionsConnectionEventListener ConnectionEventConnectionPoolDataSource RowsetEventDataSourcePooledConnection RowSetRowSetListenerRowSetMetaDateRowSetReader/WriterXAConnectionXADataSource

Q) java.lang PackageInterfaces Classes ExceptionsCloneable Double, Float, Long,

Integer, Short, Byte, Boolean, Character,

ArithmeticException, ArrayIndexOutOfBoundOf.E, ClassCast.E, ClassNotFound.E

Runnable Class, ClassLoader IlleAcess.E, IllegalArgument.EComparable Process, RunTime, Void IllegalSate.E, NullPointer.E

String, StringBuffer NoSuchField.E, NoSuchMethod.E

Thread, ThreadGroup NumberFormat.E

Q) java.IO Package

Interfaces Classes ExceptionsDataInputstream BufferInputstream,

BufferOutputStreamDataOutputstream BufferReader, BufferWriterObjectInputStream ByteArrayInputStream,

ByteArrayOutputstreamObjectOutputstream

CharacterarrayReader, CharacterArayWriter

Serializable DataInputStream, DataOutputStream

Externializable Filereader, FileWriterObjectInputStream, ObjectOutputStream

Nazar BabuNazar Babu 46

Page 47: Final Java Faqs

Java TechnoloiesJava Technoloies

SERVLETsSERVLETs

Class path: - set path= c:\j2sdk1.4.2\bin set classpath= c:\ j2sdk1.4.2\lib\tools.jar;c:\servlet.jar C:\Tomcat5\bin\startup.bat shortcut

Q) ServletServlet 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. Servlets will be loaded in the Address space of web server. Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the configuration file 3) Through an administration interface.

Q) What is Temporary Servlet?

A) When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.Java weblogic.jspc—keepgenerated *.jsp

Q) What is the difference between Server and Container?A) A server provides many services to the clients, A server may contain one or more containers such as ejb containers, servlet/jsp container. Here a container holds a set of objects.

Q) Servlet ContainerThe servlet container is a part of a Web server (or) Application server that

provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via that server’s native extension API. All servlet containers must support HTTP as a protocol for requests andresponses, but additional request/response-based protocols such as HTTPS (HTTP over SSL) may be supported.

Q) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text as well as some dynamic text, what method do you use?A) Using 'RequestDispather.include(“xx.html”) in the servlet code we can mix the partial static HTML Directory page.

Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(“xx.html”); rd.include(request,response);

Nazar BabuNazar Babu 47

Page 48: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Servlet Life cycle

Public void init (ServletConfig config) throws ServletExceptionpublic void service (ServletRequest req, ServletResponse res) throws ServletException, IOExceptionpublic void destroy ()

The Web server when loading the servlet calls the init method once. (The init method typically establishes database connections.)

Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet. If u put “Private” modifier for the service() it will give compile time error.

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, this will call only once.

ServletException Signals that some error occurred during the processing of the request and the container should take appropriate measures to clean up the request.

IOException Signals that Servlet is unable to handle requests either temporarily or permanently.

Q) Why there is no constructor in servlet?A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.

Q) Can we use the constructor, instead of init(), to initialize servlet? A) Yes, of course you can use. There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?A) No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

Q) Directory Structure of Web Applications?A) WebApp/(Publicly available files, such as | .jsp, .html, .jpg, .gif) | +WEB-INF/-+ | + classes/(Java classes, Servlets) | + lib/(jar files) |

Nazar BabuNazar Babu 48

Page 49: Final Java Faqs

Java TechnoloiesJava Technoloies

+ web.xml / (taglib.tld) | + weblogic.xml WAR-> WARfile can be placed in a server’s webapps directory

Q) Web.xml: - <web-app><!-- Defines WebApp initialization parameters.--><context-param>

<param-name>locale</param-name><param-value>US</param-value>

</context-param>

<!-- Defines filters and specifies filter mapping --><filter>

<filter-name>Test Filter</filter-name><filter-class>filters.TestFilter</filter-class>

<init-param> <param-name>locale</param-name>

<param-value>US</param-value></init-param>

</filter>

<filter-mapping><filter-name>Test Filter</filter-name><servlet-name>TestServlet</servlet-name>

</filter-mapping>

<!-- Defines application events listeners --><listener> <listener-class>

listeners.MyServletContextListener</listener-class> </listener><listener> <listener-class>

listeners.MySessionCumContextListener </listener-class></listener>

<!-- Defines servlets --><servlet>

<servlet-name>HelloServlet</servlet-name><servlet-class>servlets.HelloServlet</servlet-class>

<init-param><param-name>driverclassname</param-name><param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param><init-param>

<param-name>dburl</param-name>

Nazar BabuNazar Babu 49

Page 50: Final Java Faqs

Java TechnoloiesJava Technoloies

<param-value>jdbc:odbc:MySQLODBC</param-value></init-param> <security-role-ref>

<!-- role-name is used in HttpServletRequest.isUserInRole(String role) method. -->

<role-name>manager</role-name><!-- role-link is one of the role-names specified in security-role

elements. --><role-link>supervisor</role-link>

</security-role-ref></servlet>

<!-- Defines servlet mappings --><servlet-mapping>

<servlet-name>HelloServlet</servlet-name><url-pattern>*.hello</url-pattern>

</servlet-mapping>

<!--specifies session timeout as 30 minutes. --><session-config>

<session-timeout>30</session-timeout><session-config>

<welcome-file-list><welcome-file>index.html</welcome-file>

</welcome-file-list>

<! -- Error page -- ><error-page>

<error-code>404</error-code><location>notfoundpage.jsp</location>

</error-page>

<error-page><exception-type>java.sql.SQLException</exception-type><location>sqlexception.jsp</location>

</error-page>

<taglib><taglib-uri>http://abc.com/testlib</taglib-uri><taglib-location>/WEB-INF/tlds/testlib.tld</taglib-location>

</taglib><taglib><taglib-uri>/examplelib</taglib-uri><taglib-location>/WEB-INF/tlds/examplelib.tld</taglib-location></taglib>

<!-- only POST method is protected --><http-method>POST</http-method>

<web-resource-collection><web-resource-name>Another Protected Area</web-resource-name>

Nazar BabuNazar Babu 50

Page 51: Final Java Faqs

Java TechnoloiesJava Technoloies

<url-pattern>*.hello</url-pattern></web-resource-collection>

<!-- auth-method can be: BASIC, FORM, DIGEST, or CLIENT-CERT --><auth-method>FORM</auth-method>

<realm-name>sales</realm-name> <form-login-config>

<form-login-page>/formlogin.html</form-login-page><form-error-page>/formerror.jsp</form-error-page>

</form-login-config></login-config>

</web-app>

Q) Automatically start Servlet?A) If present, calls the servlet's service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:

<servlet servlet-name='test.HelloWorld'> <run-at>0:00, 6:00, 12:00, 18:00</run-at></servlet>

Q) ServletConfig Interface & ServletContex InterfacesServletConfig ServletConfig object is used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.

This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

Ex:- <web-app><servlet>

<servlet-name>TestServlet</servlet-name><servlet-class>TestServlet</servlet-class>

<init-param><param-name>driverclassname</param-name><param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param><init-param>

<param-name>dburl</param-name><param-value>jdbc:odbc:MySQLODBC</param-value>

</init-param></servlet></web-app>--------------------------------------

Nazar BabuNazar Babu 51

Page 52: Final Java Faqs

Java TechnoloiesJava Technoloies

public void init(){

ServletConfig config = getServletConfig();String driverClassName = config.getInitParameter("driverclassname");String dbURL = config.getInitParameter("dburl");Class.forName(driverClassName);dbConnection = DriverManager.getConnection(dbURL,username,password);

}

ServletContext ServletContext is also called application object. ServletContext is used to obtain information about environment on which a servlet is running.There is one instance object of the ServletContext interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.

Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.

Q) How to add application scope in Servlets?

A) In Servlets Application is nothing but ServletContext Scope.ServletContext appContext = servletConfig.getServletContext();appContext.setAttribute(paramName, req.getParameter(paramName));appContext.getAttribute(paramName);

Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean?A) HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.

Q) Can we store objects in a session?A) session.setAttribute("productIdsInCart",productIdsInCart); session.removeAttribute("productIdsInCart");

Q) Servlet Listeners

(i) ServletContextListenervoid contextDestroyed (ServletContextEvent sce) void contextInitialized (ServletContextEvent sce)

Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

(ii) ServletContextAttributeListener (I)void attributeAdded (ServletContextAttributeEvent scab)void attributeRemoved (ServletContextAttributeEvent scab)void attributeReplaced (ServletContextAttributeEvent scab)

Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification

Nazar BabuNazar Babu 52

Page 53: Final Java Faqs

Java TechnoloiesJava Technoloies

events, the implementation class must be configured in the deployment descriptor for the web application.

Q) HttpListeners

(i) HttpSessionListener (I)public void sessionCreated(HttpSessionEvent event)public void sessionDestroyed(HttpSessionEvent event)

Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

(ii) HttpSessionActivationListener (I)public void sessionWillPassivate(HttpSessionEvent se)public void sessionDidActivate(HttpSessionEvent se)

Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated.

(iii) HttpSessionAttributeListener (I)public void attributeAdded(HttpSessionBindingEvent se)public void attributeRemoved(HttpSessionBindingEvent se)public void attributeReplaced(HttpSessionBindingEvent se)

This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application.

(iv) HttpSession Binding Listener (** If session will expire how to get the values)

Some objects may wish to perform an action when they are bound (or) unbound from a session. For example, a database connection may begin a transaction when bound to a session and end the transaction when unbound. Any object that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound (or) unbound from a session. The interface declares two methods, valueBound() and valueUnbound(), that must be implemented:

Methods: -public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)

valueBound() method is called when the listener is bound into a sessionvalueUnbound() is called when the listener is unbound from a session. The javax.servlet.http.HttpSessionBindingEvent argument provides access to the name under which the object is being bound (or unbound) with the getName() method:

public String HttpSessionBindingEvent.getName()

The HttpSessionBindingEvent object also provides access to the HttpSession object to which the listener is being bound (or unbound) with getSession() :

public HttpSession HttpSessionBindingEvent.getSession()

Nazar BabuNazar Babu 53

Page 54: Final Java Faqs

Java TechnoloiesJava Technoloies

=========public class SessionBindings extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter (); HttpSession session = req.getSession(true); session.putValue("bindings.listener", new CustomBindingListener(getServletContext())); // Add a CustomBindingListener }}=============class CustomBindingListener implements HttpSessionBindingListener { ServletContext context;

public CustomBindingListener(ServletContext context) { this.context = context; }

public void valueBound(HttpSessionBindingEvent event) { context.log("BOUND as " + event.getName() + " to " + event.getSession().getId()); }

public void valueUnbound(HttpSessionBindingEvent event) { context.log("UNBOUND as " + event.getName() + " from " + event.getSession().getId()); }}

Q) FilterFilter is an object that intercepts a message between a data source and a data destination, and then filters the data being passed between them. It acts as a guard, preventing undesired information from being transmitted from one point to another.

When a servlet container receives a request for a resource, it checks whether a filter is associated with this resource. If a filter is associated with the resource, the servlet container routes the request to the filter instead of routing it to the resource. The filter, after processing the request, does one of three things:• It generates the response itself and returns it to the client.• It passes on the request (modified or unmodified) to the next filter in the chain• It routes the request to a different resource.

Examples of Filtering Components

• Authentication filters • Logging and auditing filters • Image conversion filters • Data compression filters• Encryption filters • Tokenizing filters • Filters that trigger resource access events• MIME-type chain filters • Caching filters • XSL/T filters that transform XML content

Nazar BabuNazar Babu 54

Page 55: Final Java Faqs

Java TechnoloiesJava Technoloies

The javax.servlet.Filter interface defines three methods:public void doFilter (ServletRequest request, ServletResponse response,

FilterChain chain) public FilterConfig getFilterConfig() public void setFilterConfig (FilterConfig filterConfig)

Ex:-public class SimpleFilter implements Filter{ private FilterConfig filterConfig; public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) { try { chain.doFilter (request, response); // for Filter Chain } catch (IOException io) { System.out.println ("IOException raised in SimpleFilter"); } }

public FilterConfig getFilterConfig() { return this.filterConfig; }

public void setFilterConfig (FilterConfig filterConfig) { this.filterConfig = filterConfig; }}

Filter and the RequestDispatcherversion 2.4 of the Java Servlet specification is the ability to configure filters to be invoked under request dispatcher forward() and include() calls. By using the new <dispatcher>INCLUDE / FORWARD</dispatcher> element in the deployment descriptor,

Q) Are Servlets multithread?A) Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.

Q) What happens to System.out & System. err output in a Servlet?A) System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console.

Q) Session TrackingSession tracking is the capability of the server to maintain the single client

sequential list.

Nazar BabuNazar Babu 55

Page 56: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Servlet chainingIs 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) HttpTunnellingIs 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) Diff CGI & Servlet Servlet is thread based but CGI is process based. CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent.

Q) Diff GET & POST GET & POST are used to process request and response of a client. GET method is the part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length). Using POST we can send large amount of data through hidden fields. Get is to get the posted html data, POST is to post the html data.

Q) Diff Http & Generic Servlet HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child. Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package. Http implements all Http protocols, Generic servlet will implements all networking protocol Http is stateless protocol, which mean each request is independent of previous one, In generic we cannot maintain the state of next page only main state of current page. A protocol is said to be stateless if it has n memory of prior connection. Http servlet extra functionality is capable of retrieving Http header information. Http servlet can override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service() method only.

Q) Can I catch servlet exception and give my own error message? (or) custom error pages?A) Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.

Nazar BabuNazar Babu 56

Page 57: Final Java Faqs

Java TechnoloiesJava Technoloies

RequestDispatcher dispatcher = null;request.getRequestDispatcher(/err/SQL.jsp);try { // SQL operation}catch (SQLException se) {dispatcher.forward(request, response);}

Web.xml<error-page> <error-code> HTTP error code (404) <error-code> <exception-type> java.lang.RuntimeException </exception-type> <location> /err/RuntimeException.jsp </location></error-page>

Q) How many ways we can instantiate a class?A) Class.forName().newInstance() and new keyword

Q) Client pull & Server push?

Client pull Client pull is similar to redirection, with one major difference: the browser

actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It's called client pull because the client is responsible for pulling the content from the next page. Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3");And here's a call that tells the client to display Netscape's home page after the three seconds: setHeader("Refresh", "3; URL=http://home.netscape.com");

Server pushServer push because the server sends, or pushes, a sequence of response

pages to the client. With server push, the socket connection between the client and the server remains open until the last page has been sent.<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">

Nazar BabuNazar Babu 57

Page 58: Final Java Faqs

Java TechnoloiesJava Technoloies

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

Q) How can i upload File using a Servlet?

<FORM ENCTYPE="multipart/form-data" method=post action="/utils/FileUploadServlet"> <INPUT TYPE="file" NAME="currentfilename"> <INPUT TYPE="submit" VALUE="upload"> </FORM>

Q) Session Tracking techniques (i) URL Rewriting(ii) Hidden form Field(iii) Persistence Cookies(iv) Session Tracking API(v) User Authorization

URL RewritingURL 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

Hidden form FieldHidden form fields are HTML input type that are not displayed when read by

the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:

<FORM ACTION="/servlet/MovieFinder" METHOD="POST"> <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"></FORM>In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

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.

Nazar BabuNazar Babu 58

Page 59: Final Java Faqs

Java TechnoloiesJava Technoloies

Sending cookies from a servlet

Cookie cookie = new Cookie ("ID", "123");res.addCookie (cookie);

A servlet retrieves cookies by calling the getCookies () method of HttpServlet- Request: public Cookie[] HttpServletRequest.getCookies()This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:

Reading browser cookies from a Servlet

Cookie [] cookies = req. getCookies();if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String name = cookies [i]. getName (); String value = cookies [i]. getValue(); }}

Deleting the Cookies<% Cookie killMyCookie = new Cookie("mycookie", null); killMyCookie.setMaxAge(0); killMyCookie.setPath("/"); response.addCookie(killMyCookie);%>

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)

Session Tracking APIIn Java the javax.servlet.http.HttpSession API handles many of the details of

session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session. A session object is created through the HttpServletRequest using the getSession() method:

HttpSession session = request.getSession(true);

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

Nazar BabuNazar Babu 59

Page 60: Final Java Faqs

Java TechnoloiesJava Technoloies

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 AuthorizationServers 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) Retrieving query parameters names? Enumeration params = request.getParameterNames(); String paramName = null; String[] paramValues = null;

while (params.hasMoreElements()) { paramName = (String) params.nextElement(); paramValues = request.getParameterValues(paramName); System.out.println("\nParameter name is " + paramName); for (int i = 0; i < paramValues.length; i++) { System.out.println(", value " + i + " is " + paramValues[i].toString()); } }

Q) SessionSession is a persistence network connection between client and server that

facilitate the exchange of information between client and server. The container generates a session ID, when you create a session the server saves the session ID on the clients machine as a cookie. 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.

// If “True” means creating a session if session is not there// if “False” means session is not created should one does not existHttpSession session = req.getSession(true);session.putValue ("MyIdentifier1", count1); // Storing Value into session Objectsession.putValue ("MyIdentifier2", count2); session.getValue(MyIdentifier1); // Prints value of Countsession.removeValue(MyIdentifier1); // Removing Valuefrom Session Object

Nazar BabuNazar Babu 60

Page 61: Final Java Faqs

Java TechnoloiesJava Technoloies

Invalidating a SessionThere are 6 different ways to invalidate the session.1 Httpsession.setMaxInactiveIntervel(int sec)2 Session will automatically expire after a certain time of inactivity3 User closes browser window, notice that the session will time out rather than directly triggering session invalidate.4 calling invalidate()5 if server cashes6 put <session-timeout> in web.xml

Q) Cookie advantages & DisadvantagesAdvantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.Disadvantage The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application.

Q) Advantages of Sessions over Cookies & URLRewriting? Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side. Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not, if cookies are disable also we can maintain sessions using URLRewriting. In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. Where in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.

Q) If the cookies at client side are disabled then session don't work, in this case how can we proceed? A) 1. (from servlet) write the next page with a hidden field containing a unique ID that serves as "session ID". So next time when the user clicks submit, you can retrieve the hidden field. 2. If you use applet, you may avoid "view source" (so that people can't see the hidden field). Your applet reads back an ID from the servlet and use that from then on to make further requests

Q) How to confirm that user's browser accepted the Cookie?A) There's no direct API to directly verify that user's browser accepted the cookie. But the quick alternative would be, after sending the required data to the users browser, redirect the response to a different Servlet which would try to read back the cookie. If this Servlet is able to read back the cookie, then it was successfully saved, else user had disabled the option to accept cookies.

Q) Diff between Multiple Instances of Browser and Multiple Windows? How does this affect Sessions?A) From the current Browser window, if we open a new Window, then it referred to as Multiple Windows. Sessions properties are maintained across all these windows,

Nazar BabuNazar Babu 61

Page 62: Final Java Faqs

Java TechnoloiesJava Technoloies

even though they are operating in multiple windows. Instead, if we open a new Browser, by either double clicking on the Browser Shortcut then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are not maintained across these windows.

Q) encodeURL & encodeRedirectURL These are methods of HttpResponse object, “encodeURL” is for normal links inside your HTML pages, “encodeRedirectURL” is for a link your passing to response.sendRedirect().

Q) SingleThread modelSingleThreadModel 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.

public interface SingleThreadModel { }

Q) Request HeadersUser-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running.request.getHeader(“user-agent”);

Q) Why do you need both GET & POST methods in servlets?A) A single servlet can be called from different HTML pages, so different method calls can be possible.

Nazar BabuNazar Babu 62

Page 63: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Servlet output - to - another Servlet? Inter-servlet communication?A) As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including Request Dispatching HTTP Redirect Servlet Chaining 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);}

Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.

Ex:- ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.

There are some Servlet engine specific configurations for servlet chaining.

Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object.

Ex:- TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); otherServletDetails= Test.getServletDetails();

You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls.

Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet.

Nazar BabuNazar Babu 63

Page 64: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Servlet – to- JSP/Servlet communicate? (or) How Servlet invoke a JSP page? public void doPost(HttpServletRequest req, HttpServletResponse res){ Try{

govi.FormBean f = new govi.formBean(); f.setName(req.getParameter(“name”)); f.setAdress(req.getParameter(“addr”)); f.setPersonalizationInfo(info); req.setAttribute(“fBean”,f); getServletConfig().getServletContext().getRequestDispatcher(“/jsp/Bean1.jsp”).forward(req, res); } catch(Exception ex);}}The jsp page Bean1.jsp can then process fBean,

<jsp:useBean id=”fBean” class=”govi.formBean” scope=”request” /><jsp:getProprety name=”fBean” property=”name” /><jsp:getProprety name=”fBean” property=”addr” />------------------------------------------ (Or) -----------------------------------------You can invoke a JSP page from a servlet through functionality of the standard javax.servlet.RequestDispatcher interface. Complete the following steps in your code to use this mechanism:

1) Get a servlet context instance from the servlet instance: ServletContext sc = this.getServletContext();

2) Get a request dispatcher from the servlet context instance, specifying the page-relative or application-relative path of the target JSP page as input to the getRequestDispatcher() method: RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");

Prior to or during this step, you can optionally make data available to the JSP page through attributes of the HTTP request object. See "Passing Data Between a JSP Page and a Servlet" below for information.

3) Invoke the include() or forward() method of the request dispatcher, specifying the HTTP request and response objects as arguments.

rd.include(request, response); / rd.forward(request, response);

The functionality of these methods is similar to that of jsp:include and jsp:forward actions. The include() method only temporarily transfers control; execution returns to the invoking servlet afterward. Note that the forward() method clears the output buffer.

Q) c ontext.getRequestDispatcher() request.getRequestDispatcher() context.getNamedDispatcher()

Nazar BabuNazar Babu 64

Page 65: Final Java Faqs

Java TechnoloiesJava Technoloies

1) ServletContext.getRequestDispatcher( / ) —> You must use Absolute paths, it can extend outside current servlet context.

2) ServletRequest.getRequestDispatcher(Relative Path) —> The path may be Relative, but cannot extend outside current servlet context, the URL in the address bar doesn’t change. The client looses path information when it receives a forwarded request.

3) ServletRequest.getNamedDispatcher(String name) —> This name is the name of the servlet for which a dispatcher is requested, and is in the web.xml file

Ex :- public class ServletToServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException { try { getServletConfig() .getServletContext().getRequestDispatcher("/HelloWorldExample").forward(request, response); } catch (Exception ex) { ex.printStackTrace (); } }}

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);if (dispatcher == null) { out.println (path + “not available"); Return;} else{ dispatcher.include (request, response);}

Q) Different cases for using sendRedirect () vs. getRequestDispatcher () / getNamedDispatcher? When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher (or) getNamedDispatcher. If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.

Q) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context? A) You can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.

Nazar BabuNazar Babu 65

Page 66: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) How can I share data between two different web applications?

A) Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications.

Q) How do servlets handle multiple simultaneous requests?A) The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

Q) How do i get the name of the currently executing script?A) req.getRequestURI() / req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info.

URLhttp://www.javasoft.com/servlets/HelloServlet/jdata/userinfo?pagetype=s3&pagenum=4

GetRequestURI servlets/HelloServlet/jdata/userinfoGetServletPath servlets/HelloServlet/GetPathInfo /jdata/userinfoGetQueryString pagetype=s3&pagenum=4

Q) How can i stress test my Servlets?A) following products to stress test your Servlets.

ServletKiller, E-Load, Web Application Stress Tool, JMeter from Apache

Q) Connection pool classpublic class ConnectionPool { private Hashtable connections; private int increment; private String dbURL, user, password; public ConnectionPool(String dbURL, String user, String password, String

driverClassName,int initialConnections, int increment) throws SQLException, ClassNotFoundException {

Class.forName(driverClassName); this.dbURL = dbURL; this.user = user; this.password = password; this.increment = increment;

connections = new Hashtable(); // Put our pool of Connections in the Hashtable // The FALSE value indicates they're unused for(int i = 0; i < initialConnections; i++) { connections.put(DriverManager.getConnection(dbURL, user, password), Boolean.FALSE); } } public Connection getConnection() throws SQLException {

Nazar BabuNazar Babu 66

Page 67: Final Java Faqs

Java TechnoloiesJava Technoloies

Connection con = null; Enumeration cons = connections.keys(); synchronized (connnections) { while(cons.hasMoreElements()) { con = (Connection)cons.nextElement(); Boolean b = (Boolean)connections.get(con); if (b == Boolean.FALSE) { // So we found an unused connection. Test its integrity with a quick setAutoCommit(true) call. // For production use, more testing should be performed, such as executing a simple query. try { con.setAutoCommit(true); } catch(SQLException e) { // Problem with the connection, replace it. con = DriverManager.getConnection(dbURL, user, password); } // Update the Hashtable to show this one's taken connections.put(con, Boolean.TRUE); return con; } } } // If we get here, there were no free connections. // We've got to make more. for(int i = 0; i < increment; i++) { connections.put(DriverManager.getConnection(dbURL, user, password), Boolean.FALSE); } // Recurse to get one of the new connections. return getConnection(); } public void returnConnection(Connection returned) { Connection con; Enumeration cons = connections.keys(); while (cons.hasMoreElements()) { con = (Connection)cons.nextElement(); if (con == returned) { connections.put(con, Boolean.FALSE); break; } } }}

Nazar BabuNazar Babu 67

Page 68: Final Java Faqs

Java TechnoloiesJava Technoloies

J S P J S P

Why JSP Technology?

•Servlets are good at running logic–Not so good at producing large amounts of output–out.write() is ugly

•JSP pages are great at producing lots of textual output–Not so good at lots of logic–<% %> is ugly

How does it Work ?•“JSP page”

–Mixture of text, Script and directives–Text could be text/ html, text/ xml or text/ plain

•“JSP engine”–‘Compiles’ page to servlet–Executes servlet’s service() method

•Sends text back to caller•Page is

–Compiled once–Executed many times

Directives:

Page Directive

<%@ Page language="java" extends="className" import="className" session="true|false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType” %>

XML syntax: -

<Jsp: directive.page import=” ” />

Page directive defines information that will be globally available for that page

Include Directive

<%@ include file="relative URL" %>

XML syntax: -

<Jsp: directive.include file=” ” /><Jsp: directive.page file=” ” />

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.

Nazar BabuNazar Babu 68

Page 69: Final Java Faqs

Java TechnoloiesJava Technoloies

Taglib Directive

<%@ taglib uri="uriToTagLibrary" prefix="prefixString" %>

XML syntax: -

<Jsp: root xmlns:prefix1=”http://..” version=”1.2” /></Jsp: root>

Taglib directive enables you to create your own custom tags.

Actions:

<Jsp: useBean>

<Jsp: useBean id="beanInstanceName" scope="page|request|session|application” class=""/ type="" bean Name=" "</jsp: useBean>

UseBean tag is used to associate a java bean with jsp.

<Jsp: setProperty>

<Jsp: setProperty name="beanInstanceName” property="*" |"propertyName” param="paramName" value="{string | <%= expression %>}" />

Sets a property value or values in a bean.

<Jsp: getProperty>

<Jsp: getProperty name="beanInstanceName" property="propertyName" />

Gets the value of a bean property so that you can display it in a result page.

<Jsp: param>

<Jsp: param name="beanInstanceName" value=" parameterValue " />

It is used to provide other tags with 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: param name="username" value="jsmith" /> </jsp: include>

Jsp Include includes the JSP are Servlet at request time, it is not 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 %>}" > <jsp: param name="paramName" value="paramValue"/></jsp: forward>

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 and it will also forward

Nazar BabuNazar Babu 69

Page 70: Final Java Faqs

Java TechnoloiesJava Technoloies

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" codebase="classFileDirectoryName" name="instanceName" archive="” align="" height=" " width=" " hspace=" " vspace=" </jsp: plugin>

This action is used to generate client browser specific html tags that ensures the java plug in software is available, followed by execution of applet or java bean component specified in tag.

Implicit Objects Objects Type / purpose Scope Sum useful

methodsRequest Subclass of

javax.servlet.http.ServletRequest

- Refers to the current request passed to the _jspService() method

Request- Objects accessible from pages processing the request where they were created.

getAttribute, getParameter, getParameterNames, getParameterValues, setAttribute

Response Subclass of javax.servlet.http.ServletResponse

- Refers to the response sent to the client. It is also passed to the _jspService() method.

Page Not typically used by JSP page authors

Session javax.servlet.http.HttpSession

- JSP 1.2 specification states that if the session directive is set to false, then using the session keyword results in a fatal translation time error.

Session- Objects accessible from pages belonging to the same session as the one in which they were created.

getAttribute, getId, setAttribute.

application

javax.servlet.ServletContext

- Use it to find information about the servlet engine and the servlet environment.

Application- Objects accessible from pages belonging to the same application.

getAttribute, getMimeType, getRealPath, setAttribute

Nazar BabuNazar Babu 70

Page 71: Final Java Faqs

Java TechnoloiesJava Technoloies

Out javax.servlet.jsp.JspWriter

- Refers to the output stream of the JSP page.

Page clear, clearBuffer, flush, getBufferSize, getRemaining

Config javax.servlet.ServletConfig

- The initialization parameters given in the deployment descriptor can be retrieved from this object.

Page getInitParameter, getInitParameterNames

page java.lang.Object.

- Refers to the current instance of the servlet generated from the JSP page.

Page- Objects accessible only within jsp pages where it was created.

Not typically used by JSP page authors

pageContext

javax.servlet.jsp.PageContext.

- Provides certain convenience methods and stores references to the implicit objects.

Page findAttribute, getAttribute, getAttributesScope, getAttributeNamesInScope, setAttribute.

exception java.lang.Throwable.

- Available for pages that set the page directive attribute isErrorPage to true. It can be used for exception handling.

Page getMessage, getLocalizedMessage, printStackTrace, toString

Scripting Elements:

Elements Type / purpose Sum useful methods

Scriptlet

<% Java_code %>

XML syntax: -

<Jsp: scriptlet> Date today = new Date();</jsp: scriptlet>

A scriptlet can contain variable (or) method declarations (or) expressions. 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.

Nazar BabuNazar Babu 71

Page 72: Final Java Faqs

Java TechnoloiesJava Technoloies

Declaration

Ex: <%! int a, b, c; %> <%! int accountnumber=23468; %> <%! private void processAmount () { ... } %>

XML syntax: -

<jsp: declaration> int counter=0;</jsp: Declaration>

A declaration declares one or more variables (or) methods for use later in the JSP source file. This is used for “Global declaration”.

Expressions

Ex: <%= (new java.util.Date()).toLocaleString() %>XML syntax: - <jsp: expression> // -------</jsp: expression>

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.

Comments

Html comment Creates a comment that is sent to the client in the viewable page source. Ex: <! -- <%= expression %> -->

Hidden Comment Documents the JSP file, but is not sent to the client. Ex: <%-- comment --%>

Comments are removed from the viewable source of your HTML files by using only JSP comment tags. HTML comments remain visible when the user selects view source in the browser.

Q) Diff Explicit Objects & Implicit Objects

Explicit Explicit objects are declared and created within the code of your JSP page, accessible to that page and other pages according to the scope setting you choose.

Explicit objects are typically JavaBean instances declared and created in jsp:useBean action statements. <jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

Implicit Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets (or) expressions in JSP pages according to the inherent scope setting of the particular object type. Q) MVC

Nazar BabuNazar Babu 72

Page 73: Final Java Faqs

Java TechnoloiesJava Technoloies

Model: - model is a java bean/entity bean that represent the data being transmitted are receivedController: - 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) WebApplication scopes?A) Request, Session, Application.Request :- Life time is until the response is return to the userSession :- Until the session timeout (or) session id invalidate.Application :- Life of container (or) explicitly killed

Q) Life-cycle of JSPPage translationJsp compilationLoad classCreate InstancejspInit( ), _jspservice( ), jspDestroy( )

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. Destroy is not called if the container crashes. jspInit() & jspDestroy() called only once so we cannot override these methods.

Q) RequestDispatcher.forward(req, res) RequestDispatcher.include(req, res) PageContext.forward() res.sendRedirect(url) <jsp:forward>

RequestDispatcher.forward(req, res) in forward req, res would be passed to the destination URL and the control will return back to the same method, it will execute at “server side”.

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”. If page1.jsp redirects to page2.jsp, the browser's address bar be updated to show page2.jsp.

Nazar BabuNazar Babu 73

Page 74: Final Java Faqs

Java TechnoloiesJava Technoloies

PageContext.forward() and RequestDispatcher.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.

The difference between the two is that sendRedirect always sends a header back to the client/browser. this header then contains the resource(page/servlet) which you wanted to be redirected. the browser uses this header to make another fresh request. thus sendRedirect has a overhead as to the extra remort trip being incurred. it's like any other Http request being generated by your browser. the advantage is that you can point to any resource(whether on the same domain or some other domain). for eg if sendRedirect was called at www.mydomain.com then it can also be used to redirect a call to a resource on www.theserverside.com.

In the case of forward() call, the above is not true. resources from the server, where the fwd. call was made, can only be requested for. But the major diff between the two is that forward just routes the request to the new resources which you specify in your forward call. that means this route is made by the servlet engine at the server level only. no headers are sent to the browser which makes this very efficient. also the request and response objects remain the same both from where the forward call was made and the resource which was called.

RequestDispatcher.include(req, res) RequestDispatcher.include() and <jsp:include> both include content. The included page is inserted into the current page or output stream at the indicated point. It will execute at “server side”.

<Jsp: forward> Forwards a client request to an HTML file/JSP file/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. Forward operations are faster because all processing is done at server side. res.sendRedirect() operations updates the browser history.

Ex -- of RequestDispatcher.forward(req, res)public class BookStoreServlet extends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

// Get the dispatcher; it gets the main page to the user RequestDispatcher dispatcher =

config.getServletContext().getRequestDispatcher("/bookstore.html"); if (dispatcher == null) {

// No dispatcher means the resource (bookstore.html in this case) cannot be found

res.sendError(response.SC_NO_CONTENT); } else {

// Send the user the bookstore's opening pagedispatcher.forward(request, response);

}

Nazar BabuNazar Babu 74

Page 75: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Diff res.sendRedirect( ) & req.forward( )

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

Q) Diff <%@ include file="file" %> & <jsp:include page=”abc.jsp” %> <%@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.

Q) Diff Jsp & ServletInternally 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.

Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?A) By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false:

<%@ page is ThreadSafe=”false” %>

Q) How does JSP handle runtime exceptions?A) You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request

processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage=\"true\" %>.

Nazar BabuNazar Babu 75

Page 76: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server?A) Web browser caching <% response.setHeader("Cache-Control","no-store"); response.setHeader("Pragma","no-cache"); response.setDateHeader ("Expires", 0); %> Proxy server caching response.setHeader("Cache-Control","private");

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.

Q) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a JSP page?A) Use <jsp:forward page="/relativepath/YourServlet" />

(or) response.sendRedirect("http://path/YourServlet").

Variables also can be sent as: <jsp:forward page=/relativepath/YourServlet> <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /></jsp:forward>

You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1").

Q) JSP- to-EJB Session Bean communication?

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %><%! AccountHome accHome=null; public void jspInit() { InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java: comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); }%><% Account acct = accHome.create(); acct.doWhatever(...); %>

Nazar BabuNazar Babu 76

Page 77: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) How do you pass an InitParameter to a JSP?<%!

ServletConfig cfg =null;public void jspInit(){

ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)

{ String name=(String)e.nextElement();

String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } }%>

Q) How to view an image stored on database with JSP?<%@ page language="java" import="java.sql.*,java.util.*"%><% String image_id = (String) request.getParameter("ID"); if (image_id != null){ try { Class.forName("interbase.interclient.Driver");

Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database/employee.gdb","java","java");

Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id);if (rs.next())

{String dim_image = rs.getString("IMMAGINE_DIMENSIONE");byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE");response.setContentType("image/jpeg");ServletOutputStream op = response.getOutputStream();for(int i=0;i<Integer.parseInt(dim_image);i++){

op.write(blocco[i]);}

} rs.close(); stmt.close(); con.close(); } catch(Exception e) {

out.println("An error occurs : " + e.toString()); }

}%>

Nazar BabuNazar Babu 77

Page 78: Final Java Faqs

Java TechnoloiesJava Technoloies

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:

What's your favorite movie?<form method=post action=Movies.jsp><input type=checkbox name=faveMovies value="2001: A Space Odyssey"> 2001: A Space Odyssey<input type=checkbox name=faveMovies value="The Waterboy"> The Waterboy<input type=checkbox name=faveMovies value="The Tin Drum"> The Tin Drum<input type=checkbox name=faveMovies value="Being John"> Being John Malkovich<input type=submit></form>To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:

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; %>

<jsp:useBean id="movieBean" class="foo.MovieBean"> <jsp:setProperty name="movieBean" property="movies" param="faveMovies" /></jsp:useBean>

<% movies = movieBean.getMovies(); if (movies != null) { out.println("You selected: <br>"); out.println("<ul>"); for (int i = 0; i < movies.length; i++) {

Nazar BabuNazar Babu 78

Page 79: Final Java Faqs

Java TechnoloiesJava Technoloies

out.println ("<li>"+movies[i]+"</li>"); } out.println("</ul>"); } else out.println ("Don't you watch any movies?!");%></body></html>

Q) Tag LibrariesThese all methods are callback methods. Tag methods: doStartTag() doEndTag() Body Tag : doAfterBody()

Nazar BabuNazar Babu 79

Page 80: Final Java Faqs

Java TechnoloiesJava Technoloies

Struts Struts

Q) Framework?

A) A framework is a reusable, ``semi-complete'' application that can be specialized to produce custom applications

Q) Why do we need Struts?

A) Struts combines Java Servlets, Java ServerPages, custom tags, and message resources into a unified framework. The end result is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone in between.

Q) Diff Struts1.0 & 1.1?

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) What is the difference between Model2 and MVC models?

In model2, we have client tier as jsp, controller is servlet, and business logic is java bean. Controller and business logic beans are tightly coupled. And controller receives the UI tier parameters. But in MVC, Controller and business logic are loosely coupled and controller has nothing to do with the project/ business logic as such. Client tier parameters are automatically transmitted to the business logic bean, commonly called as ActionForm.So Model2 is a project specific model and MVC is project independent.

Q) How to Configure Struts?Before being able to use Struts, you must set up your JSP container so that it

knows to map all appropriate requests with a certain file extension to the Struts action servlet. This is done in the web.xml file that is read when the JSP container starts. When the control is initialized, it reads a configuration file (struts-config.xml) that specifies action mappings for the application while it's possible to define multiple controllers in the web.xml file, one for each application should suffice

Q) ActionServlet (controller)The class org.apache.struts.action.ActionServlet is the called the

ActionServlet. In 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. The Controller receives the request from the browser; invoke a business operation and coordinating the view to return to the client.

Q) Action ClassThe 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

Nazar BabuNazar Babu 80

Page 81: Final Java Faqs

Java TechnoloiesJava Technoloies

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.Ex: -package com.odccom.struts.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BillingAdviceAction extends Action { public ActionForward execute(ActionMapping mapping,

ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BillingAdviceVO bavo = new BillingAdviceVO(); BillingAdviceForm baform = (BillingAdviceForm)form; DAOFactory factory = new MySqlDAOFactory(); BillingAdviceDAO badao = new MySqlBillingAdviceDAO(); ArrayList projects = badao.getProjects(); request.setAttribute("projects",projects); return (mapping.findForward("success")); }}Q) Action FormAn 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.Ex: -package com.odccom.struts.form;public class BillingAdviceForm extends ActionForm {

private String projectid;private String projectname;

public String getProjectid() { return projectid; }public void setProjectid(String projectid) { this.projectid = projectid; }

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if(getProjectName() == null || getProjectName().length() < 1){

errors.add(“name”, new ActionError(“error.name.required”)); } return errors; }public void reset(ActionMapping mapping, HttpServletRequest request){

this.roledesc = "";this.currid = "";}}

Nazar BabuNazar Babu 81

Page 82: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Message Resource Definition file M.R.D file are simple “.properties” file these files contains the messages

that can be used in struts project. The M.R.D can be added in struts-config.xml file through <message-resource> tag

ex: <message-resource parameter=”MessageResource”>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.

public class TestAction extends ActionForm{ public void reset(ActionMapping mapping, HttpServletRequest request request)}

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 does not already exist. The frame work will create only a single instance of each Action class.

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)

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.

Public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)

Q) What is Validator? Why will you go for Validator?

Validator is an independent framework, struts still comes packaged with it.Instead of coding validation logic in each form bean’s validate() method,

with validator you use an xml configuration file to declare the validations that should be applied to each form bean. Validator supports both “server-side and client-side” validations where form beans only provide “server-side” validations.

Flowing steps: -1. Enabling the Validator plug-in: This makes the Validator available to the system. 2. Create Message Resources for the displaying the error message to the user. 3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation. 4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.

Using Validator FrameworkUsing the Validator framework involves enabling the Validator plug-in,

configuring Validator's two configuration files, and creating Form Beans that extend the Validator's ActionForm subclasses.

Nazar BabuNazar Babu 82

Page 83: Final Java Faqs

Java TechnoloiesJava Technoloies

Enabling the Validator Plug-in Validator framework comes packaged with Struts; Validator is not enabled by default. To enable Validator, add the following plug-in definition to your application's struts-config.xml file.

<plug-in className="org.apache.struts.validator.ValidatorPlugIn"><set-property property="pathnames" value="/technology/WEB-INF/validator-

rules.xml, /WEB-INF/validation.xml"/>

</plug-in>This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property.

Validator-rules.xml<form-validation> <global> <Validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired"

methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required"> <javascript> <![CDATA[

function validateRequired(form) { ]]> </javascript> </validator> </global></form-validation>

Q) How struts validation is working?

Validator uses the XML file to pickup the validation rules to be applied to a form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

The Validator Framework uses two XML configuration files validator-rules.xml & validation.xml. The validator-rules.xml defines the standard validation routines; such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. These are reusable and used in validation.xml. To define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q) What is Tiles?

A) Tiles is a framework for the development user interface, Tiles is enables the developers to develop the web applications by assembling the reusable tiles.

Nazar BabuNazar Babu 83

Page 84: Final Java Faqs

Java TechnoloiesJava Technoloies

1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml. 2. Create layout JSPs. 3. Develop the web pages using layouts.

Q) How to call ejb from Struts? 1…use the Service Locator patter to look up the ejbs. 2…Or you can use InitialContext and get the home interface.

Q) What are the various Struts tag libraries?Struts-html tag library -> used for creating dynamic HTML user interfaces and forms. Struts-bean tag library -> provides substantial enhancements to the basic capability provided by . Struts-logic tag library -> can manage conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management. Struts-template tag library -> contains tags that are useful in creating dynamic JSP templates for pages which share a common format.Struts-tiles tag library -> This will allow you to define layouts and reuse those layouts with in our site.Struts-nested tag library ->

Q) How you will handle errors & exceptions using Struts?-To handle “errors” server side validation can be used using ActionErrors classes can be used. -The “exceptions” can be wrapped across different layers to show a user showable exception. - Using validators

Q) What are the core classes of struts?A) ActionForm, Action, ActionMapping, ActionForward etc.

Q) How you will save the data across different pages for a particular client request using Struts?A) If the request has a Form object, the data may be passed on through the Form object across pages. Or within the Action class, call request.getSession and use session.setAttribute(), though that will persist through the life of the session until altered.(Or) Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request

Q) How would struts handle “messages” required for the application?A) Messages are defined in a “.properties” file as name value pairs. To make these messages available to the application, You need to place the .properties file in WEB-INF/classes folder and define in struts-config.xml

<message-resource parameter=”title.empname”/>

and in order to display a message in a jsp would use this

<bean:message key=”title.empname”/>

Nazar BabuNazar Babu 84

Page 85: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) What is the difference between ActionForm and DynaActionForm?A) 1. In struts 1.0, action form is used to populate the html tags in jsp using struts custom tag.when the java code changes, the change in action class is needed. To avoid the chages in struts 1.1 dyna action form is introduced.This can be used to develop using xml. The dyna action form bloats up with the struts-config.xml based definetion.2. There is no need to write actionform class for the DynaActionForm and all the variables related to the actionform class will be specified in the struts-config.xml. Where as we have to create Actionform class with getter and setter methods which are to be populated from the form3.if the formbean is a subclass of ActionForm, we can provide reset(),validate(),setters(to hold the values),gettters whereas if the formbean is a subclass to DynaActionForm we need not provide setters, getters but in struts-config.xml we have to configure the properties in using .basically this simplifies coding

DynaActionForm which allows you to configure the bean in the struts-config.xml file. We are going to use a subclass of DynaActionForm called a DynaValidatorForm which provides greater functionality when used with the validation framework.

<struts-config> <form-beans> <form-bean name="employeeForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="name" type="java.lang.String"/> <form-property name="age" type="java.lang.String"/> <form-property name="department" type="java.lang.String" initial="2" /> <form-property name="flavorIDs" type="java.lang.String[]"/> <form-property name="methodToCall" type="java.lang.String"/> </form-bean> </form-beans></struts-config>

This DynaValidatorForm is used just like a normal ActionForm when it comes to how we define its use in our action mappings. The only 'tricky' thing is that standard getter and setters are not made since the DynaActionForms are backed by a HashMap. In order to get fields out of the DynaActionForm you would do:

String age = (String)formBean.get("age"); Similarly, if you need to define a property: formBean.set("age","33");

Q) Struts how many “Controllers” can we have?

A) You can have multiple controllers, but usually only one is needed

Q) Can I have more than one struts-config.xml?A) Yes you can I have more than one.<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

Nazar BabuNazar Babu 85

Page 86: Final Java Faqs

Java TechnoloiesJava Technoloies

<init-param> <param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <! — module configurations -- > <init-param> <param-name>config/exercise</param-name>

<param-value>/WEB-INF/exercise/struts-config.xml</param-value> </init-param> </servlet>

Q) Can you write your own methods in Action class other than execute() and call the user method directly?

A) Yes, we can create any number of methods in Action class and instruct the action tag in struts-config.xml file to call that user methods.

Public class StudentAction extends DispatchAction { public ActionForward read(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

Return some thing; } public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

Return some thing; }If the user want to call any methods, he would do something in struts-config.xml file.<action path="/somepage" type="com.odccom.struts.action.StudentAction" name="StudentForm" <b>parameter=”methodToCall”</b> scope="request" validate="true">

<forward name="success" path="/Home.jsp" /></action>

Q) Struts-config.xml

<struts-config> <data-sources> <data-source> <set-property property=”key” value=”” url=”” maxcount=”” mincount=”” user=”” pwd=”” > </data-source> <data-sources>

<!— describe the instance of the form bean-- > <form-beans> <form-bean name="employeeForm" type="net.reumann.EmployeeForm"/> </form-beans>

Nazar BabuNazar Babu 86

Page 87: Final Java Faqs

Java TechnoloiesJava Technoloies

<!— to identify the target of an action class when it returns results -- > <global-forwards> <forward name="error" path="/error.jsp"/> </global-forwards>

<!— describe an action instance to the action servlet-- > <action-mappings> <action path="/setUpEmployeeForm" type="net.reumann.SetUpEmployeeAction" name="employeeForm" scope="request" validate="false"> <forward name="continue" path="/employeeForm.jsp"/> </action>

<action path="/insertEmployee" type="net.reumann.InsertEmployeeAction" name="employeeForm" scope="request" validate="true" input="/employeeForm.jsp"> <forward name="success" path="/confirmation.jsp"/> </action> </action-mappings> <!— to modify the default behaviour of the struts controller-- > <controller processorClass=”” bufferSize=” ” contentType=”” noCache=”” maxFileSize=””/> <!— message resource properties -- > <message-resources parameter="ApplicationResources" null="false" />

<!—Validator plugin <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/> </plug-in>

<!—Tiles plugin <plug-in className="org.apache.struts.tiles.TilesPlugIn"> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml "/> </plug-in>

</struts-config>

Q) Web.xml: - Is a configuration file describe the deployment elements.<web-app> <servlet> <servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <!—Resource Properties --> <init-param> <param-name>application</param-name> <param-value>ApplicationResources</param-value>

Nazar BabuNazar Babu 87

Page 88: Final Java Faqs

Java TechnoloiesJava Technoloies

</init-param> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param>

<load-on-startup>1</load-on-startup> </servlet>

<!-- Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name>

<url-pattern>/do/*</url-pattern> </servlet-mapping> <!-- The Welcome File List --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- tag libs --> <taglib>

<taglib-uri>struts/bean-el</taglib-uri><taglib-location>/WEB-INF/struts-bean-el.tld</taglib-location>

</taglib> <taglib> <taglib-uri>struts/html-el</taglib-uri> <taglib-location>/WEB-INF/struts-html-el.tld</taglib-location> </taglib> <!—Tiles tag libs --> <taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> </taglib><!—Using Filters --> <filter>

<filter-name>HelloWorldFilter</filter-name> <filter-class>HelloWorldFilter</filter-class> </filter>

<filter-mapping> <filter-name>HelloWorldFilter</filter-name> <url-pattern>ResponseServlet</ url-pattern > </filter-mapping> </web-app>

Nazar BabuNazar Babu 88

Page 89: Final Java Faqs

Java TechnoloiesJava Technoloies

HibernateHibernate

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

• API for performing basic CRUD operations • API to express ries refering to classes • Facilities to specify metadata • Optimization facilities : dirty checking, lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

1)Pure relational (stored procedure.) 2)Light objects mapping (JDBC) 3)Medium object mapping 4)Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

• Improved productivityo High-level object-oriented API o Less Java code to write o No SQL to write

• Improved performanceo Sophisticated caching o Lazy loading o Eager loading

• Improved maintainability

Nazar BabuNazar Babu 89

Page 90: Final Java Faqs

Java TechnoloiesJava Technoloies

o A lot less code to write • Improved portability

o ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

• Saving and retrieving your domain objects• Making database column and table name changes • Centralizing pre save and post retrieve logic• Complex joins for retrieving related items• Schema creation from object model

7.What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:

• Programmatic configuration • XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?

An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

Nazar BabuNazar Babu 90

Page 91: Final Java Faqs

Java TechnoloiesJava Technoloies

10.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

• Session interface • SessionFactory interface • Configuration interface • Transaction interface • Query and Criteria interfaces

11.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

• Wraps a JDBC connection • Factory for Transaction

Nazar BabuNazar Babu 91

Page 92: Final Java Faqs

Java TechnoloiesJava Technoloies

• Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?

The general flow of Hibernate communication with RDBMS is :

• Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files

• Create session factory from configuration object • Get one session from this session factory • Create HQL Query • Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

• First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.

• Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :

<hibernate-mapping> <class name="com.test.User" table="user"> <property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java.lang.String"/> </class></hibernate-mapping>

Nazar BabuNazar Babu 92

Page 93: Final Java Faqs

Java TechnoloiesJava Technoloies

16.What’s the difference between load() and get()? load() vs. get() :

load() get()

Only use the load() method if you are sure that the object exists.

If you are not sure that the object exists, then use one of the get() methods.

load() method will throw an exception if the unique id is not found in the database.

get() method will return null if the unique id is not found in the database.

load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

get() will hit the database immediately.

17.What is the difference between and merge and update ?

Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate?

Using <generator> tag.Example:-

<id column="USER_ID" name="id" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param> <generator></id>19.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.inverse="true|false"

Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

20.What does it mean to be inverse?

It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.

Nazar BabuNazar Babu 93

Page 94: Final Java Faqs

Java TechnoloiesJava Technoloies

21.What do you mean by Named – SQL query?

Named SQL queries are defined in the mapping xml document and called wherever required.Example:

<sql-query name = "empdetails"> <return alias="emp" class="com.test.Employee"/> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name</sql-query>

Invoke Named Query :

List people = session.getNamedQuery("empdetails") .setString("TomBrady", name) .setMaxResults(50) .list();

22.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee"> <return-property name="empid" column="EMP_ID"/>

<return-property name="name" column="EMP_NAME"/> <return-property name="address" column="EMP_ADDRESS"/> { ? = call selectAllEmployees() } </return></sql-query>

23.Explain Criteria API ?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

Example :

List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston"))

.addOrder(Order.asc("name") ) .list();

Nazar BabuNazar Babu 94

Page 95: Final Java Faqs

Java TechnoloiesJava Technoloies

24.Define HibernateTemplate?

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

25.What are the benefits does HibernateTemplate provide?

The benefits of HibernateTemplate are :

• HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.

• Common functions are simplified to single method calls. • Sessions are automatically closed. • Exceptions are automatically caught and converted to runtime exceptions.

26.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

27.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:

<property name="show_sql">true</property>

28.What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

29.What is component mapping in Hibernate?

• A component is an object saved as a value, not as a reference • A component can be saved directly without needing to declare interfaces or

identifier properties • Required to define an empty constructor • Shared references not supported

Nazar BabuNazar Babu 95

Page 96: Final Java Faqs

Java TechnoloiesJava Technoloies

Example:

30.What is the difference between sorted and ordered collection in hibernate?

sorted collection vs. order collection :-

sorted collection order collection

A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.

Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.

If your collection is not large, it will be more efficient way to sort it.

If your collection is very large, it will be more efficient way to sort it .

31.What is the advantage of Hibernate over jdbc?

Hibernate Vs. JDBC :-

JDBC Hibernate

With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

Nazar BabuNazar Babu 96

Page 97: Final Java Faqs

Java TechnoloiesJava Technoloies

With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.

Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.

Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table.

Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

With JDBC, caching is maintained by hand-coding.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every

Nazar BabuNazar Babu 97

Page 98: Final Java Faqs

Java TechnoloiesJava Technoloies

time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?

• Bag • Set • List • Array • Map

33.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

• An implicit association join • An ordinary join in the FROM clause • A fetch join in the FROM clause. • A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.inverse="true|false"

Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

Nazar BabuNazar Babu 98

Page 99: Final Java Faqs

Java TechnoloiesJava Technoloies

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

• dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed

• dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ?

A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

40.What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

41.What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

42.What are Callback interfaces?

Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded,

Nazar BabuNazar Babu 99

Page 100: Final Java Faqs

Java TechnoloiesJava Technoloies

saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ?

Three types of instance states:

• Transient -The instance is not associated with any persistence context • Persistent -The instance is associated with a persistence context • Detached -The instance was associated with a persistence context which has

been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate?

Hibernate Vs EJB 3.0 :-

Hibernate EJB 3.0

Session–Cache or collection of loaded objects relating to a single unit of work

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit

XDoclet Annotations used to support Attribute Oriented Programming

Java 5.0 Annotations used to support Attribute Oriented Programming

Defines HQL for expressing queries to the database

Defines EJB QL for expressing queries

Supports Entity Relationships through mapping files and annotations in JavaDoc

Support Entity Relationships through Java 5.0 annotations

Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API

Provides and Entity Manager Interface for managing CRUD operations for an Entity

Provides callback support through lifecycle, interceptor, and validatable interfaces

Provides callback support through Entity Listener and Callback methods

Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships

Entity Relationships are bidirectional or unidirectional

45.What are the types of inheritance models in Hibernate?

There are three types of inheritance models in Hibernate:

• Table per class hierarchy

• Table per subclass

• Table per concrete class

Nazar BabuNazar Babu 100

Page 101: Final Java Faqs

Java TechnoloiesJava Technoloies

1.What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and

query service. This lets the users to develop persistent classes following object-

oriented principles such as association, inheritance, polymorphism, composition, and

collections.

2.What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and

translucent perseverance of objects in a Java application in to the tables of a

relational database using the metadata that describes the mapping between the

objects and the database. It works by transforming the data from one representation

to another.

3.What does an ORM solution comprises of?

• It should have an API for performing basic CRUD (Create, Read, Update, Delete)

operations on objects of persistent classes

• Should have a language or an API for specifying queries that refer to the classes

and the properties of classes

• An ability for specifying mapping metadata

• It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4.What are the different levels of ORM quality?

There are four levels defined for ORM quality. i. Pure relational ii. Light object mapping iii. Medium object mapping iv. Full object mapping

5.What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6.What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities,

Nazar BabuNazar Babu 101

Page 102: Final Java Faqs

Java TechnoloiesJava Technoloies

or applications with common, metadata-driven data models. This approach is most known to all.

7.What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8.What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

9.What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most

important one.

i. Productivity - Hibernate reduces the burden of developer by providing much of

the functionality and let the developer to concentrate on business logic.

ii. Maintainability - As hibernate provides most of the functionality, the LOC for the

application will be reduced and it is easy to maintain. By automated object/relational

persistence it even reduces the LOC.

iii. Performance - Hand-coded persistence provided greater performance than

automated one. But this is not true all the times. But in hibernate, it provides more

optimization that works all the time there by increasing the performance. If it is

automated persistence then it still increases the performance.

iv. Vendor independence - Irrespective of the different types of databases that are

there, hibernate provides a much easier way to develop a cross platform application.

10.How does hibernate code looks like?

Session session = getSessionFactory().openSession();Transaction tx = session.beginTransaction();MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");session.save(mpc);tx.commit();session.close();

Nazar BabuNazar Babu 102

Page 103: Final Java Faqs

Java TechnoloiesJava Technoloies

The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.

11.What is a hibernate xml mapping document and how does it look like?

In order to make most of the things work in hibernate, usually the information is

provided in an xml document. This document is called as xml mapping document.

The document defines, among other things, how properties of the user defined

persistence classes' map to the columns of the relative tables in database.

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

<class name="sample.MyPersistanceClass" table="MyPersitaceTable">

<id name="id" column="MyPerId">

<generator class="increment"/>

</id>

<property name="text" column="Persistance_message"/>

<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>

</class>

</hibernate-mapping>

Everything should be included under <hibernate-mapping> tag. This is the main tag

for an xml mapping document.

12.Show Hibernate overview?

Nazar BabuNazar Babu 103

Page 104: Final Java Faqs

Java TechnoloiesJava Technoloies

13.What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most

important one.

i. Session Interface - This is the primary interface used by hibernate applications.

The instances of this interface are lightweight and are inexpensive to create and

destroy. Hibernate sessions are not thread safe.

ii. SessionFactory Interface - This is a factory that delivers the session objects to

hibernate application. Generally there will be a single SessionFactory for the whole

application and it will be shared among all the application threads.

iii. Configuration Interface - This interface is used to configure and bootstrap

hibernate. The instance of this interface is used by the application in order to specify

the location of hibernate specific mapping documents.

iv. Transaction Interface - This is an optional interface but the above three

interfaces are mandatory in each and every application. This interface abstracts the

code from any kind of transaction implementations such as JDBC transaction, JTA

transaction.

v. Query and Criteria Interface - This interface allows the user to perform queries

and also control the flow of the query execution.

14.What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they're useful for implementing certain kinds of generic functionality.

15.What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

16.What are the Extension interfaces that are there in hibernate?

• There are many extension interfaces provided by hibernate.

• ProxyFactory interface - used to create proxies

• ConnectionProvider interface - used for JDBC connection management

• TransactionFactory interface - Used for transaction management

• Transaction interface - Used for transaction management

Nazar BabuNazar Babu 104

Page 105: Final Java Faqs

Java TechnoloiesJava Technoloies

• TransactionManagementLookup interface - Used in transaction management.

• Cahce interface - provides caching techniques and strategies

• CacheProvider interface - same as Cache interface

• ClassPersister interface - provides ORM strategies

• IdentifierGenerator interface - used for primary key generation

• Dialect abstract class - provides SQL support

17.What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs. i. Managed environment - In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere. ii. Non-managed environment - This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

18.What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filename.hbm.xmlThe filename varies here. The extension of these files should be ".hbm.xml".This is just a convention and it's not mandatory. But this is the best practice to follow this extension.

19.What do you create a SessionFactory?

Configuration cfg = new Configuration();

cfg.addResource("myinstance/MyConfig.hbm.xml");

cfg.setProperties( System.getProperties() );

SessionFactory sessions = cfg.buildSessionFactory();

First, we need to create an instance of Configuration and use that instance to

refer to the location of the configuration file. After configuring this instance is used to

create the SessionFactory by calling the method buildSessionFactory().

20.What is meant by Method chaining?

Method chaining is a programming technique that is supported by many

hibernate interfaces. This is less readable when compared to actual java code. And it

is not mandatory to use this format. Look how a SessionFactory is created when we

use method chaining.

SessionFactory sessions = new

Nazar BabuNazar Babu 105

Page 106: Final Java Faqs

Java TechnoloiesJava Technoloies

Configuration().addResource("myinstance/MyConfig.hbm.xml").setProperties(

System.getProperties() ).buildSessionFactory();

21.What does hibernate.properties file consist of?

This is a property file that should be placed in application class path. So when

the Configuration object is created, hibernate is first initialized. At this moment the

application will automatically detect and read this hibernate.properties file.

hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB

hibernate.transaction.factory_class =

net.sf.hibernate.transaction.JTATransactionFactory

hibernate.transaction.manager_lookup_class =

net.sf.hibernate.transaction.JBossTransactionManagerLookup

hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

22.What should SessionFactory be placed so that it can be easily accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed

in JNDI then it can be easily accessed and shared between different threads and

various components that are hibernate aware. You can set the SessionFactory to a

JNDI by configuring a property hibernate.session_factory_name in the

hibernate.properties file.

23.What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that

have defined setter and getter methods for all the properties that are there in that

bean. Besides they can also have some business logic related to that property.

Hibernate applications works efficiently with POJOs rather then simple java classes.

24.What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the

mapping between classes and tables, properties and columns, associations and

foreign keys, Java types and SQL types. This information is called the

object/relational mapping metadata. It defines the transformation between the

different data type systems and relationship representations.

25.What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express

queries in its own portable SQL extension and this is called as HQL. It also allows the

user to express in native SQL.

Nazar BabuNazar Babu 106

Page 107: Final Java Faqs

Java TechnoloiesJava Technoloies

26.What are the different types of property and class mappings?

• Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

Or

<property name="description" type="string">

<column name="DESCRIPTION"/>

</property>

• Derived properties

<property name="averageBidAmount" formula="( select

AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )"

type="big_decimal"/>

• Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

• Controlling inserts and updates

<property name="name" column="NAME" type="string"

insert="false" update="false"/>

27.What is Attribute Oriented Programming?

XDoclet has brought the concept of attribute-oriented programming to Java.

Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses

the Javadoc tag format (@attribute) to specify class-, field-, or method-level

metadata attributes. These attributes are used to generate hibernate mapping file

automatically when the application is built. This kind of programming that works on

attributes is called as Attribute Oriented Programming.

28.What are the different methods of identifying an object?

There are three methods by which an object can be identified.

i. Object identity -Objects are identical if they reside in the same memory location

in the JVM. This can be checked by using the = = operator.

ii. Object equality - Objects are equal if they have the same value, as defined by

the equals( ) method. Classes that don't explicitly override this method inherit the

implementation defined by java.lang.Object, which compares object identity.

iii. Database identity - Objects stored in a relational database are identical if they

represent the same row or, equivalently, share the same table and primary key

value.

Nazar BabuNazar Babu 107

Page 108: Final Java Faqs

Java TechnoloiesJava Technoloies

29.What are the different approaches to represent an inheritance

hierarchy?

1. Table per concrete class.

2. Table per class hierarchy.

3. Table per subclass.

30.What are managed associations and hibernate associations?

Associations that are related to container management persistence are called

managed associations. These are bi-directional associations. Coming to hibernate

associations, these are unidirectional.

Q: What is Hibernate?

A: Hibernate is a java-based Object/relational mapping(ORM) tool.

Q: What are ORM tools?

A: ORM tools provide automated solutions for the Object/relational paradigm

mismatch problem, using metadata that describes the mapping between the objects

and the database.

Q: What is Object/relational paradigm mismatch?

A: Object-Oriented paradigm is based on software engineering principles, whereas

relational paradigm on mathematical principles. Object-oriented technology supports

the building of applications out of networks of objects with both data and behavior.

Relational technology supports the storage of data in tables and manipulation of that

data using data manipulation language (DML). Because the underlying paradigms are

different the two technologies do not work seamlessly, hence the name

Object/relational paradigm mismatch.

Q: What role does the Session interface play in Hibernate?

A: The Session is a persistence manager that manages operation like storing and

retrieving objects. Instances of Session are inexpensive to create and destroy. They

are not threadsafe.

Q: What is SessionFactory interface?

A: The application obtains Session instances from a SessionFactory. SessionFactory

instances are not lightweight and typically one instance is created for the whole

application. If the application accesses multiple databases, it needs one per database

Q: What is Configuration interface?

A: The application uses a Configuration instance to specify the location of mapping

Nazar BabuNazar Babu 108

Page 109: Final Java Faqs

Java TechnoloiesJava Technoloies

documents and Hibernate-specific properties and then creates the SessionFactory.

Q: What is the naming convention for Hibernate XML mapping file extensions?

A: .hbm.xml

Q: What are the most common methods of configuring Hibernate?

A: 1. By placing hibernate.properties file in the classpath.

2. Including <property> elements in hibernate.cfg.xml in the classpath.

Q: How can the mapping files be configured in Hibernate?

A: 1. Mapping files can be added to Configuration in the application code or,

2. They can be configured in hibernate.cfg.xml using the <mapping> elements.

Q: What happens when both hibernate.properties and hibernate.cfg.xml are in the

classpath?

A: The settings of the XML configuration file will override the settings used in the

properties.

Q: Since SessionFactory instances are not lightweight, where is the single created

instance placed in J2EE environments?

A: Usually it is bound to JNDI, it will bind itself automatically if

hibernate.session_factory_name is set to the name of directory node.

Q: How to set Hibernate to log all generated SQL to the console?

A: By setting the hibernate.show_sql property to true.

Q: In hibernate, what interfaces/classes must the persistent classes (classes that are

mapped to database tables) implement/extend?

A: NONE, they can be regular POJOs.

Q: Does hibernate require persistent classes to implement Serializable?

A: Hibernate doesn't require that persistent classes implement Serializable. However,

when objects are stored in an HttpSession or passed by value using RMI,

serialization is necessary.

Q: What methods must the persistent classes implement in Hibernate?

A: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it

requires a constructor with no arguments for every persistent class. And getter and

setter methods for all the instance variables.

Q: How can Hibernate be configured to access a instance variable directly and not

through a setter method?

A: By mapping the property with access="field" in Hibernate metadata. This forces

hibernate to bypass the setter method and access the instance variable directly while

initializing a newly loaded object.

Nazar BabuNazar Babu 109

Page 110: Final Java Faqs

Java TechnoloiesJava Technoloies

Q: What is dirty checking in Hibernate?

A: Hibernate automatically detects object state changes in order to synchronize the

updated state with the database, this is called dirty checking. An important note here

is, Hibernate will compare objects by value, except for Collections, which are

compared by identity. For this reason you should return exactly the same collection

instance as Hibernate passed to the setter method to prevent unnecessary database

updates.

Q: What is the root level element in a hibernate mapping file?

A:<hibernate-mapping>

Q: Is it possible to declare mappings for multiple classes in one mapping file?

A: Yes, by using multiple <class> elements. But, the recommended practice is to use

one mapping file per persistent class.

Q: How are the individual properties mapped to different table columns?

A: By using multiple <property> elements inside the <class> element.

Q: What are derived properties?

A: The properties that are not mapped to a column, but calculated at runtime by

evaluation of an expression are called derived properties. The expression can be

defined using the formula attribute of the <property> element.

Q: How can you make a property be read from the database but not modified in

anyway (make it immutable)?

A: By using the insert="false" and update="false" attributes.

Q: How can a whole class be mapped as immutable?

A: By using the mutable="false" attribute in the class mapping.

Q: What is the use of dynamic-insert and dynamic-update attributes in a class

mapping?

A: They tell hibernate whether to include unmodified properties in SQL INSERT and

SQL UPDATE.

Q: How do you achieve table-per-class hierarchy while mapping classes in

Hibernate?

A: By using several <subclass> elements one for each sub-class inside the <class>

element. The <subclass> class element can in turn contain other <subclass>

elements.

Q: How do you achieve table-per-subclass while mapping classes in Hibernate?

A: By using <joined-subclass> element inside the <class> element. A <joined-

subclass> element may contain other <joined-subclass> elements.

Nazar BabuNazar Babu 110

Page 111: Final Java Faqs

Java TechnoloiesJava Technoloies

Q: Does hibernate allow mixing table-per-class hierarchy and table-per-subclass

strategies?

A: No, you cannot have a <joined-subclass> inside <subclass> and vice versa.

1.What is different between Hibernate and iBatis?

Ans:

1. Hibernate works well when you control the data model, iBatis works well when you

need to intergate with an existing database,

2. With IBatis you will get full control on SQL but hibenate deals with relationships of

tables.

2.Why Hibernate came in to picture

Anybody tell me please, where exactly Hibernate is used..tell me about the mapping

and .xml file in Hibernate

Ans: To make the application developemnt more productive. its saves development

time and also mainly it deals with Objects(POJO) . and .xml file is nuthing but

mapping between database column and POJO variable. you can easily switch the

database like MySql ...

3.Lazy initialisation (what is lazy initialisation in hibernate )

Ans: when loading an obj that has a collection, hibernate loads collection elements

ONLY when actually you ask for them; so this improves performance, among other

advantages.when u use hibernate u can make lazy=true or lazy=false. ...

4.Execute Stored procedure in Hibernate

How to invoke a stored procedure in Hibernate and pass in a parameter?I have { ? =

call myservice.TEST_PROC3( ? ) }While I can get stored proc output if there is no

input to TEST_PROC3, e.g. call

Ans: You can declare it as Named queiries in one of your mapping files and give

unique name.Call it in your code. Sample code is below.SQLQuery sq = (SQLQuery)

session.getNamedQuery("findSearchResultsListSP");sq.addEntity("documentTypeCod

e", ...

5.What J2EE design problems does Hibernate solves apart from Data Base in-

dependency and being an ORM

What J2EE design problems does Hibernate solves apart from Data Base in-

dependency and being an ORM tool?

Nazar BabuNazar Babu 111

Page 112: Final Java Faqs

Java TechnoloiesJava Technoloies

6.Why Hibernate is advantageous over Entity Beans & JDBC?

Ans: Hibernate and EJB have different purpose.EJB is for writing business logic as

well and provide Database independency just as hibernate provide for us.EJB infact

use the container services(EJB container) like transaction, securiry etc as well.Which

is ...

7.What is the difference between and merge and update

Ans: Update():- if you are sure that the session does not contains an already

persistent instance with the same identifier,then use update to save the data in

hibernateMerge():-if you want to save your modificatiions at any time with out

knowing abot ...

8.What is Hibernate proxy?

Ans: Proxies are created dynamically by subclassing your object at runtime. The

subclass has all the methods of the parent, and when any of the methods are

accessed, the proxy loads up the real object from the DB and calls the method for

you. Very nice in ...

9.What is the difference between hibernate and spring JDBC template? List any

advantages and disadvantages

What is the difference between hibernate and spring JDBC template? List any

advantages and disadvantages

10.What is the main difference between Entity Beans and Hibernate ?

Ans: 1)Â In Entity Bean at a time we can interact with only one data Base. Where

as in Hibernate we can able to establishes the connections to more than One Data

Base. Only thing we need to write one more configuration file.  2) Entity Beans

does not support ...

11.How are joins handled using HQL.

Ans: HQL provides four ways of expressing (inner and outer) joins:1) An ordinary

join in the from clause2) A fetch join in the from clause3) A theta-style join in the

where clause4) An implicit association join ...

12.How does Hibrnate maintain relations of RDBMS

Ans: Those are .. 1Â to many, many to many, many to one.. relations. these

relational mappings are done by using the hibernates utilities such as list, set, bags,

object... In detail Go thru.... www.hibernate.org ...

Nazar BabuNazar Babu 112

Page 113: Final Java Faqs

Java TechnoloiesJava Technoloies

13.How to use hibernate in NetBeans IDE?

Ans: Add the hibernate related jar files into lib directory of any web application using

net beans.http://www.netbeans.org/kb/41/hibernate.html ...

14.What is the use of cascade in hbm file?

Ans: cascade specifies which operations should be casecaded from the parent object

to the associated object. The meaningfull values would be persist , merge, delete,

save_update, evict , replicate, lock , refresh , all , delete_orphan. ...

15.What is the difference between hibernate and Spring

Ans: Hibernate is ORM tool used for data persistency.Spring is a framework for

enterprise applications with default APIs for presentation, middle tiers and

presistence layers and allows to integrate with various presentations, middle tier and

presistence APIs ...

16.What is database persistence?How well it is implemented in Hibernate

Ans: Preserving the data inside a database is database persistence. Persistence is

once of the fundamental concepts of application developement. There are many

alternatives to implement persistence. Object/relational mapping (ORM) is the

technique that Hibernate ...

17.What is the difference between beans and hibernate(which one is good)?

Ans: Its is one of the most popular ORM technology available to date in the

market.Java bean is a simple resuble component. There is no persistency on bean

hibernate provides the service to make the bean persistent so that we can make use

of it. In hibernate ...

18.What is the latest version of Hibernate using in current industry?

Ans: Hibernate 3.2 ...

19.What is the advantage of Hibernate over jdbc?

Ans: 1) Hiberante is not tightly tied with any underlaying database.Where as JDBC is

tighlty tield with the underlaying database."Write Once presist anywhere" using

hibernate can achieved by changing the dialect in configuration xml file.where as ...

20.How to create primary key using hibernate?

Ans: We can also specify primary key using annotations in the POJO

using:@javax.persistence.Id before the appropriate field in POJO with @Column

@Id@Column(name="user_id") ...

Nazar BabuNazar Babu 113

Page 114: Final Java Faqs

Java TechnoloiesJava Technoloies

21.What is the main advantage of using the hibernate than using the sql

Ans: Hibernate is based on object oriented concept like java. so it has better

compatibility with java than sql.In Jdbc we have to mannualy handle exception and

every time we need to open/cose the connection,create/close the statement ,

resultset whatever ...

22.What is the difference between sorted and orderd collection in hibernate?

Ans: A component is an object saved as a value, not as a reference A component

can be saved directly without needing to declare interfaces or identifier properties

Required to define an empty constructor Shared references not supported ...

23.Why do you need ORM tools like hibernate?

Ans: Basically we need Hibernate like tools for the purpose of developing the

application in short period of time. The product like Hibernate used for the

productivity. When large amount of data have to handle that time instead of using

JDBC we used Hibernate. ...

24.How do you handle the situation where persistence class attribute name is one of

the reserved keyword

How do you handle the situation where persistence class attribute name is one of the

reserved keyword in database; e.g. user ? Will this cause any issue while hibenrate

executes SQL statements behind the scene?

25.What is component mapping in hibernate?

Ans: A component is a contained object that is persisted as a value type ,not an

entity reference.eg)public class person{private Name name;public Name getName(){

return name;}public void setName(Name name){this.name=name;}.....}public class

Name{chat initial;String ...

26.How JPA and hibernate are related as per EJB 3 specifications?

Ans: first things first ..i have just seen ppl venting thier personal grudge over java /

jpa or whatever over this forum.suns official sacceptence that jpa is a failure. please

lets keep it out.as for the answer , JPA is a specification , its nt a frame work ...

27.What is lazy fetching in hibernate

Ans: There are two types of Loading in application. Eager loading and Lazy loading.

In eager loading we will fetch all the values from the Persistent storage and cache it.

It will make serious performance issues. There we use lazy loading to avoid that ...

Nazar BabuNazar Babu 114

Page 115: Final Java Faqs

Java TechnoloiesJava Technoloies

Q1: What is the difference between Hibernate and EJB 2.1? Q2: Which one, among

EJB 2.1 and Hibernate,

Q1: What is the difference between Hibernate and EJB 2.1?

Q2: Which one, among EJB 2.1 and Hibernate, is better?Explain with reason.

Q3: When to use EJB 2.1 and when to use Hibernate? Explain with scenarios.

I am using hibernate.What is the use In Data(POJO) class primary key is sending as

an argument with

I am using hibernate.What is the use In Data(POJO) class primary key is sending as

an argument with constructor?

Nazar BabuNazar Babu 115

Page 116: Final Java Faqs

Java TechnoloiesJava Technoloies

E J B E J B

Q: What is the J2EE?

The J2EE is a set of coordinated specifications and practices that together enable solutions for developing, deploying and managing multi-tier server-centric applications.

Q) What is enterprise java bean? Why ejb?

A) It’s a collection of java classes and xml descriptor files bundled together as a unit. The java classes must provide certain rules and call back methods as per ejb specifications.When the application is so complex and requires certain enterprise level services such as concurrency, scalability, transaction services, resource pooling, security, fail-over, load-balancing ejb is the right choice.

Q) New in EJB 2.1?

Message-driven beans (MDBs): can now accept messages from sources other than JMS. EJB query language (EJB-QL): many new functions are added to this language: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD. Support for Web services: stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference. EJB timer service: a new event-based mechanism for invoking EJBs at specific times. Many small changes: support for the latest versions of Java specifications, XML schema, and message destinations.

Q) Application server & Web server A.S is a generalized server for running more than one application like ejb, rmi, jsp and servlets. W.S is for request, response paradigm. It takes the client request and send response back to the client and the connection is closed. A.S cannot process Http request, but takes the forwarded request from W.S and process the business logic and send the output to the W.S which it turns send to the client. W.S understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols. A.S manage transactions, security, persistence, clustering, caching, but W.S cannot help in this regards. W.S takes only the Http request. A.S provides runtime environment for server side components, they provide middleware services such as resource pooling and network.

Q) What does Container contain?

Nazar BabuNazar Babu 116

Page 117: Final Java Faqs

Java TechnoloiesJava Technoloies

A) 1. Support for Transaction Management, 2. Support for Security 3. Support for Persistence 4. Support for management of multiple instances (Instance passivation, Instance Pooling, Database connection pooling)5. Life Cycle Management

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

Q) Statefull Session Bean & Stateless Session Bean

Q) Entity BeanEntity 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.

Bean managed Persistence & Container managed Persistence B.P is an entity bean that must be persisted by hand, other words component developer must write the code to translate your in-memory fields into an underlying

Nazar BabuNazar Babu 117

Stateless Session Bean Stateful Session BeanStateless session bean these are single request business process is one that does not require state to be maintained across method invocation. Stateless session bean cannot hold the state.

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.

There should be one and only one create method that to without any argument in the home interface.

There can be one or more create methods with or without arguments in the Home Interface.

Stateless session bean instance can be pooled. Therefore “n” number of beans can cater to n+1 number of clients.

Statefull session bean do not have pooling concept. Stateful bean will be given individual copy for every user.

Stateless bean will not be destroyed after client has gone.

Stateful bean will be destroyed once the client has gone (or after session time out)

If the business last only for a single method call, S.S.B are suitable

If the business process spans multiple invocations there by requiring a conversational then S.S.B will be ideal choice.

Stateless session bean cannot have instance variable

Stateful session bean will have instance variable and state is maintained in these instance variables

EjbRemove() method does not destroy the bean , it remains in the pooled state.

Stateful bean can be destroyed by calling the ejbRemove() method

Page 118: Final Java Faqs

Java TechnoloiesJava Technoloies

data store. You handle these persist operations your self, you place your data base calls in ejbLoad() and ejbStore(). Finder methods only for B.M.P for C.M.P your ejb container will implement the finder methods. In this commit, rollback, begin are transactions In B.M.P findByPK() return a reference to the actual bean object. You do not have to do anything to synchronize with database. In entity bean deployment descriptor you specify which fields that the container should manage. The transactions in C.M.P are TX-Support, TX-NotSupport, TX-require. He findByPK() in C.M.P return void because the method is internally implemented.

Q) Message Driven Bean M.D.B process messages asynchronously are deliver via JMS. M.D.B’s are stateless, server side, transaction aware components used for asynchronous JMS messages. It acts as a JMS message listener which JMS messages, the messages may be sent by any J2ee component, an application client, another enterprise bean, or by a JMS application. When EJB application server starts it parse the D.D and then loads and initializes declared beans. In case of M.D.B container establish a connection with the message provide(MOM server), client access message beans through the beans JMS interface (java.JMS.messageListerner) which exposes a single method.Public void onmessage(javax.JMS.message message)

Q) Diff Statefull Session & Entity Bean?Both S.S.B & E.B undergo passivation and activation. The E.B have a separate

ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation. We do not need these callbacks for S.S.B because the container is simply uses object serialization to persist S.S.B fields.

Q) Diff MDB & Stateless Session beans?- MDB’s process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. - MDB have no H.I / R.I, and therefore cannot be directly accessed by internal or external clients. Clients interact with MDB’s only indirectly, by sending a message to a JMS Queue or Topic. - Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary-The Container maintains the entire lifecycle of a MDB; instances cannot be created or removed as a result of client requests or other API calls.

Q) When to choose Statefull & Stateless Session bean?A) Does the business process span multiple method invocations, requiring a conversational state if so the state full model fits very nicely. If your business process last for a single method call the stateless paradigm will better suite needed.

Q) When to choose Session Bean & Entity Bean? E.B are effective when application want to access one row at a time, if many rows needed to be fetched using session bean can be better alternative. E.B are effective when working with one row at a time cause of lot of N.W traffic. S.B are efficient when client wants to access database directly, fetching, updating multiple rows from database. S.B for application logic.

Q) When to choose CMP & BMP?

Nazar BabuNazar Babu 118

Page 119: Final Java Faqs

Java TechnoloiesJava Technoloies

CMP is used when the persistent data store is a relational database and there is “one to one” mapping between a data represented in a table in the relational database and the ejb object.

Bean managed persistence is used when there is no “one to one” mapping of the table and a complex query retrieving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the persistence data storage is not a relational database.

Q) How do Stateful Session beans maintain consistency across transaction updates?A) S.S.B maintain data consistency by updating their fields each time a transaction is committed. To keep informed of changes in transation status, a S.S.B implements the SessionSynchronization interface. Container then calls methods of this interface as it initiates and completes transactions involving the bean.

Q) Can't stateful session beans persistent? Is it possible to maintain persistence temporarily in stateful sessionbeans?A) Session beans are not designed to be persistent, whether stateful or stateless. A stateful session bean instance typically can't survive system failures and other destructive events.Yes, it is possible using Handle.

Q) Object-Relational MappingMapping 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 DescriptorD.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.

Q) Can a Session Bean be defined without ejbCreate() method?The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not

return an error because there is no ejbCreate() method.

- 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

Q) Can I develop an Entity Bean without implementing the create() method in the home interface?

As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. In cases where create() method is not provided, the only

Nazar BabuNazar Babu 119

Page 120: Final Java Faqs

Java TechnoloiesJava Technoloies

way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke business methods.

Q) How do you determine whether two entity beans are the same?

A) By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object.

Q) How can you capture if findBy method returns more than one row?A) If finder method returns more than one row, create or instantiate an object (which has instance variable equal to number of columns to be stored) each time and add the object to vector that stores. Vector stores only the memory address not object reference. So every time when you instantiate and store object into vector a separate memory address will be allocated and the same is stored in the vector.

Q) Diff Context, InitialContext & SessionContext & EntityContextjavax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.

There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Where as, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

Q) Can i call remove() on a Stateless Session bean?A) Yes, The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the bean…after the execution of that method if the client calls another method, then a different bean is taken from the pool. So the container very well knows that a bean has finished its life for a client and can put it back in the pool.

Q) Can a Stateless Session Bean maintain state?A) Yes, A Stateless Session bean can contain no-client specific state across client-invoked methods. For ex states such as socket connection, dbase connection, references to an EJBObject and so on can be maintained.

Nazar BabuNazar Babu 120

Page 121: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) How can I map a single Entity Bean to multiple tables?A) If you use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this. If you choose Container-Managed Persistence(CMP), use the vendors object/relational mapping tool to specify the mapping between your object state and the persistence schema.

Q) Can EJB handle transaction across multiple databases?A) The transaction manager in EJB handling transaction across multiple databases. This is accomplished with multiple Entity beans handling to each database and a single session bean to manage a transaction with the Entity bean.

Q) Session Bean CallBack methods?public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean{ public abstract void ejbActivate(); public abstract void ejbCreate(); public abstract void ejbPassivate(); public abstract void ejbRemove(); public abstract void setSessionContext(SessionContext ctx);}

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, i.e. 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();}

Nazar BabuNazar Babu 121

Page 122: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) EJBContext Rollback Methods

EJBContext interface provides the methods setRollbackOnly() & getRollbackOnly().setRollbackOnly( )Once a bean invokes the setRollbackOnly() method, the current transaction is marked for rollback and cannot be committed by any other participant in the transaction--including the container.getRollbackOnly( ) method returns true if the current transaction has been marked for rollback. This can be used to avoid executing work that wouldn't be committed anyway.

Q) How can I call one EJB from inside of another EJB?A) EJB can be clients of another EJB’s it just works. Use JNDI to locate the Home Interface of the other bean, and then acquire an instance.

Q) Conversational & Non-conversationalConversational is an interaction between the bean and client, stateless session bean is a bean that do not hold multi method conversation with clients. Stateless.S.B cannot hold state, Statefull.S.B can hold conversational with client that may span multiple method requests.

Q) JNDI to locate Home ObjectsH.O are physically located some where on the N.W, perhaps in the address space of the Ejb Container. For client to locate H.O, you must provide nick name for your beans H.O. Client will use this nick name to identify the H.O it wants, we will specify the nice name in the Deployment descriptor. Container will use this nick name, JNDI goes over the N.W to some directory service to look for the H.O. Properties props = System.getProperties();Context ctx = new InitialContext(props);MyHome home = (MyHome)ctx.lookup(“MyHome”);MyRemoteInterface remote = home.create();

Q) ejbCretae( ) & ejbPostCreate( ) ejbCreate() is called just before the state of the bean is written to the persistence storage. After this method is completed a new record is created and written. ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an Ejb object.

Q) EAR, WAR, JAR All EJB classes should package in a JAR file, All web components pages, servlets, gif, html, applets, beans, ejb modules, classes should be packaged into WAR file. EAR file contain all the JAR & WAR files. Note that each JAR, WAR, EAR file will contain D.D

Q) What is the need of Remote and Home interface. Why cant it be in one?The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and beans) and you need two different interfaces for accessing to both of them.

Nazar BabuNazar Babu 122

Page 123: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) L ife cycle

L ife cycle of a Stateful Session Bean

- 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

L ife cycle of a Stateless Session Bean : -

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

Nazar BabuNazar Babu 123

Page 124: Final Java Faqs

Java TechnoloiesJava Technoloies

- 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

-

Nazar BabuNazar Babu 124

Page 125: Final Java Faqs

Java TechnoloiesJava Technoloies

Life cycle of M.D.B

Does Not ExistWhen an MDB instance is in the Does Not Exist state, it is not an instance in the memory of the system. In other words, it has not been instantiated yet.

The Method-Ready Pool

MDB instances enter the Method-Ready Pool as the container needs them. When the EJB server is first started, it may create a number of MDB instances and enter them into the Method-Ready Pool. (The actual behavior of the server depends on the implementation.) When the number of MDB instances handling incoming messages is insufficient, more can be created and added to the pool.

Transitioning to the Method-Ready Pool

When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are performed on it. First, the bean instance is instantiated

Nazar BabuNazar Babu 125

Page 126: Final Java Faqs

Java TechnoloiesJava Technoloies

when the container invokes the Class.newInstance() method on the MDB class. Second, the setMessageDrivenContext() method is invoked by the container providing the MDB instance with a reference to its EJBContext. The MessageDrivenContext reference may be stored in an instance field of the MDB.Finally, the no-argument ejbCreate() method is invoked by the container on the bean instance. The MDB has only one ejbCreate() method, which takes no arguments. The ejbCreate() method is invoked only once in the life cycle of the MDB.

Q) Transaction Isolation levels

TRANSACTION_READ_UNCOMMITTEDThe 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_SERIALIZABLEThe 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 Phantom is a new set of data that magically appears in a database between two databases read operations.

Q) Diff Phantom & Un-repeatable Un-repeatable occurs when existing data is changed, where as phantom read

occurs when new data is inserted that does not exist before.

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.

Nazar BabuNazar Babu 126

Page 127: Final Java Faqs

Java TechnoloiesJava Technoloies

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 PropertiesWhen you properly use transaction your operations will execute ACID

properties.

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.

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

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.

Durability Resources keep a transactional log for resources crashes; the permanent data can be reconstructed by reapplying the steps in the log.

Nazar BabuNazar Babu 127

Page 128: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Diff SAX & DOM

DOM SAX1. Tree of nodes2. Occupies more memory

preferred for small XML documents

3. Slower at runtime4. Stored as objects5. Programmatically easy, since

objects6. Easy of navigation7. DOM creates a tree structure in

memory

1.Sequence of events2.Does not use any memory preferred for large documents.3.Faster at runtime4.Objects are to be created5.Need to write code for creating objects are to referred6.backward navigation is not possible

Q) Hot deployment Hot Deployment in Web Logic is he acts of deploying, re-deploying and un-deploying EJBs while the server is still running.

Q) When should I use TxDataSource instead of Datasource? If your application (or) environment meets the following criteria you should use - Uses JTA- Uses EJB container in web logic server to manage transactions.- Includes multiple database updates with single transaction.- Access multiple resources, such as database & JMS during transactions.- Use same connection pool on multiple servers.

Q) Clustering In J2ee container can be distributed, a distributed container consists 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.

Q How to deploy in J2EE (i.e Jar, War file)? 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.

Nazar BabuNazar Babu 128

Page 129: Final Java Faqs

Java TechnoloiesJava Technoloies

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.

Q) How do you configure a session bean for bean-managed transactions?

A) By set transaction-attribute in the xml file or in the deployment descriptor.

Q) Deployment descriptor of EJB (ejb-jar.xml)<?xml version="1.0"?><!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD EnterpriseJavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

<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></enterprise-beans><! – Transactions in EJB -- >

Nazar BabuNazar Babu 129

Page 130: Final Java Faqs

Java TechnoloiesJava Technoloies

<assembly-descriptor> <container-transaction> <method> <ejb-name>EJBName</ejb-name> <method-name>methodName / *</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> ...</ejb-jar>

Q) Weblogic-ejb-jar.xml<weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>demo.Story</ejb-name> <entity-descriptor> <entity-cache> <max-beans-in-cache>100</max-beans-in-cache> <idle-timeout-seconds>600</idle-timeout-seconds> <read-timeout-seconds>0</read-timeout-seconds> <concurrency-strategy>Database</concurrency-strategy> </entity-cache> <lifecycle> <passivation-strategy>default</passivation-strategy> </lifecycle> <persistence> <delay-updates-until-end-of-tx>true</delay-updates-until-end-of-tx> <finders-load-bean>true</finders-load-bean> <persistence-type> <type-identifier>WebLogic_CMP_RDBMS</type-identifier> <type-version>5.1.0</type-version> <type-storage>META-INF/weblogic-rdbms11-persistence-600.xml</type-storage> </persistence-type> <db-is-shared>true</db-is-shared> <persistence-use> <type-identifier>WebLogic_CMP_RDBMS</type-identifier> <type-version>5.1.0</type-version> </persistence-use> </persistence> <entity-clustering> <home-is-clusterable>true</home-is-clusterable> </entity-clustering> </entity-descriptor> <transaction-descriptor> <trans-timeout-seconds>30</trans-timeout-seconds> </transaction-descriptor> <enable-call-by-reference>true</enable-call-by-reference> <jndi-name>demo.StoryHome</jndi-name> </weblogic-enterprise-bean></weblogic-ejb-jar>

Nazar BabuNazar Babu 130

Page 131: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) Session Bean Example

Remote Interface public interface Hello extends javax.ejb.EJBObject {

public String hello() throws java.rmi.RemoteException; } Home Interface public interface HelloHome extends javax.ejb.EJBHome {

Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException; }

Bean Class public class HelloBean implements javax.ejb.SessionBean {

private SessionContex ctx;public void ejbCreate();public abstract void ejbRemove();public abstract void ejbActivate();public abstract void ejbPassivate();public abstract void setSessionContext(SessionyContext ctx);

public String hello(){System.out.println(“hello()”);Return “hello world”;

}

Client public class HelloClient {

public static void main(String args[ ])properties props = system.getProperties();Context ctx = new InitialContext(props);Object obj = ctx.lookup(“HelloHome”);HelloHome home = (HelloHome) javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class);Hello hello = home.create();System.out.println(hello.hello());Hello.remove();

}

Q) Entity Bean Example

Home.java (Home Interface)package test;

public interface Home extends javax.ejb.EJBHome {public String hello() throws RemoteException;

public int add(int a, int b) throws RemoteException;public HomeObj findByPrimaryKey(String a) throws RemoteException, FinderException;

}

Nazar BabuNazar Babu 131

Page 132: Final Java Faqs

Java TechnoloiesJava Technoloies

HelloObj.java (Remote Interface)package test;

public interface HelloObj extends javax.ejb.EJBObject {}

HelloBean.java (Bean class)package test;import javax.ejb.*;

public class HelloBean extends com.caucho.ejb.AbstractEntityBean { public String ejbHomeHello() { return "Hello, world"; } public int ejbHomeAdd(int a, int b) { return a + b; } public String ejbFindByPrimaryKey(String key) throws FinderException { throw new FinderException("no children"); }}

Clientpackage test.entity.home;import javax.naming.*;

public class HomeServlet extends GenericServlet { Home home;

public void init() throws ServletException { try { Context env = (Context) new InitialContext().lookup("java:comp/env"); home = (Home) env.lookup("ejb/home"); } catch (Exception e) { throw new ServletException(e); } }

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { PrintWriter pw = res.getWriter(); try { pw.println("message: " + home.hello() + ""); pw.println("1 + 3 = " + home.add(1, 3) + ""); pw.println("7 + 1 = " + home.add(7, 1) + ""); } catch (Exception e) { throw new ServletException(e); } }}

Nazar BabuNazar Babu 132

Page 133: Final Java Faqs

Java TechnoloiesJava Technoloies

Design Design Patterns Patterns

J2EE Design Patterns

Q) What is a Desing Pattern? Why use patterns?

A) A pattern describes a proven solution to a recurring design problem. Patterns provide a ready-made solution that can be adapted to different problems as necessary.

Q) J2EE Design Patterns?Dispatcher View: Combines a Dispatcher component with the Front Controller and View Helper patterns, deferring many activities to View processing.

Service to Worker: Combines a Dispatcher component with the Front Controller and View Helper patterns.

Transfer Object Assembler: It is used to build the required model or submodel. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.

Composite Entity :It model, represent, and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans. A Composite Entity bean represents a graph of objects.

Service Activator: Service Activator enables asynchronous access to enterprise beans and other business services. It receives asynchronous client requests and messages. On receiving a message, the Service Activator locates and invokes the necessary business methods on the business service components to fulfill the request asynchronously. In EJB2.0, Message Driven beans can be used to implement Service Activator for message based enterprise applications. The Service Activator is a JMS Listener and delegation service that creates a message façade for the EJBs.

Nazar BabuNazar Babu 133

Tier Pattern Name? Intercepting Filter? Front Controller? View Helper? Composite view? Service to Worker? Dispacther View? Business Delegate? Value Object? Session Façade? Composite Entity? Value Object Assembler? Value List Handler? Service Locator? Data Access Object? Service Activator

Presentation Tier

Business Tier

Integration Tier

Page 134: Final Java Faqs

Java TechnoloiesJava Technoloies

Q) What is architectural design pattern?A) Describe MVC2 & Front Controller.

Front Controller It will dispatch the request to the correct resource, Centralized controller for

managing and holding of a request.

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

Session FaçadeEJB 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

Nazar BabuNazar Babu 134

Page 135: Final Java Faqs

Java TechnoloiesJava Technoloies

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

Nazar BabuNazar Babu 135

Page 136: Final Java Faqs

Java TechnoloiesJava Technoloies

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 (DTO-DataTransfer 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();there are three 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 a Value Object and fill that object locally PersonInfo person = new PersonInfo(); person.setName("Ravi"); person.setCity("Austin"); // send Value Object through network

Nazar BabuNazar Babu 136

Page 137: Final Java Faqs

Java TechnoloiesJava Technoloies

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.

ValueObjectFactoryFor 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 placeholders and respond with a single ValueObject for a client request.

Nazar BabuNazar Babu 137

Page 138: Final Java Faqs

Java TechnoloiesJava Technoloies

Value List Handler (DAO)

J2EE applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client, the client takes long time to retrieve that large data and if that application uses entity bean to search data, it has an impact on.

1. Use Data Access Objects (DAO) rather than Entity beans2. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client.

DAO encapsulates JDBC access logic. ValueListHandler caches list of Value objects that are retrieved through DAO. When client wants to search data, it calls ValueListHandler that is in turn responsible for caching data and returning data to the client iteratively.

Singleton You can achieve this by having the private constructor in the class, so that other classes can't create a new instance. 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

1.Create a Private constructor, so that outside class can not access this constructor. And declare a private static reference of same class.

Nazar BabuNazar Babu 138

Page 139: Final Java Faqs

Java TechnoloiesJava Technoloies

2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

public class Singleton{private static Singleton ref; private Singleton (){ } public static Singleton getSingleton() { if (ref == null) ref = new Singleton (); return ref; }}Business Delegate

The B.D acts as a client-side business abstraction and hides the implementation of the business services. such as lookup & access details of the EJB architecture.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.B.D 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 client requests the BusinessDelegate to provide access to the underlying business service. The BusinessDelegate uses a LookupService to locate the required BusinessService component.

Q). Where do you use singleton pattern and why?

A) If I require a single instance of an object in a particular JVM, ex while designing database connection pool. I would require a single connection object for all the users coming in, not a separate one for each user.

Q). Why Factory Pattern is used and an example?

A) Factory pattern is used in place where the implementation varies over time. Factory pattern suggest creating many different instances from interfaces. Interfaces

Nazar BabuNazar Babu 139

Page 140: Final Java Faqs

Java TechnoloiesJava Technoloies

are the one that faces client and implementation of those methods come from factory depending on a specific condition. ex: If the OS is Windows, look and feel of the application changes to Window style, for Linux it is Metal and for machintosh it will be different.

Q). Where do you use visitor pattern and why?

A) If I want to defrag business logic in different sets of modules and the final processing requires all these module to be included in a particular fashion. Visitor pattern generally calls a visit method of these modules /objects andall the different logic stored in different modules and call one by one. It is something like visiting many modules one at a time.

Q). What problem an observer pattern solves?

A) If a particular event has to be notified to many objects, and list grows over time and it is hardly possible to call /notify each and every listeners at design time. We use observer pattern , just to register many objects listening to a particular event and getting notified automatically, as and when the event occurs. Q) What is the difference between J2EE design patterns and the Gang of Four patterns? A) The GOF design patterns apply generically to any object-oriented programming language. J2EE design patterns address common problems encountered in designing J2EE architecture. This course presents the key J2EE design patterns required when implementing a J2EE system.

Nazar BabuNazar Babu 140

Page 141: Final Java Faqs

Java TechnoloiesJava Technoloies

DatabaseDatabase ConceptsConcepts

Q) DML insert, update, delete DDL create, alter, drop, truncate, rename. DQL select DCL grant, revoke. TCL commit, rollback, savepoint.

Q) Normalization

Normalization is the process of simplifying the relationship between data elements in a record.

(i) 1st normal form: - 1st N.F is achieved when all repeating groups are removed, and P.K should be defined. big table is broken into many small tables, such that each table has a primary key.(ii) 2nd normal form: - Eliminate any non-full dependence of data item on record keys. I.e. The columns in a table which is not completely dependant on the primary key are taken to a separate table.(iii) 3rd normal form: - Eliminate any transitive dependence of data items on P.K’s. i.e. 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) Diff Primary key and a Unique key? What is foreign key?A) Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

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.

Q) Diff Delete & Truncate?

A) Rollback is possible after DELETE but TRUNCATE remove the table permanently and can’t rollback. Truncate will remove the data permanently we cannot rollback the deleted data.

Dropping : (Table structure + Data are deleted), Invalidates the dependent objects, Drops the indexes

Nazar BabuNazar Babu 141

Page 142: Final Java Faqs

Java TechnoloiesJava Technoloies

Truncating : (Data alone deleted), Performs an automatic commit, Faster than deleteDelete : (Data alone deleted), Doesn’t perform automatic commit

Q) Diff Varchar and Varchar2?

A) The difference between Varchar and Varchar2 is both are variable length but only 2000 bytes of character of data can be store in varchar where as 4000 bytes of character of data can be store in varchar2.

Q) Diff LONG & LONG RAW?

A) You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum length of a LONG value is 32760 bytes. You use the LONG RAW datatype to store binary data (or) byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum length of a LONG RAW value is 32760 bytes.

Q) Diff Function & Procedure Function is a self-contained program segment, function will return a value but

procedure not.Procedure is sub program will perform some specific actions.

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-5555SQL> select count (empssn), empssn from employee group by empssn having count (empssn) > 1;

COUNT (EMPSSN) EMPSSN------------- ----------- 2 555-55-5555 2 555-58-5555SQL> delete from employee where (empid, empssn) not in (select min (empid), empssn from employee group by empssn);

Q) Select the nth highest rank from the table?A) Select * from tab t1 where 2=(select count (distinct (t2.sal)) from tab t2 where t1.sal<=t2.sal)

Q) a) Emp table where fields empName, empId, address b) Salary table where fields EmpId, month, Amountthese 2 tables he wants EmpId, empName and salary for month November?A) Select emp.empId, empName, Amount from emp, salary where emp.empId=salary.empId and month=November;

Nazar BabuNazar Babu 142

Page 143: Final Java Faqs

Java TechnoloiesJava Technoloies

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

Q) What is an alias and how does it differ from a synonym? A) An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. The alias is not dropped when the table is dropped.

Q) What are joins? Inner join & outer join?

Nazar BabuNazar Babu 143

Page 144: Final Java Faqs

Java TechnoloiesJava Technoloies

A) By using joins, you can retrieve data from two or more tables based on logical relationships between the tablesInner 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.

• LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.• RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.• FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.Q. Diff join and a Union? A) A join selects columns from 2 or more tables. A union selects rows. when using the UNION command all selected columns need to be of the same data type. The UNION command eliminate duplicate values.

Q. Union & Union All?

A) The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It cannot eliminate duplicate values. > SELECT E_Name FROM Employees_NorwayUNION ALL SELECT E_Name FROM Employees_USA

Q) Is the foreign key is unique in the primary table? A) Not necessary

Q) Table mentioned below named employeeID NAME MID1 CEO Null2 VP CEO3 Director VP

Asked to write a query to obtain the following outputCEO NullVP CEODirector VP

A) SQL> Select a.name, b.name from employee a, employee b where a.mid=b.id(+).

Q) Explain a scenario when you don’t go for normalization?

Nazar BabuNazar Babu 144

Page 145: Final Java Faqs

Java TechnoloiesJava Technoloies

A) If we r sure that there wont be much data redundancy then don’t go for normalization.

Q) What is Referential integrity? A) R.I refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.

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) What is a view? Why use it? A) A view is a virtual table made up of data from base tables and other views, but not stored separately.

Q) SELECT statement syntax?A) SELECT [ DISTINCT | ALL ] column_expression1, column_expression2, .... [ FROM from_clause ] [ WHERE where_expression ] [ GROUP BY expression1, expression2, .... ] [ HAVING having_expression ] [ ORDER BY order_column_expr1, order_column_expr2, .... ]

column_expression ::= expression [ AS ] [ column_alias ]from_clause ::= select_table1, select_table2, ...from_clause ::= select_table1 LEFT [OUTER] JOIN select_table2 ON expr ...from_clause ::= select_table1 RIGHT [OUTER] JOIN select_table2 ON expr ...from_clause ::= select_table1 [INNER] JOIN select_table2 ...select_table ::= table_name [ AS ] [ table_alias ]select_table ::= ( sub_select_statement ) [ AS ] [ table_alias ]order_column_expr ::= expression [ ASC | DESC ]

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) Diff HAVING CLAUSE & WHERE CLAUSE?

A) Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

Q) Diff GROUP BY & ORDER BY? A) Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the SELECT statement.

> SELECT "col_nam1", SUM("col_nam2") FROM "tab_name" GROUP BY "col_nam1"

Nazar BabuNazar Babu 145

Page 146: Final Java Faqs

Java TechnoloiesJava Technoloies

> SELECT "col_nam" FROM "tab_nam" [WHERE "condition"] ORDER BY "col_nam" [ASC, DESC]

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

Q) Index? Types of indexes?A) Locate rows more quickly and efficiently. It is possible to create an index on one (or) more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries.

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)

Q) Diff subqueries & Correlated subqueries?A)subqueries are self-contained. None of them have used a reference from outside the subquery.correlated subquery cannot be evaluated as an independent query, but can reference columns in a table listed in the from list of the outer query.

Q) Predicates IN, ANY, ALL, EXISTS?A) Sub query can return a subset of zero to n values. According to the conditions which one wants to express, one can use the predicates IN, ANY, ALL or EXISTS.

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.

Q) What are some sql Aggregates and other Built-in functions? A) AVG, SUM, MIN, MAX, COUNT and DISTINCT.

Nazar BabuNazar Babu 146

Page 147: Final Java Faqs

Java TechnoloiesJava Technoloies

Security Security ConceptsConcepts

Q) Java Security Model

Byte code verifierWhich examine the byte code of a class before executing. The verifier checks

that the instructions cannot perform actions that are obviously damaging.ClassLoader

ClassLoader, which restrict access to the classes, which can be loaded into JVM, ClassLoader keeps the record of classes, which can be loaded into JVM.Security manager

Restrict access to potentially dangerous operations. S.M provides a sand box in which applet run. You can also define a set of sand boxes, applying a different san box to each program. S.M is a class that controls weather a specific operation are permitted, S.M will perform operations like opening N.W socket, creating S.M, perform N.W multi cast etc…

Q) Basic Authentication & Digest Authentication

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.

Nazar BabuNazar Babu 147