corejava full

Upload: javed-akhtar

Post on 03-Jun-2018

223 views

Category:

Documents


2 download

TRANSCRIPT

  • 8/12/2019 CoreJava Full

    1/159

  • 8/12/2019 CoreJava Full

    2/159

  • 8/12/2019 CoreJava Full

    3/159

    Q) Syste !o"t!println#) +rintln98 is a methd o4 java.io.+rintWriter. o/t is an instance varia7le o4 java.lang. :stem class.

    Q) $ransient & volatile!ransient AA> !he transient modi4ier a++lies to varia7les onl:, the o7ject are varia7le ;ill not +ersist.!ransient varia7les are not seriali val/e ;ill 7e changed /ne*+ectedl: 7: the other +art o4 the +rogram, it tells the com+iler avaria7le ma: change as:nchrono/sl: d/e to threads

    Q) %ccess Specifiers & %ccess odifiers?ccess +eci4iers . gives access +rivileges to o/tside o4 a++lication 9or8 others, the: are P/7lic,Protected, Private, 6e4a/lts.ccess Modi4iers .M ;hich gives additional meaning to data, methods and classes, 4inal cannot 7emodi4ied at an: +oint o4 time.

    Private P/7lic Protected o modi4ier ame class Fes Fes Fes Fesame +ac)age /7class o Fes Fes Fesame +ac)age nonAs/7class o Fes Fes Fes6i44erent +ac)age s/7class o Fes Fes o6i44erent +ac)age nonAs/7class o Fes o o

    Q) efa"lt 'al"es

    long A2G'3 to 2G'3 "1 #H

    do/7le #.#d

    Int A2G31 to 2G31 "1 # (loat #.#4 hort A2G15 to 2G15 "1 # Boolean 4alse

    B:te A2G% to 2G% "1 # Char # to 2G% "1 n/ll character 9or8 J/####K

    Q) Byte code & J($ co piler & J' & J* & J ,

    B:te code is a highl: o+timi

  • 8/12/2019 CoreJava Full

    4/159

    &ava +asses all arg/ments 7: val/e, not 7: re4erence

    Q) %r-" ents & .ara etersWhile de4ining method, varia7le +assed in the method are called +arameters. While /sing those methods,val/es +assed to those varia7les are called arg/ments.

    rg/ment " Passing endParameter " Method di4inaton

    Q) ."blic static void ain #Strin- /0 ar-s) We can overHoad the main98 method. What i4 the main method is declared as Private

    !he +rogram com+iles +ro+erl: 7/t at r/ntime it ;ill give Main method not +/7lic. Message What i4 the static modi4ier is removed 4rom the signat/re o4 the main method

    %ro"ram compiles. &ut at runtime throws an error ' o uchMethod rror'. We can ;rite static +/7lic void instead o4 +/7lic static void 7/t not +/7lic void static . Protected static void main98, static void main98, +rivate static void main98 are also valid.

    B/t r/n time it ;ont ;or)N I4 I do not +rovide the tring arra: as the arg/ment to the method

    %ro"ram compiles but throws a runtime error ' o uchMethod rror'. I4 no arg/ments on the command line, tring arra: o4 Main method ;ill 7e em+t: or n/ll

    It is em+t:. B/t not n/ll. Daria7les can have the same name as a method or a class

    Q) Can an application have "ltiple classes havin- ain#) ethod?8 Fes it is +ossi7le. While starting the a++lication ;e mention the class name to 7e r/n. !he &DM ;ill loo)4or the Main method onl: in the class ;hose name :o/ have mentioned. ence there is not con4lict amongstthe m/lti+le classes having main method.

    Q) Can ( have "ltiple ain ethods in the sa e class?8 o the +rogram 4ails to com+ile. !he com+iler sa:s that the main method is alread: de4ined in the class.Else ;ith di44erent arg/ments

    Q) Constr"ctor !he a/tomatic initiali

  • 8/12/2019 CoreJava Full

    5/159

    Class B e*tends QB98Q :stem.o/t.+rintln9 4riend 8

    Class +rint QP/7lic static void main 9 tring args RS8QB 7 T ne; B98

    o?+ A hello 4riend

    Q) iff between Constr"ctor & ethod

    Constr/ctor MethodUse to instance of a class Grouping java statement

    o ret/rn t:+e Doid 9or8 valid ret/rn t:+eame name as class name s a name e*ce+t the class method name, 7egin

    ;ith lo;er case.

    !his re4er to another constr/ctor in the sameclass

    Refers to instance of class

    /+er to invo)e the s/+er class constr/ctor Execute an overridden method in the superclass

    nheritance! cannot "e inherited Can 7e inherited#e can overload! "ut $e cannotoverridden!

    Can 7e inherited

    #ill automaticall% invo&e $hen ano"ject is created

    Method has called e*+licitl:

    Q) 1arba-e collection.C is also called a/tomatic memor: management as &DM a/tomaticall: removes the /n/sed

    varia7les?o7jects 9val/e is n/ll8 4rom the memor:. User +rogram cannLt directl: 4ree the o7ject 4rom memor:,instead it is the jo7 o4 the gar7age collector to a/tomaticall: 4ree the o7jects that are no longer re4erenced 7: a

    +rogram. Ever: class inherits 4inali

  • 8/12/2019 CoreJava Full

    6/159

    (inal class cannot have static methods (inal class cannot have a7stract methods 9Beca/se o4 4inal class never allo;s an: class to inherit it8 'inal class can have a final method.

    (inall: A (inall: create a 7loc) o4 code that ;ill 7e e*ec/ted a4ter tr: catch 7loc) has com+leted. (inall: 7loc) ;ill e*ec/te ;hether or not an e*ce+tion is thro;n. I4 an e*ce+tion is thro;n, the 4inall: 7loc) ;ille*ec/te even i4 no catch statement match the e*ce+tion. n: time a method is a7o/t to ret/rn to the caller4rom inside tr:?catch 7loc), via an /nca/ght e*ce+tion or an e*+licit ret/rn statement, the 4inall: cla/se is alsoe*ec/te.

    Using :stem.e*it98 in tr: 7loc) ;ill not allo; 4inall: code to e*ec/te

    (inali

  • 8/12/2019 CoreJava Full

    7/159

    I4 the s/+erclass method is +/7lic, the overriding method m/st 7e +/7lic. I4 the s/+erclass method is +rotected, the overriding method ma: 7e +rotected or +/7lic. I4 the s/+erclass method is +ac)age, the overriding method ma: 7e +ac)agage, +rotected, or +/7lic. I4 the s/+erclass methods is +rivate, it is not inherited and overriding is not an iss/e. Methods declared as 4inal cannot 7e overridden.

    !he thro;s cla/se o4 the overriding method ma: onl: incl/de e*ce+tions that can 7e thro;n 7: thes/+erclass method, incl/ding its s/7classes.

    Onl: mem7er method can 7e overriden, not mem7er varia7leclass ParentQ

    int i T #void amethod98Q

    :stem.o/t.+rintln9 in Parent 8

    class Child e*tends ParentQ

    int i T 1#void amethod98Q :stem.o/t.+rintln9 in Child 8

    class !estQ +/7lic static void main9 tringRS args8QParent + T ne; Child98Child c T ne; Child98:stem.o/t.+rint9 iT X+.iX 8

    +.amethod 98

    :stem.o/t.+rint9 iT Xc.iX 8c.amethod98

    o?+ A iT# in Child iT1# in Child

    Q) 3inal variable0nce to declare a !ariable as final it cannot occupy memory per instance basis.

    Q) Static bloc9tatic bloc2 which exactly executed exactly once when the class is first loaded into JVM. &efore "oin" to the

    main method the static bloc2 will execute.

    tatic and contructor ( static initiali)er bloc& will execute when a class is initiali)ed ** right after the class is loaded. his will happen "basically# the first time the class isreferenced in the program. $o instances need to be created. he static bloc& will only be executed once "or in any case, only once each time the classis loaded.#

    ( constructor executes when, and only when, the +new+ operator is used, or the Class.new nstance"# or Constructor.new nstance"# methods arecalled.

    here are also instance initializer blocks - they loo& li&e static initiali)ers except without the +static+ &eyword- just a bare set of brac&ets outside ofany method. hese get inserted into each of the class s constructors immediately after the call to the superclass constructor, and before thestatements in the constructor body.

    Q) Static variable & Static ethod

    %

  • 8/12/2019 CoreJava Full

    8/159

    tatic !ariables 3 methods are instantiated only once per class. In other words they are class !ariables, notinstance !ariables. If you chan"e the !alue of a static !ariable in a particular ob4ect, the !alue of that !ariable chan"esfor all instances of that class.

    tatic methods can be referenced with the name of the class. It may not access the instance !ariables of thatclass, only its static !ariables. *urther it may not in!o2e instance (non static) methods of that class unless it pro!idesthem with some ob4ect.

    When a mem7er is declared a static it can 7e accessed 7e4ore an: o7ject o4 its class are created. Instance varia7les declared as static are essentiall: glo7al varia7les. I4 :o/ do not s+eci4: an initial val/e to an instance tatic varia7le a de4a/lt val/e ;ill 7e assigned

    a/tomaticall:. Methods declared as static have some restrictions the: can access onl: static data, the: can onl: call other

    static data, the: cannot re4er this or s/+er. tatic methods cant 7e overriden to nonAstatic methods. tatic methods is called 7: the static methods onl:, an ordinar: method can call the static methods, 7/t

    static methods cannot call ordinar: methods. tatic methods are im+licitl: 4inal , 7eca/se overriding is onl: done 7ased on the t:+e o4 the o7jects !he: cannot re4er this are s/+er in an: ;a:.

    Q) Class variable & (nstance variable & (nstance ethods & class ethodsInstance !ariable !ariables defined inside a class are called instance !ariables with multiple instance of class, eachinstance has a !ariable stored in separate memory location.

    Class varia7les :o/ ;ant a varia7le to 7e common to all classes then ;e crate class varia7les. !o create aclass varia7le +/t the static )e:;ord 7e4ore the varia7le name.

    Class methods ;e create class methods to allo; /s to call a method ;itho/t creating instance o4 the class.!o declare a class method /se the static )e: ;ord .

    Instance methods ;e de4ine a method in a class, in order to /se that methods ;e need to 4irst create o7jectso4 the class.

    Q) Static ethods cannot access instance variables why? tatic methods can 7e invo)ed 7e4ore the o7ject is created Instance varia7les are created onl: ;hen

    the ne; o7ject is created. ince there is no +ossi7ilit: to the static method to access the instance varia7les.Instance varia7les are called called as nonAstatic varia7les.

    Q) Strin- & Strin-B"ffer tring is a 4i*ed length o4 se@/ence o4 characters, tring is imm/ta7le.

    tringB/44er re+resent gro;a7le and ;ritea7le character se@/ence, tringB/44er is m/ta7le ;hichmeans that its val/e can 7e changed. It allocates room 4or 1'Aaddition character s+ace ;hen no s+eci4ic lengthis s+eci4ied. &ava.lang. tringB/44er is also a 4inal class hence it cannot 7e s/7 classed. tringB/44er cannot 7eoverridden the e@/als98 method.

    Q) Conversions tring to Int Conversion A

    int I T integer.val/eO49 2$ 8.intDal/e98 int * T integer.+arseInt9 $33 8 4loat 4 T 4loat.val/eO4923.08.4loatDal/e98

    -

  • 8/12/2019 CoreJava Full

    9/159

    Int to tring Conversion A tring arg T tring.val/eO491#8

    Q) S"per#)uper() always callin" 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?8 ested to+Alevel classesA I4 :o/ declare a class ;ithin a class and s+eci4: the static modi4ier, the com+ilertreats the class j/st li)e an: other to+Alevel class. n: class o/tside the declaring class accesses the nestedclass ;ith the declaring class name acting similarl: to a +ac)age. e.g., o/ter.inner. !o+Alevel inner classesim+licitl: have access onl: to static varia7les. !here can also 7e inner inter4aces. ll o4 these are o4 the nestedto+Alevel variet:.

    Mem7er classes A Mem7er inner classes are j/st li)e other mem7er methods and mem7er varia7les and accessto the mem7er class is restricted, j/st li)e methods and varia7les. !his means a +/7lic mem7er class actssimilarl: to a nested to+Alevel class. !he +rimar: di44erence 7et;een mem7er classes and nested to+Alevelclasses is that mem7er classes have access to the s+eci4ic instance o4 the enclosing class.

    Hocal classes A Hocal classes are li)e local varia7les, s+eci4ic to a 7loc) o4 code. !heir visi7ilit: is onl: ;ithinthe 7loc) o4 their declaration. In order 4or the class to 7e /se4/l 7e:ond the declaration 7loc), it ;o/ld need toim+lement a more +/7licl: availa7le inter4ace. Beca/se local classes are not mem7ers the modi4iers +/7lic,

    +rotected, +rivate and static are not /sa7le.

    non:mo/s classes A non:mo/s inner classes e*tend local inner classes one level 4/rther. s anon:mo/sclasses have no name, :o/ cannot +rovide a constr/ctor.

    Inner class inside method cannot have static mem7ers or 7loc)s

    Q) Which circ" stances yo" "se %bstract Class & (nterface?**/ f you need to change your design ma&e it an interface.AA> 7stract class +rovide some de4a/lt 7ehavio/r, .C are e*cellent candidates inside o4 a++lication4rame;or). .C allo; single inheritance model, ;hich sho/ld 7e ver: 4aster.

    Q) %bstract Classn: class that contain one are more a7stract methods m/st also 7e declared as an a7stract, there can 7e

    no o7ject o4 an a7stract class, ;e cannot directl: instantiate the a7stract classes. .C can contain concretemethods.

    n: s/7 class o4 an 7stract class m/st either im+lement all the a7stract methods in the s/+er class or 7edeclared itsel4 as 7stract.

    Com+ile time error occ/r i4 an attem+t to create an instance o4 an 7stract class. Fo/ cannot declare a7stract constr/ctor and a7stract static method . n a7stract method also declared +rivate, native, 4inal, s:nchroni, ;hich is accessi7ilit: as

    +ac)age. n a7stract method declared in a nonAa7stract class. O n a7stract class can have instance methods that im+lement a de4a/lt 7ehavior.

    0

  • 8/12/2019 CoreJava Full

    10/159

    class can 7e declared a7stract even i4 it does not act/all: have an: a7stract methods. 6eclaring s/ch aclass a7stract indicates that the im+lementation is someho; incom+lete and is meant to serve as a s/+er class4or one or more s/7classes that ;ill com+lete the im+lementation.

    class ;ith an a7stract method. gain note that the class itsel4 is declared a7stract, other;ise a com+iletime error ;o/ld have occ/rred.

    7stract class QP/7lic a7stract callme98Doid callmetoo98Q

    class B e*tends 9void callme(){

    class 7stract6emoQ

    +/7lic static void main9string argsRS8QB 7 T ne; B98

    7.callme98 7.callmetoo98

    Q) When we "se %bstract class?8 Het /s ta)e the 7ehavio/r o4 animals, animals are ca+a7le o4 doing di44erent things li)e 4l:ing, digging,Wal)ing. B/t these are some common o+erations +er4ormed 7: all animals, 7/t in a di44erent ;a: as ;ell.When an o+eration is +er4ormed in a di44erent ;a: it is a good candidate 4or an a7stract method.

    P/7lic 7starctclass nimalQ P/7lic void eat94ood 4ood8 Q +/7lic void slee+9int ho/rs8 Q +/7lic a7stract void ma)e oise98

    +/7lic 6og e*tends nimalQ

    +/7lic void ma)e oise98 Q :stem.o/t.+rintln9 Bar)Y Bar) 8

    +/7lic Co; e*tends nimalQ +/7lic void ma)e oise98 Q :stem.o/t.+rintln9 mooY moo 8

    1

  • 8/12/2019 CoreJava Full

    11/159

  • 8/12/2019 CoreJava Full

    12/159

    Q) iff (nterface & %bstract Class? .C ma: have some e*ec/ta7le methods and methods le4t /nim+lemented. Inter4ace contains no

    im+lementation code. n .C can have nona7stract methods. ll methods o4 an Inter4ace are a7stract. n .C can have instance varia7les. n Inter4ace cannot. n .C m/st have s/7classes ;hereas inter4ace canLt have s/7classes n .C can de4ine constr/ctor. n Inter4ace cannot. 5n 5.6 can ha!e any !isibility+ public, pri!ate, protected. 5n Interface !isibility must be public (or) none. n .C can have instance methods that im+lement a de4a/lt 7ehavior. n Inter4ace can onl: declare

    constants and instance methods, 7/t cannot im+lement de4a/lt 7ehavior.

    Q) What is the difference between (nterface and class? class has instance varia7le and an Inter4ace has no instance varia7les. O7jects can 7e created 4or classes ;here as o7jects cannot 7e created 4or inter4aces. ll methods de4ined inside class are concrete. Methods declared inside inter4ace are ;itho/t an: 7od:.

    Q) What is the difference between %bstract class and Class? Classes are 4/ll: de4ined. 7stract classes are not 4/ll: de4ined 9incom+lete class8 O7jects can 7e created 4or classes, there can 7e no o7jects o4 an a7stract class.

    16.Describe the wrapper classes in Java.

    Answer: Wra++er class is ;ra++er aro/nd a +rimitive data t:+e. n instance o4 a ;ra++er class contains, or;ra+s, a +rimitive val/e o4 the corres+onding t:+e.

    (ollo;ing ta7le lists the +rimitive t:+es and the corres+onding ;ra++er classes

    .ri itive Wrapper

    Boolean java.lang.Boolean

    Byte java.lang.B:te

    har java.lang.Character

    Double java.lang.6o/7le

    !loat java.lang.(loat

    Int java.lang.Integer "on# java.lang.Hong

    $hort java.lang. hort

    %oi& java.lang.Doid

    '. What is similarities(&i))erence between an Abstract class an& Inter)ace*

    1

  • 8/12/2019 CoreJava Full

    13/159

  • 8/12/2019 CoreJava Full

    14/159

    eriali

  • 8/12/2019 CoreJava Full

    15/159

  • 8/12/2019 CoreJava Full

    16/159

    \ Preserves comments\ [ generall: r/ns a little 4aster than 6OM

    Q) ar9er (nterfaces #or) $a--ed (nterfaces >n Inter4ace ;ith no methods. Is called mar)er Inter4aces, eg. eriali

  • 8/12/2019 CoreJava Full

    17/159

    Q) CloneGenerate a duplicate copy of the object on which it is called. Cloning is a dangerous action.

    Q) Co parable (nterfaceClasses that im+lements com+ara7le contain o7jects that can 7e com+ared in some meaning4/l

    manner. !his inter4ace having one method com+are the invo)ing o7ject ;ith the o7ject. (or sorting

    com+ara7le inter4ace ;ill 7e /sed.E* A int com+are!o9O7ject o7j8

    Q) ClassClass encapsulate the run*time state of an object or interface. Methods in this class are

    static Class for$ame"!tring name#throws Class$ot'ound1xception

    getClass"#

    getClass6oader"# getConstructor"#get'ield"# get7eclared'ields"#getMethods"# get7eclearedMethods"#get nterface"# get!uperClass"#

    Q) java!jlan-!*eflect #pac9a-e)Ve4lection is the a7ilit: o4 so4t;are to anal:se it sel4, to o7tain in4ormation a7o/t the 4ield, constr/ctor,

    methods modi4ier o4 class. Fo/ need this in4ormation to 7/ild so4t;are tools that ena7les :o/ to ;or) ;ith java 7eans com+onents.

    Q) (nstanceOf nstanceof means "% $hich %our program can o"tain run time t%pe information a"out

    an o"ject'Ex*+ A a , ne$ A()- a'instance f A-

    .) /ava pass arguments "% value are "% reference0A) 1% value

    .) /ava lac& pointers ho$ do implements classic pointer structures li&e lin&ed list0A) Using o"ject reference'

    .) java' Exe2icro soft provided sd& for java3 $hich includes jexegentool!' 4his converts class fileinto a 'Exec! form' nl% disadvantage is user needs a 2'5 java 6'2 installed'

    8 Bin Hi7 in jd)8in contains all tools such as javac, appletviewer and awt tool.Hi7 contains PI and all +ac)ages.

    ! What is a platfor ?

    +lat4orm is the hard;are or so4t;are environment in ;hich a +rogram r/ns. Most +lat4orms can 7edescri7ed as a com7ination o4 the o+erating s:stem and hard;are, li)e Windo;s 2### and [P, Hin/*, olaris,and MacO .

    ! What is the ain difference between Java platfor and other platfor s?

    1

  • 8/12/2019 CoreJava Full

    18/159

    !he &ava +lat4orm di44ers 4rom most other +lat4orms in that itLs a so4t;areAonl: +lat4orm that r/ns on to+ o4other hard;areA7ased +lat4orms.

    !he &ava +lat4orm has t;o com+onents

    1. !he &ava Dirt/al Machine 9&ava DM82. !he &ava ++lication Programming Inter4ace 9&ava PI8

    D! What is the Java 'irt"al achine?

    !he &ava Dirt/al Machine is so4t;are that can 7e +orted onto vario/s hard;areA7ased +lat4orms

    E! What is the Java %.(?

    !he &ava PI is a large collection o4 read:Amade so4t;are com+onents that +rovide man: /se4/l ca+a7ilities,s/ch as gra+hical /ser inter4ace 9 UI8 ;idgets.

    F! What is the pac9a-e?

    !he +ac)age is a &ava names+ace or +art o4 &ava li7raries. !he &ava PI is gro/+ed into li7raries o4 relatedclasses and inter4aces these li7raries are )no;n as +ac)ages.

    6G! What is native code?

    !he native code is code that a4ter :o/ com+ile it, the com+iled code r/ns on a s+eci4ic hard;are +lat4orm.

    66! (s Java code slower than native code?

    ot reall:. s a +lat4ormAinde+endent environment, the &ava +lat4orm can 7e a 7it slo;er than native code.

    o;ever, smart com+ilers, ;ellAt/ned inter+reters, and j/stAinAtime 7:tecode com+ilers can 7ring +er4ormance close to that o4 native code ;itho/t threatening +orta7ilit:.

    67! Can ain#) ethod be overloaded?

    Fes. the main98 method is a s+ecial method 4or a +rogram entr:. Fo/ can overload main98 method in an: ;a:s.B/t i4 :o/ change the signat/re o4 the main method, the entr: +oint 4or the +rogram ;ill 7e gone.

    68! What is the seriali5ation?

    !he seriali

  • 8/12/2019 CoreJava Full

    19/159

    ns O7ject class'8 O7ject class is a s/+erclass o4 all other classes!r/e?(alsens !r/e%8 &ava s/++orts m/lti+le inheritance!r/e?(alsens (alse1#8 Which method is /sed to call the constr/ctors o4 the s/+erclass 4rom the s/7classns s/+er9arg/ment8118 Which is /sed to e*ec/te an: method o4 the s/+erclass 4rom the s/7classns s/+er.methodAname9arg/ments8128 Which methods are /sed to destro: the o7jects created 7: the constr/ctor methodsns 4inali

  • 8/12/2019 CoreJava Full

    20/159

    Concrete Classes4 abstract classes & (nterfaces

    6! What is an object ?

    5n ob4ect is a software entity( unit ) that combines a set of data with a set of operations to manipulate that data.

    In 6, &asic and %ascal etc. lan"ua"es we can directly manipulate data from anywhere of thepro"ram. 6han"in" of data by one part of the pro"ram, affects whole pro"ram and if any other partdesires to ha!e the old !alues, it can not "et.

    5 class defines a type of object . That is, each ob4ect belon"s to some class and ob4ect isalso called as an instance .

    The Ja!a pro"rammin" lan"ua"e is ob4ect oriented, which means that classes, instancesand methods ma2es a basis for a pro"ram;s desi"n.

    public class #emo )

    %bstract class (nterface

    9. 5bstract class may contain all concrete Interface should contain only abstractmethods or abstract methods or a mixture. methods.

    :. The methods may ha!e any access specifier The access specifier must be public.except pri!ate.

    H. The !ariables can ha!e any access specifier The !ariables must be public, static andexcept pri!ate. final.

    . Multiple inheritance is not possible. Multiple inheritance is possible.

    . Inheritance "oes with extends 2eyword. Inheritance "oes with implements2eyword.

    2

  • 8/12/2019 CoreJava Full

    24/159

    K. abstract 2eyword must be included in public and abstract, e!en if omitted, theymethod declaration. are assumed by default.

    The followin" is a typical example for an interface defined in java!awt!event pac2a"e+

    public interface -indowDistener extends !entDistener

    In the followin" pro"ram, the instance !ariable x is bloc2ed by the subclass !ariable. Ceres"per is used to print the superclass !ariable.

    2

  • 8/12/2019 CoreJava Full

    27/159

  • 8/12/2019 CoreJava Full

    28/159

    &( ) < ystem.out.println( #efault &/ ) @&( int x ) )

    Generally, a superclass method can be o!erriden by the subclass if it wants a differentfunctionality. 0r, it can use the same method if it wants the same functionality( output ). If thesuperclass desires that the subclass shoud not o!erride its method by the subclass, it declares the

    method as final . That is mehods declared final can not be o!erridden( else it is a compilationerror ).

    class 5 o. of en"ines #6 contains Ho. of en"ines #69F contains

    In the abo!e pro"ram, interface Jet%lane "i!es a template and dictates that e!ery planeshould ha!e en"ines. Interface always says what to do but not how to do. The class thatimplements Jet%lane should o!erride this method and can put its own number of en"ines. In theabo!e pro"ram, #6 2eeps H en"ines and #69F 2eeps en"ines. &ut the subclass cannot escapeof puttin" en"ines( as all the abstract methods of an interface must be "i!en body in the subclass ).

    .ac9a-es and %ccess odifiers

    6D! What are pac9a-es and what for they are "sed ?

    % pac9a-e is a collection of classes and interfaces# -enerally4 havin- a co on f"nctionality )!.ac9a-es provide access restrictions to other classes!

    5 pac2a"e "roups to"ether a set of classes and interfaces that are needed to wor2 as a whole. The java!io pac2a"e contains classes and interfaces for mana"in" !arious 2inds input and output operations.

    %ac2a"e defines boundary lines to "o!ern how classes and interfaces may interact (access) with each other.

    %ac2a"es also red"ce the potential na e clashes between classes. 5 sin"le pac2a"ecannot ha!e classes with the same name more than one. &ut the classes with the same namecan exist in different pac2a"es. That is, we can ma2e a &utton class of our own and 2eep in ourown pac2a"e. The &utton in our own pac2a"e does not clash with the &utton of java!io pac2a"e.

    ach class and interface belon"s to some pac2a"e( li2e a file cannot exist without adirectory) . -hen we compile a class without mentionin" the pac2a"e name, it is placed in thedefault( unnamed ) pac2a"e created by the JVM. %ac2a"es can be nested, if needed. That iswe can create sub pac2a"es to pac2a"es. *or example, in java!awt!event e!ent is thesub pac2a"e to awt pac2a"e.

    In declarin" a class, the order of state ents is very i portant as "i!en below, else compilation error. 5lwayspac9a-e na e "st be the first , if one exists.

    pac2a"e animal @import 4a!a.io.N @

    3

  • 8/12/2019 CoreJava Full

    32/159

    class #o" < A

    6E! isc"ss the followin- access odifiers > 6! p"blic 7! protected 8! defa"ltH! private

    6! p"blic>

    p"blic is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method declared

    p"blic can be accessed freely( without restrictions ) by any class belon"in" to any pac2a"e. p"blic 9eyword has "otmaximum access of all access modifiers. 5 class must be declared as public or default.

    7! protected>

    protected is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method,constructor or !ariable declared protected , is accessible to all classes of the same pac2a"e and to s"bclasses ofother pac9a-es . That is, no restrictions to the methods belon"in" to the same pac2a"e.

    8! defa"lt>

    5ctually, there is no default access modifier@ the absence of a modifier is treated as default. 5 method or!ariable, declared default( that is, no access modifier specified at all ), can be accessed by any class belon"in" to the

    same pac2a"e. 6lasses belon"in" to other pac9a-es cannot access . That is why default access modifier is 2nown aspac9a-e level access .

    5 class can be either default or public.

    Aote> defa"lt is 9eyword and is used with switch statements.

    H! private >

    private is a 2eyword in Ja!a and dictates the accessibility of a member. 5 method or a!ariable declared pri!ate cannot be accessed by other classes. That is permission of access is "ranted to the ob4ects of the same class.

    5 class cannot be declared pri!ate.

    %ccess ;evels for class and interface e bers

    %ublic 2eyword 5ccessible to all the classes.%rotected 2eyword 5ccessible to classes in the same pac2a"e or

    subclasses of other pac2a"e.o 2eyword( default ) 5ccessible only to classes of the same

    pac2a"e%ri!ate 2eyword ot accessible to any other class.

    Java ;an-"a-e# or java!lan- pac9a-e )

    6F! Why Java is preferred as a lan-"a-e of (nternet ?or

    What feat"res a9es Java to be preferred as a prod"ction lan-"a-e than that of C C++ ?

    -hen jd96!G ( Ja!a;s first !ersion ) was released to the world in 9OO o!ember, it was described by Mr !JamesGoslin", who heads the Ja!a de!elopment team at un Microsystems as+

    Java is si ple4 object oriented4 distrib"ted4 interpreted4 rob"st4 sec"re4 architect"re ne"tral4 hi-hperfor ance4 "ltithreaded and dyna ic pro-ra in- lan-"a-e!

    3

  • 8/12/2019 CoreJava Full

    33/159

    5t the same time, --- team was searchin" for a lan"ua"e that suits its Internet applications. 5ll the abo!efeatures suited their re8uirements and they adopted Ja!a as the lan"ua"e of Internet.

    The followin" points ma2e the abo!e hi"hly technical terms more clear >

    6! Si ple>

    Ja!a has been described as C+ + in"s / because of many of the most complex and

    confusin" elements of 6B B were omitted, li2e pointers, memory mana"ement, operator o!erloadin", !irtual functionsetc. *indin" a pointer error in a lar"e pro"ram is a tou"hest 4ob.

    Memory mana"ement occurs automatically in Ja!a. %ro"rammers need not ha!e to write clean up statementsli2e free( ) or delete( ). Memory allocation and deallocation is implicit built in feature of Ja!a. Garba"e (unwantedob4ects, members etc.) collection is a continuous process that automatically ta2es place throu"h out the execution of thepro"ram.

    -oto is reser!ed word in Ja!a, but pro"rammer is not allowed to use it. -ith -oto , pro"rammer looses these8uence of flow of control, and it becomes !ery difficult to debu" a pro"ram. There are cases, when maintenancepro4ects were abandoned, due to -oto , and written afresh.

    -ith this simplicity, it is easy to learn Ja!a than learnin" 6 E 6B B.

    Object oriented >

    0b4ect oriented pro"rammin"(00%) is a powerful way of or"ani7in" and de!elopin" software. The componentsof 00% called as objects , exist independently of the other. Ja!a exploits the ad!anta"es of 00%s concepts li2encapsulation, Inheritance and %olymorphism.

    The Ja!a lan"ua"e includes a set of class libraries( in the form of pac2a"es ) that pro!ide basic functionality towrite pro"rams in a simple way, li2e java!lan- ( contains classes re8uired for runnin" e!ery Ja!a pro"ram), java!io ( forInput and 0utput operations ) and java!applet ( for writin" applets ) etc.

    Sec"re >

    5nother essential to Ja!a;s success as an Internet lan"ua"e is that it is safe and sec"re . 5 Ja!a pro"ram that

    executes from a -eb pa"e is called an applet . -hen an applet is downloaded by the browser into the system, alon"text and ima"es, it may brin" vir"ses 1 the enemy of your software on the dis2.

    *or this, Ja!a pro!ides security at different le!els. *irst, it eliminated pointers that can chan"e data on the dis2.ext, bytecode verifier chec2s anythin" suspicious ( li2e access permissions ) is "oin" on. 5n applet, by default,cannot open, read or write files on the user system.

    jd96!6 offers more ad!anced approach to security by allowin" applets to be di"itally si"ned for !erificationpurposes. Jar files can be protected with public and pri!ate 2eys. 5lso you can o!erride the default ecurityMana"erclass for extra safe"uards.

    .latfor independent >

    Most computer software is de!eloped for a specific operatin" system. %latform independent means, the samepro"ram( !class file ) can wor2 on different operatin" systems. The bytecode of !class file ma2es it platformindependent. That is, we compile only once and can run on any operatin" system any time.

    $his feat"re is very i portant for an applet! $he applet downloaded and e:ec"ted on o"r syste is not9nown on which syste it was co piled!

    *ob"st >

    Ja!a is a stron"ly typed lan"ua"e and it chec2s the pro"ram both at compile time and run time. *irst of all,memory lea2s are pre!ented by implicit memory mana"ement. It;s exception handlin" mechanism eliminates common

    3

  • 8/12/2019 CoreJava Full

    34/159

    problems li2e di!ide by 7ero / or file not found / etc. Pnassi"ned instance !ariables and unassi"ned elements ofarrays are "i!en default !alues instead of "i!in" 4un2 !alues.

    "ltithreaded >

    Ja!a;s multithreadin" allows us to do many thin"s at a time. That is, downloadin" an applet, runnin" ananimation and editin" a source code 1 all can be done at once. Ja!a;s $hread class ma2es it easy and simple to writea multithreaded pro"ram.

    istrib"ted >

    Ja!a was desi"ned for the distributed en!ironment of the Internet because it handles T6%EI% protocols. Ja!a;sRMI( Remote Method In!ocation) is unparalleled in distributed en!ironment of remote clientEser!er pro"rammin". -ecan access a resource by usin" a PRD.

    yna ic >

    The Ja!a system supports executable code in dynamic lin2 libraries. 5 dyna ic lin9 library is library of Ja!aclasses that can be accessed at run time. The load;ibrary# ) method is used to load a dynamic lin2 library.

    7G! What are wrapper classes ?or

    2ow to convert pri itive data types into Objects ?

    Wrapper class objects wraps# covers ) pri itive data types and a9es the to behave li9e objects! Wecan "se these objects where pri itive data types are re="ired as objects!

    0ne circumstance where we re8uire primiti!e data types as ob4ects is when we want to store them in datastructures of Ja!a li2e Vector or tac2.

    very pri itive data type has -ot a correspondin- wrapper class with which we can con!ert it into anob4ect. *or example, int has "ot (nte-er class, do"ble has "ot o"ble class and boolean has "ot Boolean class.

    The followin" code con!erts int into (nte-er object .

    int x ? 9F @Inte"er i9 ? new Inte"er( x ) @ EE -e say ob4ect i6 wraps primiti!e data type int : .

    The followin" code con!erts do"ble into o"ble object .

    double x ? 9F. @

    #ouble d9 ? new #ouble( x ) @ EE -e say ob4ect d6 wraps primiti!e data typeEEdo"ble .

    The wrapper classes also pro!ide methods to retrie!e primiti!e data type !alues from ob4ects.

    int y ? i9.intValue( ) @ EE to "et bac2 int !alue from i6 ob4ectdouble y ? d9.doubleValue( ) @ EE to "et bac2 do"ble !alue from d6 ob4ect

    76! What is the difference between (nte-er and int ?

    (nte-er is a class defined in java!lan- pac9a-e! int is pri itive data type defined in Java ;an-"a-e itself!( plicit conversion does not place in between (nte-er and int!

    3

  • 8/12/2019 CoreJava Full

    35/159

    Ja!a lan"ua"e supports two types of data+ 9. Reference types :. %rimiti!e types.

    5 reference type holds reference to a !alue. That is a reference !ariable points to( li2e pointers ) some location.

    %rimiti!e types hold raw !alues without any ob4ect oriented support.

    5lthou"h, the Ja!a lan"ua"e is stron"ly ob4ect oriented, it includes the primiti!e types because of their speed,

    simplicity and compactness.6omin" to the memory they occupy, both int and (nte-er occupies H: bits( bytes ).

    The data structures of Ja!a, li2e Vector, does not store primiti!e data types directly. They must be con!ertedinto ob4ects and then stored. To con!ert int into an ob4ect class (nte-er helps.

    Vector !ect ? new Vector( ) @int x ? 9F @!ect.add lement ( x ) @ EE raises a compilation error because int can;t be added

    ow, con!ert int into Inte"er ob4ect and then add as follows+

    Inte"er i9 ? new Inte"er( x ) @!ect.add lement ( i9 ) @

    77! Write the r"les -overnin- type cast operation on pri itive data types ?

    There are primiti!e data types in Ja!a 1 byte, short, int, lon", float, double, char andboolean. 0ne type can be con!erted into another implicitly( by the system ) or explicitly( by thepro"rammer ). The followin" rules apply.

    9. The data types that occupies less memory can be assi"ned with to data types that occupiesmore memory. The followin" castin" is performed imlicitly.

    int x ? @double y ? x @ystem.out.println( y ) @ EE prints .F

    In the abo!e code, : ( int occupies bytes ) can be assi"ned to d ( double occupies bytes )and this assi"nment is done implicitly( automatically ) without an extra code by the pro"rammer.

    :. &ut the followin" code does not compile as explicit castin" is needed by the pro"rammer.

    double d ? .K @int i ? d @ystem.out.println( i ) @ EE raises a compilation error

    In the abo!e pro"ram, d ( of bytes ) can be assi"ned to i ( of bytes ). It needs explicitcastin". The abo!e code re written as follows +

    double d ? .K @int i ? ( int ) d @ystem.out.println( i ) @ EE prints

    3

  • 8/12/2019 CoreJava Full

    36/159

    This explicit castin" sometimes results in data truncation and precision of the !alue is lost.

    H. 5n important point to note is boolean data type cannot be cast to any other data type. It isinco patible with any other data type. 5lways con!ersion( either explicitly or implictly ) ispossible between compatible data types only. The followin" code raises a compilation error +

    boolean b ? true @int x ? b @

    78! What is object castin- and e:plain itKs r"les ?or

    Can we cast in between objects ?

    Truly spea2in", we can not cast in between ob4ects e!en thou"h all ob4ects in Ja!a ta2e H: bits of memory. &ut,it is possible to cast in between a subclass ob4ect and superclass ob4ect.

    0b4ect castin" is possible in between the classes in!ol!ed in inheritance only.class *lower < Aclass Rose < A EE obser!e there is no e:tends 2eyword here*lower f ? new *lower( ) @Rose r ? new Rose( ) @

    The followin" statements ca"ses co pilation error because ob4ects a and b are not connected at all to"ether.

    f ? r @r ? f @

    &ut the followin" code does not ca"se co pilation error as class *lower and 6lass Rose are in!ol!ed ininheritance. Rules of castin"+

    9. a subclass ob4ect can be assi"ned to a superclass ob4ect( implicit ob4ect con!ersion ta2es place ).:. 5 superclass ob4ect cannot be assi"ned to a subclass ob4ect and it needs explicit ob4ect castin".

    class *lower < Aclass Rose e:tends *lower < A EE obser!e e:tends 9eyword here

    *lower f ? new *lower( ) @Rose r ? new Rose( ) @

    f < r I EE it is le"al, as per rule 9.r < f I EE it is ille"al, as per rule :

    r < # *ose ) f I EE now le"al, as explicit casin" is done

    7H! What are different variables4 Java lan-"a-e s"poorts ?or

    ifferentiate between local4 instance and class variables ?

    Ja!a lan"ua"e supports three types of !ariables+ class !ariables, instance !ariables and local !ariables.

    (nstance variables are those which maintain a separate copy of data when lin2ed toob4ects( maintains this reference ). That is, instance !ariables maintain different memory locations.

    Class variable is that which can be accessed by all ob4ects( this reference does not exists) of the class. 6lass!ariable does not maintain different memory locations when lin2ed to ob4ects. The only one memory location, occupiedby the class !ariable, is accessed by the whole class. That is, if one part of the pro"ram chan"es the !alue, all otherparts "et affected. If any part wants old !alue, it cannot "et. 6lass !ariable should be declared static . 5 class !ariablecan be accessed without the help of an ob4ect.

    5 local variable is that whose access is limited within the method in which it is declared.The followin" pro"ram explains +

    3

  • 8/12/2019 CoreJava Full

    37/159

  • 8/12/2019 CoreJava Full

    38/159

  • 8/12/2019 CoreJava Full

    39/159

    5 6II ran"e and afterwards it adds its own !alues for the alphabets of many world lan"ua"es. Pnicode is alreadyincludes up to H ,9: characters.

    7E! What are jar files ? isc"ss briefly how to create and e:tract files ?

    J5R( Ja!a 5Rchi!e ) is Ja!a;s platform independent file format that allows us to bundle different files into one.The files, to "roup, may include !class files( li2e applets), !-if files( ima"e files), !a" files(sound files) etc. Ja!acompresses all these files and 2eeps in a 4ar file, specified.

    *or example+ jar cvf 2ello!jar e o!class y.hoto!-if Space "sic!a"

    In the abo!e statement, jar is Ja!a command( tool ) with which we can create a J%* file.c stands for to create new 4ar file( updatin" of a 4ar file is also possible with other option)v stands for to display the 4ar information on a standard output( monitor ).f indicates that 4ar file name is included in the command line.

    #emo.class, My%hoto."if and paceMusic.au files are compressed( li2e win7ip or p27ip) and placed in the 4arfile by name 2ello!jar . !jar should be "i!en extension for all archi!e files. The 4ar command also displays the ori"inalsi7e( in bytes) of each file and how much it is compressed and the percenta"e of compression etc.

    jar tvf 2ello!jar EE t stands for list table of archi!e file

    The abo!e command displays the contents( that is, all file names) present in Cello.4ar file.

    jar :vf 2ello!jar EE: is for e : tractin" all files

    The abo!e command extracts( un7ips ) all the included files of the 4ar file.

    jar :vf 2ello!jar e o!class

    The abo!e command extracts #emo.class only from Cello.4ar file.

    %dvanta-es of jar files > 9. -ith 4ar files, we can download many files with a sin"le re8uest.

    :. &ecause files are compressed, the download time or transmissiontime is drastically reducedH. 5s the files are compressed, it ta2es less space on hard dis2

    when stored.

    7F! isc"ss 6! instanceof 7! transient 8! volatile H! strictof ! native ?

    6! instanceof > The instanceof 2eyword is a two ar"ument operator that tests whether the type of its first ar"ument isassi"nment compatible( that is, can be assi"ned or not ) with its second ar"ument.

    instanceof is a 2eyword of Ja!a which can chec2 ( an ob4ect belon"s to a class or not ) both at a) compile timeand b) run time.

    Co pile N ti e chec9in->

    In the followin" pro"ram, instanceof chec2s whether an ob4ect belon"s to a class or not at compile time.

    class $ < Ainterface 5 < Aclass & implements 5 < Apublic class 6 extends & )

    The primary use of instanceof is to chec2 at run time whether an ob4ect can be comparable ( or assi"nble, orbelon"s to ) to another ob4ect.

    In the followin" pro"ram with one catch bloc2 we can catch many exceptions( loo2s stran"e and absurd ).

    public class RunInstance#emo ) ? < 9F, :F A @try < c ? a E b @ ystem.out.println( x= 9F > ) @Acatch( Runtime xception e )

    native 2eyword is used with methods as modifier. If we would li2e to write some other

    lan"ua"e code in a Ja!a pro"ram, we use nati!e 2eyword. -hen a method in a Ja!a pro"ram isnati!e, then the Ja!a pro"ram is not platform independent. The nati!e code of the pro"ram, iscon!erted into a #DD that can be lin2ed dynamically at run time.

    8G! What is finali5e # ) ethod in Java ? ( 0ctober, :FFF )

    -hen all references to an ob4ect are dropped, the ob4ect is no lon"er re8uired and becomeseli"ible for "arba"e collection. &efore an ob4ect is "arba"e collected, the runtime system callsfinali5e# ) ethod to release system resources, if any, li2e operatin" system lin2s established bythe files opened by the pro"rammer or closin" soc2et connections systematically.finali5e# ) ethod is defined in the 0b4ect class (as follows), so e!ery class can ma2e use of it.

    protected void finali5e# ) throws java!lan-!$hrowableI

    %i > to illustrate the use of finali7e( ) method.

    public class *inali7e#emo ? new int= 9F > @ EEdeclaration of an arrayystem.out.println( sub4ect= 9 > ) @ EE if not assi"ned, default F is assi"ned for int elementsub4ect= 9 > ? @ EE assi-nin- a !alue to an elementystem.out.println( sub4ect= 9 > ) @ EE now, prints

    7! (nitiali5ation of arrays>

    5rrays are data structures that can store lar"e amount of data of the sa e type "roupedto"ether and 2nown by a common name. ach member is called an element of the array. 5rraysare capable of storin" primiti!e data types as well as ob4ects. The elements of the array are can beaccessed by its index !alue that starts from F. 0nce array is declared, its si7e cannot be altereddynamically.

    5rrays can be a) declared and assi"ned later or b) initiali7ed.

    int sub4ect= > ? < :, , S, 9F A @ EE initiali7in" an arrayystem.out.println( sub4ect = 9 > ) @ EE prints

    The si7e of the array should not be specified ( optional in 6 E 6B B ) at initiali7ation time. Thefollowin" raises a compilation error.

    int sub4ect= > ? < :, , S, 9F A @ EE si7e should not written, e!en if it is correct.

    88! 2ow Java arrays of Java are different fro C C + + ?

    $

  • 8/12/2019 CoreJava Full

    44/159

  • 8/12/2019 CoreJava Full

    45/159

  • 8/12/2019 CoreJava Full

    46/159

    e="als# ) method is inherited from 0b4ect class and is o!erridden in trin" class. It returns aboolean !alue of true if the strin"s are same or false, if the strin"s are different. In the comparison,case( upper or lower) of the letters is considered.

    xample+trin" str9 ? Rao @trin" str: ? snrao @ystem.out.println( str9.e8uals( str: ) ) @

    The abo!e println statement prints false because case of letters is different. This cano!ercome with e="als(-noreCase# ) method which does not consider case of the letters intoaccount in comparison. The followin" statement illustrates+

    ystem.out.println( str9.e8ualsI"nore6ase( str: ) ) @ EE prints tr"e

    H! to;owerCase# ) and to@pperCase# ) >

    to;owerCase# ) is an instance method and con!erts all uppercase letters of the strin"into lowercase. to@pperCase# ) does in the re!erse way.

    trin" str9 ? Rao @trin" str: ? r.*aculty @ystem.out.println( str9.toDower6ase( ) ) @ EE prints snraoystem.out.println( str:.toPpper6ase( ) ) @ EE prints S*!3%C@;$P

    8 ! :pain Strin- class in Java! 1ive s"itable e:a ples for creatin- objects ofStrin- class ?

    5 se8uence of character data enclosed in double 8uotes is called a strin". trin"s of Ja!a wor2 differently fromthat of 6 and 6 B B. In 6, strin" is an array of characters with a terminatin" G. &ut in Ja!a, strin" is an ob4ect of Strin-class . That is manipulation of strin"s is 8uite different from 6 and in Ja!a, it is !ery easy due the rich methods of trin"class. *or example, we can concatenate strin"s with B operator.

    trin"s are immutable. That is, strin"s once created cannot be chan-ed at the sa e e ory location .-hene!er a new !alue is assi"ned to a strin", a new memory location is created and the new !alue is stored in it andthe old location( with old !alue ) is "arba"e collected. It is definitely a o!erhead to the operatin" system. &ut this ismade to increase the performance and for the same reason trin" class is declared as final .

    The followin" the class si"nature of Strin- class defined in java!lan- pac2a"e+

    public )inal class $trin# e,ten&s O7ject implements eriali

  • 8/12/2019 CoreJava Full

    47/159

    ome important methods of trin" class are +

    val"eOf# ) > 6on!erts all primiti!e data types and ob4ects into strin" form.

    e="als(-noreCase# ) > 6ompares two strin"s while i"norin" their case.

    tri # ) > Remo!es all prefix and suffix white spaces of the strin".

    to@pperCase# ) and to;owerCase# ) > 6han"es the case of the letters of the strin".

    trin" ob4ects can be created in different ways.

    9. trin" str ? new trin"( hello ) @ystem.out.println( str ) @

    :. trin" str ? hello @ ystem.out.println( str ) @

    H. char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @ trin" str ? new trin"( b ) @ ystem.out.println( str ) @

    . char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @ trin" str ? new trin"( b, 9,H ) @ EE copies H characters startin" from index number 9 ystem.out.println( str ) @ EE prints ell

    . char b= > ? < Q h Q, Q e Q, Q l Q, Q l Q, Q o Q A @ trin" str ? trin".copyValue0f( b ) @ ystem.out.println( str ) @

    K. trin"&uffer sb ? new trin"&uffer( ' hello ' ) @ trin" str ? sb.to trin"( ) @ ystem.out.println( str ) @

    1. What &oes a well7written pro#ram loo8 li8e*4&onate& in July2 '99

    ;ellA;ritten OO +rogram e*hi7its rec/rring str/ct/res that +romote a7straction, 4le*i7ilit:, mod/larit: andelegance.

    7! Can yo" have virt"al f"nctions in Java? #donated in J"ly 7GG )

    Fes, all 4/nctions in &ava are virt/al 7: de4a/lt. !his is act/all: a +se/do tric) @/estion 7eca/se the ;ordvirt/al is not +art o4 the naming convention in &ava 9 as it is in CXX, CAshar+ and DB. E!8, so this ;o/ld 7ea 4oreign conce+t 4or someone ;ho has onl: coded in &ava. Dirt/al 4/nctions or virt/al methods are 4/nctionsor methods that ;ill 7e rede4ined in derived classes.

    8! What is ore advisable to create a thread4 by i ple entin- a *"nnable interface or bye:tendin- $hread class?#donated in J"ne 7GG )

    $

  • 8/12/2019 CoreJava Full

    48/159

  • 8/12/2019 CoreJava Full

    49/159

    +.

  • 8/12/2019 CoreJava Full

    50/159

    varia7le ;hen no more in /se. I &ava on calling $ystem.#c4 and >untime.#c4 2 &DM tries to rec:cle the/n/sed o7jects, 7/t there is no g/arantee ;hen all the o7jects ;ill gar7age collected.

    ?.

  • 8/12/2019 CoreJava Full

    51/159

    Private 6e4a/lts

    16.Describe the wrapper classes in Java.

    Answer: Wra++er class is ;ra++er aro/nd a +rimitive data t:+e. n instance o4 a ;ra++er class contains, or;ra+s, a +rimitive val/e o4 the corres+onding t:+e.

    (ollo;ing ta7le lists the +rimitive t:+es and the corres+onding ;ra++er classes

    .ri itive Wrapper

    Boolean java.lang.Boolean

    Byte java.lang.B:te

    har java.lang.Character

    Double java.lang.6o/7le

    !loat java.lang.(loat

    Int java.lang.Integer "on# java.lang.Hong

    $hort java.lang. hort

    %oi& java.lang.Doid

    1 . >ea& the )ollowin# pro#ram:

    +/7lic class test Q +/7lic static void main9 tring RS args8 Q int * T 3 int : T 1 i4 9* T :8 :stem.o/t.+rintln9 ot e@/al 8 else :stem.o/t.+rintln9 E@/al 8

    What is the res/lt . !he o/t+/t is E@/al B. !he o/t+/t in ot E@/al C. n error at i4 9* T :8 ca/ses com+ilation to 4all. 6. !he +rogram e*ec/tes 7/t no o/t+/t is sho; on console.Answer:

    1?. an a private metho& o) a superclass be &eclare& within a subclass*

    Answer: /re. +rivate 4ield or method or inner class 7elongs to its declared class and hides 4rom itss/7classes. !here is no ;a: 4or +rivate st/44 to have a r/ntime overloading or overriding 9+ol:mor+hism84eat/res.

    5

  • 8/12/2019 CoreJava Full

    52/159

    1 . Why Java &oes not support multiple inheritence*

    Answer: &ava 6OE s/++ort m/lti+le inheritance via inter4ace im+lementation

    1?. What is the &i))erence between )inal2 )inally an& )inali=e*Answer: o 4inal A declare constant o 4inall: A handles e*ce+tion o 4inali

  • 8/12/2019 CoreJava Full

    53/159

    Answer: +arsers are 4/ndamental *ml com+onents, a 7ridge 7et;een [MH doc/ments and a++lications that +rocess that [MH. !he +arser is res+onsi7le 4or handling *ml s:nta*, chec)ing the contents o4 the doc/mentagainst constraints esta7lished in a 6!6 or chema.

    ' .

  • 8/12/2019 CoreJava Full

    54/159

    ; . What s new with the stop4 2 suspen&4 an& resume4 metho&s in JDF 1.'*

    Answer: !he sto+98, s/s+end98 and res/me98 methods have 7een de+recated in &6_ 1.2.

    +1. What is the %ector class*

    Answer: !he Dector class +rovides the ca+a7ilit: to im+lement a gro;a7le arra: o4 o7jects ;hat modi4iersma: 7e /sed ;ith an inner class that is a mem7er o4 an o/ter class 9nonAlocal8 inner class ma: 7e declaredas +/7lic, +rotected, +rivate, static, 4inal, or a7stract.

    +'. I) a metho& is &eclare& as protecte&2 where may the metho& be accesse&*

    Answer: +rotected method ma: onl: 7e accessed 7: classes or inter4aces o4 the same +ac)age or 7:s/7classes o4 the class in ;hich it is declared.

    +;. What is an Iterator inter)ace*

    Answer: !he Iterator inter4ace is /sed to ste+ thro/gh the elements o4 a Collection.

    ++.

  • 8/12/2019 CoreJava Full

    55/159

    '. Hame omponent subclasses that support paintin#.

    Answer: !he Canvas, (rame, Panel, and ++let classes s/++ort +ainting

    ;. What is a native metho&*

    Answer: native method is a method that is im+lemented in a lang/age other than &ava

    +.

  • 8/12/2019 CoreJava Full

    56/159

    Answer: !he +ro+erties class is a s/7class o4 ashta7le that can 7e read 4rom or ;ritten to a stream. It also +rovides the ca+a7ilit: to s+eci4: a set o4 de4a/lt val/es to 7e /sed.

    6;. What is the purpose o) the >untime class*

    Answer: !he +/r+ose o4 the V/ntime class is to +rovide access to the &ava r/ntime s:stem.

    6+. What is the purpose o) the $ystem class*

    Answer: !he +/r+ose o4 the :stem class is to +rovide access to s:stem reso/rces.

    6 . What is the purpose o) the )inally clause o) a try7catch7)inally statement*

    Answer: !he 4inall: cla/se is /sed to +rovide the ca+a7ilit: to e*ec/te code no matter ;hether or not ane*ce+tion is thro;n or ca/ght.

    66. What is the "ocale class*

    Answer: !he Hocale class is /sed to tailor +rogram o/t+/t to the conventions o4 a +artic/lar geogra+hic, +olitical, or c/lt/ral region.

    D! What "st a class do to i ple ent an interface?

    Answer: It m/st +rovide all o4 the methods in the inter4ace and identi4: the inter4ace in its im+lements cla/se.

    E! What is an abstract ethod?

    Answer: n a7stract method is a method ;hose im+lementation is de4erred to a s/7class. Or, a method thathas no im+lementation 9an inter4ace o4 a method8.

    6-. What is a static metho&* Answer: static method is a method that 7elongs to the class rather than an: o7ject o4 the class and doesnLta++l: to an o7ject or even re@/ire that an: o7jects o4 the class have 7een instantiated.

    DG! What is a protected ethod?

    Answer: +rotected method is a method that can 7e accessed 7: an: method in its +ac)age and inherited 7:an: s/7class o4 its class.

    D6! What is the difference between a static and a non static inner class?

    Answer: nonAstatic inner class ma: have o7ject instances that are associated ;ith instances o4 the classLso/ter class. static inner class does not have an: o7ject instances.

    D7! What is an object s loc9 and which object s have loc9s?

    Answer: n o7jectLs loc) is a mechanism that is /sed 7: m/lti+le threads to o7tain s:nchroni

  • 8/12/2019 CoreJava Full

    57/159

    D8! When can an object reference be cast to an interface reference?

    Answer: n o7ject re4erence 7e cast to an inter4ace re4erence ;hen the o7ject im+lements the re4erencedinter4ace.

    +. What is the &i))erence between a Win&ow an& a !rame*

    Answer: !he (rame class e*tends Windo; to de4ine a main a++lication ;indo; that can have a men/ 7ar.

    .What &o heavy wei#ht components mean*

    Answer: eav: ;eight com+onents li)e 7stract Windo; !ool)it 9 W!8, de+end on the local ;indo;ingtool)it. (or e*am+le, java.a;t.B/tton is a heav: ;eight com+onent, ;hen it is r/nning on the &ava +lat4orm4or Uni* +lat4orm, it ma+s to a real Moti4 7/tton. In this relationshi+, the Moti4 7/tton is called the +eer to the

    java.a;t.B/tton. I4 :o/ create t;o B/ttons, t;o +eers and hence t;o Moti4 B/ttons are also created. !he &ava +lat4orm comm/nicates ;ith the Moti4 B/ttons /sing the &ava ative Inter4ace. (or each and ever:

    com+onent added to the a++lication, there is an additional overhead tied to the local ;indo;ing s:stem, ;hichis ;h: these com+onents are called heav: ;eight.

    6. Which pac8a#e has li#ht wei#ht components*

    Answer: java*. ;ing +ac)age. ll com+onents in ;ing, e*ce+t & ++let, &6ialog, &(rame and &Windo; arelight;eight com+onents.

    . What are peerless components*

    Answer: !he +eerless com+onents are called light ;eight com+onents.

    ?. What is the &i))erence between the !ont an& !ont/etrics classes*

    Answer: !he (ontMetrics class is /sed to de4ine im+lementationAs+eci4ic +ro+erties, s/ch as ascent anddescent, o4 a (ont o7ject.

    -. What happens when a threa& cannot ac5uire a loc8 on an ob3ect*

    Answer: I4 a thread attem+ts to e*ec/te a s:nchroni

  • 8/12/2019 CoreJava Full

    58/159

  • 8/12/2019 CoreJava Full

    59/159

    -9. What a&vanta#e &o Java s layout mana#ers provi&e over tra&itional win&owin# systems*

    Answer: &ava /ses la:o/t managers to la: o/t com+onents in a consistent manner across all ;indo;ing +lat4orms. ince &avaLs la:o/t managers arenLt tied to a7sol/te si

  • 8/12/2019 CoreJava Full

    60/159

  • 8/12/2019 CoreJava Full

    61/159

    Answer: n o7ject m/st im+lement the eriali

  • 8/12/2019 CoreJava Full

    62/159

    Answer: o. !he: are com+letel: di44erent. ome s:nta* ma: 7e similar.

    11-.What is a ontainer in a GI*

    Answer: Container contains and arranges other com+onents 9incl/ding other containers8 thro/gh the /se o4la:o/t managers, ;hich /se s+eci4ic la:o/t +olicies to determine ;here com+onents sho/ld go as a 4/nction o4 the si

  • 8/12/2019 CoreJava Full

    63/159

    1'+. What is the &i))erence between inter)ace an& abstract class*

    Answer:

    o inter4ace contains methods that m/st 7e a7stract a7stract class ma: contain concrete methods.

    o inter4ace contains varia7les that m/st 7e static and 4inal a7stract class ma: contain nonA4inal and 4inalvaria7les.

    o mem7ers in an inter4ace are +/7lic 7: de4a/lt, a7stract class ma: contain nonA+/7lic mem7ers.

    o inter4ace is /sed to im+lements ;hereas a7stract class is /sed to e*tends .

    o inter4ace can 7e /sed to achieve m/lti+le inheritance a7stract class can 7e /sed as a single inheritance.

    o inter4ace can e*tends another inter4ace, a7stract class can e*tends another class and im+lementsm/lti+le inter4aces.

    o inter4ace is a7sol/tel: a7stract a7stract class can 7e invo)ed i4 a main98 e*ists.

    o inter4ace is more 4le*i7le than a7stract class 7eca/se one class can onl: e*tends one s/+er class, 7/tim+lements m/lti+le inter4aces.

    o I4 given a choice, /se inter4ace instead o4 a7stract class.

    Java Basics

    1.!he &ava inter+reter is /sed 4or the e*ec/tion o4 the so/rce code.!r/e(alsens a.28 On s/ccess4/l com+ilation a 4ile ;ith the class e*tension is created.a8 !r/e

    78 (alsens a.38 !he &ava so/rce code can 7e created in a ote+ad editor.a8 !r/e

    78 (alsens a.$8 !he &ava Program is enclosed in a class de4inition.a8 !r/e

    78 (alsens a.58 What declarations are re@/ired 4or ever: &ava a++licationns class and the main9 8 method declarations.'8 What are the t;o +arts in e*ec/ting a &ava +rogram and their +/r+osesns !;o +arts in e*ec/ting a &ava +rogram are&ava Com+iler and &ava Inter+reter.

    '

  • 8/12/2019 CoreJava Full

    64/159

  • 8/12/2019 CoreJava Full

    65/159

    contains all +ac)ages and varia7les.

    Data types2variables an& Arrays18 What is meant 7: varia7lens Daria7les are locations in memor: that can hold val/es. Be4ore assigning an: val/e to a varia7le, it m/st

    7e declared.28 What are the )inds o4 varia7les in &ava What are their /sesns &ava has three )inds o4 varia7les namel:, the instance varia7le, the local varia7le and the class varia7le.Hocal varia7les are /sed inside 7loc)s as co/nters or in methods as tem+orar: varia7les and are /sed to storein4ormation needed 7: a single method.Instance varia7les are /sed to de4ine attri7/tes or the state o4 a +artic/lar o7ject and are /sed to storein4ormation needed 7: m/lti+le methods in the o7jects.Class varia7les are glo7al to a class and to all the instances o4 the class and are /se4/l 4or comm/nicating

    7et;een di44erent o7jects o4 all the same class or )ee+ing trac) o4 glo7al states.38 o; are the varia7les declaredns Daria7les can 7e declared an:;here in the method de4inition and can 7e initiali

  • 8/12/2019 CoreJava Full

    66/159

    78(alsens a.1$8 Which o+erator is to create and concatenate stringns ddition o+erator9X8.158 Which o4 the 4ollo;ing declare an arra: o4 string o7jectstringR S string R SstringR sString sR Sns a, 7 and d1'8 What is the val/e o4 aR3S as the res/lt o4 the 4ollo;ing arra: declaration123$ns d1%8 Which o4 the 4ollo;ing are +rimitive t:+es

    7:te

    tringinteger(loatns a.1-8 What is the range o4 the char t:+e# to 2 1'

    # to 2 15

    # to 2 1' A1# to 2 15A1ns. d108 What are +rimitive data t:+es

    ns 7:te, short, int, long4loat, do/7le

    7ooleanchar 2#8 What are de4a/lt val/es o4 di44erent +rimitive t:+esns int A #short A #

    7:te A #long A # l4loat A #.# 4 do/7le A #.# d

    7oolean A 4alsechar A n/ll218 Converting o4 +rimitive t:+es to o7jects can 7e e*+licitl:.a8!r/e

    78(alsens 7.228 o; do ;e change the val/es o4 the elements o4 the arra:ns !he arra: s/7scri+t e*+ression can 7e /sed to change the val/es o4 the elements o4 the arra:.238 What is 4inal varai7lens I4 a varia7le is declared as 4inal varia7le, then :o/ can not change its val/e. It 7ecomes constant.

    '

  • 8/12/2019 CoreJava Full

    67/159

    2$8 What is static varia7lens tatic varia7les are shared 7: all instances o4 a class.

    perators18 What are o+erators and ;hat are the vario/s t:+es o4 o+erators availa7le in &avans O+erators are s+ecial s:m7ols /sed in e*+ressions.!he 4ollo;ing are the t:+es o4 o+eratorsrithmetic o+erators,ssignment o+erators,Increment 6ecrement o+erators,Hogical o+erators,Bi;ise o+erators,Com+arison?Velational o+erators andConditional o+erators28 !he XX o+erator is /sed 4or incrementing and the AA o+erator is /sed 4ordecrementing.

    a8!r/e 78(alsens a.38 Com+arison?Hogical o+erators are /sed 4or testing and magnit/de.a8!r/e

    78(alsens a.$8 Character literals are stored as /nicode characters.a8!r/e

    78(alsens a.

    58 What are the Hogical o+eratorsns OV9b8, 69 8, [OV9G8 6 O!9 8.'8 What is the o+eratorns o+erator is the mod/lo o+erator or reminder o+erator. It ret/rns the reminder o4 dividing the 4irsto+erand 7: second o+erand.%8 What is the val/e o4 111 1335%0ns c.

    -8 Is T a valid o+eratorns o.08 Can a do/7le val/e 7e cast to a 7:tens Fes1#8 Can a 7:te o7ject 7e cast to a do/7le val/e ns o. n o7ject cannot 7e cast to a +rimitive val/e.118 What are order o4 +recedence and associativit:ns Order o4 +recedence the order in ;hich o+erators are eval/ated in e*+ressions.ssociativit: determines ;hether an e*+ression is eval/ated le4tAright or rightAle4t.128 Which &ava o+erator is right associativit:

    '

  • 8/12/2019 CoreJava Full

    68/159

    ns T o+erator.138 What is the di44erence 7et;een +re4i* and +ost4i* o4 AA and XX o+eratorsns !he +re4i* 4orm ret/rns the increment or decrement o+eration and ret/rns the val/e o4 the increment ordecrement o+eration.!he +ost4i* 4orm ret/rns the c/rrent val/e o4 all o4 the e*+ression and then

    +er4orms the increment or decrement o+eration on that val/e.1$8 What is the res/lt o4 e*+ression 5.$5 X 3,2!he do/7le val/e -.'!he string -.'!he long val/e -.!he tring 5.$53.2ns d158 What are the val/es o4 * and : * T 5 : T XX*ns * T ' : T '1'8 What are the val/es o4 * and

    jd9 6!6 !ersion, introduces character based streams. 6haracter based input and outputstreams( subclasses of Reader and -riter classes) pro!ide se!eral ad!anta"es. -hile bytestreams( subclasses of Input tream and 0utput tream classes) reads bit 5 6II byte at a time,

    0

  • 8/12/2019 CoreJava Full

    96/159

  • 8/12/2019 CoreJava Full

    97/159

    &ufferedInput tream is a hi"h le!el stream as it is a subclass of *ilterInput tream. &ein" ahi"h le!el stream, it cannot read a file directly. 5lways it re8uires a low le!el stream li2e*ileInput tream ob4ect as a parameter. The followin" is the code snippet+

    *ileInput tream fis ? new *ileInput tream( ' a.4a!a ' ) @&ufferedInput tream bis ? new &ufferedInput tream( fis ) @

    The followin" full pro"ram illustrates the use of &ufferedInput tream+( in this pro"ram a file is copied to monitor)

    import 4a!a.io.N @public class Psin"&uffer < public static !oid main( trin" ar"s=>) throws I0 xception < *ileInput tream fis ? new *ileInput tream( ' a.4a!a ' ) @

    &ufferedInput tream bis ? new &ufferedInput tream( fis ) @

    int 2 ? F @ EE 4ust initiali7e as it is a local !ariable for compiler satisfaction

    trin"&uffer sb ? new trin"&uffer( ) @while( ( 2 ? bis.read( ) ) ? 9 )

    %rint tream class belon"s to byte streams. 5 %rint tram adds functionality to another outputstream. pecial features of %rint tream are +

    9. Pnli2e other output streams, a %rint tream ne!er throws an I0 xception @ instead, inexceptional situations merely set an internal fla" that can be tested !ia the chec2 rror method.

    :. %rint tream flushes the stream of bytes automatically. That is, the flush method isautomatically in!o2ed after a byte array is written or one of the println methods is in!o2edor a newline character or byte ( Q Wn Q) is written.

    The %rint-riter is e8ui!alent to %rint tream in character streams. %rint-riter class should

    be used in situations that re8uire writin" characters rather than bytes.

    The followin" is the hierarchy.

    0b4ect 0utput tream *ilter0utput tream %rint tream

    The followin" code illustrates+

    import 4a!a.io.N@public class %rint tream#emo ) ) @ EE password6ount( fr ) @ystem.out.println( ' Total words in file+ ' B words) @

    AA

    Method si"nature of word6hars( ) +

    public !oid word6hars( int low, int hi"h )+

    +eci4ies that all characters 7et;een the range lo; and high are ;ord constit/ents. ;ord to)en consistso4 a ;ord constit/ent 4ollo;ed 7:

  • 8/12/2019 CoreJava Full

    99/159

    #ataInput tream defines methods li2e readInt( ), read#ouble( ) and readDine( ) etc., thatreads an inte"er, a double and a line as a whole. This speeds up the readin" and thereby increasesthe performance. The followin" pro"ram describes its usa"e +

    import 4a!a.io.N @public class #ata tream#emo < public static !oid main( trin" ar"s= > ) < try < *ileInput tream fis ? new *ileInput tream( ' Cello.4a!a ' ) @ EE low le!el stream #ataInput tream dis ? new #ataInput tream( fis ) @ EE hi"h le!el stream

    trin" str @ EE a temporary strin" !ariable while( ( str ? dis.readDine( ) ) ? null )

    ystem.out.println( str ) @ dis.close( ) @ fis.close( ) @ EE close the streams in re!erse order A catch( I0 xception e ) < e.print tac2Trace( ) @

    A AA

    In the abo!e pro"ram readDine( ) method reads a line as a whole and returns as a strin". It returnsnull when 0* is encountered. The followin" are the exceptions raised in the pro"ram.

    ethod Constr"ctor :ception

    *ileInpust tream( ) *ile ot*ound xceptionreadDine( ) I0 xception

    close( ) I0 xception

    18 What is the di44erence 7et;een thro;K and thro;sK nd itKs a++licationns E*ce+tions that are thro;n 7: java r/ntime s:stems can 7e handled 7: !r: and catch 7loc)s. With thro;e*ce+tion ;e can handle the e*ce+tions thro;n 7: the +rogram itsel4. I4 a method is ca+a7le o4 ca/sing ane*ce+tion that it does nothandle, it m/st s+eci4: this 7ehavior so the callers o4 the method can g/ardagainst that e*ce+tion.28 What is the di44erence 7et;een E*ce+tionK and errorK in javans E*ce+tion and Error are the s/7classes o4 the !hro;a7le class. E*ce+tion class is /sed 4or e*ce+tional

    conditions that /ser +rogram sho/ld catch. With e*ce+tion class ;e can s/7class to create o/r o;n c/stome*ce+tion.Error de4ines e*ce+tions that are not e*ce+ted to 7e ca/ght 7: :o/ +rogram. E*am+le is tac) Over4lo;.38 What is Veso/rce lea)Kns (reeing /+ other reso/rces that might have 7een allocated at the 7eginning o4 a method.$8What is the 4inall:K 7loc)ns (inall: 7loc) ;ill e*ec/te ;hether or not an e*ce+tion is thro;n. I4 an e*ce+tion is thro;n, the 4inall:

    7loc) ;ill e*ec/te even i4 no catch statement match the e*ce+tion. n: time a method is a7o/t to ret/rn to thecaller 4rom inside tr:?catch 7loc), via an /nca/ght e*ce+tion or an e*+licit ret/rn statement, the 4inall: cla/seis also e*ec/te.

    0

  • 8/12/2019 CoreJava Full

    100/159

    58 Can ;e have catch 7loc) ;ith o/t tr: 7loc) I4 so ;henns o. !r:?Catch or !r:?4inall: 4orm a /nit.'8 What is the di44erence 7et;een the 4ollo;ing statementsCatch 9E*ce+tion e8,Catch 9Error err8,Catch 9!hro;a7le t8ns

    %8 What ;ill ha++en to the E*ce+tion o7ject a4ter e*ce+tion handlingns It ;ill go 4or ar7age Collector. nd 4rees the memor:.-8 o; man: E*ce+tions ;e can de4ine in thro;sK cla/sens We can de4ine m/lti+le e*ce+tions in thro;s cla/se.ignat/re is..t:+e methodAname 9+arameterAlist8 thro;s e*ce+tionAlist 08 !he 4inall: 7loc) is e*ec/ted ;hen an e*ce+tion is thro;n, even i4 no catch matches it.

    !r/e?(alsens !r/e1#8 !he s/7class e*ce+tion sho/ld +recede the 7ase class e*ce+tion ;hen /sed ;ithin the catch cla/se.!r/e?(alsens !r/e118 E*ce+tions can 7e ca/ght or rethro;n to a calling method.!r/e?(alsens !r/e128 !he statements 4ollo;ing the thro; )e:;ord in a +rogram are not e*ec/ted.!r/e?(alsens !r/e

    138 !he to tring 9 8 method in the /serAde4ined e*ce+tion class is overridden.!r/e?(alsens !r/e

    1

  • 8/12/2019 CoreJava Full

    101/159

  • 8/12/2019 CoreJava Full

    102/159

    4es, we can call run56 method of a Thread class but then it will behave like a normal method. To actuall" execute

    it in a Thread, we need to start it using Thread.start() method.

    S. Cow can we pause the execution of a Thread for specific timeY

    *e can use Thread class sleep56 method to pause the execution of Thread for certain time. 0ote that this will not

    stop the processing of thread for speci c time, once the thread awake from sleep, it&s state gets changed to

    runnable and based on thread scheduling, it gets executed.

    . -hat do you understand about Thread %riorityY

    7ver" thread has a priorit", usuall" higher priorit" thread gets precedence in execution but it depends on Thread

    (cheduler implementation that is 1( dependent. *e can specif" the priorit" of thread but it doesn&t guarantee

    that higher priorit" thread will get executed before lower priorit" thread. Thread priorit" is an int whose value

    varies from 8 to 89 where 8 is the lowest priorit" thread and 89 is the highest priorit" thread.

    O. -hat is Thread cheduler and Time licin"Y

    Thread (cheduler is the 1perating ("stem service that allocates the #$% time to the available runnable threads.

    1nce we create and start a thread, it&s execution depends on the implementation of Thread (cheduler. Time

    (licing is the process to divide the available #$% time to the available runnable threads. Allocation of #$% time

    to threads can be based on thread priorit" or the thread waiting for longer time will get more priorit" in getting

    #$% time. Thread scheduling can&t be controlled b" +ava, so it&s alwa"s better to control it from application itself.

    9F. -hat is context switchin" in multi threadin"Y

    #ontext (witching is the process of storing and restoring of #$% state so that Thread execution can be resumed

    from the same point at a later point of time. #ontext (witching is the essential feature for multitasking operating

    s"stem and support for multi!threaded environment.

    99. Cow can we ma2e sure main() is the last thread to finish in Ja!a%ro"ramY

    *e can use Thread +oin56 method to make sure all the threads created b" the program is dead before nishing

    the main function. :ere is an article about Thread +oin method .

    9:. Cow does thread communicate with each otherY

    *hen threads share resources, communication between Threads is important to coordinate their e orts. 1b+ect

    class wait56, notif"56 and notif"All56 methods allows threads to communicate about the lock status of a resource.

    #heck this post to learn more about thread wait, notif" and notif"All .9H. -hy thread communication methods wait(), notify() and notify5ll() are

    in 0b4ect classY

    In Java ever" 1b+ect has a monitor and wait, notif" methods are used to wait for the 1b+ect monitor or to notif"

    other threads that 1b+ect monitor is free now. There is no monitor on threads in +ava and s"nchroni;ation can be

    used with an" 1b+ect, that&s wh" it&s part of 1b+ect class so that ever" class in +ava has these essential methods

    for inter thread communication.

    1

    http://www.journaldev.com/1024/java-thread-join-example-with-explanationhttp://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-examplehttp://www.journaldev.com/1024/java-thread-join-example-with-explanationhttp://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example
  • 8/12/2019 CoreJava Full

    103/159

  • 8/12/2019 CoreJava Full

    104/159

    t8.set%ncaught7xception:andler5new %ncaught7xception:andler56>

    ?1verride

    public void uncaught7xception5Thread t, Throwable e6 >

    ("stem.out.println5@exception occured @Be.get essage566C

    D

    D6C

    :9. -hat is Ja!a Thread #ump, Cow can we "et Ja!a Thread dump of a%ro"ramY

    Thread dump is list of all the threads active in the J , thread dumps are ver" helpful in anal";ing bottlenecks in

    the application and anal";ing deadlock situations. There are man" wa"s using which we can generate Thread

    dump - %sing $ro ler, Eill !F command, +stack tool etc. I prefer +stack tool to generate thread dump of a program

    because it&s eas" to use and comes with J3E installation. (ince it&s a terminal based tool, we can create script to

    generate thread dump at regular intervals to anal";e it later on. /ead this post to know more about generating

    thread dump in +ava .

    ::. -hat is #eadloc2Y Cow to analy7e and a!oid deadloc2 situationY

    3eadlock is a programming situation where two or more threads are blocked forever, this situation arises with at

    least two threads and two or more resources.

    To anal";e a deadlock, we need to look at the +ava thread dump of the application, we need to look out for the

    threads with state as 2

  • 8/12/2019 CoreJava Full

    105/159

    +ava.util.TimerTask is an abstract class that implements /unnable interface and we need to extend this class to

    create our own TimerTask that can be scheduled using +ava Timer class.

    #heck this post for +ava Timer example .

    : . -hat is Thread %oolY Cow can we create Thread %ool in Ja!aY

    A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.

    A thread pool manages the collection of /unnable threads and worker threads execute /unnable from the queue.

    +ava.util.concurrent.7xecutors provide implementation of +ava.util.concurrent.7xecutor interface to create the

    thread pool in +ava. Thread $ool 7xample program shows how to create and use Thread $ool in +ava.

    Ja!a 6oncurrency Inter!iew Zuestions 5nswers

    9. -hat is atomic operationY -hat are atomic classes in Ja!a6oncurrency 5%IY

    Atomic operations are performed in a single unit of task without interference from other operations. Atomic

    operations are necessit" in multi!threaded environment to avoid data inconsistenc".

    intBB is not an atomic operation. (o b" the time one threads read it&s value and increment it b" one, other

    thread has read the older value leading to wrong result.

    To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using

    ("nchroni;ation but Java = +ava.util.concurrent.atomic provides wrapper classes for int and long that can be used

    to achieve this atomicall" without usage of ("nchroni;ation. )o to this article to learn more about atomicconcurrent classes .

    :. -hat is Doc2 interface in Ja!a 6oncurrency 5%IY -hat are it;s benefitso!er synchroni7ationY

  • 8/12/2019 CoreJava Full

    106/159

    The 7xecutor framework is a framework for standardi;ing invocation, scheduling, execution, and control of

    as"nchronous tasks according to a set of execution policies.

    #reating a lot man" threads with no bounds to the maximum threshold can cause application to run out of heap

    memor". (o, creating a Thread$ool is a better solution as a nite number of threads can be pooled and reused.

    7xecutors framework facilitate process of creating Thread pools in +ava. #heck out this post to learn with

    example code to create thread pool using 7xecutors framework .

    . -hat is &loc2in"ZueueY Cow can we implement %roducer 6onsumerproblem usin" &loc2in" ZueueY

    +ava.util.concurrent.2lockingHueue is a Hueue that supports operations that wait for the queue to become non!

    empt" when retrieving and removing an element, and wait for space to become available in the queue when

    adding an element.

    2lockingHueue doesn&t accept null values and throw 0ull$ointer7xception if "ou tr" to store null value in the

    queue.

    2lockingHueue implementations are thread!safe. All queuing methods are atomic in nature and use internal

    locks or other forms of concurrenc" control.

    2lockingHueue interface is part of +ava collections framework and it&s primaril" used for implementing producer

    consumer problem.

    #heck this post for producer!consumer problem implementation using 2lockingHueue .

    . -hat is 6allable and *utureY

    Java = introduced +ava.util.concurrent.#allable interface in concurrenc" package that is similar to /unnable

    interface but it can return an" 1b+ect and able to throw 7xception.

    #allable interface use )eneric to de ne the return t"pe of 1b+ect. 7xecutors class provide useful methods to

    execute #allable in a thread pool. (ince callable tasks run in parallel, we have to wait for the returned 1b+ect.

    #allable tasks return +ava.util.concurrent.'uture ob+ect. %sing 'uture we can nd out the status of the #allable

    task and get the returned 1b+ect. It provides get56 method that can wait for the #allable to nish and then return

    the result.

    #heck this post for #allable 'uture 7xample .

    K. -hat are 6oncurrent 6ollection 6lassesY

    Java #ollection classes are fail!fast which means that if the #ollection will be changed while some thread is

    traversing over it using iterator, the iterator.next56 will throw #oncurrent odi cation7xception.

    #oncurrent #ollection classes support full concurrenc" of retrievals and ad+ustable expected concurrenc" for

    updates.

    a+or classes are #oncurrent:ash ap, #op"1n*riteArra"

  • 8/12/2019 CoreJava Full

    107/159

    7xecutors class can be used to easil" create Thread $ool in +ava, also this is the onl" class supporting execution

    of #allable implementations.

    "ltithreadin-

    H ! What is a thread ?

    5 thread is a sin"le se8uential( separate ) flow of control within pro"ram.ometimes, it is called an e:ec"tion conte:t or li-ht wei-ht process . 5 thread itself is not apro"ram. 5 thread can not run on it;s own( as it is a part of a pro"ram ). Rather, it runs within apro"ram. 5 pro"ram can be di!ided into a number of pac2ets of code each representin" athread ha!in" its own separate flow of control.

    $wo threads r"nnin- conc"rrently in a sin-le pro-ra

    ;i-ht wei-ht process + 5 thread is considered a li"ht wei"ht process because it runs within thecontext of a pro"ram and ta2es ad!anta"e of the resources allocated to that pro"ram.

    2eavy wei-ht process + In the hea!y wei"ht process, the control chan"es in between threadsbelon"in" to different processes. ( In li"ht wei"ht process, the control chan"es in between threadsbelon"in" to same(one) process ).

    :ec"tion contest > 5 thread will ha!e its own execution stac2 and pro"ram counter. The coderunnin" within the thread wor2s only within that context.

    0ne of the stren"ths of Ja!a is its support for multithreadin". 5ll the classes needed to write a multithreadedpro"ram are included in the default imported pac2a"e java!lan- throu"h class Object , class $hread and interface*"nnable .

    HD! 2ow to create a thread and start r"nnin- ?

    We can create a thread by instantiatin- $hread class# or of its s"bclasses) and invo9e start# ) on it!

    5 thread is an instance of Thread class. To create a thread of a class, we must extend the class with Threadclass or Runnable interface.

    public class #emo extends Thread )

    wait# ) >

    This method is used in thread synchroni7ation. ynchroni7ation helps inte"rity of data that is shared in betweenconcurrently runnin" threads. Doc2in" of a shared resource is necessary to ha!e consistent( or durable) data. Inmonitors, when a thread tries to access an ob4ect which already bein" accessed, wait( ) method is called and threadwaits until notify( ) is called. The followin" is the method si"nature as defined in 0b4ect class+

    p"blic final void wait# ) throws Interrupted xceptionThis method cannot be o!erridden in its subclasses as it final . wait( ) method is o!erloaded.

    notify# ) and notify%ll# ) >

    In thread synchroni7ation, notify( ) or notify5ll( ) is called on the waitin" thread(s) to "et access to thesynchroni7ed code. The followin" is the method si"nature as defined in 0b4ect class+

    public final !oid notify ( )public final !oid notify%ll ( )

    1

    http://var/www/apps/conversion/java/lang/InterruptedException.htmlhttp://var/www/apps/conversion/java/lang/InterruptedException.html
  • 8/12/2019 CoreJava Full

    110/159

    notify( ) is called on a sin"le waitin" thread, notifyin" the thread that the condition of thesynchroni7ed code to be accessed is chan"ed. notify5ll( ) is called when threads are many waitin"in the 8ueue.

    The abo!e methods cannot be o!erridden in the subclasses as they are final .

    D! join# ) >

    join# ) ethod a9es the thread to wait "ntil other threads finish their tas9!

    Generally, threads are desi"ned to run independently of the other. join# ) method in!ol!es two threads. Thein!ocation of 4oin causes the currently executin" thread to suspend execution until tar"et thread finished its execution.The followin" is the method si"nature+

    p"blic final void join# ) throws (nterr"pted :ception

    4oin( ) method is o!erloaded. The difference between join# ) and wait# ) is 4oin( ) method does not in!ol!e insynchroni7ation( that is, no loc2in" of data). wait( ) method is used by JVM in thread synchroni7ation. 0ther way, 4oin( )and wait( ) methods are used in thread communication.

    E! yeild# ) >

    It is the thread scheduler to decide which thread should be "i!en next processor time.This is decided by the waitin" time of the thread for processor and its priority. Threads with more priority will definitely"et first preference than lower priority threads. If many threads of the same priority exist, they execute in round robinfashion.

    (f yield# ) ethod is called on a thread4 it vol"ntarily -ives off its processor ti e to other threads!yield# ) ethod yields its ti e to other threads of sa e priority only!-hen the thread "i!es off its time, it is the thread scheduler to decide a"ain which thread is to be "i!en next slice ofprocessor time. The followin" is the method si"nature defined Thread class >

    p"blic static void yield# )

    HF! isc"ss the life cycle of a thread ?

    Just li2e an applet and ser!let, threads too "ot a life cycle between their birth and death.

    s"spend# )4 wait# )4 sleep# )4 ( O bloc9in- start# )

    res" e# )4 notify# )4 sleep ti e o"t4 ( O finished

    stop# ) stop# ) stop# )

    $he $hread life Cycle

    1

    Runnable

    Bloc9ed

    Hewlyreate&

    ead

  • 8/12/2019 CoreJava Full

    111/159

    Born state > -hen a thread is created, the thread will be in born state . The thread in born stateis not eli-ible for processor ti e .

    Thread t9 ? new Thread( ) @

    In the abo!e statement, thread t6 is created and is in born state .

    *"nnable state > 5fter the creation of thread, when start( ) method is called, it comes into

    r"nnable state . The thread in runnable state is eli"ible for processor time. Inthe runnable state, the thread calls run( ) method and executes the code.

    t6!start# ) I This method "ets the thread into r"nnable state.

    Bloc9ed state > -e can bloc2 the microprocessor time for a thread by callin" sleep( ), wait( ) orsuspend( ) methods on it. The thread in bloc2ed state is alive and is noteli"ible for processor time e!en if the processor is idle.

    ead state > The thread in dead state is liable for -arba-e collection .!ents when a thread can come into dead state >

    9. when stop( ) method is called on the thread.:. -hen the thread completes the execution of run( ) method.H. -hen the power supply to the system is cut off.

    G! What ethods can stop a thread ?

    5 runnin" thread can be stopped with the followin" methods defined in Thread class.

    9. sleep# ) method ma2es a runnin" thread inacti!e. That is the thread stops its functionin". The thread is not"i!en any microprocessor time.

    :. s"spend# ) method suspends( stops ) a thread execution for an indefinite time until resume( ) method iscalled on it.

    H. wait# ) method calls a runnin" thread to wait for some time until it calls notify( ) or notity5ll( ) method on it.This method is used in synchroni7ation.

    . stop# ) method stops a thread;s execution permanently. -hen stop( ) is called on a runnin" thread, anob4ect of Thread#eath is called on it and the thread ob4ect is "arba"e collected. That is a stopped thread bycallin" stop( ) method can not be restarted a"ain.

    6! What is thread synchroni5ation ?or

    Write briefly abo"t synchroni5ed 9eyword ?

    $hread synchroni5ation provides the tool for ens"rin- that different threads ta9e proper t"rns when"sin- shared reso"rces!

    Thread synchroni7ation is important in a multithreaded pro"ram to maintain the consistency and durability ofdata that is accessed by different threads.

    Multiple threads of a pro"ram run independently of one another. ach thread does not bother about theacti!ities of other threads. -hen a thread wor2s on its own and on separate data( i.e., not shard ), the data will not bein inconsistent state. The problem( due to inconsistency of data ) occurs when the sa e data is accessed( or shared )by different threads.

    -hen the threads act on shared data, ti in- is an important issue. &y the process of synchroni7ation, we anensure only one thread can access the source at a time and other threads should wait in a 8ueue until the first threadcomes out after finishin" its execution. -e use synchroni5ed 2eyword to monitor the acti!ities of different threads. -ecan use synchroni5ed as an access modifier.

    The followin" method is synchroni7ed >

    1

  • 8/12/2019 CoreJava Full

    112/159

    public synchroni5ed !oid update( int amount )

    5ll the threads in a thread "roup can be stopped to"ether by callin" t".stop( ) or can besuspended by callin" t".suspend( ) or can be resumed by callin" t".resume( ) where t- is a thread

    "roup. &ut we canKt start by callin" t".start( ). ach thread must be started indi!idually.

    So e ethods of $hread1ro"p >

    -et$hread1ro"p# ) > This method returns an ob4ect ThreadGroup class. -ith this "roup we can8uestion a thread to what "roup it belon"s.

    -et.arent# ) > This method returns an ob4ect of ThreadGroup class. -ith this method, we can2now the parent thread "roup to which a thread "roup belon"s.

    activeCo"nt