1core.docx

download 1core.docx

of 82

Transcript of 1core.docx

CoreJavaQ) 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 > are not overloaded for I/O operationsQ) Opps conceptsPolymorphismAbility to take more than one form, in java we achieve this using Method Overloading (compile time 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.Abstraction Nothing but representing the essential futures without including background details.Dynamicbinding Code associated with a given procedural call is not known until the time of the call at runtime. Dynamic binding is nothing but late binding.Q) 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. 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.PrivatePublicProtectedNo modifier

Same classNoYesYesYes

Same package SubclassNoYesYesYes

Same package non-subclassNoYesYesYes

Different package subclassNoYesYesNo

Different package non-subclassNoYesNoNo

Q) Default ValuesLong -2^63 to 2^63 1 0LDouble0.0d

Int-2^31 to 2^31 1 0Float0.0f

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

Byte-2^7 to 2^7 1 0Char0 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. 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 generatorQ) 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 referenceQ) 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 classQ) 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. 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 friendQ) Diff Constructor & MethodConstructorMethod

Use to instance of a classGrouping java statement

No return typeVoid (or) valid return type

Same name as class nameAs a name except the class method name, begin with lower case.

This refer to another constructor in the same classRefers to instance of class

Super to invoke the super class constructorExecute an overridden method in the super class

Inheritance cannot be inheritedCan be inherited

We can overload but we cannot overriddenCan be inherited

Will automatically invoke when an object is createdMethod 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 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 alow-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 executeFinalize: - 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 cant 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. Q) Superclass & SubclassA super class is a class that is inherited whereas subclass is a class that does the inheritingQ) 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 variableclass Parent{ int i = 0; void amethod(){ System.out.println("in Parent"); } } class Child extends Parent{ int i = 10; void amethod(){ 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 ChildQ) Final variable Once to declare a variable as final it cannot occupy memory per instance basis. Q) Static block Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.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.Class variables you want a variable to be common to all classes then we create 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) ConversionsString 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 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 blocksQ) 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 , 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.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; Interfaces are useful for?a) Declaring 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();}}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 doesnt force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

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.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 or 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 mannerQ) Different level of locking using Synchronization?A) Class level, Object level, Method level, Block levelQ) MonitorA monitor is a mutex, once a thread enters 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 same 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"; (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)) TQ) Marker Interfaces (or) Tagged Interfaces :- An Interface with no methods. Is called marker Interfaces, eg. Serializable, SingleThread Model, Cloneable.Q) URL Encoding & URL DecodingURL 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 & URLConnectionURL 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()}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) CloneGenerate 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 ClassNotFoundExceptiongetClass()

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 or by reference?A) By valueQ) 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.Collections Frame WorkQ)Collection classesCollection InterfacesLegacy classesLegacy interface

Abstract collectionCollection DictionaryEnumerator

Abstract ListListHash Table

Abstract SetSetStack

Array ListSorted SetVector

Linked ListMapProperties

Hash setIterator

Tree Set

Hash Map

Tree Map

Abstract Sequential List

Collection ClassesAbstract collection Implements most of the collection interfaces.Abstract List Extends Abstract collection & Implements List Interface. A.L allows random access.Methods>> void add (intindex, Objectelement), boolean add(Objecto), boolean addAll(Collectionc), boolean addAll(intindex, Collectionc), 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 allows 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 (intindex, Objectelement), boolean add(Objecto), boolean addAll(Collectionc), boolean addAll(intindex, Collectionc), 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 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 (intindex, Objectelement), boolean add(Objecto), boolean addAll(Collectionc), boolean addAll(intindex, Collectionc), 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 elementsMethods>>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 elementsMethods>> boolean add(Object o), boolean addAll(Collectionc), 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 InterfacesCollection 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).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 ClassesDictionary is an abstract class that represent key/value storage repository and operates much like Map once the value is stored you can retrieve it by using key.Hash Table HashTable stores key/value pairs in hash table, HashTable is synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. 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 InterfacesEnumeration 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 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 variablesQ) 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();

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

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(); } // 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); ExceptionHandlingObject

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 StirngIndexoutOfBoundQ)Exception & ErrorException and Error both are subclasses of the Throwable class.ExceptionException is generated by java runtime system (or) by manually. An exception is an abnormal condition that transfers program execution from a thrower to catcher.Error Will stop the program execution, Error is an 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.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() methodUnchecked 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 ExceptionsUn checked exception

