J
A
V
A
A
N
D
J
2
E
E
h
c
S e e
m and Sy lla u
b s
Su jb ce t dC e: o 10IS753 I. .A Mar sk : 52 H uo rs/Week : 40 E ax m H r :ou s 30 To H utal o rs : 25 E mx Mar :a k 0s 1 0 R A P T - A T I N U - 1 N O I T C U D O R T N I TO AJ VA: Java da n Javaappilcaitons;Java Development tiK (JDK ;) a v a J si interpreted, Byte Code, JVM; Object-oriented programming; Simple aJ v a m a r g o r p s. D ata types da n other tokens: Boolean variables, i nn,t l g, ao c r, o eh p rator ,s , s y a r r a wh tie spaces, literals, assigningvalue ;s Creaitng da destr yn o ni g o cb t ;je s A cc e ss s r e if i c e ps . O r tpe a ors and E rxp essions: Ar tihmetic Operators, Btiwise o rpe ators, l a n o it a l e R operator ,s T he Assignment Operato ,r The? Operator; O ep r ta ro Precedence ; l a c i g o L expression; Type c t nas i g; Str ni gs Control Statements: Seleciton statement ,s n o it a r e ti statements,JumpStatements. 6 Ho su r T I N U - 2 S E S S A L C , INHERITANCE, EXCEPT OI NS, APPLETS: Classes: Classes in Java ; a l c e D r gi a n class; Class name; Super classes; Constructors; Cr ae t ni g si t cn an e of s c s; las r e n n I classes. Inhertiance: Simple, mulitple, a nd mu tllievel inhertiance; Overriding , l r e v o oading. Excep iton handilng: Excep iton handilng ni aJ v .a T eh Applet Class: Two s e p y t fo Applets; Applet basics; Applet Ar ic t ch e tur ;e nA Applet sk ee to ;l n Simple t e l p p A display methods; Reques itng repain itng; Using t eh Stat su Windo ;w eT HTML h T E L P P A t ag; Passi gn parameters ot Applets; getDocumentbase )( a getCond debase )( ; t x e t n o C t e l p A da n showDocument( ;) eT h AudioCilpInterface; eT h AppletSt bu nI terface; t u p t u O ot t eh Co sn o el . 6 Ho su r T I N U - 3 MUL IT THREADED PROGRAMMING, EVENT HANDLING :M ti hul T readed : g n i m m a r g o r P What ea r threads? How ot m ke t ea h classes threadable; Extending ; s d a e r h t Implemenitng runnable; Synchronizaiton; Changing state fo t hhe t read ; d e d n u o
B bu ffer problems, read-wrtie problem, producer-co un mer pro ls b e .m s Event g n il d n a H : Twoeventhandilng mechanisms; eT h delega iton event mod Ev ne;l e t classes; s e c r u o S fo events; Event ilstener interfaces; Using ht e ld ge e ation ev ne t mod e;l Adapt re ; s e s s a l c Innerclasses . 7 Ho su r T I B J S , E S I f o . t p e D Page 1
www.vtucs.com
E E 2 J d n a a v a J 10IS753 T I N U - 4 : S G N I W S Swings: The origins fo wS ing; Two k ey Swing features; Components and ; s r e n i a t n o C eT h Swing Packages; A simple Swing Appilca iton; Create a Swing A lppe ; t l e b a lJ na d ImageIcon; JTextField;The Swing Bu ttons; aJ bbe aT d n ;p e cJ roS llPane; J t; Lis ; x o B o b m o C J JTable. 7 Ho su r T R A P - B T I N U - 5 A V A J 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS: Overv wi o f e E E 2 J a J2 .nd S E T he Concept fo JDBC; JDBC Driver Types; JDBC Packag ;e A Br fs i e w e i v r e v O fo et h JDBC process; Database Conneciton; Associaitng et h JDBC/ODBC Bridge w tih t he Databas e; Statement Objects; Resu tlSe ;t Transaction Processing; , a t a d a t e M Data type ;s Exceptio sn . 6 Ho su r T I N U - 6 E L V R E S T :S Background; T he L fie Cycle fo a Servle ;t Using Tomcat for eS vr l e t ;t n e m p o l e v e D A simple Servle ;t T he Servlet A P ;I T he Javax e. vs r el t P kag ;ac e Reading t e l v r e S Parameter; T he Javaxs.ervle .th ttp package; Handilng HTTP Re uq ests na d ; s e s n o p s e R UsingCookies;Session Tr ca k ni g . 7 Ho su r T I N U - 7 , P S J RMI :JavaServer Pages(JSP :) PJ , PS J S Tags, Tomca ,t Request rS nt i g, sU er Se is o ss n , o o C kies, Session O cb ts. je Java Remote Method vI o an c tio :n Remote Method Invoca iton ;t p e c n o c eS r rv e side, ilC ent side. 6 Ho su r T I N U - 8 E S I R P R E T N E JAVA BEANS: Enterprise java Beans; Deployment Descriptor ;s Session a v a J Bean, EnttiyJavaBean; Message-Drive Be ;n a en T Rh JA F eli . 7 Ho su r
www.vtucs.com
T X E T BOOKS: 1. Java - T he Complete Reference – Herbert Schlid,t 7thEdi iton, T M Gata c ra w 7 0 0 2 , ll i H . 2. J2EE - eT h CompleteReference – miJ Keogh ,Tata M Gc r wa H 20 7li,l 0 . E C N E R E F E R BOOKS: 1. Introduciton ot JAVA rP go ramming – Y. Daniel Liang, 6th iE tio ,d n P rso ea n , n o it a c u d E 2007. 2. T he J2EE Tuto lri – a Stephanie Bodo ff te ,la 2ndEdi iton, P rson ea Educatio ,n 0 0 2 4. T I B J S , E S I f o . t p e D Page 3
www.vtucs.com
e
d
n
I
x
S
h
e
e
t
N O I T C U D O R T N I OT AJ VA a v a J d n a a v a J app ilcations ;JavaDevelopmentKit ( JDK) ; t n i s i a v a J erpreted ,Byte dC e.o t c e j b O , M V J -orientedprogramming ;Sim e pl Javaprograms h t o d n a s e p y t a t a D ertokens :Booleanvariables, i nt,l on g , p o , r a h c erators ,arrays ,white spaces ,il et rals, r C , s e u l a v g n i n g i s s A eatinganddestroyingobjects ;Acces s p s e ifc e si r . r p x E d n a s r o t a r e p o essions :ArithmeticOperators ,Bitwise p o l a n o i t a l e R , s r o t a r e p o erators ,The Assignment Operator , p O ; r o t a r e p O ? e h T eratorPrecedence; Logica lexpression ; m e t a t S l o r t n o C , s g n i r t S ; g n i t s a c e p y T ents :Selection m e t a t s ents, i terationstatements ,JumpStatements , S E S S A L C INHERITANCE, EXCEPTIONS, APPLETS D ; a v a J n i s e s s a l C : s e s s a l C eclaring aclass ;Classname ; r C ; s r o t c u r t s n o C ; s e s s a l c r e p u S eating i nstanceso fclass ; n n I erclasses h n I eritance :Simple ,multiple ,and multlievel i nheritance ; v O erriding ,overloading. c x E e ip ot nhandilng :Exceptionhandilngi nJava. h T e Applet Class :Two typeso fApplets ;Appletbasics ;Applet r u t c e t i h c r A e ;AnAppletskeleton ;SimpleApplet display d o h t e m u q e R esting repainting ;Usingthe StatusWindow ;The HTML l p p A o t s r e t e m a r a p g n i s s a P ; g a t T E L P P A e ;t s getDocumentbase( )andgetCodebase)( m u c o D w o h s d n a t x e t n o C t e l p A ent)( ;The AudioCilpInterface ; h T e AppletStubInterface ;Output tothe Console. I T L U M THREADED PROGRAMMING, VE ENT N I L D N A H G r h T i t l u M eaded Programming :What are threads?How to h t e k a m e classesthreadable; r h t g n i d n e t x E eads ;Implementingrunnable ;Synchronization ; r h t e h t f o e t a t s g n i g n a h C ead ;Bounde bd u fferproble sm Re da -w e rit problem ,producer-consumerproble sm v e o w T ent hand ilng mechanisms h T e ld ee gationevent model ;Eventclasses ;Sourceso fevents t s il t n e v E ener i nterfaces ;Using the delegationeventmo lde t p a d A er classes ;Innerclasses SWINGS h T : s g n i w S e originso fSwing ;TwokeySwingf eatures n i a t n o C d n a s t n e n o p m o C e sr h T e SwingPackages ;Asimple SwingAppilcation a P geNo . 1- 21 1 1 3 4 4 6 3 1 - 82 3 1 5 1 8 1 0 2 2 2 3 2 9 2 - 14 9 2 0 3 3 3 5 3 6 3 7 3 9 3 2 4 - 94 2 4 2 4 5 4 UNIT No. 1 2 3 4www.vtucs.com
A J VA 2 ENTERPRISE EDITION OVERV WIE , E S A B A T A D ACCESS: i v r e v O e w o fJ2EEandJ2SE. h T e Concepto fJDBC ;JDBCDriverTypes ;JDBCPackages i r B A e fOverviewo ftheJDBC process ;Database Connectio ;n h t g n i t a i c o s s A e JDBC/ODBC Bridge withthe Database ; j b O t n e m e t a t S ects, ResultSet ; r P n o i t c a s n a r T ocessingMetadata,. Datatypes ;Exceptions. E L V R E S TS o r g k c a B u dn l v r e S a f o e l c y C e fi L e h T et ;UsingTomcatf orServlet l p m i s A ; t n e m p o l e v e D e Servlet h T e ServletAPI ;TheJavax.servletPackage S g n i d a e R e lr ev t Parameter ;The Javax s. e lr ev t.http package R P T T H g n il d n a H equestsand Responses o C g n i s U okies SessionTracki gn . , P S J RMI S a v a J e vr erPages( JSP) :JSP ,JSPTags R , t a c m o T equest String ,UserSessio sn S , s e i k o o C ession Objects R a v a J emoteMethodInvocatio :n RemoteMethod Invocation c n o c e tp v r e S erside d i s t n e il C e. C M I S K c i D single windows agency SISI,NSI SC I B, D I,KSFC S N A E B A V A J E S I R P R E T N E B a v a j e s i r p r e t n E eans; s e D t n e m y o l p e D criptors v a J n o i s s e S a e nB a B a v a J y t i t n E e ;an Message-DrivenBean ,The JAR Flie. 0 5 - 35 0 5 0 5 0 5 1 5 2 5 3 5 4 5 - 06 4 5 4 5 5 5 6 5 7 5 8 5 9 5 1 6 - 56 1 6 2 6 4 6 4 6 5 6 5 6 5 6 5 6 6 6 - 86 6 6 7 6 7 6 7 6 8 6 5 6 7 8
www.vtucs.com
E E 2 J d n a a v a J 10IS753
U TN -1 NI I TRODUCT NIO OT JAVA 1. Introducti no ot Java
• vJ a is an ob ea j tc -orien et d p or gramming al ngu ga e developed by Sun Mic or sy est m a cs, ompany eb st known rf its h go i h-end Un xi works at ot i n .s
• Java si modeled fa t re C++
• Java al ngu ga e aw s design de to be sm s mal,l i p el , and p ro ta ac sble r s p ao l t mfor s and o ep ar ting syste sm , ob ht at the sour ec da at the in b n ya r level (m e oor a ut b th si al et .)r
• Java la os provides for p ro ta p oble r g mra ming iw th pa p sl . App eet l st pa p re in a a b
e
W p ea mu hg c in the s ma e aw y as mi a eg s od , b tu un eil k images, a pp el st ea r y
d na c and intmi e trac ive .
• pA p tl s can ee b su de to c ar ee t an aim tions, gif u sr , re o areas ht at can er ps ond ot n
i put rf om ht e reade , mr ga e , rs o oth re in ater c eti ffv e e on the s mcts a e W be pages among t eh et tx and g ar phic .s 1.1 Java sI Platform-Independent o f t a l
P rm-i dn ependence is a program's capabiilt fy o mov ni g ae s liy from one computer sys mte ot another.
• P al t mfor in ed pendence is o en fo the om ts sign ifi cant advanta s age t t h Java has eo r v t
o h re program ng l nmi a guages, p ra t ci ularly of r sy ts me s that n de to work on ae m ny ff
i
d e er tn pla ftorms .
• Java si p al t mfor -in ed pen ed nt ta both the s ro ce and the iu b n ya vr l e .l e 1.2 Java Development K ti (JDK)- B ey c et o d
• Bytecod se ea a set fr o instruct ni s that o look a ol t il ake m hc ine c eo , d b eut a n tr o spec ci to any eif o p on r c se s ro
• P al t mfor -independence od se n't ts op at t eh os urce level, however. J aa iv b n ya er f s li e
r
a la so pla ftorm-in ed pen ed nt and can r nu on multip el p al t mfor s iw ht o tu the n de to e e
r c mo p eli the sourc .e Java ib n ya lir f es ea actu yr a nll i a mfor called yb tec eo s . d 1.3 Object-Oriented Program ing m
• Many fo Java's objec - et ori n dte c no cepts ea inr h t derie from +C +, the al ngu ea ng o wh ci h it is ab s de , tb it ou b rrows am ny con ec pts from o ht re o ct- ebje o nt dri e al ngu ea s g
s a well .
• Java inclu ed s a set fo c al ss ilbraries ht at provide ab sic ad ta typ se , sy ts me pi ut and n output capabiilt ,i des a ot rn h te u ili ty uf nctions .
• These basic cla es s are as p tr fo the Java development kit, which also has classes to us p op rt networking, common Internet p tocols, and us rro e interface toolkit fu tn io sc n .
• Beca su e these c al ss il rb aries ra e written in Java, they are por at b el ac or ss plat rf ms as all Ja ao v ap lp ica itons a er .
4 . 1 Crea itng a simple Java Program Hello W lo d example : r l c a ss HelloW ro dl {
pub ilc ts atic ov id m ia n (String arg ]s ) { [ s
y
S tem.o tu . rp intln "( eH llo W ro ld! "); }
}
This program has two m ia n ap r st :
• All the program is en lc osed in a c al ss ed fi in tion—here, a cla ss called Hello W lo d. r
• T eh body fo the prog mra (here, j su t t eh one ilne) is contained in a met oh d c
n u f
( tion) c la l de am in(). In Java a lp ications, as in a C rp o C++ pr ro am, main )g ( is the first meth do f( unction) ht at is run when ht e program is executed.
1.5 oC mpil ni g the above progr ma :
• In Sun s' JDK, ht e Java oc m ip ler is called javac. j aa c H lv e ol Wor dl j.ava
• When the p gr ram compi eo l s without e rr or ,s a file called He lloW lo d.c ar l ss is cre ta ed, in the same d ri ect ro y as ht e source if el . This is ht e Java yb tecode fil .e
• Then run that bytecode fi el using t eh Java interpreter. In ht e JDK, t eh Java interp tr er is c le a l de simply jav .a
java HelloW ro ld
If the program aw s yt ped a dn compil de oc rrectly, the o tu put w lli be : "Hello W ro ld!" T I B J S , E S I f o . t p e D Page 2
www.vtucs.com
E E 2 J d n a a v a J 10IS753
2. Variab el s and Data Ty ep s
• V ra iab el s are loca itons in memo yr in which values can be store .d T eh y have a a
n m , a type, and a value. e
• Java has three kinds of variab el s: instance variab el s, class var ai bles, and c
o
l al variables.
• Ins at nce variabl se , are su ed to de ifne attributes ro the ts ate for a ap rticular obje tc . C al ss variables are si im lar to in ts a cn e var ai bl se , e cx ept ht e values a pir p ly to all ht at cla ss 's i sn tances (and to ht e c al ss itsel )f ar ther than ah vi gn different values of r ae ch obj te . c
• L al variables are eoc d c al red and su de i sn di e method d fe initions, r
o
f example, rf index co no u te sr in loops, as tempora yr va ir ables, or to hold va ul es th ta you n de o le n y inside ht e m hod de ifnition i eet t lf s
Var ai ble dec rl ations consist fa o a type and a va ir able name: Examples : int ym Age; String myName; b oo lean isT ri de ; 2.1 nI teg re types. y T pe S e i z R n a g e t y b e 8 bi st —128 to 21 7 short 61 bits — 23 7, 86 to 32,767 int 32 bi st —2 1, 74 4, 38 6, 84 to 2,147,483,647 —922337203685477 85 08 to 922337203685 74 57 807 long 46 bi st 2.2 oF a il t ng- op ni t
This is used for un m eb sr wi ht a decim la part. Java floating-point numbers are compliant with EI EE 7 (an i t54 n ernation la sta an rd for de ifning lfoating-point d
There are two lfoati gn -point types: olf at (32 bi st , sing el -precision) and dou lb e (64 i
b ts, double-precision).
2.3 Char
The char ty ep is used rf ind vo i idual hc aracter .s Beca su e aJ va uses the Unicode character set, the char type has 61 bi st of precision, u sn igned.
2.4 B oo l n ea
The boolean ty ep can ah ve one fo two valu se , true ro af lse. N to e that unlike in h
t
o er C- kil e lang au ges, ob lean is not a o number, n ro can it be tr ae ted as one. All te ss of B ot o lean var ai bl se sho lu d t for true or f lest a s .e
2.5 Literals ti
L erals are used to indicate simple v ues in your Ja aal v programs. Number Literals
• T eh re are several in et ger ilterals. 4, f ro ex ma p el , is a decimal i tn eger literal of type i tn
• A de ic m la integer lite ar l al rger than an i tn is auto am tically of ty ep long.
• Floating- op int liter la s su ual yl have two parts: the i tn eger part and ht e ed ic m la a
p rt—for exam lp e, .5 76 77 77 . B oo l ae n Lit re la s
o o
B l an lit re e als consist fo the keywords true and af l es . These keywords can be used anywhere needed a te ts ro as the o ln y po ss ible v la eu s f ro boole n a variables.
2.6 Chara tc re Literals
Charact re liter la s are express de by a sing el hc aracter surrounded by single quotes: 'a', '#', '3', and so o .n Chara tc ers are stored as 16- ib t Uni oc de c ah racters.
3. xE pressions and O ep rators
• Expre is ons are hs t e sim lp est form fo stat me ent in aJ va that a tc ually accomplish se some ht ing. E px ressions are ts atemen st th ta return a v la ue.
• Operators are special sy bm ols ht at are commo ln y su ed in expr se io ss n .
T I B J S , E S I f o . t p e D Page 4
www.vtucs.com
E E 2 J d n a a v a J 10IS753
Arithmetic and tests rf equality a do n magnitude are c mo mon examples fo expre ss io sn . Because ht ey return a v la uethe v la ue can be as is gned to a va ir ab el or te ts ht at value in o ht er Java ts atements.
Operators in Java incl du e arith em tic, vari uo s forms of a ss ign em nt, n
i crement and decrement, and l go ical operatio sn . 3.1 A tri hmetic
Java has five operators of r ab sic arithmetic r A ti h em tic op ae tors. r O ep rator Exam M ae ning p e l + y is y S st me .out.p ir ntln("x + y = " ( + )y ;) - y)); Sy es m.out pt . ri tn ln("a si " + a + ", b is " Sy es m.out pt . ri tn ln("a / b = " + (a / b)); t n e m n g i s s A operators. Express on Meaning i x += y x = x + y + Addition 3 + 4 — Subtr ca tion 5 — * Multi lp ication 5 * 5 / Division 1 / 4 7 % M do ul su 02 % 7 Ex ma ple p or gram : c al ss A ir thmet ci Test {
pub ilc static ov di main S( tring args[ )] { sh to x = 6; r int y = 4; float a = 12.5f; float b = 7f; + y); + b; ," " + x / )y ;) + x y S st me .out.p ir ntln("x - y = " ( } }
www.vtucs.com
x —= y x = x — y x =* y x = x * y x = x / y x =/ y r c n I emenitng da n Decremen itng + +
x i cn rements the v la ue of x by 1 ju ts as if you h da u es d the expre ss oi n x = x + 1. Similarly x-- ed crem ne ts the v la ue of x by 1.
Exercise : rw ite the fid fere cn e eb tween : y = x++; y = + x+ ; i r a p m o C s no operators.
O rp ator Meaning e E mxa ple
== Equal x == 3 = ! N to qe u la x < Less ht an x < > Greater ht an x > <= Less than or x >= Gr ae et r ht an ro qe ual to x >= 3 Logical r o t a r e p O s
• Exp er ssions that er s lu t in boolean values (for example, t eh com ap rison p
o erators) can be co bm i en d yb su ing gl ic lo a operators that re rp es te t en h logic la c mo b natio si n
• AND, RO , OX R, and logical NOT.
• rF AND co bo m inatio sn , use either t eh & ro && . hT e expre ss ion iw ll be true o ln y if both xe rp es is ons are also true
• rF OR expressions, use ei ho t er | or || . OR xe p er ssions result in true if ie ther or t
o
b h of the operands is also true
• In ad id tio ,n t eh re is t eh OX R o ep rat ro ^, which returns true only if its p
o erands ra e d fif re ent (one true a dn one fa sl e, ro v ei versa) and false tc o he wr i es (even if both are true).
• In ge en r la , o ln y the && and || are commo yn sl u ed as ac ut al l go ic la combinatio sn . &, |, and ^ are m re o commonly us de f ro bi wt ise l ical og operatio sn . T I B J S , E S I f o . t p e D Page 6
www.vtucs.com
E E 2 J d n a a v a J 10IS753
• rF N To O , use the ! o ep rat ro with a single expression argu em tn T . he value of the NOT expression is the negation of the expressio ;n fi x is true, !x is fals .e
e s i w ti B Operators e s e h T ea r used ot performopera itons no individual sb nti i integers. p O erator Meaning
& Bi wt ise AND | Bi wt ise RO ^ Bi wt ise OX R << L ft shi te f >> Rig th sh fit
> >> Zero fill rig th shi tf ~ Bi wt ise c mo plem te n
< =< L ft shi te f a ss ignm te xn ( = x << y) > => Rig th sh fit assignme tn (x = x >> y)
= > >
> Ze or f lli gr ht sh fit assignment (x = x >i > > y) x =& y AND a ss ignm te (x = x & y) n
| x =y OR assignment (x + x | y) ^ x =y XOR a ss ignment (x = x ^ y) p O e ar tor P er ced ne ce
Operat ro preced ne ce de et mr ines the ro der in which expressions are evaluated. This, in some cases, can d te re mi en ht e overall value fo ht e expre ss ion. oF r examp el , ta ek the foll wo ing expr se sion:
y = 6 + 4 / 2
Depending on wh te her the 6 + 4 xe press oi n ro t eh 4 / 2 expre ss ion is evaluated
r
a e evaluated b fe ore arithmetic, arithmetic expressions a er eval au ted b fe ro e compariso sn , and comparisons are evaluat de be of re logical expressio sn .
s
A signment expre ss ions are evaluat de al st.
4 A rr ays
A rr ays in Java are actual jo ects that can be passed a ob r und and treated ju ts like t
o her objects.
r r
A ays are a way ot store a list of ite sm . Each ls ot fo ht e a rr ay holds an individu la element, and oy u can p al ce elements into ro change the contents or those slots as uy need to. o
T rh ee steps to create an a rr ay: .
1 Declare a var ai ble to hold the array. .
2 C er ate a new ar ar y obje tc and assign it to the a rr ay var ai bl .e . 3 St eo hr t ings in ht ta ar ar y. E.g. String[] names; n ma es = new Strin [g 1 ;]0 n ma es 1[ ] = “ ”; n1 names 2[ ] = ‘n ’2 ; . . . 4.1 Mu tl idimensio an l Arrays
Java d eo s not s pu port m itdimension lul a a rr a sy . H wo ever, oy u can dec al re and create an ar ar y of arra sy (a dn those arrays can contain a rr ays, a dn so on, f ro however many dimensions you need), a dn a cc ess t eh m as you would C-sty el
u
m ltidim ne sion la arra sy :
int coord [s ] [] = new int[12] [1 ]2 ; coord [s ]0 [0] = 1; coo dr s[0] [1] = ;2 5 oC ntrol S tt e ea m nt 5.1 if oC dn it oi nals T I B J S , E S I f o . t p e D Page 8
www.vtucs.com
E E 2 J d n a a v a J 10IS753
• T eh if conditional, which e an bles you to exe tc e different bits of code bas du e n
o a simple te ts in Java, is nea lr y i ed tn ic la to if ts atemen st in .C
• if co dn i iton la s co tn ain the keyword fi, of l ol wed by a bool ae n test, o
f l wlo ed by a ts atement o( ften a block s at tement) to execute if ht e te ts is true:
• if x( < y) s
y
S tem.o tu . rp intln "( x is smaller than y"); n
A optio an l else keyw d p oor r vi ed s ht e ts atem te to exe tn c e if the test is au f ls :e if (x < y)
y
S stem.o tu .println("x is sma ller than "y ); le se s
y
S tem.o tu . rp intln("y is ib gg er" ;)
5.2 T eh C di ion t o an l Oper ta or
An alternative to using the fi a dn else keywords in a c do itional statement is to n use ht e conditional o ep rator, sometim se called ht e ternary o ep rator.
The condi itonal operator is a tern ra y operator beca su e it has three terms. Syntax : test ? trueresult : af lseresult
The test is an xe pression that returns tr eu or af lse, just kil e ht e test in the if statement. If ht e test is true, the conditio an l o rp at re o r u set r the v ln a ue fo
tr eu result; if it's false, it r te urns the value of falseresult. rF example, the fo llowing o conditional tests ht e values fo x a dn y, returns the smaller fo the two, and a ss igns that value to the vari ba le smaller:
int sm la ler = x < y ? x : y;
The con id tional o ep rat ro has a ve yr l wo rp eceden ec ; ht at is, i s't u us la yl evaluated n
o ly after a ll its s expressions are evalua eub t d. The only operat ro s ol w r in e preced ne ce ra e ht e a ss ignm te o en p rators. .
5.3 ws itch Conditio an ls
This is ht e ws i ct h or case ts ta emen ;t in Java it s' swi ct h and be ah ves as it does in C: switch (test) { case
break; case valueTwo: re us ltT ow ; break; case valueThree: re us ltThree; break; ...
defau tl: defau tlresult; }
In t eh swi ct h state em nt, ht e test (a primitive type of yb te, ac r, short, rh o int) is compared tiw h ae ch fo t eh case values in ut nr .If a ma ct h is of und, the stateme tn , or statements after t eh test is ex ue t dc e . If no ma ct h is found, the default state em nt is executed. The ed fault is option la , so if there isn t' a ma ct h in any fo t eh cases and de af ult doesn t' exi ts , ht e swi ct h ts atement completes witho tu doing anything.
5.4 for L oo ps
The f ro loop, as in ,C er ep ats a st ta ement ro lb ock of statem te s some number of n times unt li a condition is ma ct eh d. rf loops are frequently us do e f ro sim lp e tieration in which you re ep at a block fo statements a cert ia n un m eb r fo times and then sto ,p b tu you can use for ol ops for ju ts about any kind of loop.
The for loop in aJ va ol ko s roug lh y like this: r
o
f i(niti la izati no ; te ts ; ni cr me ent) { ts a men ste t ; }
The ts art fo the of r loop has thr ee par st :
• Initialization is an exp er ss ion that initiali ez s ht e ts art fo t eh loo .p If you have a loop i dn ex, this expression mig th declare and initiali ez ti, rf example, int i = 0. o Var ai bl se ht at oy u declare in this part fo ht e rf l oo o p are loc la to the ol p so ti le f; t eh y c ae se existing after the loop is finis eh d exe uc ting. Te ts is the st t he t at
c c
o urs after ae ch pass of ht e loop. The et st must be a ob olean xe pre ss ion ro c
n u
f tion t ah t returns a obo l an value, re f exam lo p e, i < 10. If t eh t se t is true, the o
l op executes. O e the nc t is false, the loop stops xest e e uc ting T I B J S , E S I f o . t p e D Page 10
www.vtucs.com
E E 2 J d n a a v a J 10IS753
• Increment is any expre is on rs o fun itc on call. Commonly, the increment is used to change the val eu fo the l oo p i dn ex to ib ng t er h state fo t eh ol p closer to o returning f la se and c mo pleting.
The s at tement ap rt fo t eh for loop is t eh ts atements ht at are execut de each time t eh ol op iterates. Ju ts as w tih if, you can i cn lude ie ther a single ts atement here or a block; the previous exam lp e su de a lb ock because that is more commo .n
e
H re's an example fo a for loop that initia ilzes all t eh values of a String a rr ay to null rs ings: t
String st rr ra ][A y = new String 0[ ]; 1 int i; // loop index
r o
f (i = 0; i < strA rr ay.lengt ;h i++) strA rr ay[i] = "";
5.5 while and do L oo ps
Finally, there a er whi el a dn do loops. while and do ol ops, like f ro loo sp , enable a l
b ock fo Java code ot be exe tc ed repeat lu e y unt li a sp cd e ific condition is em t. Whet eh r you su e a f ro loop, a while, or a do is mostly a matter of your pro
r
g a mm ing sty el . while and od loop, are exactly the same as in C and C++ xe cept their test co dn ition must be a boole n. a
5.6 while Loops
The hw eli loop is used to er peat a statement ro block of statements as long as a a
p rtic lu ar co dn i iton is true. w ih el loops lo ko like this:
while (condition) { o
b dyOfLoo ;p }
The con tid ion is a b oo el an xe p sr sion. If it te r urns true, the while loop e execu et s the statemen st in bodyOfLoop a dn ht en te ss the condition ag it a ,n re ep ating u l the condition is false: n it
int count = ;0
while ( co tu < array 1 . en l ng ht && array 1 [count] !=0)
5.7 do...wh li e L oo ps
The do l oo p is j su t ilke a w lih e loo ,p e cx ept that do xe ecu et s a given statement r
o block u tn li t eh condition is f la se. T eh main difference is that w ih le loops st t e the condition
be rf e looping, making it possible that t eo h ob dy fo the loop w lli en ver xe ecute if t eh condition is false the ifrst time it's te ts de . do ol ps run the body of the l oo o p at
e
l a ts once before te ts ing the condition. do l oo ps l oo k like this:
do { o
b dyOfLoop; } while (condi iton);
Here, the bodyOfL oo p part is ht e ts at me ents that a er exe uc ted w tih ae ch int x = ;1
do { y
S stem.o tu .println("L oo ping, round " + x); +x ; + } while x( =< 10);
Here s' ht e o tu p tu of these ts atemen st :
Looping, rou dn 1 Looping, round 2 Looping, rou dn 3 oL oping, or und 4 Looping, o
r und 5 Looping, round 6 o
L oping, ro nu d Looping, or nu d Looping, round L oo ping, or nu d
T I B J S , E S I f o . t p e D Page 12
www.vtucs.com
E E 2 J d n a a v a J 10IS753
I N U T- :2 CLASSES, INHERITAN , EXCE CEPTIONS, APPLETS 1. Defining aC sl s e as, C ss l Name
• To d ne a c aeif l s ,s use the c sl yas k w de o and the nr ame fo the clas :s c slas MyClassName {
.. . }
• If this c al ss is a us bc al ss fo an to eh r c al ss, u es e tx ends ot in id cate et sup rh e c sl s of a th si class: c slas myClassName xe ten sd m upyS erClass mNa e { .. . }
• If ht is c sl s ma i plements a spec ifi c interface, use mi plements to r r to that efe in et ar c :f e c slas MyRunn la eb C slas Name mi plemen st Runn ea { bl .. . } r e p u S C s slas e
• aE hc c al ss has a sup re c sl s t(he c sa l s a above ti in the hierarc )hy , da cn e h c aa l ss can h ea o ev n ro m e uor s bc al ss se (c sl ses be wa lo that c sl s in the ha ierarc )hy . C sl ses a fur et r h down ni the hierarc y rh a e s da to ini h t eri from c al ss se fur ht re up in the hierarc y . h
• Subc sla s nes i h ire t lla the meth do s and v a eari b s l from ht e uir s p re c al ss es—that si , ni any p ra t ci u rl c aa l ss, fi the us p re c sl s a d nes eeif b havior ht ta your c al ss ne se , od y u
o
d t'n h ea to v rede ifne ti ro copy ht ta c do e rf om some o et r c ah l ss. Your c slas automatic ya ell g st that eb havior fr mo i st sup re c al ss, that sup re c al ss gets eb havior
r
f om its sup re class, da so nn o lla the w payu the hierarc .hy
• At et t ph o of et Java c ah l ss hierarc yh is the c al ss Object; lla c sl ses na i h ie t or f m r h
t is one su ep rc al ss. O jb te is ec t h m t genos e c sral l s in the ha ierarchy; it d n se if e e
b havior i enh r t die yb lla ht e c sl ses in the a Java c al ss hierarchy. aE hc c sl s a f h rart e w
o
d n in the hierarchy a s m rdd o e in of rmat oi n and eb comes mo er t lia o dr oe t a spec ci purpos .if e
E.g .
pu cb c ail l ss HelloA ig n pa A p tl e te x en sd java. pa p tl . pe A p tl { } e 2. nC s uo t cr tors, Creaitng ni s nt c sa e fo a c al ss
The f o ioll w ng ex ma p el demon ts ar tes the c ar t oe i n fo c al ss se , cre ita ng ob ej tc s and the us ea fg o construct ro s c slas Mot ro cyc el { } c ar te se ome ni ts na ce va irable rsf ho t si c sl as St ir ng make; St ir ng co rl ; o boolean en ig n Se t ;a te d d A some eb havior e(m th do s) to the class. d i o v ts ra tEn ig n )(e { fi (en ig n Se tate == tr eu ) y S es m.ou .tp nt r tln "i ( T eh en ig ne si already on".;) le se { en ig ne State = rt u ;e y S es m.ou .tp nt r tln "i ( T eh en ig ne si n wo no . ;)" } } The p gro ram ol oks eil th sk i n wo : c sl Mot ras o cyc el { St ir ng make; St ir ng co ; lor bo ao n en ile g n Se tat ;e d i o v ts ra tEn ig n )(e { fi e( n ig n Se ta et == tru )e y S ts me .ou .tp nr tln "i ( T eh
The hs wo A ts meth dt o p ir nts the uc rrent values fo the instance v a eari b s nl i na ni ts ance f o oy ur Mot ro cyc el c al s .s rH e s' wh te a ti looks il ke: d i o v hs wo A ts )( { t y S es m. out .pt rinltn T( h s" i om t ro cyc el si a " + co + " " + lor make;) T I B J S , E S I f o . t p e D Page 14 en ig ne is already o .n ;)" en ig ne is n wo o .n ;)" }
www.vtucs.com
E E 2 J d n a a v a J 10IS753
fi (en ig n Se tate == tr eu ) y S s et m.ou .tp nr tln "i ( T eh en ig ne si no . ;)" le se yS ts me .o p iu.t r ntln T( he en i" g ne si ffo . ;)" The showA tt s m h det o p ir nts t ow ilnes ot the sc er en: t eh make and c oo r of the l
o
m ot rcyc el o c ,t and wh tbje e eh r ro n to the en ig ne si no ro .fo f 2.1 A eddt h main method pu ilb c st ita c void am ni S( t ir ng ga s )]r [ { oM t ro cyc el m = n we Mo cycle )(; m.tor m e = ak "Yamaha ZR 350 ;" m.co = lor "yellow"; y S es m.ou .tp nt r tlni ("Calilng sh wo A ..tt . ;)s " sm h w. o A tts( y;) S ts me .ou .tp ir ntln "( ——— — ;)" yS ts me .o p iu.t r ntln S( t r" a ting en ig ne ... ;)" .m s at rtEn ig n ;)e ( y S es m.ou .tp nt r tln "i (————" ;) y S es m.ou .tp nt r tlni ("Calilng sh wo A ..tt . ;)s " sm h w. o A tts( y;) S ts me .ou .tp ir ntln "( ——— — ;)" yS ts me .o p iu.t r ntln S( t r" a ting en ig ne ... ;)" .m s rt tEn ia g n ;)e ( } i
W th ht e m n )( eai m t dh , the Mot ro o cycle c al ss is n wo an pa p ilcat oi n, and oy u c na c mo p eli ti again and st t ehi im it ll' run.Here's h wo the uo tput shou dl look:
il l a C ng sh wo Att s... Th si om t ro cyc el si a yellow Yamaha RZ350 The en ig ne si .fo f St ra ting en ig n ..e h. T e en ig ne si n wo .o n il l a C ng sh wo Att s... Th si om t ro cyc el si a yellow Yamaha RZ350 The en ig ne si o n . St ra ting en ig n ..e . The en ig ne si already on. 3. Inher n
www.vtucs.com
ti ce aInh ie ta cr n e is a powerful mechanism that m ns when oea y u iw ert a c sl s oa y u on yl h ea v to spec yfi h wo ht at c al ss is different from some o et r c sh las ; ni h ie t nr a ec w ill g oive y u automat ci acc se to the ins format oi n c no t ia n de ni th ta to eh r c al s .s
i
W th ni h ie tance, llr a c al ss es—those oy u iw t ,r e those of m o hr t re c al ss ilbrar ei s that oy u us ,e and ht ose from the ts andard ut ili ty ac sl s es as w — eell a ar ar r n dg in a st ie r ct hierarc y h
3.1 Single da n Mulitple Inher nti ce a i
S n eg inh il e tan er c m ns hea t at ce h a Java c sl can h eas a on yv l one sup re c al ss tl( hough a any given us p re c al ss nc ha ea v multip el subc al ss es .)
In to h re objec - et ori n dte program ng ami l ngu ea s, such as g C , c a++ l ss es c na h va e more than one sup re c slas , and th ye ni eh ir t combin de variables and meth do s from lla ht ose c sl ses. Th sa i si c lla ed multip el ni h ie tanc .r e
u
M ltip el ni h re itance ac n provide enormou ps ower in t me s fr o ib ng e a to create ble c sl s sa e that af ct ro just a ut llbo a imagin la e eb b havior, b tu ti can la so s gi n ifi can ylt c mo p ilcate c sl s a deifnit oi sn and t eh c do e to p dr uce th mo e . J aa v makes inher tiance simpler yb being o yn sl inglyinher dti . e
3.2 Overriding Metho sd
• When a m h det o is called on an o ct, bje Java looks for ht at m h det o d nit oeif i n ni the c sl s fa o th ta o ct, dbje a fi it n doesn't ifnd one, it pa ss es the m h det o c lla up the c al ss hierarc y u th n li a method de ifniti no si of un .d
• M te h do i hn e ta cri n e enable os y u ot d ne and use ee if m ht do s er peatedly in us bc sl s sa e i
w thout h ia ng to v dupilcate the c eo ti ed s .fl
• wHo e rv , th re e e m eay b t mi e when os y u aw tn an jobe to ect r spond to the same e
m ht do s ub t h ea v differen et b h iavo when that r m h det o is called. In this c ea , os y u c na override ht at m h .et o Od verriding a em ht do involve de ifn gs i a m hn et o in a d subc sl s ha t at has the msa e s gi na ut re as a em ht do in a sup re c al ss. Th ne , when th ta
e
m ht do is called, t eh m het o in t ed h subc sl s is oa f nu d and ex ce uted i tns e fad o t eh one ni the su rp ce lass .
3.3 Crea itngMethods thatO r eve rid iE s nx it g Methods
To vo e dr e a eri m th do , lla you h va e to do is c ar te a ee m ht do in y uo r subc sl s ha t ta h sa the s ma e s gi n ta ure (n ma e, r ue rn type, and t parameter il ts ) as a em th do d n deif e yb one
f
o oy ur c al ss 's us p re c al ss se . eB c ua se Java e cx utes he t e rif st m h det o d nit oe if i n it ifn sd that m c eat h s t eh signat eur , this effect li y "h eve i s" the d origin la m het o d d nite if ion .
e r e H s' a s mi p el example I B J S , E S I f o . t p e D T Page 16
www.vtucs.com
E E 2 J d n a a v a J 10IS753
e h T PrintClass class . c slas P ir tnClass { int x = ;0 int y = ;1 d i o v p ir nt eM )( { y S es m.ou .tp nt r tln Xi ( s" i " + x + ," Y si " + ;)y y S es m.ou .tp nt r tln Ii ( m" a na ni ts na ce fo the c al ss " + th si . tg C se l s )(.a getName()); a e r C te a c slas called P ir tn SubClass th ta si a bs c au l ss fo e( tx ends) P nr ti Class . c slas P ir tn SubClasse n sxte d PrintClass { ti z = ;n 3 pu ilb c as tic t void am ni S( t ir ng ga s )]r [ { P ir n St ubClas js o = n wb e iP ntSur bClass )(; bo j .p ir ntM ;)e ( } } e r e H s' t eh ou pt ut of m P ir r n St ubClas :s X si ,0 Y si 1 I ma na ni ts na ce fo the c slas P ir ntSubClass
In the m n )( ai m h det o fo P ir tn SubClass, oy u create a P ir ntSubClass o ct and c llbje a the p ir ntM )(e meth do . oN te th ta P ir tn SubClass ed sn't o d ne th seif i em ht o so d, Java looks
o
f r ti in ae hc fo P ir ntSubClass sup rs' e c sla s s—and ifnds ti, in this case, in P te r Cin lass . b ce ua se p ir ntM )(e si s itlld n de if e ni P ir tnClass, ti doesn t' p tr the z inst nin a ce variable . To c lla et h origin la me ht do rf om i sn di e a em th do ed ifnit ni , use t eo h su ep r yke w dor to p sa the es m ht do c lla pu the hierarch :y d i o v ym Me ht do S( t grin ,a St ir ng )b { // od stu ff h ee r su ep r. ym M the od(a, ;)b // maybe od more st ffu h ee } r
The sup re keyword, somewhat eil the th sk i ek ywo dr , si a p al ceholder for th si c sl s s' a su ep rc sl s. You can u ea s it an wy h eer oy u can use th si , b tu to re rf oe t the us p re c sl s a
t a
r h re ht na to the cu er nt cr lass .
4. xE cepiton hand ilng
An ex pc t oe i n is an ve ent th ta occurs du ir ng the ex ce tu ni fo o a p or g mra that id s ur pts the normal wlfo fo ni s rt uctions.
4.1 T eh Three Kinds fo xE cepitons
• Chec dk e ce x ept ni s a eo r sub tej oc t the aC tch ro Spec yfi R qe uiremen . llt A e cx pe tions r
a e hc ec dk e ce x pe tions, xe cept rf ho t ose in id c date yb rE r ro , uR ntimeEx e tc p ni , and o th re subc ai l ss .e s
• E r rr o s a er not su ejb ct to the Catch ro Spec yfi Requirement. rE r ro s ra e those c
x
e e tp oi ns in id cat de yb rE or and sr ti subc sl s .a e s
• Ru tnime e cx pe t oi ns a er not us ejb tc ot t eh C ch or Spec yat fi Requirement. Ru tnime c
x
e e tp oi ns ea those r indic date yb uR tnime xE cept ni and so ti subc al ss e s . d
il a
V Java pro rg a mm ni g al ngu ea c eg o ud m ts hon ro the Ca ht or c Specify Requriemen . t
This means that c eo hd t at gm ht th wi ro ec rt ia n e cx epitons um st eb enclosed yb ie t rh e f
o the following:
• A t yr ts atemen th tt a c ta ches the e cx pe tion. T eh t yr m tu ps rovide a hand rler f the o e cx eption, sa ed cs ribed ni C hing and aatc H n ild ng xE ceptions .
• A em ht do that s ep c ei s that it can th wif ro et xh e cept ni . The o m h det o m tu ps rovide a th wro s c ul se that ilsts the xa e cept ni , so a ed cs ribed in Spec ifi ng hy t e E cx pe t oi ns Th wro n yb a M te ho d .
e d o
C th ta falis to hon ro the C hatc ro Spec yfi R qe uirement w not mill co p .li e
This ex ma p el desc er s h wib o ot u es the three xe ce tp oi n han ed r c ml o ponents — the t yr , c ta c ,h and ifn ya oll b cks l
4.2 yt or b ck l
• The rif st step ni c no ts ur tc ing an ex pc t ne i hano d is oler t enc ol se the c eo hd t at gm ht i th wro na xe cept ni tio w h ni a t yr ob c .l k nI eg ne , a t yral r ob ck l looks eil the k following. t yr { co ed } ca ht a dc n ifnally lb ocks . . . Ex ma p el : T I B J S , E S I f o . t p e D Page 18
www.vtucs.com
E E 2 J d n a a v a J 10IS753
p ariv te eV tc ro cv t ;re o p ariv te ts at ci ifn la int S ZI E = ;1 0 P ir tn W t rrie out = nu ;ll t yr { y S es m.ou .tp nt r tln ni ("E t re ed t yr statement" ;)
out = n we P nr ti W t (rie n wr e liF eW erit "r Out li( F e.t tx" );) r o f i( tn i = ;0 i < SI ;Z i +E + ) { out.p ir ntln("Value :ta " + i + " = " + vect ro .elemen At t ;)( )i } } e h T c ta ch B ol c sk o
Y u sa soc ai et xe cept oi n hand s iler w th a t yr block by providing o en or m eo ca cr t h o
l
b cks direc ytl fa et r t eh t yr ob ck. ol N c eo can ed b eb t ew n the end fe o the t yr ob ck and l the beginning fo the rif st c ta ch ob c .l k
t yr {
} cat hc (ExceptionType na )m { e } cat hc (ExceptionType na )m { e }
a
E ch catch ob ck is nl a e cx epiton hand rl de a han en d s the type fl o ce e tx p oi n in id ca et d y b its ga u er m nt l a n i f ly ob ck l
The runt eim sy ts me always ee cu sx t t ee h statements iw ht in the ifn ya b oll l ck gr a ee rdl s s f
o wh ta happens tiw h ni the t yr ob c .l k oS ti's the p ee ct p arf l ce to perform cleanup. The following fin ya oll b ck f rl o ht e w te iri L st m h det o c nlea s up and then c ol s the es P ir tnW t rri e .
ifn ya { ll
} else { y S es m.ou .tp nt r tln "i ( P ir tnWrtier n to open ;)" } } 5. T eh Applet aC ss l t e l p p A aB sics
• An pa p el t si a spec li ia k nd fo Java p or gram that a brows re enabled iw th Java t he n oc o gy c nl a wdo n dloa mfro the in rt n te e and run.
• An pa p el t is typic ya ll embedded i sn ei a w bd e -p ea and runs in the c ng o t xe t fo the r
b owser.
• An pa pl te um ts eb a subc sl s fa o ht e java. pa p tl . pe A p el t c al ss, w ch phi rovide the s standard int ae ce rf between the pa plet and et h brows re en ov nir m t . en
• mS p ei l ex ma p el : pu ilb c c al ss HelloWorld e n sxte d java. pa p .tl Applet { e pu cb il void p ia tn j(ava.awt.G pr h sa i )c g { g.drawSt ir ng("Hello World"!, 05 , ;)2 y5 S st me .ou .tp nr tlni ("Hello World! ;)" } }
An pa p el t can eb ni clu dd in an HTML p ge a e, much in the same aw y an image is inclu dd ne i a pa ge.
When Java ct hne ology enabled rB ows re is used to iv ew a p ea that co tg n ia ns an pa p tl , e the pa pl te 's c eo is t ad r nsferred ot your sy es m and ex ct e u dt ye b ht e brows 'rs ve J a a
r i V ut la M hine Vac J( M) o w T Types of Applets
1 . oL c la a pp el t - ope e in sin lrat g e am chine brows re whi hc is not c no n ce t de in network, 2.Remote pa p tl - re oe m te pa p tl op ae e te vr o er in et rnet av net oi w rk. t e l p p A rA c eh c eti tur v E ent d en : riv n A pa p tl e watis u tn li na event occu .r s T I B J S , E S I f o . t p e D Page 20
www.vtucs.com
E E 2 J d n a a v a J 10IS753
The AWT not ei s the app eif l t oab u an t event yb c ila ng e el v tn handler ht at has been provided yb the pa pl et .
The pa pl te t ea s pk a p or p ar te a ti c oi n and then quic yk el r turn cont lr to AWT llo A wS ing
c mo ponen st sd cend me fro the A TW Cont na er c ai l ss
U es r init ai tes i tn ae tr c oi n iw th an App el t (and not et o rh t way a ohe r und) nA Applet t e l e k S o n m i p ro t java.a . ;* wt m i p ro t javax.s iw ng. ;* /* < pa p tl c de o =e "Apple kt e "l dS wi th=3 h h00 eig t=100> < p/ p >a let / * pu cb c ail l ss pA p el tS exten skel d pJA p tl { /e / Called rif s .t pu cb il void init )( { // initiailzat ni o }
/* C lla ed secon ,d fa t re init .)( lA so c lla ed whe en v the per a p tl se i er s rt ea t .d */ pu cb il void ts ra t )( { // st ta rr o er su em ee cut nx i o } // Called wh ne the pa p tl se i st po p .e pu cd b il void ts po )( { // ss pen su d execut ni o } /* C lla ed wh ne a pp l set i terminat .e Th sd i si the tl as e m th do execut .e /d * pu cb il void ed tsroy)( { // ep rform sh tu down a tc iviites }
www.vtucs.com
// Called wh ne na pa p el t s' iw n wdo mu ts eb restored. pu cb il void p ia tn (G ar ph si )c g { // redisp yl co ta n en st fo iw n od w } } 5.1 Simple AppletDisplay Methods d i o v d wra s itr ng(St ir ng em ss a , nge i t x, int )y - vo di tse B ca kground(Color n we Color) d i o v tse Foreg o nr u d(Color en wColor) Example : pu ilb c c sl s a S pim leApp el t e tx ends pA p el t { pu ilb c void p ia nt (G pr h ca i s )g { g.drawSt ir ng( F" ir ts pA pl te ," ,5 00 5 ;) } } e u q e R s git n Repainting e
r p na t( ) fu ci n t oi n is called when oy u h ea c av h n dg se omething and aw nt oy ur hc an eg s to sh wo pu no the cs reen e r p na t( ) si i a er q su t --it e might n to h pa p ne Wh ne oy u c lla er p ia nt( ,) Java cs h de u sl a c lle a to up ad et (G pr hics )a g e r e H s' wh ta up ad te does: pu cb il void update(G pr h sa i )c g { // llF s pi a p tl ie w th ab c gk ro nu d co , th nlor e p ia nt ;)( g Us gi T en h Status Window y S ntax : pu cb il void showSta ut s S( t ir ng ts atus) a P rameter : s t satus - a ts ir ng to display ni the tsatus iw ndow. Reques st th ta ht e argument ts ir ng eb sd pi layed ni the s" tatus iw ndow".
Many brows re s and pa p el t viewers provide s cu h a iw n wdo , wh ee the pr a p ilcat oi n can in mfor eu ss r fo its cu er nt tr s at .e e l p m a x E : T I B J S , E S I f o . t p e D Page 22
www.vtucs.com
E E 2 J d n a a v a J 10IS753
m i p ro t java. pa p .tl ;* me i p ro t java.a . ;* wt pu cb c ail l ss eN tExamplee n sxte d pA p tl e { p ariv te pA p el t oC tn ext rb ows re = nu ;ll
p ariv te Butt no showStat su = n we uB tton("Show Status ;)" pu cb il void init )( { Pan le pa en l = n we Panel)(; pan le .setLayout(n we GridLayout 1( , ;)2 ) pan le .add(showStat su ;) t e s Layou ( et n w BorderLayout ))( ; add("South ," pa en ;)l w o r b s re = eg t pA pl te oC tn e tx ;)( } pu cb il boolean a tc oi n(Event ,e Object )o { fi (et.arget == hs owStatus) w o r
b s re .showSta stu ("Here si something rf oo y ur tsatus ilne ... ;)" er ut nr tru ;e }
}
6. T eh HT LM Applet Tag
• The A PP EL T t ga is us de to ts ra t an pa p tl e from b to h an H MT L od cument and r
f om na pa p tl e viewe .r
• An app el t viewer wi ll execu et e h AP Eac P T t gL a ht at ti ifn sd in a separate i
w n wdo ,wh eli w reb b ows re s il ke N cets a pe Navigator, In rt n te e xE plorer, a nd o
H tJava w illallow am ny pa p sl net o a sin eg pl age .
• The s ny tax rf the ao s nt dard A PP EL T t ga is sh wo n h ee . ar B c er k et d it me s ea r o tp oi nal .
< PA P TL E C
[ ODE A EB S = co bd ae seURL]
C DO E = appeltFiel [A TL = a etl nr a et Tex]t E M A N [ = appelItnstanc Ne a ] me
WIDTH = pixesl HEIGHT = pix les [AL GI N = ailgnme ]tn S V [ PA = eCE p l ]ix s S[H PAC = E pixesl] > [< AP RAM AN ME = A b Ntt ir ute a me VALUE = A b ett ir u Va et l >] <u [ AP R M N MA A E = tt A bir tu eNam e2 VALUE = ttA irb eu Va et l >] . . . u [HTML iD ps al dy in ee t bh a sence of Java] < A/ P EPL T>
• CODEBA is an op oSE it n la a tt bri u e th tt a spec ei s the aif b se URL fo ht e pa p el t c do e, wh ci h is the direc rto y that w be s rill e ch da e rf eo t ph a pl te ’s executa c sble l s ea f li (speci ifed yb the CO ED t )a . The H Mg T L od cu em nt’s U rRL d ect yi o is us dr e as the C DO E A EB S fi this a tt br u ei t is not sp ce iifed. The C DO EBASEdoes not h ea to be nv o
h
t e host mfro which et H Mh T L cd uo ment w asread .
• CODE is a qr u de ire a tt br ute that vi g es the ni ame fo t eh ef con ili t ning oa y ur p
a p el t’s c mo p dli .c se l s lia f e. This lif e is ar t eel i ov t the c eo ad b se U of the pRL a p ,tl e wh ci h is t eh direc ory that the Tt H ML ef ali w s in or et h direc ory in it d ca et d by C DO E A EB S fi s .e t
• LA T is an opt oi n la attribu et u es d to spec yfi a sh ro t te tx em ss a hge t at shou dl eb i
d ps layed fi et h brows re under ts ands the PA P EL T gt but can t’ cu ea r nt yr l r nu Java p
a p tl s. Th se i si sd t ni i tc from t eh la et rnate H MT L oy u provide rf br wo o s re s th ta o
d n t’ ps p ru o t pa plets.
• WIDTH A DN EH GI HT ra e qr u de ire a tt ir b tu es that g eive t s zh i e i(n pix le s) fo the p
a p tl ie d sp yl a area .
• A I NL G is an op itonal a tt bri u e th tt a spec ifi se the a n eilg m nt fo the app tl . Th se i a tt br ute si i t ar t de e the same sa the H MT L GIM t ga w these p stih o s ei lbl v u :a e s
• L T, RIG TEF H , TOP, BOTT MO , MI DD L , E BASELI EN , TEXTT PO , A SB M DI D ,L E and A BB OTTS OM .
C A P S
V E A DN HS AP C T eE h es attributes are optional. VSPACE spec fiies ht e space, in pixels, a ob ve and b le ow the applet. HSPACE ps ecifi se the space, in
T I B J S , E S I f o . t p e D Page 24
www.vtucs.com
E E 2 J d n a a v a J 10IS753
pixels, on ae ch side of the applet. They’re treated ht e same as the MI G ta ’g s P
S
V ACE and HSPACE attributes. M
A R A
P NAMEANDVALU The P RE A AM tag a llows you to specify a lp e sp t p ce ific arguments in an HT LM ap ge. Apple st acce ss ht eir attribu st e wi ht the ge Pt aramet re ( ) method.
a
P ss ing Pa ar m ters oe t pA plets
Parame et rs are pass de to app el ts in NAME= AV L E pa sU i in Pr < A AR M tags betwe n> e the opening and lc osing A PP EL T tags.
• Inside the applet, y uo read the v la ues pa ss ed through the PARAM tags iw th the getPara em ter() method fo ht e java.a pp el t.Applet c al ss .
The a pp l te ap rameter "Me ss age" is the rs ing to be drawn. t import java.ap lp et. *; import
java a. wt. ;*
public class Dr wa StringA lppe extends App et l t { private String de af ul Mt essage = "Hello "! ; public
o
v id ap int(G ar hp i sc g) {
String in up tFromPage = this .getParameter "( Mes sage )" ;
if i( pn utFrom aP ge == un ll) in up t rF mo Page = de af ult eM ssage; g. rd awString(in up Ft romPage, 05 , 25);
} }
HTML fi el that referen sc the a ve b e a po p el t. <HT LM > <HEAD>
T I T
< LE> Draw String /< T TI LE> < H/ EAD >
<BODY>
This is ht e a pp l te : P< >
P A
< PLET cod =e "DrawStri Ang pp el t" w di th="3 00" height=" 05 "> A
P
< R MA name="M se sage" lv ue=a "Howdy, th ee !"> hr T is p ea ig w ll eb ev ry boring if o y ru w o r b s re ed sn t' under to s and Java. < A/ P EPL T> < O/B D >Y /< HTM >L t e
g DocumentBas )(e da n getCodeBas (e ) y S ntax : pu cb il U RLgetDocumentBas (e ) u t e R rns:
the URL fo the cd u eo m nt th ta cont ia ns ht si pa pl et .
• G se the URL ft o the od cu em nt ni wh hi th sc i pa p tl se i embedde .d
• For ex ma p ,l ue s pp eo ns a pa plet si c no t ia n de iw ht ni the od uc m n :t e
htt :p // java.su .n com/p dro u t /c s jdk/1.2/in ed x h. t lm • The od uc m nt e base :i s htt :p // java.su .n com/p dro u t /c s jdk/1.2/in ed x h. t lm y S tn ax : pub cil RU L getCodeBas (e ) n r u t e R s: h t e ab se U LR fo the rdi ecto wh hry i co tc na th sins i app .tl e
• G se the at b se UR .L Th si si the URL fo the direc yto wh hr i co tc n ia ns th si pa p .tl e
• Ex ma p el segmen :t s L R U codeBase = eg Ct odeBas ;)e ( Image ym Ima eg = g Ite mage(c eod B eas , i"mages/myimage. fig "); Applet Context a dn showDocument)( p
A p el t oC nte tx is na i tn e ce that p vrfa r i eo d s the means to co tn lr ho t e rb owser en ov nment nir i which the pa p tl se i nr nin .u g
e h
T AudioCilp Interface
• The AudioC pil ni et ar ce sf i a s mi p el ba ts ar tc oi n rf po l ng a s uayi o nd c .il p
• Multip el Au id Co ilp it me s can eb playing ta the same t eim , da the en r sulting s uo nd si im x de together to p dro u e a c mc o posit .e T I B J S , E S I f o . t p e D Page 26
www.vtucs.com
E E 2 J d n a a v a J 10IS753
• tI h sa the following m het o : ds y a l p pu cb bil a tsr act void play() • loop • s pt o pu cb bil a tsr act void os p )( t Stops playing th si au od ci il p . e h T AppletStub Interface
The App el tS ut b ni t ae ce prf rovides a way ot get informat oi n from et r nh u -t eim rb owser en ov nment . ir
The App el t c al ss provides em th do s iw ht simliar names that c these meth dall o s . M te h so d
u
p blic ab rs a tt c bo elo an siActive ()
The isActive )( em th do er ut nr s ht e cu er nt tr s a et fo the pa p .tl Wh ee li an pa p tl se i initiailzing, it is n to ca t vi e, and c lla s to isAc vit e )( r te urn lf se. The sy ta s me marks the
p a p tl ac ee it uv j st p rr to c ilio a ng tl s ra t ;)( fa t re th si poin,t c sa to isAcll itve )( er tu nr tru .e • p b cu il ab rs a tt c U DRL get ocumentBa es )( The eg Dt co um t aenB s )(e em th do er ut r sn the c mo pl te e RU L fo t eh H MT L f eli th ta d e d a o
l the pa plet. T s hi m h det o can eb us de iw ht the eg tImage() ro tge AudioCilp )( e
m th so to d load na image ro au od ei f ali r t eel i to the Tv H ML f lie.
• up b cil ab rs a tt c U CRL get o Bd a ee s )(
The tg C de o e aB es )( meth do r ue nt r s t eh complete URL fo the .cla ss ef that cont ili a sn the p
a p tl . This ee m th do ac n eb us de iw ht the eg Itm e )( m hag et o or the td ge AudioCilp )( e
m th do to load na image ro au od ei f reli la itve to the . lc a ss ef . li
• up b cil ab rs a tt c tS ir gn Pg ar met a e ter (St irng n ma )e
The eg Pt aramet )(e er m thod allows oy u to eg t paramet re s from P< ARAM> t ga s tiw h ni the <A PP EL T> t ga fo the H MT L ef that li loaded ht e pa p tl . The ne ame paramet r of e g Pet aramet )(e m sr u t am ht the nc ame s it ng of the Pr < A AR M t g> a ; n ma e is case ins ne sit vi e. T eh tr u ne r lv ue fa o eg Pt arameter )( is et lh v ue sa a sociated iw th n ma e; it si
y a w l a s a St ir ng re ag r ed ss fl o ht e ty ep fo ad ta in the t ga . If name is not uf nd tio w h ni the P< A AR M > tags fo ht e A< PP EL T ,> eg Pt aramet )(e er r ut r nu .ns ll • up b cil ab rs a tt c AppeltContext getAppl te oC ntext () St ra st playing ht is audio c il .p E h ac itme this m h det o si called, the c pil si er ts ra t de mfro the beginnin .g
pu cb bil a tsr act void ol p )( o
The eg At pp el t oC n et x )(t em th do er ut r sn the current A pp el t oC nt xe t fo the pa p tl . Th se i s
i p ta fr o the s ut b th ta si s te yb the sy es m t when set tS u )(b si called.
• up b cil ab rs a tt c v io d appeltRe isze (i tn wi ,d i tth n h ie )tg h
The pa pl te eR size )( m het o sd i called yb ht e r se ei z m h det o fo the App el t c slas . The e
m th do chang se the zs e fi o the a pp el t sp ea to c w h x hidt eight. The brows r must e s pu p ro t chan ig ng the pa p tl spac ;e e fi ti doesn't, the s ei z remains u cn han dg e
t u p t u O To et nh C s eo o l
The drawString em th do c na eb su de to to put tu s ir n sg to the c no s .o The posit nle i fo o the t te c nx a la so eb speci ifed . The llf o io w ng p gr o shows th si c no cep :t pu cb c ail l ss Cons eo P il r tn pA p el t1 e tx en sd java. pa p tl . pe A p tl e { pu cb il void in ti )( { // Put c eo ed b t ew en th si ilne o d u eb x = 5. ;l 0 od u eb y = 3. ;l 0 y S es m.ou .tp nt r tln( xi " * y = +" (x )* ;) y y S es m.ou .tp nt r tln( xi " / y = +" ( /x )y ;) / / / and th s/ i iln .e } // P ia nt em ss ea ng i ht e pa plet iw n wdo . Pu cb il T I B J S , E S I f o . t p e D Page 28