Home >Documents >Java Material Bala

Java Material Bala

Date post:07-Apr-2018
View:221 times
Download:0 times
Share this document with a friend
  • 8/4/2019 Java Material Bala


    Core 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 inJava. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions thatresult 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 notsupport destructors, but rather, add the finalize() function. (vi) Java does not have the delete operator. (vii) The > are not overloaded for I/O operations

    Q) oops conceptsPolymorphismAbility 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 arereusability 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 classand cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. OrEncapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outsideinterference 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 isnothing 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.Memoryheap: Generally the objects are created using the new keyword. Some heap memory is allocated to thisnewly created object. This memory remains allocated throughout the life cycle of the object. When the object is nomore 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 arecreated 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. Transienvariables are not serialized.Volatile --> value will be changed unexpectedly by the other part of the program,"it tells the compiler a variable maychange asynchronously due to threads"

    Q)Access Specifies & Access modifiers?

    Access Specifiers A.S gives access privileges to outside of application (or) others, they are Public, ProtectedPrivate, Defaults.

    Page 1

  • 8/4/2019 Java Material Bala


    Access Modifiers A.M which gives additional meaning to data, methods and classes, final cannot be modified at anypoint of time.

    Private Public Protected No modifier

    Same class No Yes Yes Yes

    Same package Subclass No Yes Yes Yes

    Same package non-subclass No Yes Yes Yes

    Different package subclass No Yes Yes No

    Different 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 programinto 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 theperformance 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 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, valuespassed 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 Mainmethod only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classeshaving main method.

    Q) Can I have multiple main methods in the same class?

    Page 2

  • 8/4/2019 Java Material Bala


    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 aconstructor of the same class. Super() is used to invoke a super class constructor. Constructor is called immediatelyafter the object is created before the new operator completes.

    Constructorcan use the access modifiers public, protected, private orhave no access modifier Constructorcan not use the modifiers abstract, static, final, native, synchronized orstrictfpConstructorcan beoverloaded, we cannot override.You cannot use this() and Super() in the same constructor.

    Class A(A(){


    Class B extends A {B(){



    Class print {Public static void main (String args []){B b = new B();}o/p:- hello friend

    Q) Diff Constructor & Method

    Constructor Method

    Use to instance of a class Grouping java statement

    No return type Void (or) valid return typeSame name as class name As a name except the class method name, beginwith lower case.

    This refer to another constructor in the sameclass

    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 inherited

    We can overload but we cannot overridden Can be inherited

    Will automatically invoke when an object iscreated

    Method has called explicitly

    Q) Garbage collectionG.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 thegarbage collector to automatically free the objects that are no longer referenced by a program. Every class inheritsfinalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines nomore references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in usecalling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all theobjects 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 shortof memory. The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make aneffort to do garbage collection.

    Page 3

  • 8/4/2019 Java Material Bala


    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 itsreference is set to null. The objects referred by method variables or local variables are eligible for garbage collectionwhen they go out of scope.

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

    Q) Final, Finally, Finalize

    Final: - When we sub class a final class the compiler will give error as cannot subclass final class Final to preventinheritance 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 wilexecute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catchstatement match the exception. Any time a method is about to return to the caller from inside try/catch block, via anuncaught 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 somenon-java resource such as file handle (or) window character font, these resources are freed before the object is going todestroy.

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

    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 classesi.e overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract toothen 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 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 theirnumbeof 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 typeare 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 datatypes.

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

    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 thesuperclass method.

    Page 4

  • 8/4/2019 Java Material Bala


    If the superclass method is public, the overriding method must be public.

    If the superclass method is protected, the overriding method may be protected orpublic.

    If the superclass method is package, the overriding method may be packagage, protected, orpublic.

    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 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 changesfor all instances of that class.

    Static methods can be referenced with the name of the class. It may not access the instance variables of thatclass, 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 otherstatic data, they cannot referthis orsuper.

    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 staticmethods cannot call ordinary methods.

    Static methods are implicitly "final", because overriding is only done based on the type of the objects

    Page 5

  • 8/4/2019 Java Material Bala


    They cannot refer this are super in any way.

    Q) Class variable & Instance variable & Instance methods & class methods

    Instance variable variables defined inside a class are called instance variables with multiple instance of class, eachinstance has a variable stored in separate memory location.

    Class variables you want a variable to be common to all classes then we crate class variables. To create a classvariable 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. Todeclare 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 theclass.

    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 variablesare called called as non-static variables.

    Q) String & StringBuffer

    String is a fixed length of sequence of characters, String is immutable.

    StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means that itsvalue can be changed. It allocates room for 16-addition character space when no specific length is specifiedJava.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden theequals() 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 theclass just like any other top-level class. Any class outside the declaring class accesses the nested class with thedeclaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access onlyto 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 themember class is restricted, just like methods and variables. This means public member class acts similarly to a nestedtop-level class. The primary difference between member classes and nested top-level classes is that member classeshave 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 blockof their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a morepublicly available interface. Because local classes are not members the modifiers public, protected, private and staticare not usable

    Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classeshave no name, you cannot provide a constructor.

    Page 6

  • 8/4/2019 Java Material Bala


    Inner class inside method cannot have static members or blocks

    The classes and interfaces we have seen so far in this chapter have all been top-level classes (i.e., they are directmembers of packages, not nested within any other classes). Starting in Java 1.1, however, there are four other types ofclasses, loosely known as inner classes, that can be defined in a Java program. Used correctly, inner classes are anelegant and powerful feature of the Java language. These four types of classes are summarized here:

    Static member classes

    A static member class is a class (or interface) defined as a static member of another class. A static method iscalled a class method, so, by analogy, we could call this type of inner class a "class class," but this terminologywould obviously be confusing. A static member class behaves much like an ordinary top-level class, except thait can access the static members of the class that contains it. Interfaces can be defined as static members ofclasses.

    Member classes

    A member class is also defined as a member of an enclosing class, but is not declared with the static modifier

    This type of inner class is analogous to an instance method or field. An instance of a member class is alwaysassociated with an instance of the enclosing class, and the code of a member class has access to all the fieldsand methods (both static and non-static) of its enclosing class. There are several features of Java syntax thatexist specifically to work with the enclosing instance of a member class. Interfaces can only be defined as staticmembers of a class, not as non-static members.

    Local classes

    A local class is a class defined within a block of Java code. Like a local variable, a local class is visible onlywithin that block. Although local classes are not member classes, they are still defined within an enclosingclass, so they share many of the features of member classes. Additionally, however, a local class can accessany final local variables or parameters that are accessible in the scope of the block that defines the classInterfaces cannot be defined locally.

    Anonymous classes

    An anonymous class is a kind of local class that has no name; it combines the syntax for class definition withthe syntax for object instantiation. While a local class definition is a Java statement, an anonymous classdefinition (and instantiation) is a Java expression, so it can appear as part of a larger expression, such asmethod invocation. Interfaces cannot be defined anonymously.

    Java programmers have not reached a consensus on the appropriate names for the various kinds of inner classesThus, you may find them referred to by different names in different situations. In particular, static member classes aresometimes called "nested top-level" classes, and the term "nested classes" may refer to all types of inner classes. Theterm "inner classes" is itself overloaded and sometimes refers specifically to member classes. On other occasions,"inner classes" refers to member classes, local classes, and anonymous classes, but not static member classes.

    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 is excellent candidates inside of application framework. A.Callow single inheritance model, which should be very faster.

    Q) Abstract ClassAny 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.

    Page 7

  • 8/4/2019 Java Material Bala


    Any sub class of an Abstract class must either implement all the abstract methods in the super class or be declareditself 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 classabstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one omore 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 errowould 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. Butthese are some common operations performed by all animals, but in a different way as well. When an operation isperformed in a different way it is a good candidate for an abstract method.

    Public Abstractclass 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() {

    Page 8

  • 8/4/2019 Java Material Bala


    System.out.println(moo! moo);}


    Q) InterfaceInterface 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 implicitlyabstract, 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 inneinterfaces.

    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 orsynchronized.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 ithey 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 implementationcode.

    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

    Page 9

  • 8/4/2019 Java Material Bala


    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 andinstance 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 aninstance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to thinkabout each message you forward, because the instance is of a known class, rather than a new class, and because idoesnt force you to accept all the methods of the super class: you can provide only the methods that really makesense. 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 --> Serialization 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.

    Externalizable is an Interface that extends Serializable Interface. And sends data into Streams inCompressed 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) Serialization

    Serialization is the process of writing the state of the object to a byte stream, this is useful when ever you wantto save the state of your programme to a persistence storage area.

    Q) SynchronizationSynchronization 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 theshared resources they need to some way ensure that the resources will be used by only one thread at a time. Thisprocess which is achieved is called synchronization.

    (i) Ex: - Synchronizing a functionpublic synchronized void Method1 () }

    (i) Ex: - Synchronizing a block of code inside a functionpublic 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

    Page 10

  • 8/4/2019 Java Material Bala


    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


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

    (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 programs

    Page 11

  • 8/4/2019 Java Material Bala


    You can use java to execute other heavy weight process on your multi tasking operating system, several formof 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, errvariables.

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


    getClassLoader() getConstructor()

    getField() getDeclaredFields()

    getMethods() getDeclearedMethods()

    getInterface() getSuperClass()

    Q) java.jlang.Reflect (package)Reflection is the ability of software to analyse it self, to obtain information about the field, constructor, methods

    & modifier of class. You need this information to build software tools that enables you to work with java beanscomponents.

    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

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

    Q) java. ExeMicrosoft provided sdk for java, which includes jexegentool. This converts class file into a .Exec form. Onlydisadvantage is user needs a M.S java V.M installed.

    Page 12

  • 8/4/2019 Java Material Bala


    Q) Bin & Lib in jdk?Bin contains all tools such as javac, appletviewer and awt tool.Lib contains API and all packages.

    Collections Frame Work

    Collection classes Collection Interfaces Legacy classes Legacy interface

    Abstract collection Collection Dictionary Enumerator Abstract List List Hash Table

    Abstract Set Set Stack

    Array List Sorted Set Vector

    Linked List Map Properties

    Hash set Iterator

    Tree Set

    Hash Map

    Tree Map

    Abstract Sequential List

    Collection Classes

    Abstract collection Implements most of the collection interfaces.Abstract List Extends Abstract collection & Implements List Interface. A.L allows random access.Methods>> void add (int index, Objectelement), boolean add(Objecto), boolean addAll(Collection c), booleanaddAll(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 ofarray of object references, ArrayList support dynamic array that grow as needed. A.L allows rapid random access toelement but slow for insertion and deletion from the middle of the list. It will allow duplicate elements. Searching isvery 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, Objectelement), boolean add(Objecto), boolean addAll(Collection c), booleanaddAll(int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexOf(Objecelement), int latIndexOf(Object element), int size(), Object [] toArray().

    Page 13

  • 8/4/2019 Java Material Bala


    Linked List Extends AbstactSequentialList and implements List interface. L.L provide optimal sequence accessin expensive insertion and deletion from the middle of the list, relatively slow for random access. When ever there isa lot ofinsertion & deletion we have to go for L.L. L.L is accessed via a reference to the first node of the list. Eachsubsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via thelink-reference number stored in the previous node.

    Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add (int index,Objectelement), boolean add(Objecto), 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 forstorage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet. It will not allowduplicate 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 orderAccess 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 elementsso the order in which the elements are added to a H.M is not necessary the order in which they are ready by theiterate. 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 sortedorder and allow rapid retrieval.

    Abstract Sequential ListExtends Abstract collection; use sequential access of its elements.

    Collection Interfaces

    CollectionCollection 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 duplicateselements 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), inindexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index), ObjecremoveAll(Collection c), Object set(int index, Object obj).

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

    Sorted Set Extends Setto handle sorted sets, Sorted Set elements will be in ascending order.Methods >> Object last(), Object first(), compactor compactor().Exceptions >> NullPointerException, ClassCastException, NoSuchElementException.

    Page 14

  • 8/4/2019 Java Material Bala


    Map Map maps unique key to value in a map for every key there is a corresponding value and you will lookupthe values using keys. Map cannot contain duplicate key and value. In map both the key & value areobjects.

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

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

    Before accessing a collection through an iterator you must obtain one if the collection classes provide aniterator()methodthat returns an iterator to the start of the collection. By using iterator object you can access eachelement 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 IteratorList Iterator gives the ability to access the collection, either forward/backward directionLegacy Classes

    Dictionaryis an abstract class that represent key/value storage repository and operates much like Map oncethe value is stored you can retrieve it by using key.

    Hash TableHashTable stores key/value pairs in hash table, HashTable is synchronizedwhen using hash tableyou 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 thenhashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T tostore 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), Objectput(Object key, Object value)

    Stackis 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 storeprimitive 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 booleanremoveElementAt(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 isString.

    Legacy Interfaces

    Enumeration Define methods by which you can enumerate the elements in a collection of objects. Enumerationis 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:

    Page 15

  • 8/4/2019 Java Material Bala


    1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitationlike a Vector where when the size is exceeded a new internal structure is created. 4. Permits user-controlledsynchronization 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 rowArrays work well for that as you know the size, though a custom class might be best so you can convert the contents tothe 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 searchinsertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to theorder of the key. Another reason is that when no good hash function can be found for a certain application, the time andspace 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 bebetween 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and thecurrent capacity, the capacity is increased by calling the rehash method. Larger load factors use memory moreefficiently, 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 theHashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or moredifferent 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 localvariables

    Q) Diff Iterator & Enumeration & List Iterator

    Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interfacethat extends from List interface. Enumeration is a legacy interface, Enumeration having 2 methods BooleanhasMoreElements() & Object NextElement(). Iterator having 3 methods boolean hasNext(), object next(), voidremove(). Iterator also has an extra feature not present in the older Enumeration interface - the ability to removeelements 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 ispart 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 acollection implementation, you could manually traverse each element of the array and add it using the add(Objectmethod.

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

    Page 16

  • 8/4/2019 Java Material Bala


    // Convert back to a collectionCollection c2 = new HashSet();for(int i = 0; i < array.length; 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 listfor (int indx = 0; indx < args.length; indx++){


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

    // PRE : Collection has all parameterswhile (i.hasNext()){

    String param = (String) i.next();

    // Use the remove method of iteratorif (! param.startsWith("-") )

    i.remove();}// POST: Collection only has parameters that start with -

    // Demonstrate by dumping collection contents

    Page 17

  • 8/4/2019 Java Material Bala


    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 arrayof 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 acustom Comparator to help you sort the elements in the array.Arrays.sort(theArray, theComparator);


    Exception Handling



    Error Exception

    AWT Error Virtual Machine Error

    Compile time.Ex Runtime Exception(checked) (Unchecked)

    OutOfMemory.E StackOverFlow.E EOF.E FilenotFound.EArithmetic.E NullPointer.E Indexoutof


    ArrayIndexoutOfBound.E StirngIndexoutOfBound

    Q) Diff Exception & ErrorException and Error both are subclasses of the Throwable class.

    Page 18

  • 8/4/2019 Java Material Bala


    ExceptionException is generated by java runtime system (or) by manually. An exception is a abnormal condition thattransfer 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 tocatching 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, whicheventually 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 isthrown 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 areunchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could bethrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caughat compile time. Runtime exceptions do not need to be. Errors often cannot be.

    Checked Exceptions Un checked exception

    ClassNotFoundException ArithmeticExceptionNoSuchMethodException ArrayIndexOutOfBoundException

    NoSuchFieldException ClasscastException

    InterruptedException IllegalArgumentException

    IllegalAccessException IllegalMonitorSateException

    CloneNotSupportedException IllegalThreadStateException





    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 thearray size.StringIndexOutOfbound --> For accessing character of a string or string buffer with index values orequal 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 --> Ifattempt to made to use a null object.NumberFormat Exception --> Invalid conversition of string to numeric format.

    Page 19

  • 8/4/2019 Java Material Bala


    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. Aseach 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. Twomethods 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 currenexception. getCause returns the exception that caused the current exception, and initCause returns the currenexception.

    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

    Number Type Description

    1xx Informational Requested received, continuing to process

    2xx Success The action was successfully received, understood, and accepted

    3xx Redirection Further action must be taken in order to complete the request

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

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

    Page 20

  • 8/4/2019 Java Material Bala


    Q) throwable classMethods: -

    String getMessage() Void printStackTrace()

    String toString() Throwable fillInStackTrace()

    Q) Javax.servlet Package

    Interfaces Classes Exceptions

    Servlet GenericServlet ServletExceptionServletConfig ServletInputStream UnavaliableException

    ServletContext ServletOutputStream

    ServletRequest ServletContextAttributeEvent





    ServletContextInitialization parameters







    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;

    Page 21

  • 8/4/2019 Java Material Bala


    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.4public int getRemotePort(); // servlet 2.4public String getLocalName(); // servlet 2.4public 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 Package

    Interfaces Classes Exceptions

    HttpServletRequest Cookies ServletException

    HttpServletResponse HttpServlet (Abstarct Class) UnavaliableException

    HttpSession HttpUtils

    HttpSessionListener HttpSessionBindingEvent




    HttpSessionContext (deprecated)


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

    Page 22

  • 8/4/2019 Java Material Bala


    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)

    Page 23

  • 8/4/2019 Java Material Bala


    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 Exceptions

    Connection DriverManager

    CallableStatement Date ClassNotFoundException

    Driver TimeStamp Instantiation Exception

    PreparedStatement Time

    ResultSet Types

    ResultSetMetaData SQL Exception, SQL





    Clob, Blob

    SQLInput, SQLOutput, SQLPermission


    Q) javax.sql Package

    Interfaces Classes Exceptions

    ConnectionEventListener ConnectionEvent

    ConnectionPoolDataSource RowsetEvent








    Q) java.lang Package

    Interfaces Classes Exceptions

    Cloneable Double, Float, Long, Integer, Short,

    Byte, Boolean, Character,


    ArrayIndexOutOfBoundOf.E,ClassCast.E, ClassNotFound.E

    Runnable Class, ClassLoader IlleAcess.E, IllegalArgument.E

    Comparable Process, RunTime, Void IllegalSate.E, NullPointer.E

    String, StringBuffer NoSuchField.E, NoSuchMethod.E

    Thread, ThreadGroup NumberFormat.E

    Q) java.IO Package

    Interfaces Classes Exceptions

    DataInputstream BufferInputstream, BufferOutputStream

    DataOutputstream BufferReader, BufferWriter

    Page 24

  • 8/4/2019 Java Material Bala


    ObjectInputStream ByteArrayInputStream, ByteArrayOutputstream

    ObjectOutputstream CharacterarrayReader, CharacterArayWriter

    Serializable DataInputStream, DataOutputStream

    Externializable Filereader, FileWriter

    ObjectInputStream, ObjectOutputStream

    SERVLET Questions

    Class path: -set path= c:\j2sdk1.4.2\binset 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 memoryspecially instructed to be destroyed. Servlets will be loaded in theAddress 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 anadministration 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 iscalled as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on aJSP 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 containersservlet/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 servle

    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 thatservers 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 thatinclude 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 cycle

    Page 25

  • 8/4/2019 Java Material Bala


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

    Any request from client is handled initially by the service () method before delegating to the doXxx () methods in thecase 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 calledThis 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 shouldtake 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 thatancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give theconstructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. Soyou 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. SoServletConfig will not be accessible in the constructor.

    Q) Directory Structure of Web Applications?

    A) WebApp/(Publicly available files, such as| .jsp, .html, .jpg, .gif)


    + classes/(Java classes, Servlets

    + lib/( jar file

    + web.xml / (taglib.tld)

    + weblogic.xml

    WAR-> WARfile can be placed in a servers webapps directory

    Q) Web.xml: -


    Page 26

  • 8/4/2019 Java Material Bala


    Test Filterfilters.TestFilter


    Test FilterTestServlet










    Page 27

  • 8/4/2019 Java Material Bala







    Another Protected Area*.hello




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

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

    Q) ServletConfig Interface & ServletContex Interfaces

    ServletConfigServletConfig object is used to obtain configuration data when it is loaded. There can be multipleServletConfig 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 servletcontainers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. Thecontainer, in turn, passes these parameters to the servlet via the ServetConfig.


    Page 28

  • 8/4/2019 Java Material Bala





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


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

    Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and otherresources. 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));


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

    Q) Can we store objects in a session?A) session.setAttribute("productIdsInCart",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 webapplication they are part of. To receive notification events, the implementation class must be configured in thedeployment descriptor for the web application.

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

    Page 29

  • 8/4/2019 Java Material Bala


    Implementations of this interface receive notifications of changes to the attribute list on the servlet context of aweb application. To receive notification events, the implementation class must be configured in the deploymendescriptor 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. Toreceive notification events, the implementation class must be configured in the deployment descriptor for the webapplication.

    (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 bepassivated 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 ofsessions 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. Anyobject that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound (orunbound from a session. The interface declares two methods, valueBound() and valueUnbound(), that must beimplemented:

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

    public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)

    valueBound() method is called when the listener is bound into a session

    valueUnbound() 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 beingbound (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()

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

    Page 30

  • 8/4/2019 Java Material Bala


    }=============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 databeing passed between them. It acts as a guard, preventing undesired information from being transmitted from one poin

    to another.

    When a servlet container receives a request for a resource, it checks whether a filter is associated with this resource. Ia filter is associated with the resource, the servlet container routes the request to the filter instead of routing it to theresource. 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

    The javax.servlet.Filterinterface 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 Filte{private FilterConfig filterConfigpublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain{try{

    chain.doFilter (request, response); // for Filter C} catch (IOException io) System.out.println ("IOException raised in SimpleFilter")


    public FilterConfig getFilterConfig({return this.filterConfig


    Page 31

  • 8/4/2019 Java Material Bala


    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 dispatche

    forward() and include() calls. By using the new INCLUDE / FORWARD element in thedeployment 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 servleruns as if a single user were accessing using it alone, but u can use static variable to store and present information thatis 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 errorlogs and/or on console.

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

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

    Servletis 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 ServletHttpServlet 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 maintainthe 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 servletcan override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service()method only.

    Page 32

  • 8/4/2019 Java Material Bala


    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 youcan anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If aservlet relies upon system or network resources that may not be available f

Embed Size (px)