ClassNotFoundExceptionArithmeticException

NoSuchMethodExceptionArrayIndexOutOfBoundException

NoSuchFieldExceptionClasscastException

InterruptedExceptionIllegalArgumentException

IllegalAccessExceptionIllegalMonitorSateException

CloneNotSupportedExceptionIllegalThreadStateException

IndexOutOfBoundException

NullPointerException

NumberFormatException

StringIndexOutOfBounds

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 or equal to the array size.StringIndexOutOfbound-->For accessing character of a string or string buffer with index values or equal to the array size.Arithmetic Exception-->such as divide by zero.ArrayStore Exception-->Assignment to an array element of an incompatible types.ClasscastException-->Invalid casting.IllegalArgument Exception-->Illegal argument is used to invoke a method.Nullpointer Exception-->If attempt to made to use a null object.NumberFormat Exception-->Invalid conversition of string to numeric format.ClassNotfound Exception-->class not found.Instantion Exception-->Attempt to create an object of an Abstract class or Interface.NosuchField Exception-->A request field does not exist.NosuchMethod Exception-->A request method does not exist.Q) Methods in Exceptions?A) getMessage(), toString(), printStackTrace(), getLocalizedMessage(),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 taskingIf 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 NumberTypeDescription

1xxInformationalRequested received, continuing to process

2xxSuccessThe action was successfully received, understood, and accepted

3xxRedirectionFurther action must be taken in order to complete the request

4xxClient ErrorThe request contains bad syntax or cannot be fulfilled

5xxServer ErrorThe server failed to fulfil valid request

All PackagesQ) 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 PackageInterfacesClassesExceptions

ServletGenericServletServletException

ServletConfigServletInputStreamUnavaliableException

ServletContextServletOutputStream

ServletRequestServletContextAttributeEvent

ServletResponse

SingleThreadModel

ServletContextListener

ServletContextAttributeListener

ServletContextInitialization parameters

ServletRequestAttributeListener

ServletRequestListner

Filter

FilterChain

FilterConfig

RequestDispatcher

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(ServletContextAttributeEventscab) public void attributeRemoved(ServletContextAttributeEventscab) public void attributeReplaced(ServletContextAttributeEventscab)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(); 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.4ServletResponse (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 PackageInterfacesClassesExceptions

HttpServletRequestCookies ServletException

HttpServletResponseHttpServlet (Abstarct Class)UnavaliableException

HttpSessionHttpUtils

HttpSessionListenerHttpSessionBindingEvent

HttpSessionActivationListener

HttpSessionAttributeListener

HttpSessionBindingListener

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

Connection DriverManager

CallableStatementDateClassNotFoundException

Driver TimeStampInstantiation Exception

PreparedStatement Time

ResultSet Types

ResultSetMetaData SQL Exception, SQL Warnings

Statement

DatabaseMetaData

Array

ParameterMetaData

Clob, Blob

SQLInput, SQLOutput, SQLPermission

Savepoint

Q) javax.sql PackageInterfacesClassesExceptions

ConnectionEventListenerConnectionEvent

ConnectionPoolDataSourceRowsetEvent

DataSource

PooledConnection

RowSet

RowSetListener

RowSetMetaDate

RowSetReader/Writer

XAConnection

XADataSource

Q) java.lang PackageInterfacesClassesExceptions

CloneableDouble, Float, Long, Integer, Short, Byte, Boolean, Character,ArithmeticException, ArrayIndexOutOfBoundOf.E, ClassCast.E, ClassNotFound.E

RunnableClass, ClassLoaderIlleAcess.E, IllegalArgument.E

ComparableProcess, RunTime, VoidIllegalSate.E, NullPointer.E

String, StringBufferNoSuchField.E, NoSuchMethod.E

Thread, ThreadGroupNumberFormat.E

