java material 90

Upload: gauravarjaria

Post on 05-Jul-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/16/2019 Java Material 90

    1/92

      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. ThereforeJava does not have global variables or global functions. (v) Java does not support multiple inheritance.

    Java does not support destructors but rather add the finali!e() function. (vi) Java does not have the delete operator.(vii) The "" and ## are not overloaded for $%& operations

    Q) Opps conceptsPolymorphism

     Ability to ta'e more than one form in ava we achieve this using ethod &verloading (compile time polymorphism)ethod overriding (runtime polymorphism)

    Inheritance$s the process by which one obect ac*uires the properties of another obect. The advantages of inheritance arereusability of code and accessibility of variables and methods of the super class by subclasses.

    Encapslation

    +rapping of data and function into a single unit called encapsulation. ,x- all ava programs.!Or)/othing but data hiding li'e the variables declared under private of a particular class are accessed only in that classand cannot access in any other the class. &r 0iding the information from others is called as ,ncapsulation. &r,ncapsulation is the mechanism that binds together code and data it manipulates and 'eeps both safe from outsideinterference and misuse.

    "bstraction/othing but representing the essential futures without including bac'ground details.

    #ynamicbindin$1ode associated with a given procedural call is not 'nown until the time of the call at runtime. 2ynamic binding

    is nothing but late binding.

    Q) class % ob&ect?  class class is a blue print of an obect

      Ob&ect  instance of class.

    Q) Ob&ect creation?  &bect is constructed either on a memory heap or on a stac'.

    'emory heap3enerally the obects are created using the new 'eyword. Some heap memory is allocated to this newly createdobect. This memory remains allocated throughout the life cycle of the obect. +hen the obect is no more referredthe memory allocated to the obect is eligible to be bac' on the heap.(tac2uring method calls obects are created for method arguments and method variables. These obects are created onstac'.

    Q) (ystem*ot*println!)  println() is a methd of ava.io.print+riter.

       4out5 is an instance variable of ava.lang.System class.

    Q) ransient % volatileTransient # The transient modifier applies to variables only the obect are variable will not persist. Transientvariables are not seriali!ed.

      6olatile # value will be changed unexpectedly by the other part of the program "it tells the compiler a variablemay change asynchronously due to threads" 

    Page 1

    1

  • 8/16/2019 Java Material 90

    2/92

    Q) "ccess (pecifies % "ccess modifiers? Access Specifiers   A.S gives access privileges to outside of application !or) others, they are Public Protected

    Private 2efaults. Access odifiers A. which gives additional meaning to data methods and classes final cannot be modified at any

    point of time.

    Private Pblic Protected -o modifier  

    (ame class /o 7es 7es 7es

    (ame paca$e (bclass /o 7es 7es 7es

    (ame paca$e non.sbclass /o 7es 7es 7es

    #ifferent paca$e sbclass /o 7es 7es /o

    #ifferent paca$e non.sbclass /o 7es /o /o

    Q) #efalt /ales

    long 89:; to 89:; ? double >.>d

    $nt 89;= to 89;= float >.>f  

    Short 89=@ to 89=@ oolean false

    yte 89B to 89B char > to 89B >>>E

     Q) 0yte code % JI compiler % J/' % J1E % J#2 

    yte code is a highly optimi!ed set of instructions. J6 is an interpreter for byte code. Translating a ava program

    into byte code helps ma'es it much easier to run a program in a wide variety of environment. J6 is an interpreter for byte code

     J$T (Just $n Time) is a part of J6 it compiles byte code into executable code in real time will increase the

    performance of the interpretations. JF, is an implementation of the Java 6irtual achine which actually executes Java programs.

     J2G is bundle of software that you can use to develop Java based software Tools provided by J2G is

    (i) avac < compiler (ii) ava < interpretor (iii) db < debugger (iv) avap 2isassembles(v) appletviewer < Applets (vi) avadoc documentation generator (vii) avah H1H header file generator 

    Q) Wrapper classesPrimitive data types can be converted into obects by using wrapper classes. These are ava.lang.pac'age.

    Q) #oes Java pass method ar$ments by vale or by reference?Java passes all arguments by value not by reference

    Q) "r$ments % Parameters+hile defining method variable passed in the method are called parameters. +hile using those methods valuespassed to those variables are called arguments.

    Q) Pblic static void main !(trin$ 34 ar$s) 

    +e can over?oad the main() method.

      +hat if the main method is declared as 4Private5I

      The program compiles properly but at runtime it will give ain method not public. essage 

    +hat if the static modifier is removed from the signature of the main methodI

      Program compiles. ut at runtime throws an error /oSuchethod,rror.  +e can write 4static pblic void5 instead of 4pblic static void5 but not 4pblic void static5.

      Protected static void main!), static void main!), private static void main!) are also valid. 

    $f $ do not provide the String array as the argument to the methodI

      Program compiles but throws a runtime error /oSuchethod,rror.  If no ar$ments on the command line, (trin$ array of 'ain method will be empty or nll?

      $t is empty. ut not null.

    Page 2

    2

  • 8/16/2019 Java Material 90

    3/92

     6ariables can have the same name as a method or a class

    Q) Can an application have mltiple classes havin$ main!) method? A) 7es it is possible. +hile starting the application we mention the class name to be run. The J6 will loo' for the ainmethod only in the class whose name you have mentioned. 0ence there is not conflict amongst the multiple classeshaving main method.

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

    Q) Constrctor The automatic initiali!ation is performed through the constructor constructor has same name has class name.

    1onstructor has no return type not even void. +e can pass the parameters to the constructor. this() is used to invo'e aconstructor of the same class. Super() is used to invo'e a super class constructor. 1onstructor is called immediatelyafter the obect is created before the new operator completes.

      1onstructor can se the access modifiers pblic, protected, private or have no access modifier  

    1onstructor can not use the modifiers abstract, static, final, native, synchroni5ed or strictfp

     

    1onstructor can be overloaded we cannot override.

      7ou cannot use this!) and (per!) in the same constructor.

    1lass A( A()K  System.out.println(4hello5)LMM

    1lass extends A K()K  System.out.println(4friend5)LMM

    1lass print KPublic static void main (String args NO)K b new ()LMo%p- hello friend

    Q) #iff Constrctor % 'ethod

    Constrctor 'ethod

    6se to instance of a class 7ropin$ &ava statement

    -o retrn type /oid !or) valid retrn type

    (ame name as class name "s a name e8cept the class method name, be$inwith lower case*

    9his: refer to another constrctor in the same

    class

    1efers to instance of class

    9(per: to invoe the sper class constrctor E8ecte an overridden method in the sper class

    9Inheritance: cannot be inherited Can be inherited

    We can 9overload: bt we cannot 9overridden: Can be inherited

    Will atomatically invoe when an ob&ect iscreated

    'ethod has called e8plicitly

    Q) 7arba$e collection 3.1 is also called automatic memory management as J6 automatically removes the unused variables%obects

    (value is null) from the memory. Qser program cannHt directly free the obect from memory instead it is the ob of thegarbage collector to automatically free the obects that are no longer referenced by a program. ,very class inherits

    Page 3

    3

  • 8/16/2019 Java Material 90

    4/92

    finali5e!) method from &ava*lan$*Ob&ect the finali!e() method is called by garbage collector when it determines nomore references to the obect exists. $n Java it is good idea to explicitly assign nll into a variable when no more in usecalling (ystem*$c!) and 1ntime*$c!), J6 tries to recycle the unused obects but there is no guarantee when all theobects will garbage collected. 3arbage collection is a lowpriority thread.

    3.1 is a low priority thread in ava 3.1 cannot be forced explicitly. J6 may do garbage collection if it is running shortof memory. The call System.gc() does /&T force the garbage collection but only suggests that the J6 may ma'e an

    effort to do garbage collection.

    Q) ;ow an ob&ect becomes eli$ible for 7arba$e Collection? A) An obect is eligible for garbage collection when no obect refers to it An obect also becomes eligible when itsreference is set to null. The obects referred by method variables or local variables are eligible for garbage collectionwhen they go out of scope.

    $nteger i new $nteger(B)Li nullL

    Q)

  • 8/16/2019 Java Material 90

    5/92

    • &verloaded methods do not have any restrictions on what retrn type of 'ethod !Feturn type are different) (or) e8ceptions can be thrown. That is something to worry about with overriding.

    • &verloading is used while implementing several methods that implement similar behavior but for different datatypes.

    Overridin$ !1ntime polymorphism)+hen a method in a subclass has the same name, retrn 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.

    • $f the superclass method is pblic the overriding method must be pblic.

    • $f the superclass method is protected the overriding method may be protected or pblic.

    • $f the superclass method is paca$e the overriding method may be paca$a$e protected or pblic.

    • $f the superclass methods is private it is not inherited and overriding is not an issue.

    • ethods declared as final cannot be overridden.

     The throws clause of the overriding method may only include exceptions that can be thrown by the superclass

    method including its subclasses.

    Only member method can be overriden, not member variable

    class ParentKint i >Lvoid amethod()K

      System.out.println(in Parent)L  M

    Mclass 1hild extends ParentK

    int i =>Lvoid amethod()K

      System.out.println(in 1hild)L

      MMclass TestKpublic static void main(StringNO args)KParent p new 1hild()L1hild c new 1hild()LSystem.out.print(ip.i )Lp.amethod ()LSystem.out.print(ic.i )Lc.amethod()LMM

    o%p= . i> in 1hild i=> in 1hild

    Q)

  • 8/16/2019 Java Material 90

    6/92

    Static variables methods are instantiated only once per class. $n other words they are class variables notinstance variables. $f you change the value of a static variable in a particular obect the value of that variable changesfor all instances of that class.

    Static methods can be referenced with the name of the class. $t may not access the instance variables of thatclass only its static variables. Rurther it may not invo'e instance (nonstatic) methods of that class unless it providesthem with some obect.

     +hen a member is declared a static it can be accessed before any obect of its class are created. $nstance variables declared as static are essentially global variables.

     $f you do not specify an initial value to an instance Static variable a default value will be assigned automatically.

     ethods declared as static have some restrictions they can access only static data they can only call other

    static data they cannot refer this or sper . Static methods cant be overriden to nonstatic 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 obects

     They cannot refer 4this5 are 4super5 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 crate class variables. To create a class

    variable put the 4static5 'eyword 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 4static5 'ey word .

    Instance methods  we define a method in a class in order to use that methods we need to first create obects of the

    class.

    Q) (tatic methods cannot access instance variables why? Static methods can be invo'ed before the obect is createdL $nstance variables are created only when the new

    obect is created. Since there is no possibility to the static method to access the instance variables. $nstance variablesare called called as nonstatic variables.

    Q) (trin$ % (trin$0ffer String is a fixed length of se*uence of characters String is immutable.

    Stringuffer represent growable and writeable character se*uence Stringuffer is mutable which means that itsvalue can be changed. $t allocates room for =:addition character space when no specific length is specified.Java.lang.Stringuffer is also a final class hence it cannot be sub classed. Stringuffer cannot be overridden thee*uals() method.

    Q) Conversions  String to Int Conversion= .

    int $ integer.value&f(48U5).int6alue()L  int x integer.parse$nt(4U;;5)L  float f float.value&f(8;.V).float6alue()L

      Int to (trin$ Conversion =.  String arg String.value&f(=>)L

    Q) (per!)Super() always calling the constructor of immediate super class super() must always be the first statements

    executed inside a subclass constructor.

    Page 6

    6

  • 8/16/2019 Java Material 90

    7/92

    Q) What are different types of inner classes? A) Nested top-level classes $f you declare a class within a class and specify the static modifier the compiler treats theclass ust li'e any other toplevel class. Any class outside the declaring class accesses the nested class with thedeclaring class name acting similarly to a pac'age. e.g. outer.inner. Toplevel inner classes implicitly have access onlyto static variables. There can also be inner interfaces. All of these are of the nested toplevel variety.

    Member classes  ember inner classes are ust li'e other member methods and member variables and access to the

    member class is restricted ust li'e methods and variables. This means a public member class acts similarly to a nestedtoplevel class. The primary difference between member classes and nested toplevel classes is that member classeshave access to the specific instance of the enclosing class.

    Local classes  ?ocal classes are li'e local variables specific to a bloc' of code. Their visibility is only within the bloc'of their declaration. $n order for the class to be useful beyond the declaration bloc' it would need to implement a morepublicly available interface. ecause 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.

     $nner class inside method cannot have static members or bloc's

    Q) Which circmstances yo se "bstract Class % Interface?# $f you need to change your design ma'e it an interface.# Abstract class provide some default behaviour A.1 are excellent candidates inside of application framewor'. A.1allow single inheritance model which should be very faster.

    Q) "bstract Class Any class that contain one are more abstract methods must also be declared as an abstract there can be no

    obect of an abstract class we cannot directly instantiate the abstract classes. A.1 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.  1ompile time error occur if an attempt to create an instance of an Abstract class.

      7ou cannot declare 4abstract constructor5 and 4abstract static method5.

      An 4abstract method5 also declared private, native, final, synchroni5ed, strictfp, protected* 

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

      Abstract class have visibility pblic, private, protected.

      y default the methods variables will ta'e the access modifiers is AdefaltB which is accessibility as pac'age.

     

     An abstract method declared in a nonabstract 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. 2eclaring such a class

    abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one ormore 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 AKPublic abstract callme()L6oid callmetoo()KM

    M

    class extends A(void callme()KM

    M

    Page 7

    7

  • 8/16/2019 Java Material 90

    8/92

    class Abstract2emoKpublic static void main(string argsNO)K

    b new ()Lb.callme()Lb.callmetoo()L

    MM

    Q) When we se "bstract class?") ?et us ta'e the behaviour of animals animals are capable of doing different things li'e flying digging+al'ing. ut these are some common operations performed by all animals but in a different way as well. +hen anoperation is performed in a different way it is a good candidate for an abstract method.

    Public Abstarctclass AnimalK  Public void eat(food food) K  M  public void sleep(int hours) K  M  public abstract void ma'e/oise()M

    public 2og extends AnimalK  public void ma'e/oise() K  System.out.println(4ar'W ar'5)L  MM

    public 1ow extends AnimalK  public void ma'e/oise() K  System.out.println(4mooW moo5)L  M

    M

    Q) Interface$nterface is similar to class but they lac' instance variable their methods are declared with out any body.

    $nterfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitlyabstract even if the abstract modifier is omitted. $nterface methods have no implementationL

    Interfaces are sefl for?a) 2eclaring methods that one or more classes are expected to implementb) 1apturing similarities between unrelated classes without forcing a class relationship.c) 2etermining an obectHs programming interface without revealing the actual body of the class.

    Why Interfaces?4 one interface multiple methods 4 signifies the polymorphism concept.

     

    $nterface has visibility pblic*

     

    $nterface 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 "bstract Pblic even if the public modifier is omitted.

      An interface methods cannot be declared protected, private, strictfp, native or synchroni5ed.

     All /ariables are implicitly final, pblic, static fields*

     

     A compile time error occurs if an interface has a simple name the same as any of itHs enclosing classes or interfaces.

      An $nterface can only declare constants and instance methods but cannot implement default behavior.

    Page 8

    8

  • 8/16/2019 Java Material 90

    9/92

      top.level interfaces may only be declared pblic, 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.

      $nterface can extend more than one interface.

    $nterface AK

    final static float pi ;.=UfLM

    class implements AK

    public float compute(float x float y) Kreturn(xXy)L

    MM

    class testK

    public static void main(String argsNO)K

     A a new ()La.compute()L

    MM

    Q) #iff Interface % "bstract Class? A.1 may have some executable methods and methods left unimplemented. $nterface contains no implementation

    code. An A.1 can have nonabstract methods. All methods of an $nterface are abstract.

     An A.1 can have instance variables. An $nterface cannot.

     An A.1 must have subclasses whereas interface canHt have subclasses An A.1 can define constructor. An $nterface cannot.

     An A.1 can have any visibility- public private protected. An $nterface visibility must be public (or) none.

     An A.1 can have instance methods that implement a default behavior. An $nterface 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 $nterface has no instance variables.

     &bects can be created for classes where as obects cannot be created for interfaces.

     All methods defined inside class are concrete. ethods declared inside interface are without any body.

    Q) What is the difference between "bstract class and Class? 1lasses are fully defined. Abstract classes are not fully defined (incomplete class)

     &bects can be created for classes there can be no obects of an abstract class.

    Q) What are some alternatives to inheritance? ") 2elegation is an alternative to inheritance. 2elegation means that you include an instance of another class as aninstance variable and forward messages to the instance. $t is often safer than inheritance because it forces you to thin'about each message you forward because the instance is of a 'nown class rather than a new class and because itdoesnEt force you to accept all the methods of the super class- you can provide only the methods that really ma'esense. &n the other hand it ma'es you write more code and it is harder to reuse (because it is not a subclass).

    Q) (eriali5able % E8ternali5able

    Page 9

    9

  • 8/16/2019 Java Material 90

    10/92

    Seriali!able # is an interface that extends seriali!able interface and sends data into streams in compressedformat. $t has 8 methods writeE8ternal!ob&ectOtpt ot), readE8ternal!ob&ectInpt in)*

    ,xternali!able is an $nterface that extends Seriali!able $nterface. And sends data into Streams in

    1ompressed Rormat. $t has two methods write,xternal(&bect&uput out) and read,xternal(&bect$nput in)

    Q) Internalisation % ocali5ation

    $nternalisation a'ing a programme to flexible to run in any locale called internalisation.?ocali!ation a'ing a programme to flexible to run in a specific locale called ?ocali!ation.

    Q) (eriali5ationSeriali!ation is the process of writing the state of the obect to a byte stream this is useful when ever you want

    to save the state of your programme to a persistence storage area. 

    Q) (ynchroni5ation Synchroni!ation 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) +hen 8 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 synchroni!ation.

    (i) ,x- Synchroni!ing a function-public synchroni!ed void ethod= () KM

    (i) ,x- Synchroni!ing a bloc' of code inside a function-public myRunction ()K synchroni!ed (this) K  MM

    (iii) ,x- public Synchroni!ed void main(String argsNO)  ut this is not the right approach because it means servlet can handle one re*uest at a time.

    (iv) ,x- public Synchroni!ed void service()  Servlet handle one re*uest at a time in a serialized manner 

    Q) #ifferent level of locin$ sin$ (ynchroni5ation?") 1lass level &bect level ethod level loc' level

    Q) 'onitor  A monitor is a mutex once a thread enter a monitor all other threads must wait until that thread exist the

    monitor.

    Q) #iff D D and *eals!)?")  1ompare obect references whether they refer to the sane instance are not.

      e*uals () method compare the characters in the string obect.

      Stringuffer sb= new Stringuffer(Amit)LStringuffer sb8 new Stringuffer(Amit)L

      String s= AmitLString s8 AmitLString s; new String(abcd)LString sU new String(abcd)L

      String ss= AmitL

    (sb=sb8)L R (s=.e*uals(s8))L T

    (sb=.e*uals(sb8))L R ((s=s8))L T

    Page 10

    10

  • 8/16/2019 Java Material 90

    11/92

    (sb=.e*uals(ss=))L R

    (s;.e*uals(sU))L T

    ((s;sU))L R

      String s= abcL  String s8 new String(abc)L  s= s8 R

      s=.e*uals(s8)) T

     

    Q) 'arer Interfaces !or) a$$ed Interfaces =. An $nterface with no methods. $s called mar'er $nterfaces eg. Seriali!able SingleThread odel 1loneable.

    Q) 61 Encodin$ % 61 #ecodin$  QF? ,ncoding is the method of replacing all the spaces and other extra characters into their corresponding 0ex1haracters and QF? 2ecoding is the reverse process converting all 0ex 1haracters bac' their normal form.

    Q) 61 % 61Connection

    QF? is to identify a resource in a networ' is only used to read something from the networ'.QF? url new QF?(protocol name host name port url specifier)

    QF?1onnection can establish communication between two programs in the networ'.QF? hp new QF?(4www.yahoo.com5)LQF?1onnection con hp.open1onnection()L

    Q) 1ntime classFuntime class encapsulate the runtime environment. 7ou cannot instantiate a 1ntime obect. 7ou can get a

    reference to the current Funtime obect by calling the static method 1ntime*$et1ntime!)

    Funtime r Funtime.getFuntime()?ong mem=Lem= r.freeemory()Lem= r.totalemory()L

    Q) E8ecte other pro$rams7ou can use ava to execute other heavy weight process on your multi tas'ing operating system several form of

    exec() method allow you to name the programme you want to run.Funtime r Funtime.getFuntime()LProcess p nullLTryK

    p r.exce(4notepad5)Lp.waiRor()

      M

    Q) (ystem class

    System class hold a collection of static methods and variables. The standard input output error output of the ava runtime are stored in the in, ot, err variables.

    Q) -ative 'ethods/ative methods are used to call subroutine that is written in a language other than ava this subroutine exist as

    executable code for the 1PQ.

    Q) Cloneable Interface Any class that implements the cloneable interface can be cloned this interface defines no methods. $t is used to

    indicate that a class allow a bit wise copy of an obect to be made.

    Page 11

    11

  • 8/16/2019 Java Material 90

    12/92

    Q) Clone3enerate a duplicate copy of the obect on which it is called. 1loning is a dangerous action.

    Q) Comparable Interface1lasses that implements comparable contain obects that can be compared in some meaningful manner. This

    interface having one method compare the invo'ing obect with the obect. Ror sorting comparable interface will be used.,x- int compareTo(&bect ob)

    Q) Class1lass encapsulate the runtime state of an obect or interface. ethods in this class are

    static 1lass for/ame(String name) throws1lass/otRound,xception

    get1lass()

    get1lass?oader() get1onstructor()

    getRield() get2eclaredRields()

    getethods() get2eclearedethods()

    get$nterface() getSuper1lass()

    Q) &ava*&lan$*1eflect !paca$e)Feflection is the ability of software to analyse it self to obtain information about the field constructor methods

    modifier of class. 7ou need this information to build software tools that enables you to wor' with ava beanscomponents.

    Q) InstanceOf $nstanceof means by which your program can obtain run time type information about an obect.

    ,x- A a new A()L  a.instance&f AL

    Q) Java pass ar$ments by vale are by reference?") y value

    Q) Java lac pointers how do I implements classic pointer strctres lie lined list?") Qsing obect reference.

    Q) &ava* E8eicro soft provided sd' for ava which includes 4exegentool5. This converts class file into a 4.,xec5 form. &nlydisadvantage is user needs a .S ava 6. installed.

    Q) 0in % ib in &d?in contains all tools such as avac appletviewer and awt tool.?ib contains AP$ and all pac'ages.

    Page 12

    12

  • 8/16/2019 Java Material 90

    13/92

     

    Collections > void add (int index, Object element), boolean add ( Object  o), boolean addll ( Collection c), booleanaddll (int index, Collection c), Object remove(int index), void clear(), Iterator iterator()!

    "bstract (et ,xtends Abstract collection $mplements Set interface.

    "rray ist  Array ?ist extends Abstract?ist and implements the ?ist interface. Array?ist is a variable length of

    array of obect references Array?ist support dynamic array that grow as needed. A.? allow rapid random access toelement but slow for insertion and deletion from the middle of the list. $t will allow dplicate elements* Searching is

    very faster. A.? internal node traversal from the start to the end of the collection is significantly faster than ?in'ed ?ist traversal.

     A.? is a replacement for 6ector.

    Methods>>void add (int index, Object  element), boolean add ( Object o), boolean addll ( Collection c), booleanaddll (int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexO(Objectelement), int latIndexO(Object element), int si#e(), Object $% torray()! 

    ined ist ,xtends AbstactSe*uential?ist and implements ?ist interface. ?.? provide optimal se*uence access

    in expensive insertion and deletion from the middle of the list relatively slow for random access. +hen ever there isa lot of insertion % deletion we have to go for ?.?. ?.? is accessed via a reference to the first node of the list. ,achsubse*uent node is accessed via a reference to the first node of the list. ,ach subse*uent node is accessed via thelin'reference number stored in the previous node.

    Methods>> void add&irst(Object obj), add'ast(Object obj), Object get&irst(), Object get'ast(),void add  (int index,Object  element), boolean add( Object o), boolean addll ( Collection c), boolean addll (int index, Collection c),Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexO(Object element),int latIndexO(Object element), int si#e(), Object $% torray()!

    ;ash (et ,xtends AbstractSet $mplements Set interface it creates a collection that uses 0ashTable for

    storage 0.S does not guarantee the order of its elements if u need storage go for TreeSet. $t will not allowduplicate elements

    Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int si#e()!

    Page 13

    13

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html

  • 8/16/2019 Java Material 90

    14/92

    ree (et ,xtends Abstract Set $mplements Set interface. &bects are stored in sorted ascending order. Access

    and retrial times are *uite fast. $t will not allow duplicate elements

    Methods>> boolean add(Object o), boolean addll ( Collection c), Object irst(), Object last(), Iterator iterator(),boolean remove(Object o)!

    ;ash 'ap ,xtends Abstract ap and implements ap interface. 0. does not guarantee the order of elements

    so the order in which the elements are added to a 0. is not necessary the order in which they are ready by theiterate. 0. permits only one nll vales in it while 0.T does not

     

    0ashap is similar to 0ashtable.

    ree 'ap implements ap interface a Treeap provides an efficient means of storing 'ey%value pairs in sorted

    order and allow rapid retrieval. 

    "bstract (eential ist ,xtends Abstract collectionL use se*uential access of its elements.

    Collection Interfaces

    Collection 1ollection is a group of obects collection does not allow dplicate elements.

    Methods >> boolean add(Object obj), boolean addll(c), int i#e(), Object$% torray(), oolean is*mpty(), Object $%torray(), void clear().Collection c), Iterator iterator(),boolean remove(Object obj), boolean removell(Collection*xceptions >> +nupportedointer*xception, ClassCast*xception!

    ist ?ist will extend 1ollection $nterface list stores a seence of elements that can contain dplicates

    elements can be accessed their position in the list using a !ero based index ( it can access ob&ects by inde8).

    Methods >> void add(int index, Object obj), boolean addll(int index, Collection c), Object get(int index), intindexO(Object obj), int lastIndexO(Object obj), 'istIterator iterator(), Object remove(int index), Objectremovell( 1ollection c ), Object set(int index, Object obj)!

    (et Set will extend 1ollection $nterface Set cannot contain duplicate elements. Set stored elements in anunordered way. (it can access ob&ects by vale).

    (orted (et ,xtends Set to handle sorted sets Sorted Set elements will be in ascending order.

    Methods >> Object last(), Object irst(), compactor compactor()!  *xceptions >> -ullointer*xception, ClassCast*xception, -ouch*lement*xception!

    'ap ap maps uni*ue 'ey to value in a map for every 'ey there is a corresponding value and you will loo'up

    the values using 'eys. ap cannot contain dplicate 4'ey5 and 4value5. $n map both the 4key 5 4value5 areob&ects.

     Methods >> Object get(Object . ) Object put(Object ., Object v ) int si#e(), remove(Object object), booleanis*mpty()

    Iterator $terator  ma'es it easier to traverse through the elements of a collection. $t also has an extra feature not

    present in the older ,numeration interface the ability to remove elements. This ma'es it easy to perform a searchthrough a collection and strip out unwanted entries.

    efore accessing a collection through an iterator you must obtain one if the collection classes provide aniterator() method that returns an iterator to the start of the collection. y using iterator obect you can access eachelement in the collection one element at a time.

    Methods >> boolean has-ext(), object next(),void remove()

    ,x- Aray?ist arr new Array?ist()L

    Page 14

    14

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html

  • 8/16/2019 Java Material 90

    15/92

     Arr.add(4c5)L  $terator itr arr.iterator()L

     +hile(itr.hash/ext()) K

    &bect element itr.next()L M

      ist Iterator ?ist $terator gives the ability to access the collection either forward%bac'ward direction

    Legacy Classes

    #ictionary is an abstract class that represent 'ey%value storage repository and operates much li'e 4ap5 once

    the value is stored you can retrieve it by using 'ey.

    ;ash able 0ashTable stores 'ey%value pairs in hash table 0ashTable is synchronized  when using hash table

    you have to specify an object that is used as a .ey  and the value that you want to lin'ed to that 'ey. The 'ey is thenhashed and the resulting hash code is used as the index at which the value is stored with the table. Qse 0.T tostore large amount of data it will search as fast as vector. 0.T store the data in se*uential order.

    Methods>> boolean contains/ey(Object .ey), boolean contains0alue(Object value), Object get(Object .ey), Object

     put(Object .ey, Object value)

    (tac is a sub class of vector stac' includes all the methods defined by vector and adds several of its own.

    /ector 6ector holds any type of obects it is not fixed length and vector is synchronized . +e can store

    primitive data types as well as ob&ects. 2efault length of vector is up to =>.

    Methods>> inal void add*lement(Object element), inal int si#e(), inal int capacity(), inal booleanremove*lementt(int index), inal void removell*lements()!

    Properties is a subclass of 0ashTable it is used to maintain the list of values in which the key!value" is

    String#

    Legacy Interfaces

      Enmeration 2efine methods by which you can enumerate the elements in a collection of obects. ,numeration

    is synchroni!ed.Methods>> hasMore*lements(),Object next*lement()!

    Q) Which is the preferred collection class to se for storin$ database reslt sets?") ?in'ed?ist is the best one benefits include-=. Fetains the original retrieval order. 8. 0as *uic' insertion at the head%tail ;. 2oesnHt have an internal si!e limitationli'e a 6ector where when the si!e is exceeded a new internal structure is created. U. Permits usercontrolledsynchroni!ation unli'e the pre1ollections 6ector which is always synchroni!ed

    FesultSet result stmt.executeYuery(...)L?ist list new ?in'ed?ist()Lwhile(result.next()) Klist.add(result.getString(col))LM

    $f there are multiple columns in the result set youHll have to combine them into their own data structure for each row. Arrays wor' well for that as you 'now the si!e 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 ;ashable . If hash table is so fast, why donFt we se it for everythin$?") &ne reason is that in a hash table the relations among 'eys disappear so that certain operations (other than searchinsertion and deletion) cannot be easily implemented. Ror example it is hard to traverse a hash table according to theorder of the 'ey. 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 lin'ed list or tree).

    Page 15

    15

  • 8/16/2019 Java Material 90

    16/92

    0ashtable has two parameters that affect its efficiency- its capacity and its load factor. The load factor should bebetween >.> and =.>. +hen 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. ?arger load factors use memory moreefficiently at the expense of larger expected time per loo'up.

    $f many entries are to be put into a 0ashtable creating it with a sufficiently large capacity may allow the entries to beinserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

    Q) ;ow does a ;ashtable internally maintain the ey.vale pairs?") The 0ashtable class uses an internal (private) class named ,ntry to hold the 'eyvalue pairs. All entries of the0ashtable are stored in an array of ,ntry obects with the hash value of the 'ey serving as the index. $f two or moredifferent 'eys have the same hash value these entries are stored as a lin'ed list under the same index.

    Q) "rray Array of fixed length of same data typeL we can store primitive data types as well as class obects.

     

     Arrays are initiali!ed to the default value of their type when they are created not declared even if they are local

    variables

    Q) #iff Iterator % Enmeration % ist Iterator $terator is not synchroni!ed and enumeration is synchroni!ed. oth are interface $terator is collection interface

    that extends from C?istE interface. ,numeration is a legacy interface ,numeration having 8 methods Coolean

    hasore,lements()E C&bect /ext,lement()E. $terator having ; methods Cboolean has/ext()E Cobect next()E Cvoidremove()E. $terator also has an extra feature not present in the older ,numeration interface the ability to removeelements there is one method 4void remove()5.

    ist Iterator $t is an interface ?ist $terator extends $terator to allow bidirectional traversal of a list and modification of the

    elements. ethods are Chas/ext()E C hasPrevious()E.

    Q) #iff ;ashable % ;ash'ap oth provide 'ey%value to access the data. The 0.T is one of the collection original collection classes in ava. 0.P is

    part of new collection framewor'. 0.T is synchroni!ed and 0. is not.

     0. permits null values in it while 0.T does not.

     $terator in the 0.P is failsafe while the enumerator for the 0.T is not.

    Q) Convertin$ from a Collection to an array . and bac a$ain?The collection interface define the toArray() method which returns an array of obects. $f you want to convert bac' to acollection implementation you could manually traverse each element of the array and add it using the add(&bect)method.

    %% 1onvert from a collection to an array&bectNO array c.toArray()L

    %% 1onvert bac' to a collection1ollection c8 new 0ashSet()Lfor(int i >L i " array.lengthL i)K

    c8.add(arrayNiO)LM

    Q) ;ow do I loo thro$h each element of a ;ash'ap?") "select idswf nameswf on1hangeshowStandard+R() stylewidth-=B@pxL#

    "option value#ltLSelect Standard +or'RlowgtL"%option#"Z

    hmap (0ashap)re*uest.getAttribute(stdwf)Lif ( hmap.si!e() W >)K

    int len hmap.si!e()L

    Page 16

    16

  • 8/16/2019 Java Material 90

    17/92

    Set set hmap.'eySet()L$terator it set.iterator()Lwhile(it.has/ext())K

    $nteger 'ey ($nteger)it.next()LZ#

    "option value"Z'eyZ##"Z(String)hmap.get('ey)Z#"%option#

    "ZMM

    Z#"%select#

    Q) 1etrievin$ data from a collection?public class $terator2emoK  public static void main(String argsNO)  K

      1ollection c new Array?ist()L

      %% Add every parameter to our array list  for (int indx >L indx " args.lengthL indx)  K  c.add(argsNindxO)L  M

      %% ,xamine only those parameters that start with   $terator i c.iterator()L

      %% PF, - 1ollection has all parameters  while (i.has/ext())

      K  String param (String) i.next()L

      %% Qse the remove method of iterator   if (W param.starts+ith() )  i.remove()L  M  %% P&ST- 1ollection only has parameters that start with

      %% 2emonstrate by dumping collection contents  $terator i8 c.iterator()L  while (i8.has/ext())  K  System.out.println (Param - i8.next())L  M  MM

    Q) ;ow do I sort an array?") 

     Arrays class provides a series of sort() methods for sorting arrays. $f the array is an array of primitives (or) an array

    of a class that implements 1omparable then you can ust call the method directly- Arrays.sort(theArray)L$f however it is an array of ob&ects that donHt implement the 1omparable interface then you need to provide a custom

    1omparator to help you sort the elements in the array.

    Page 17

    17

  • 8/16/2019 Java Material 90

    18/92

     Arrays.sort(theArray the1omparator)L

    DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD

    E8ception ;andlin$

    Ob&ect

     hrowable

      Error E8ception

      "W Error /irtal 'achine Error   Compile time*E8 1ntime E8ception

    !checed) !6ncheced)

      OtOf'emory*E (tacOver

  • 8/16/2019 Java Material 90

    19/92

    Q) What happens if an e8ception is not ca$ht? A) An uncaught exception results in the uncaught,xception() method of the threadHs Thread3roup being invo'ed 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 clase to handle an e8ception that isthrown within the body of the try statement?The exception propagates up to the next higher level trycatch statement (if any) or results in the programHs termination.

    Q) Checed % 6nCheced E8ception =.1hec'ed exception is some subclass of ,xception. a'ing an exception chec'ed forces client programmers to

    deal with the possibility that the exception will be thrown. eg $&,xception thrown by ava.io.Rile$nputStreamHs read()method[ 

    Qnchec'ed exceptions are Funtime,xception and any of its subclasses. 1lass ,rror and its subclasses also areunchec'ed. +ith an unchec'ed exception however the compiler doesnHt force client programmers either to catch theexception or declare it in a throws clause. $n fact client programmers may not even 'now that the exception could bethrown. eg String$ndex&ut&founds,xception thrown by StringHs charAt() method[ 1hec'ed exceptions must be caughtat compile time. Funtime exceptions do not need to be. ,rrors often cannot be.

    Checed E8ceptions 6n checed e8ception

    1lass/otRound,xception Arithmetic,xception/oSuchethod,xception Array$ndex&ut&found,xception

    /oSuchRield,xception 1lasscast,xception

    $nterrupted,xception $llegalArgument,xception

    $llegalAccess,xception $llegalonitorSate,xception

    1lone/otSupported,xception $llegalThreadState,xception

    $ndex&ut&found,xception

    /ullPointer,xception

    /umberRormat,xception

    String$ndex&ut&founds

    OtOf'emoryError ..B Signals that J6 has run out of memory and that the garbage collector is unable to claim

    any more free memory.(tacOver

  • 8/16/2019 Java Material 90

    20/92

    Throwable get1ause()Throwable init1ause(Throwable)Throwable(String Throwable)Throwable(Throwable)

    The Throwable argument to init1ause and the Throwable constructors is the exception that caused the currentexception. get1ause returns the exception that caused the current exception and init1ause returns the current

    exception.

    Q) Primitive mlti tasin$  $f the threads of different priorities shifting the control depend on the priority i.e.L a thread with higher priority isexecuted first than the thread with lower priority. This process of shifting control is 'nown as primitive multi tas'ing.

    Q) ;ttp (tats CodesTo inform the client of a problem at the server end you call the 4send,rror5 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 $ype %escription

    =xx $nformational Fe*uested received continuing to process

    8xx Success The action was successfully received understood and accepted

    ;xx Fedirection Rurther action must be ta'en in order to complete the re*uestUxx 1lient ,rror The re*uest contains bad syntax or cannot be fulfilled

    @xx Server ,rror The server failed to fulfil valid re*uest

    "ll Paca$es

    Q) hread Classethods-

    get/ame() run()

    getPriority() Sleep()isAlive() Start()

     oin()

    Q) Ob&ect class All other classes are sub classes of obect class &bect class is a super class of all other class.

    ethods-

    void notify() void notifyAll()

    &bect clone() Sting toString()

    boolean e*uals(&bect obect) void wait()

    void finali!e() void wait(long milliseconds int nanoseconds)

    int hashcode()

    Q) throwable classethods-

    String getessage() 6oid printStac'Trace()

    String toString() Throwable fill$nStac'Trace()

    Q) Java8*servlet Paca$e

    Interfaces Classes &'ceptions

    Servlet 3enericServlet Servlet,xception

    Servlet1onfig Servlet$nputStream Qnavaliable,xception

    Servlet1ontext Servlet&utputStream

    Page 20

    20

  • 8/16/2019 Java Material 90

    21/92

    ServletFe*uest

    (ervletConte8t"ttribteEvent

    ServletFesponse

    SingleThreadodel

    (ervletConte8tistener 

    (ervletConte8t"ttribteistener 

    (ervletConte8tInitiali5ation parameters

    (ervlet1eest"ttribteistener 

    (ervlet1eestistner 

  • 8/16/2019 Java Material 90

    22/92

     public abstract String getFemote0ost()L public abstract String getServer/ame()L public abstract int getServerPort()L 1eest#ispatcher $et1eest#ispatcher!(trin$ path)G pblic int $etocalPort!)G %% servlet *H pblic int $et1emotePort!)G %% servlet *H pblic (trin$ $etocal-ame!)G %% servlet *H

     pblic (trin$ $etocal"ddr!)G %% servlet *H

    ServletFesponse ($)  public abstract String get1haracter,ncoding()L

    public abstract Print+riter get+riter() throws $&,xceptionL public abstract void set1ontent?ength(int len)L public abstract void set1ontentType(String type)L

    Q) Java8*servlet*;ttp Paca$e

    Interfaces Classes &'ceptions

    0ttpServletFe*uest 1oo'ies Servlet,xception

    0ttpServletFesponse 0ttpServlet (Abstarct 1lass) Qnavaliable,xception

    0ttpSession 0ttpQtils

    ;ttp(essionistener ;ttp(ession0indin$Event

    ;ttp(ession"ctivationistener ;ttp(ession"ttribteistener 

    ;ttp(ession0indin$istener 

    0ttpSession1ontext (deprecated)

    Rilter 

    (ervletConte8tistener !I) pblic void conte8tInitiali5ed!(ervletConte8tEvent event)

      pblic void conte8t#estroyed!(ervletConte8tEvent event)

    (ervletConte8t"ttribteistener !I)  public void attributeAdded(Servlet1ontextAttribute,vent scab)

      public void attributeFemoved(Servlet1ontextAttribute,vent scab)  public void attributeFeplaced(Servlet1ontextAttribute,vent scab)

    (ervletConte8tInitila5ation parameters

    Cooies !C) public &bect clone()L

    public int getaxAge()Lpublic String get/ame()Lpublic String getPath()Lpublic String get6alue()Lpublic int get6ersion()Lpublic void setaxAge(int expiry)Lpublic void setPath(String uri)Lpublic void set6alue(String new6alue)Lpublic void set6ersion(int v)L

    ;ttp(ervlet !C)  public void service(ServletFe*uest req, ServletResponse res)protected void do2elete (0ttpServletFe*uest re* 0ttpServletFesponse res)protected void do3et (0ttpServletFe*uest re* 0ttpServletFesponse res)protected void do&ptions(0ttpServletFe*uest re* 0ttpServletFesponse res)

      protected void doPost(0ttpServletFe*uest re* 0ttpServletFesponse res)protected void doPut(0ttpServletFe*uest re* 0ttpServletFesponse res)protected void doTrace(0ttpServletFe*uest re* 0ttpServletFesponse res)protected long get?astodified(0ttpServletFe*uest re*)L

      protected void service(0ttpServletFe*uest re* 0ttpServletFesponse res)

    Page 22

    22

  • 8/16/2019 Java Material 90

    23/92

    ;ttp(essionbindin$Event !C) public String get/ame()L

      public 0ttpSession getSession()L

    ;ttp(ervlet1eest !I) public abstract 1oo'ieNO get1oo'ies()L

    public abstract String get0eader(String name)L  public abstract ,numeration get0eader/ames()L  public abstract String getYueryString()L

      public abstract String getFemoteQser()L  public abstract String getFe*uestedSession$d()L  public abstract String getFe*uestQF$()L  public abstract String getServletPath()L  public abstract 0ttpSession getSession(boolean create)L  public abstract boolean isFe*uestedSession$dRrom1oo'ie()L  public abstract boolean isFe*uestedSession$dRromQrl()Lpublic abstract boolean isFe*uestedSession$d6alid()L

    ;ttp(ervlet1esponse !I) public abstract void add1oo'ie(1oo'ie coo'ie)L

    public abstract String encodeFedirectQrl(String url)Lpublic abstract String encodeQrl(String url)Lpublic abstract void send,rror(int sc String msg) throws $&,xceptionL

     public abstract void sendFedirect(String location) throws $&,xceptionL pblic abstract void addInt;eader!(trin$ header, int vale)G pblic abstract void add#ate;eader!(trin$ header, lon$ vale)G public abstract void set0eader(String name String value)L pblic abstract void setInt;eader!(trin$ header, int vale)G pblic abstract void set#ate;eader!(trin$ header, lon$ vale)G public void setStatus()L

    ;ttp(ession !I) public abstract long get1reationTime()L

      public abstract String get$d()L  public setAttribute(String name &bect value)L  public getAttribute(String name &bect value)L  public remove Attribute(String name &bect value)L  public abstract long get?astAccessedTime()L  public abstract 0ttpSession1ontext getSession1ontext()L  public abstract &bect get6alue(String name)L  public abstract StringNO get6alue/ames()L  public abstract void invalidate()L  public abstract boolean is/ew()L  public abstract void put6alue(String name &bect value)L  public abstract void remove6alue(String name)L  public setax$nactive$ntervel()L

    ;ttp(essionistener !I) public void session1reated(0ttpSession,vent event)

      public void session2estroyed(0ttpSession,vent event)

    ;ttp(ession"ttribteistener !I) public void attributeAdded(Servlet1ontextAttribute,vent scab)

      public void attributeFemoved(Servlet1ontextAttribute,vent scab)  public void attributeFeplaced(Servlet1ontextAttribute,vent scab)

    ;ttp(ession0indin$istener !I)

    public void 0ttpSessioninding?istener.valueound(0ttpSessioninding,vent event)public void 0ttpSessioninding?istener.valueQnbound(0ttpSessioninding,vent event)

    ;ttp(ession"ctivationistener !I)

    public void session2idActivate(0ttpSession,vent event)public void session+illpassivate(0ttpSession,vent event)

    Page 23

    23

  • 8/16/2019 Java Material 90

    24/92

  • 8/16/2019 Java Material 90

    25/92

    Page 25

    25

  • 8/16/2019 Java Material 90

    26/92

    (E1/E Qestions

    Class path-  set path c-D8sd'=.U.8Dbin set classpath c-D 8sd'=.U.8DlibDtools.arLc-Dservlet.ar  [email protected] shortcut

    Q) (ervletServlet is server side component a servlet is small plug gable extension to the server and servlets are used to

    extend the functionality of the avaenabled server. Servlets are durable obects means that they remain in memoryspecially instructed to be destroyed. Servlets will be loaded in the  Address space of web server. Servlet are loaded ; ways =) +hen the web sever starts 8) 7ou can set this in the configuration file ;) Through an

    administration interface.

    Q) What is emporary (ervlet?") +hen we sent a re*uest to access a JSP servlet container internally creates a HservletH executes it. This servlet iscalled as HTemporary servletH. $n general this servlet will be deleted immediately to create execute a servlet base on a

    JSP we can use following command.Java weblogic.spc\'eepgenerated X.sp

    Q) What is the difference between (erver and Container?") A server provides many services to the clients A server may contain one or more containers such as eb containersservlet%sp container. 0ere a container holds a set of obects.

    Q) (ervlet Container The servlet container is a part of a +eb server (or) Application server that provides the networ' services over

    which re*uests and responses are sent decodes $,based re*uests and formats $,based responses. A servletcontainer also contains and manages servlets through their lifecycle.

     A servlet container can be built into a host +eb server or installed as an addon component to a +eb Server via thatserverEs native extension AP$. All servlet containers must support 0TTP as a protocol for re*uests and

    responses but additional re*uest%responsebased protocols such as 0TTPS (0TTP over SS?) may be supported.

    Q) 7enerally (ervlets are sed for complete ;' $eneration* If yo want to $enerate partial ;'Fs thatinclde some static te8t as well as some dynamic te8t, what method do yo se?") Qsing HFe*uest2ispather.include(4xx.html5) in the servlet code we can mix the partial static 0T? 2irectory page.

    ,x- Fe*uest2ispatcher rdServlet1ontext.getFe*uest2ispatcher(4xx.html5)L rd.include(re*uestresponse)L

    Q) (ervlet ife cycle

    Public void init (Servlet1onfig config) throws Servlet,xceptionpublic void service (ServletFe*uest re* ServletFesponse res) throws Servlet,xception $&,xceptionpublic void destroy ()

     The +eb server when loading the servlet calls the init method once. (The init method typically establishes database

    connections.)

     Any re*uest from client is handled initially by the service () method before delegating to the do*'' () methods in the

    case of 0ttpServlet. $f u put 4Private: modifier for the service() it will give compile time error.

     +hen your application is stopped (or) Servlet 1ontainer shuts down your ServletHs destroy !) method will be called.This allows you to free any resources you may have got hold of in your ServletHs init () method this will call only once.

    Page 26

    26

  • 8/16/2019 Java Material 90

    27/92

    (ervletE8ception  Signals that some error occurred during the processin$ of the re*uest and the container should

    ta'e appropriate measures to clean up the re*uest.

     IOE8ception  Signals that Servlet is unable to handle re*uests either temporarily or permanently.

    Q) Why there is no constrctor in servlet?") A servlet is ust li'e an applet in the respect that it has an init() method that acts as a constructor an initiali!ation

    code you need to run should e place in the init() since it get called when the servlet is first loaded.

    Q) Can we se the constrctor, instead of init!), to initiali5e servlet?") 7es of course you can use. ThereEs nothing to stop you. ut you shouldnEt. The original reason for init() was thatancient versions of Java couldnEt dynamically invo'e constructors with arguments so there was no way to give theconstructur a Servlet1onfig. That no longer applies but servlet containers still will only call your noarg constructor. Soyou wonEt have access to a Servlet1onfig or Servlet1ontext.

    Q) Can we leave init!) method empty and insted can we write initili5ation code inside servletFs constrctor?") /o because the container passes the Servlet1onfig obect to the servlet only when it calls the init method. SoServlet1onfig will not be accessible in the constructor.

    Q) #irectory (trctre of Web "pplications?

    ")  +ebApp%(Publicly available files such as  ] .sp .html .pg .gif)  ]

    +,$/R%  ]  classes%(Java classes (ervlets)  ]  lib%( &ar files)  ]  web*8ml !ta$lib*tld) 

    ]  weblogic.xml 

    +AF# +AFfile can be placed in a serverEs webapps directory

    Q) Web*8ml= ."webapp#AK.. #efines Web"pp initiali5ation parameters*..B"contextparam#

    "paramname#locale"%paramname#"paramvalue#QS"%paramvalue#

    "%contextparam#

    AK.. #efines filters and specifies filter mappin$ ..B"filter#

    "filtername#Test Rilter"%filtername#"filterclass#filters.TestRilter"%filterclass#

    "initparam#  "paramname#locale"%paramname#

      "paramvalue#QS"%paramvalue#"%initparam#

    "%filter#

    "filtermapping#"filtername#Test Rilter"%filtername#"servletname#TestServlet"%servletname#

    "%filtermapping#

    Page 27

    27

  • 8/16/2019 Java Material 90

    28/92

    AK.. #efines application events listeners ..B"listener#  "listenerclass#

    listeners.yServlet1ontext?istener"%listenerclass#  "%listener#"listener#

      "listenerclass#listeners.ySession1um1ontext?istener 

      "%listenerclass#"%listener#

    AK.. #efines servlets ..B"servlet#

    "servletname#0elloServlet"%servletname#"servletclass#servlets.0elloServlet"%servletclass#

    "initparam#"paramname#driverclassname"%paramname#"paramvalue#sun.dbc.odbc.Jdbc&dbc2river"%paramvalue#

    "%initparam#"initparam#

    "paramname#dburl"%paramname#"paramvalue#dbc-odbc-ySY?&21"%paramvalue#

    "%initparam#  "securityroleref#

    AK.. role.name is sed in ;ttp(ervlet1eest*is6serIn1ole!(trin$ role) method* ..B"rolename#manager"%rolename#AK.. role.lin is one of the role.names specified in secrity.role elements* ..B"rolelin'#supervisor"%rolelin'#

      "%securityroleref#"%servlet#

    AK.. #efines servlet mappin$s ..B

    "servletmapping#"servletname#0elloServlet"%servletname#"urlpattern#X.hello"%urlpattern#

    "%servletmapping#

    AK..specifies session timeot as @L mintes* ..B"sessionconfig#

    "sessiontimeout#;>"%sessiontimeout#"sessionconfig#

    "welcomefilelist#"welcomefile#index.html"%welcomefile#

    "%welcomefilelist#

    "W Error pa$e  #"errorpage#

    "errorcode#U>U"%errorcode#"location#notfoundpage.sp"%location#

    "%errorpage#

    "errorpage#"exceptiontype#ava.s*l.SY?,xception"%exceptiontype#"location#s*lexception.sp"%location#

    "%errorpage#

    Page 28

    28

  • 8/16/2019 Java Material 90

    29/92

    "taglib#"tagliburi#http-%%abc.com%testlib"%tagliburi#"tagliblocation#%+,$/R%tlds%testlib.tld"%tagliblocation#

    "%taglib#"taglib#"tagliburi#%examplelib"%tagliburi#"tagliblocation#%+,$/R%tlds%examplelib.tld"%tagliblocation#

    "%taglib#

    AK.. only PO( method is protected ..B"httpmethod#P&ST"%httpmethod#

    "webresourcecollection#"webresourcename#Another Protected Area"%webresourcename#"urlpattern#X.hello"%urlpattern#

    "%webresourcecollection#

    AK.. ath.method can be= 0"(IC, ->> :->> =8->> =^->>"%runat#"%servlet#

    Q) (ervletConfi$ Interface % (ervletConte8 Interfaces(ervletConfi$  Servlet1onfig obect is used to obtain configuration data when it is loaded. There can be multiple

    Servlet1onfig obects in a single web application.This obect defines how a servlet is to be configured is passed to a servlet in its init method. ost servlet

    containers provide a way to configure a servlet at runtime (usually through flat file) and set up its initial parameters. Thecontainer in turn passes these parameters to the servlet via the Servet1onfig.

    E8=."webapp#

    "servlet#"servletname#TestServlet"%servletname#"servletclass#TestServlet"%servletclass#

    "initparam#"paramname#driverclassname"%paramname#"paramvalue#sun.dbc.odbc.Jdbc&dbc2river"%paramvalue#

    "%initparam#"initparam#

    "paramname#dburl"%paramname#"paramvalue#dbc-odbc-ySY?&21"%paramvalue#

    "%initparam#

    Page 29

    29

  • 8/16/2019 Java Material 90

    30/92

    "%servlet#"%webapp#......................................public void init()K

    Servlet1onfig config $et(ervletConfi$!) LString driver1lass/ame config.get$nitParameter(driverclassname)L

    String dbQF? config.get$nitParameter(dburl)L1lass.for/ame(driver1lass/ame)Ldb1onnection 2riveranager.get1onnection(dbQF?usernamepassword)L

    M

    (ervletConte8t Servlet1ontext is also called application ob+ect . Servlet1ontext is used to obtain information about

    environment on which a servlet is running.There is one instance obect of the Servlet1ontext interface associated with each +eb application deployed into acontainer. $n cases where the container is distributed over many virtual machines a +eb application will have aninstance of the Servlet1ontext for each J6.

    Servlet 1ontext is a grouping under which related servlets run. They can share data QF? namespace and otherresources. There can be multiple contexts in a single servlet container.

    Q) ;ow to add application scope in (ervlets?") $n Servlets Application is nothing but Servlet1ontext Scope.

    Servlet1ontext app1ontext servlet1onfig.getServlet1ontext()Lapp1ontext.setAttribute(param/ame re*.getParameter(param/ame))Lapp1ontext.getAttribute(param/ame)L

    Q) #iff between ;ttp(eassion % (tatefl (ession bean? Why canFt ;ttp(essionn be sed instead of of (essionbean?") 0ttpSession is used to maintain the state of a client in webservers which are based on 0ttp protocol. +here asStateful Session bean is a type of bean which can also maintain the state of the client in Application servers based onF$$$&P.

    Q) Can we store ob&ects in a session?

    ") session.setAttribute(product$ds$n1artproduct$ds$n1art)L  session.removeAttribute(product$ds$n1art)L

    Q) (ervlet isteners

    !i) (ervletConte8tistener void conte8t#estroyed (Servlet1ontext,vent sce)void conte8tInitiali5ed (Servlet1ontext,vent sce)

    $mplementations 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) (ervletConte8t"ttribteistener !I)

    void attribte"dded (Servlet1ontextAttribute,vent scab)void attribte1emoved (Servlet1ontextAttribute,vent scab)void attribte1eplaced (Servlet1ontextAttribute,vent scab)

    $mplementations 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 deploymentdescriptor for the web application.

    Q) ;ttpisteners

    !i) ;ttp(essionistener !I)public void sessionCreated(0ttpSession,vent event)

    Page 30

    30

  • 8/16/2019 Java Material 90

    31/92

    public void session#estroyed(0ttpSession,vent event)$mplementations 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 webapplication.

    !ii) ;ttp(ession"ctivationistener !I)public void sessionWillPassivate(0ttpSession,vent se)

    public void session#id"ctivate(0ttpSession,vent se)&bects 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) ;ttp(ession"ttribteistener !I)public void attribte"dded(0ttpSessioninding,vent se)public void attribte1emoved(0ttpSessioninding,vent se)public void attribte1eplaced(0ttpSessioninding,vent se)

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

    !iv) ;ttp(ession 0indin$ istener !MM If session will e8pire how to $et the vales)Some obects may wish to perform an action when they are bound (or) unbound from a session. Ror example a

    database connection may begin a transaction when bound to a session and end the transaction when unbound. Anyobect that implements the avax.servlet.http.0ttpSessioninding?istener interface is notified when it is bound (or)unbound from a session. The interface declares two methods valueound() and valueQnbound() that must beimplemented-

    Methods1 2public void 0ttpSessioninding?istener.vale0ond(0ttpSessioninding,vent event)public void 0ttpSessioninding?istener.vale6nbond(0ttpSessioninding,vent event)

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

    valueQnbound() is called when the listener is unbound from a session.

    The avax.servlet.http.0ttpSessioninding,vent argument provides access to the name under which the obect is beingbound (or unbound) with the get/ame() method-

    public String 0ttpSessioninding,vent.get/ame()

    The 0ttpSessioninding,vent obect also provides access to the 0ttpSession obect to which the listener is being bound(or unbound) with getSession() -

    public 0ttpSession 0ttpSessioninding,vent.getSession()

    public class Sessionindings extends 0ttpServlet K  public void do3et(0ttpServletFe*uest re* 0ttpServletFesponse res)  throws Servlet,xception $&,xception K  res.set1ontentType(text%plain)L  Print+riter out res.get+riter ()L

      0ttpSession session re*.getSession(true)L  session.put6alue(bindings.listener  new 1ustominding?istener(getServlet1ontext()))L %% Add a 1ustominding?istener   MMclass 1ustominding?istener implements 0ttpSessioninding?istenerK  Servlet1ontext contextL

      public 1ustominding?istener(Servlet1ontext context) K

    Page 31

    31

    http://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.htmlhttp://training/vc/J2EE/J2ee/servlets2.3/javax/servlet/http/HttpSessionBindingEvent.html

  • 8/16/2019 Java Material 90

    32/92

      this.context contextL  M

      public void valueound(0ttpSessioninding,vent event) K  context.log(&Q/2 as event.get/ame() to event.getSession().get$d())L  M

      public void valueQnbound(0ttpSessioninding,vent event) K  context.log(Q/&Q/2 as event.get/ame() from event.getSession().get$d())L  MM

    Q)

  • 8/16/2019 Java Material 90

    33/92

    Filter and the RequestDispatcher version 8.U of the Java Servlet specification is the ability to configure filters to be invo'ed under re*uest dispatcherforward() and include() calls. y using the new "dispatcher#$/1?Q2, % R&F+AF2"%dispatcher# element in thedeployment descriptor

    Q) "re (ervlets mltithread?") 7es the servlet container allocates a thread for each new re*uest for a single servlet. ,ach thread of your servlet

    runs as if a single user were accessing using it alone but u can use static variable to store and present information thatis common to all threads li'e a hit counter for instance.

    Q) What happens to (ystem*ot % (ystem*err otpt in a (ervlet? A) System.out goes to Hclient sideH and is seen in browser while System.err goes to Hserver sideH and is visible in errorlogs and%or on console.

    Q) (ession racin$Session trac'ing is the capability of the server to maintain the single client se*uential list.

    Q) (ervlet chainin$$s a techni*ue in which two are more servlets cooperating in servicing a single client se*uential re*uest where

    one servlet output is piped to the next servlet output. The are 8 ways (i) Servlet Aliasing (ii) 0ttpFe*uest

    Servlet Aliasing allow you to setup a single alias name for a comma delimited list of servlets. To ma'e a servlet chain

    open your browser and give the alias name in QF?.

    0ttpFe*uest construct a QF? string and append a comma delimited list of servlets to the end.

    Q) ;ttpnnellin$$s a method used to reading and writing seriali!es obects using a http connection. 7ou are creating a sub

    protocol inside http protocol that is tunneling inside another protocol.

    Q) #iff C7I % (ervletServlet is thread based but 13$ is process based.

     13$ allow separate process for every client re*uest 13$ is platform dependent and servlet is platform independent.

    Q) #iff 7E % PO(  3,T P&ST are used to process re*uest and response of a client.

     

    3,T method is the part of QF? we send less amount of data through 3,T. The amount of information limited is 8U>

    8@@ characters (or ='b in length).  Qsing P&ST we can send large amount of data through hidden fields.

     3et is to get the posted html data P&ST is to post the html data.

    Q) #iff ;ttp % 7eneric (ervlet  0ttpServlet class extends 3eneric servlet so 3eneric servlet is parent and 0ttpServlet is child.

     3eneric is from avax.servlet pac'age 0ttpServlet is from avax.servlet.0ttp pac'age.

     0ttp implements all 0ttp protocols 3eneric servlet will implements all networ'ing protocol

      0ttp is stateless protocol which mean each re*uest is independent of previous one $n generic we cannot maintain

    the state of next page only main state of current page. A protocol is said to be stateless if it has n memory of prior connection.

     0ttp servlet extra functionality is capable of retrieving 0ttp header information.

     

    0ttp servlet can override do3et() do2elete() do3et() doPost() doTrace() generic servlet will override Service()

    method only.

    Q) Can I catch servlet e8ception and $ive my own error messa$e? !or) cstom error pa$es? A) 7es 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. $f aservlet relies upon system or networ' resources that may not be available for unexpected reasons you can use aFe*uest2ispatcher to forward the re*uest to an error page.

    Page 33

    33

  • 8/16/2019 Java Material 90

    34/92

    Fe*uest2ispatcher dispatcher nullLre*uest.getFe*uest2ispatcher(%err%SY?.sp)Ltry K %% SY? operationMcatch (SY?,xception se) K

    dispatcher.forward(re*uest response)LM

    +eb.xml"errorpage#  "errorcode#  0TTP error code (U>U)  "errorcode#  "exceptiontype#  java.lang.Runt!e"#$epton  "%exceptiontype#  "location#  %err%Runt!e"#$epton.jsp

      "%location#"%errorpage#

    Q) ;ow many ways we can instantiate a class?") 1lass.for/ame().new$nstance() and new 'eyword

    Q) Client pll % (erver psh? Client pll

    1lient pull is similar to redirection with one maor difference- the browser actually displays the content from thefirst page and waits some specified amount of time before retrieving and displaying the content from the next page. $tHscalled client pull because the client is responsible for pulling the content from the next page.1lient pull information is sent to the client using the Fefresh 0TTP header. This headerHs value specifies the number ofseconds to display the page before pulling the next one and it optionally includes a QF? string that specifies the QF?

    from which to pull. $f no QF? is given the same QF? is used. 0ereHs a call to set0eader() that tells the client to reloadthis same servlet after showing its current content for three seconds- set0eader(Fefresh ;)L And hereHs a call that tells the client to display /etscapeHs home page after the three seconds-set0eader(Fefresh ;L QF?http-%%home.netscape.com)L

    (erver pshServer push because the server sends or pushes a se*uence of response pages to the client. +ith server

    push the soc'et connection between the client and the server remains open until the last page has been sent.

  • 8/16/2019 Java Material 90

    35/92

    !v) 6ser "thori5ation

    61 1ewritin$QF? rewriting is a techni*ue in which the re*uested QF? is modified with the session id.

    QF? rewriting is another way to support anonymous session trac'ing. +ith QF? rewriting every local 61 the usermight clic' on is dynamically modified or rewritten to include extra information.http-%%server-port%servlet%FewrittenIsessionid=8; added parameter 

    ;idden form U>#  "$/PQT T7P,hidden /A,level 6A?Q,expert#"%R&F#$n a sense hidden form fields define constant variables for a form. To a servlet receiving a submitted form there is nodifference between a hidden field and a visible field.

    Persistence Cooie A coo.ie is a bit of information sent by a web server to a browser that can later be read bac' from that browser.

    +hen a browser receives a coo'ie it saves the coo'ie and thereafter sends the coo'ie bac' to the server each time itaccesses a page on that server subect to certain rules. ecause a coo'ieHs value can uni*uely identify a client coo'iesare often used for session trac'ing. ecause coo'ies are sent using 0TTP headers they should be added to theresponse before you send any content. rowsers are only re*uired to accept 8> coo'ies per site ;>> total per user andthey can limit each coo'ieHs si!e to U>V: bytes.

    Sending cookies from a servlet 

    1oo'ie coo'ie new 1oo'ie ($2 =8;)Lres.add1oo'ie (coo'ie)L

     A servlet retrieves coo'ies by calling the get1oo'ies () method of 0ttpServlet Fe*uest-public 1oo'ieNO 0ttpServletFe*uest.get1oo'ies()

    This method returns an array of 1oo'ie obects that contains all the coo'ies sent by the browser as part of the re*uestor null if no coo'ies were sent. The code to fetch coo'ies loo's li'e this-

    ,eading broser cookies from a Servlet 

    1oo'ie NO coo'ies re*. get1oo'ies()Lif (coo'ies W null) K  for (int i >L i " coo'ies.lengthL i) K  String name coo'ies NiO. get/ame ()L  String value coo'ies NiO. get6alue()L  MM

    %eleting the Cookies"Z  1oo'ie 'illy1oo'ie new 1oo'ie(mycoo'ie null)L  'illy1oo'ie.set'a8"$e(>)L  'illy1oo'ie.setPath(%)L  response.add1oo'ie('illy1oo'ie)LZ#

    7ou can set the maximum age o& a $oo'e (t te cookie.setMaxAge(int seconds) !eto*+ Nero means to delete the coo'ie

     + vale is the maximum number of seconds the coo'ie will live before it expires

    Page 35

    35

  • 8/16/2019 Java Material 90

    36/92

     . vale means the coo'ie will not be stored beyond this browser session (deleted on browser close)

    (ession racin$ "PI$n Java the avax.servlet.http.0ttpSession AP$ handles many of the details of session trac'ing. $t allows a

    session obect to be created for each user session then allows for values to be stored and retrieved for each session. Asession obect is created through the 3ttpervlet4e5uest  using the getSession() method-

    0ttpSession session re*uest.getSession(true)L

    This will return the session for this user or create one if one does not already exist. 6alues can be stored for a usersession using the 3ttpession method put6alue()-

    session.put6alue(value/ame value&bect)L

    Session obects can be retrieved using get6alue(String name) while a array of all value names can be retrieved usingget6alue/ames(). 6alues can also be removed using remove6alue(String value/ame)

    6ser "thori5ationServers can be set up to restrict access to 0T? pages (and servlets). The user is re*uired to enter a user

    name and password. &nce they are verified the client resends the authorisation with re*uests for documents to that

    site in the http header.Servlets can use the username authorisation sent with re*uest to 'eep trac' of user data. Ror example a hashtable canbe set up to contain all the data for a particular user. +hen a user ma'es another re*uest the user name can be used toadd new items to their cart using the hashtable.

    Q) 1etrievin$ ery parameters names?,numeration params re*uest.getParameter/ames()L

      String param/ame nullL  StringNO param6alues nullL

      while (params.hasore,lements()) K  param/ame (String) params.next,lement()L  param6alues re*uest.getParameter6alues(param/ame)L

      System.out.println(DnParameter name is param/ame)L  for (int i >L i " param6alues.lengthL i) K  System.out.println( value i is   param6aluesNiO.toString())L  M  M

    Q) (essionSession is a persistence networ' connection between client and server that facilitate the exchange of

    information between client and server. The container generates a session $2 when you create a session the serversaves the session $2 on the clients machine as a coo'ie. A session obect created for each user persists on the serverside either until user closes the browser or user remains idle for the session expiration time.

     As such there is no limit on the amount of information that can be saved in a Session &bect. &nly the FAavailable on the server machine is the limitation. The only limit is the Session $2 length ($dentifier) which should notexceed more than UG. $f the data to be store is very huge then itHs preferred to save it to a temporary file onto hard dis'rather than saving it in session. $nternally if the amount of data being saved in Session exceeds the predefined limitmost of the servers write it to a temporary cache on 0ard dis'.

    %% $f 4re5 means creating a session if session is not there%% if 4

  • 8/16/2019 Java Material 90

    37/92

    session.remove6alue(y$dentifier=)L %% Femoving 6aluefrom Session &bect

    Invalidating a SessionThere are : different ways to invalidate the session.= 0ttpsession.setax$nactive$ntervel(int sec)

    8 Session will automatically expire after a certain time of inactivity

    ; Qser closes browser window notice that the session will time out rather than directly triggering session invalidate.

    U calling invalidate()@ if server cashes

    : put "sessiontimeout# in web.xml

    Q) Cooie advanta$es % #isadvanta$es"dvanta$es Persistence offer efficient way to implement session trac'ing for each client re*uest a coo'ie can be

    automatically provide a clients session id.#isadvanta$e The biggest problem with coo'ies is that browser do not always accept coo'ies. Some times browser

    does not accept coo'ies. rowser only re*uires accepting 8> coo'ies per page and they can limit the coo'ie si!e toU>V: bytes. $t cannot wor' if the security level set too high in browser. 1oo'ies are stored in a plain text format so everyone can view and modify them. +e can put maximum ;>> coo'ies for entire application.

    Q) "dvanta$es of (essions over Cooies % 611ewritin$?

      Sessions are more secure and fast because they are stored at server side. ut sessions has to be used combindlywith coo'ies (or) QF?Fewriting for maintaining client id that is session id at client side. 1oo'ies are store at client side so some clients may disable coo'ies so we may not sure that the coo'ies which we

    are maintaining may wor' or not if coo'ies are disable also we can maintain sessions using QF?Fewriting. $n QF?Fewriting we cannot maintain large data because it leads to networ' traffic and access may be become slow.

    +here in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.

    Q) If the cooies at client side are disabled then session donFt wor, in this case how can we proceed?") =. (from servlet) write the next page with a hidden field containing a uni*ue $2 that serves as session $2. So nexttime when the user clic's submit you can retrieve the hidden field.

    8. $f you use applet you may avoid view source (so that people canHt see the hidden field). 7our applet reads bac'an $2 from the servlet and use that from then on to ma'e further re*uests

    Q) ;ow to confirm that serFs browser accepted the Cooie?") ThereHs no direct AP$ to directly verify that userHs browser accepted the coo'ie. ut the *uic' alternative would beafter sending the re*uired data to the users browser redirect the response to a different Servlet which would try to readbac' the coo'ie. $f this Servlet is able to read bac' the coo'ie then it was successfully saved else user had disabledthe option to accept coo'ies.

    Q) #iff between 'ltiple Instances of 0rowser and 'ltiple Windows? ;ow does this affect (essions?") Rrom the current rowser window if we open a new +indow then it referred to as ultiple +indows. Sessions

    properties are maintained across all these windows even though they are operating in multiple windows. $nstead if we open a new rowser by either double clic'ing on the rowser Shortcut then we are creating a new

    $nstance of the rowser. This is referred to as ultiple $nstances of rowser. 0ere each rowser window is consideredas different client. So Sessions are not maintained across these windows.

    Q) encode61 % encode1edirect61  These are methods of 0ttpFesponse obect 4encodeQF?5 is for normal lin's inside your 0T? pages4encodeFedirectQF?5 is for a lin' your passing to response.sendFedirect().

    Q) (in$lehread modelSingleThreadodel is a tag interface with no methods. $n this model no two threads will execute concurrently

    the service method of the servlet to accomplish this each thread uses a free servlet instance from the servlet pool. Soany servlet implementing this can be considered thread safe and it is not re*uired synchroni!e access to its variables.!or)

    Page 37

    37

  • 8/16/2019 Java Material 90

    38/92

    $f a servlet implements this interface the server ensures that each instance of the s