Q) java.IO PackageInterfacesClassesExceptions

DataInputstreamBufferInputstream, BufferOutputStream

DataOutputstreamBufferReader, BufferWriter

ObjectInputStreamByteArrayInputStream, ByteArrayOutputstream

ObjectOutputstreamCharacterarrayReader, CharacterArayWriter

SerializableDataInputStream, DataOutputStream

ExternializableFilereader, FileWriter

ObjectInputStream, ObjectOutputStream

Threading QuestionsQ) 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 PriorityMIN_PRIORITY = 1NORM_PRIORITY = 5MAX_PRIORITY = 10Q) 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 PrioritiesClass 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 levelQ) Which attribute are thread safe?ObjectiveMulti Threaded ModelSingle threaded Model

Local variablesYY

Instance variablesNY

Class variablesNN

Request attributesYY

Session attributesNN

Context attributesNN

JDBC QuestionsQ) 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, typeand properties of parameters to prepared statements.5. Retrieval of auto-generated keys: - Added a means of retrieving values from columns containing automaticallygenerated 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.Q) JDBC Drivers JDBC-ODBC Bridge Driver Native API - Partly Java Driver Network protocol - All Java Driver Native Protocol - Pure Java Driver TierDriver mechanismDescription

TwoJDBC-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 DriverThis 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.

TwoNative protocol - All - Java driverThey 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(); } catch (SQLException se) { System.out.println("SQL Exception: " + se.getMessage()); } } }Q) 4th type driverclass.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 permanentQ) 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') ");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_RESULTThe current ResultSet object should be closed when calling getMoreResults().

KEEP_CURRENT_RESULTThe 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. 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 poolWhen you are going to create 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 has 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.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 ODBCQ) 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 JDBCStatement 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 are precompiled statements once we compile the statements and send it to the server for later use. P.S are partially compiled statements placed at server side with 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.Q) In which interface the methods commit() & rollback() savepoint() defined ?A) java.sql.Connection interfaceQ) 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 packageConnection 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: ");System.out.println(warning.getErrorCode());warning = warning.getNextWarning();}}Q) ProcedureProcedure is a subprogram will perform some specific action, sub programs are name PL/SQL blocks that can take parameters to be invoked.create (or) replace procedure procedure-name (id IN INTEGER , bal IN OUT FLOAT) IS BEGINselect 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)endQ) Stored Images into a tablePublic 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 ImageStatement 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);}

SERVLET QuestionsClass 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 shortcutQ) 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.jspckeepgenerated *.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 servers 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);Q) Servlet Life cyclePublic 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. Theres nothing to stop you. But you shouldnt. The original reason for init() was that ancient versions of Java couldnt 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 wont 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) | + web.xml / (taglib.tld) | + weblogic.xmlWAR-> WARfile can be placed in a servers webapps directoryQ) Web.xml: -

localeUS

Test Filterfilters.TestFilter

locale US

Test FilterTestServlet

listeners.MyServletContextListener

listeners.MySessionCumContextListener

HelloServletservlets.HelloServlet

driverclassnamesun.jdbc.odbc.JdbcOdbcDriver

dburljdbc:odbc:MySQLODBC

manager

supervisor

HelloServlet*.hello

30

index.html

404notfoundpage.jsp

java.sql.SQLExceptionsqlexception.jsp

http://abc.com/testlib/WEB-INF/tlds/testlib.tld

/examplelib/WEB-INF/tlds/examplelib.tld

POST

Another Protected Area*.hello

FORMsales /formlogin.html/formerror.jsp

Q) Automatically start Servlet?A) If present, calls the servlet's service() method at the specified times. 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:

0:00, 6:00, 12:00, 18:00

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

TestServletTestServlet

driverclassnamesun.jdbc.odbc.JdbcOdbcDriver

dburljdbc:odbc:MySQLODBC

--------------------------------------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 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(HttpSessionEventse)public void sessionDidActivate(HttpSessionEventse)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(HttpSessionBindingEventse)public void atributeRemoved(HttpSessionBindingEventse)public void attributeReplaced(HttpSessionBindingEventse)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.HttpSessionBindingL