Java Book

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Book as PDF for free.

More details

  • Words: 40,791
  • Pages: 329
Java Programming 1

Version July 2000 Second Impression

The Team Production / Series Supervision Jambu Krishnamurthy Vice President – Product Development The Head Sridhar Subramaniam Head – Training Solutions Technical Writers Thiru Murugan .H Uma .S Ajay Balaji Review Jambu Krishnamurthy Sridhar Subramaniam Production/Design Vijay. V Editor Nurjehan Dhanani

Copyright  1999, Comp-U-Learn Inc. All Rights Reserved

No Part of this Book may be reproduced in any form by any means, stored in a retrieval system, or transmitted by any mode, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. Exceptions are made to the program listings, which can be typed, stored in a Computer System and executed. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein.

All Trade Marks Acknowledged

The Book at a Glance , %HIRUH:H%HJLQ L ,, +RZWRXVHWKLV%RRN  LL ,,, 2EMHFWLYHVRIWKLV%RRN  LLL ,9 &RQYHQWLRQVXVHGLQWKLV%RRN LLL  -DYD²$Q,QWURGXFWLRQ  )XQGDPHQWDOVRI-DYD   223VLQ-DYD   ,QWHUIDFHV 3DFNDJHV  6WUHDPV )LOHV+DQGOLQJ   ([FHSWLRQ+DQGOLQJDQG0XOWLWKUHDGLQJ  -DYD$SSOHWV  $EVWUDFW:LQGRZLQJ7RRONLW  +DQGOLQJ$:7(YHQWV  0RUHDERXW$:7   -DYD'DWD%DVH&RQQHFWLYLW\  1HWZRUNLQJLQ-DYD ,*ORVVDU\   ,,$SSHQGL[HV  ,,,,QGH[ 

Table of Contents ,%HIRUH:H%HJLQ L ,,+RZWRXVHWKLV%RRN  LL ,,,2EMHFWLYHVRIWKLV%RRN  LLL ,9&RQYHQWLRQVXVHGLQWKLV%RRN LLL -DYD²$Q,QWURGXFWLRQ            

,QWURGXFWLRQWR-DYD   +LVWRU\RI-DYD  )HDWXUHVLQ-DYD   -DYDDQGWKH,QWHUQHW   -DYD$Q223/DQJXDJH  &YV-DYD  -DYD7RROV  $SSOLFDWLRQ3URJUDPPLQJ   &UHDWLQJDQ$SSOLFDWLRQ   $SSOHW3URJUDPPLQJ &UHDWLQJDQ$SSOHW 2YHUYLHZRI-DYD

)XQGDPHQWDOVRI-DYD²      

'DWDW\SHV 9DULDEOHVLQ-DYD  /LWHUDOV.H\ZRUGV ,GHQWLILHUV  2SHUDWRUVLQ-DYD  ([SUHVVLRQ(YDOXDWLRQ 2SHUDWRU3UHFHGHQFH  6FRSHRI9DULDEOHV  &RPPHQWLQJLQ-DYD

7DEOHRI&RQWHQWV &RQWG      

'HFLVLRQ0DNLQJ  )RUORRS :KLOH 'R«:KLOH/RRS  6ZLWFK %UHDN6WDWHPHQWV $UUD\VLQ-DYD 6WULQJVLQ-DYD 

2236LQ-DYD²            

7UDGLWLRQDO3URJUDPPLQJ0RGHO 2EMHFW2ULHQWHG3URJUDPPLQJ$SSURDFK  )HDWXUHVRI2EMHFW2ULHQWHG3URJUDPPLQJ  %DVLF&RQFHSWVRI223V &UHDWLQJ&ODVVHVDQG2EMHFWVLQ-DYD &RQVWUXFWRUV  *DUEDJH&ROOHFWLRQ )LQDOL]H0HWKRG  ,QKHULWDQFH  3RO\PRUSKLVP  5HFXUVLRQ $GYDQWDJHVRI223VLQ-DYD 

,QWHUIDFHV 3DFNDJHV     

,QWURGXFWLRQWR,QWHUIDFHV  :KDWLVDQLQWHUIDFH"  ,QWULFDFLHVLQDQ,QWHUIDFH  ,QWHUIDFH5HIHUHQFHV ([WHQGLQJWKH,QWHUIDFH 

7DEOHRI&RQWHQWV &RQWG       

7KH&ORQHDEOH,QWHUIDFH  ,QQHU&ODVVHV 3DFNDJHV  1HHGIRU3DFNDJHV  &/$663$7+9DULDEOH  $FFHVV3URWHFWLRQ  2YHUYLHZRI-DYD%XLOWLQ3DFNDJHV

6WUHDPV )LOH+DQGOLQJ²            

-DYD6WUHDP&ODVV  3ULQW6WUHDP  6\VWHP3URSHUWLHV ,QSXWDQG2XWSXW6WUHDPV  )LOHVDQG'LUHFWRULHV )LOH,QSXWDQG2XWSXW6WUHDPV 'DWD,QSXWDQG2XWSXW6WUHDPV )LOWHUHG6WUHDPV %XIIHUHG6WUHDPV 3XVKEDFN,QSXW6WUHDP 5DQGRP$FFHVV)LOH  5HDGHUDQG:ULWHU&ODVVHV

([FHSWLRQ+DQGOLQJDQG0XOWLWKUHDGLQJ    

([FHSWLRQ+DQGOLQJ²$Q,QVLJKW $GYDQWDJHVRI([FHSWLRQ+DQGOLQJ 8QFDXJKW([FHSWLRQV 0XOWLSOH&DWFK&ODXVHV

7DEOHRI&RQWHQWV &RQWG        

,PSOLFLWDQG([SOLFLW([FHSWLRQV -DYDODQJ7KURZDEOH  )LQDOO\&ODXVH &UHDWLQJ2ZQ([FHSWLRQ6XEFODVVHV 0XOWL7KUHDGLQJ 7KUHDG6WDWHV  7KUHDG3ULRULW\  'DHPRQ7KUHDGV 

-DYD$SSOHWV            

,QWURGXFWLRQWR$SSOHW $SSOHWYV$SSOLFDWLRQ  $SSOHW$UFKLWHFWXUH  'HYHORSLQJDQ$SSOHW  $SSOHWLQ+70/ %DVLF0HWKRGVLQ$SSOHW  3DUDPHWHUSDVVLQJWR$SSOHWV  *UDSKLFVFODVV )RQW&ODVV &RORU&ODVV ,PDJHV $QLPDWLRQXVLQJ,PDJHV 

$EVWUDFW:LQGRZLQJ7RRONLW $:7   $Q$:72YHUYLHZ   $:7$UFKLWHFWXUH   %DVLF8,&RPSRQHQWV

7DEOHRI&RQWHQWV &RQWG         

%XWWRQV  &KHFN%R[HV  5DGLR%XWWRQV &KRLFHV  7H[W)LHOGV 7H[W$UHDV  /LVWV  6FUROOEDUVDQG6OLGHUV  &DQYDVHV 

+DQGOLQJ$:7(YHQWV            

,QWURGXFWLRQWR(YHQWV  $SSOHW(YHQWV %XWWRQ(YHQWV  +DQGOLQJ0XOWLSOH(YHQWV  ,WHP(YHQWV  0RXVH(YHQW+DQGOLQJ 'RXEOHFOLFNV 0RXVH0RYHPHQWV  0RXVH'UDJDQG0RXVH0RYH(YHQWV 0RXVH(QWHUDQG0RXVH([LW(YHQWV  .H\ERDUG(YHQWV  'HIDXOW.H\V 

0RUH$ERXW$:7  /D\RXW0DQDJHUV  )ORZ/D\RXW

7DEOHRI&RQWHQWV &RQWG  %RUGHU/D\RXW  &DUG/D\RXW   *ULG/D\RXWV  *ULG%DJ/D\RXW  ,QVHWV  3DQHOV   )UDPHV   0HQXV  0HQX$FWLRQV   'LDORJ%R[   -DYD'DWD%DVH&RQQHFWLYLW\  ,QWURGXFWLRQWR-'%&  0LFURVRIW V2'%&   7LHULQJ  -'%&$UFKLWHFWXUH   -'%&'ULYHUV   'ULYHU3URSHUW\,QIR&ODVV   &RQQHFWLRQ&ODVV   'DWDEDVH0HWD'DWD,QWHUIDFH   3UHSDUHG6WDWHPHQW  &DOODEOH6WDWHPHQW  ([HFXWLQJ64/XVLQJ-'%&  7UDQVDFWLRQ3URFHVVLQJ 

7DEOHRI&RQWHQWV &RQWG 1HWZRUNLQJLQ-DYD  1HWZRUNLQJLQ-DYD   'DWDJUDPV   :KDWLVD'DWDJUDP"  'DWDJUDP3DFNHW   'DWDJUDP6RFNHW   'XSOLFDWLRQRI6RFNHW   &UHDWLQJ/LQNV,QVLGH$SSOHWV   2SHQLQJ:HE&RQQHFWLRQV  7KH85/&RQQHFWLRQ&ODVV   6RFNHWV   2WKHU$SSOHW+LQWV  &RPPXQLFDWLQJ%HWZHHQ$SSOHWV , *ORVVDU\   ,,$SSHQGL[HV  L$SSHQGL[   LL$SSHQGL[ LLL$SSHQGL[ ,,,,QGH[ 

Before We Begin 6RPHERG\ VDLG WKDW RQH·V JRDO LV WR HYROYH DQG ILQG JUHDWHU KHLJKWV
i

How to use this Book 7KLV ERRN LV ZULWWHQ LQ D OXFLG VW\OH LQ DQ DWWHPSW WR SURYLGH FODULW\ RQ FRPSOH[WHFKQLFDOWRSLFV6LQFHWKHUHDGHUVDUHQHZWRWKHVXEMHFWWKHXQGHU PHQWLRQHGGHWDLOVZLOOPDNHWKHPXVHWKHERRNLQWKHPRVWHIILFLHQWPDQQHU $OVR LW ZLOO HQDEOH WKH UHDGHUV WR NQRZ DERXW WKH RUJDQL]DWLRQ DQG WKH SDWWHUQDGRSWHGLQWKLVERRN 7KH%RRNDWD*ODQFHJLYHV\RXDQRYHUYLHZRIWKHYDULRXVWRSLFVFRYHUHGLQ WKH %RRN 7KHVH DUH WKH VHVVLRQV ZKLFK ZLOO EH FRYHUHG LQ $GYDQFHG 7HFKQRORJLHV HPHUJLQJ DW WKH -DYD IURQW ,W DOVR SURMHFWV DQ RXWORRN RI WKH PRGXOHFRYHUDJHDQGLWVFRQWHQWVZKLFKZLOOVSDQIRUVHVVLRQV 7KH7DEOHRI&RQWHQWVHQDEOHV\RXWRNQRZDERXWWKHYDULRXVWRSLFVXQGHU HDFK 6HVVLRQ 7KH WRSLFV JLYHQ XQGHU 6HVVLRQ WLWOH UHIOHFW WKH  3RLQW SURJUDP7KHVXEMHFWLPSDUWHGLQWKHFODVVURRPVHVVLRQZLOOEHDFFRUGLQJWR WKHVH JLYHQ KHDGLQJV ,W EDVLFDOO\ KHOSV WR SUHSDUH IRU HYHU\ FODVV URRP VHVVLRQE\OHWWLQJ\RXNQRZDERXWWKHVHVVLRQFRYHUDJH$JDLQWKHVHSRLQWV ZLOODOVREHFRYHUHGLQWKHEHJLQQLQJRIHYHU\VHVVLRQXQGHUWKHWLWOH´,QWKLV 6HVVLRQµ (DFK VHVVLRQ EHJLQV ZLWK DQ REMHFWLYH 7KHVH REMHFWLYHV DUH OLVWHG RQ WKH VHVVLRQFRYHUSDJH7KLVZLOOIDFLOLWDWH\RXWR NQRZ WKH \DUGVWLFNV E\ ZKLFK \RXFDQHYDOXDWH\RXUNQRZOHGJHDFTXDLQWDQFHLQHDFKVHVVLRQ)ROORZLQJWKH FRXUVHZDUH GXULQJ FODVVURRP VHVVLRQ ZLOO HQDEOH \RX WR KDYH D EHWWHU XQGHUVWDQGLQJ RI WKH VXEMHFW ([DPSOHV DUH FLWHG WR JLYH PRUH FODULW\ DQG KHOS\RXWRKDYHDQLGHDDERXWWKHLPSOHPHQWDWLRQRIWKHFRQFHSWGHILQHG,W LVVXJJHVWHGWKDW\RXWU\WRZRUNWKHH[DPSOHVJLYHQLQ\RXUODEVHVVLRQVE\ \RXUVHOILQRUGHUWRKDYHDFOHDUXQGHUVWDQGLQJRIWKHFRQFHSW$WWKHHQGRI HYHU\VHVVLRQVHOISUDFWLFHH[HUFLVHVDUHSURYLGHG
Objectives of this Book 7KLVERRNLVLQWHQGHGWRJLYHSUHOLPLQDU\DQGLQWHUPHGLDWHH[SRVXUHRQ-DYD /DQJXDJH $W WKH HQG RI WKLV PRGXOH \RX VKRXOG EH DEOH WR ZULWH D -DYD $SSOLFDWLRQ RU -DYD $SSOHWV FRPIRUWDEO\ FRPSLOH LW DQG H[HFXWH LW
Conventions Used in this Book ♦ Each session is divided into 12 topics. It is called the Twelve Point Program (12pp). In every session, these points are distinctly shown in an underlined bigger font. ♦ Subheadings appear in bold without underlining. ♦ Note is shown inside a box. It is information which is necessary to understand the subject discussed but does not come as a part of the text flow. ♦ Summary is at the end of each session, shown in a special table, italicized. ♦ Each session ends with a ‘Going Over It Again’. This helps the student in recapitulating the session contents. ♦ Figure numbers and descriptions are given below each picture, diagram or screen for proper navigation.

iii

Session 1

Java-An Introduction

On Completion of this Session We will be able to understand...

) ) )

Basic concepts in Java

) ) )

About Java Application

Java as an OOP language Tools in Java About Java Applet Features of Java

In This Session...



Introduction to Java



History of Java



Features in Java



Java and Internet



Java-An OOP Language



C++ vs Java



Java Tools



Application Programming



Creating an Application



Applet Programming



Creating an Applet



Overview of Java

JAVA-An Introduction

Introduction to Java -DYD LV DQ REMHFW RULHQWHG PXOWLWKUHDGHG SURJUDPPLQJ ODQJXDJH GHYHORSHG E\ 6XQ 0LFURV\VWHPV-DYDLVQRWRQO\DQREMHFWRULHQWHGSURJUDPPLQJODQJXDJHEXWDOVRDFRQFXUUHQW SURJUDPPLQJODQJXDJH:HFDQFUHDWHFODVVHVREMHFWVDQGXVHLQKHULWDQFHWKDWUHIOHFWWKHW\SLFDO REMHFWRULHQWHG IHDWXUHV :H FDQ DOVR FUHDWH DQG PDQLSXODWH WKUHDGV 7KHVH SRZHUV WRJHWKHU PDNH -DYD TXLWH SRZHUIXO 0DQ\ RI -DYD·V FKDUDFWHULVWLFV FRPHV IURP RWKHU ODQJXDJHV ,W KDV ERUURZHGFRQVWUXFWVIURPPDQ\RIWRGD\·VPRGHUQREMHFWRULHQWHGODQJXDJHV,QDGGLWLRQ-DYD LVDSODWIRUPLQGHSHQGHQWRUPDFKLQHLQGHSHQGHQWODQJXDJH)URPWKHSURFHHGLQJSDUDJUDSKV ZHFDQHDVLO\XQGHUVWDQGZK\-DYDLVSODWIRUPLQGHSHQGHQW $WUDGLWLRQDOODQJXDJHDOORZVXVWRZULWHSURJUDPVWKDWQHHGVWREHFRPSLOHGXVLQJDFRPSLOHU $FRPSLOHUFRPSLOHVRXUSURJUDPLQWRVRPHWKLQJFDOOHGWKHPDFKLQHODQJXDJHZKLFKYDULHVIRU GLIIHUHQWPDFKLQHVGHSHQGLQJXSRQWKHLULQWHUQDOFRQILJXUDWLRQ$IWHUFRPSLODWLRQZHKDYHWR H[HFXWH WKLV FRPSLOHG SURJUDP RQ RXU PDFKLQH 6LQFH GLIIHUHQW FRPSXWHUV KDYH GLIIHUHQW PDFKLQH ODQJXDJHV D SURJUDP FRPSLOHG IRU RQH PDFKLQH FDQQRW EH H[HFXWHG RQ DQRWKHU PDFKLQH)RUSXWWLQJDSURJUDPRQDZHESDJHWKHEURZVHUVKRXOGFRPSLOHWKHSURJUDPHDFK WLPH DQG WKHQ UXQ 0RUHRYHU WKH ULVN LQYROYHG LV RI YLUXVHV JHWWLQJ WUDQVIHUUHG IURP VXFK D SURJUDPGXULQJWKHFRPSLODWLRQSURFHVV ,Q-DYDWKHVLWXDWLRQLVFRPSOHWHO\GLIIHUHQW7KHFRPSLOHUKDVDVSHFLDOW\LQWKDWLWJHQHUDWHVWKH VDPH PDFKLQH FRGH IRU HDFK DQG HYHU\ PDFKLQH W\SH LQ WKH ZRUOG WR EH SUHFLVH 7KH -DYD FRPSLOHU DVVXPHV D WKHRUHWLFDOO\ GHILQHG PDFKLQH FDOOHG -DYD 9LUWXDO 0DFKLQH DQG FRPSLOHV FRGHIRULW6XFKFRPSLOHGFRGHLVNQRZQDVE\WHFRGH7KLVE\WHFRGHLVPDFKLQHLQGHSHQGHQW VRWKDWZHFDQUXQWKLVH[HFXWDEOHFRGHLQDQ\W\SHRIPDFKLQHDFURVVWKH,QWHUQHW7KLVUHVXOWV LQ-DYDEHLQJUHIHUUHGWRDVD0DFKLQHLQGHSHQGHQWRUSODWIRUPLQGHSHQGHQWODQJXDJH

History of Java 7KH -DYD ODQJXDJH ZDV GHYHORSHG E\ 6XQ 0LFURV\VWHPV LQ  6XQ EHJDQ D SURMHFW IRU VRIWZDUHWRUXQ79 9&5VHWVLQWHUDFWLYH79DQG9&5,QDJURXSRI6XQHQJLQHHUV OHG E\ 3DWULFN 1DXJKWRQ DQG 6XQ IHOORZ -DPHV *RVOLQJ ZDQWHG WR GHVLJQ D VPDOO ODQJXDJH ZKLFKFRXOGEHXVHGIRULQWHUDFWLYHFRQVXPHUGHYLFHV,Q6HSWHPEHUWKHEDVLFV\VWHPZDV GUDIWHG7KHLQWHUDFWLYHFRQVXPHUGHYLFHZDVFDOOHG6WDU6HYHQDQGZDVSDUWRIDODUJHUSURMHFW FDOOHG*UHHQ3URMHFW-DYD·VRULJLQDOQDPHZDV2DNQDPHGDIWHUWKHWUHHRXWVLGH-DPHV*RVOLQJ RIILFH+RZHYHUVLQFHWKHUHZDVDOUHDG\DODQJXDJHQDPHG2DNH[LVWLQJ6XQQDPHGLW-DYD-DYD LVQRWDQDFURQ\P,WLVDWUDGHPDUNRI6XQ0LFURV\VWHPV 7KH*UHHQ3URMHFWVSHQWDOORIDQGKDOIRIORRNLQJIRUSHRSOHWREX\LWVWHFKQRORJ\ 1HYHUWKHOHVVQRERG\ZDVUHDG\WREX\LW$WWKLVWLPHWKH:RUOG:LGH:HE ::: DSDUWRI WKH ,QWHUQHW ZDV JURZLQJ ELJJHU 7KH NH\ WR WKH :HE LV WKH EURZVHU WKDW WUDQVODWHV K\SHUWH[W

Comp-U-Learn

3

Java Programming I

SDJHWRVFUHHQ7KHUHIRUH6XQUHOHDVHGWKHQHZ-DYDFDSDEOH+RW-DYDDEURZVHUZULWWHQLQ-DYD DV D YHKLFOH IRU GRZQORDGLQJ DQG UXQQLQJ WKH DSSOHWV )LQDOO\ WKH -DYD ODQJXDJH ZDV RIILFLDOO\ UHOHDVHGLQPLG 6XQ UHOHDVHG WKH ILUVW YHUVLRQ RI -DYD LQ HDUO\  ,W ZDV IROORZHG E\ -DYD  D FRXSOH RI PRQWKVODWHU+RZHYHULQWKLVYHUVLRQDOVR6XQPLVVHGVRPHWKLQJWRVDWLVI\WKH,7SHRSOH6RLQ 0D\6XQUHOHDVHG-DYDYHUVLRQZLWKDVHHPLQJO\HQGOHVVVWUHDPRILPSURYHPHQWVDQG QHZ OLEUDULHV ZKLFK EHFDPH D PRVW LPSRUWDQW DVSHFW LQ -DYD ,Q  6XQ 0LFURV\VWHPV UHOHDVHGWKHODWHVWYHUVLRQDV-DYDZKLFKUHSODFHVWKHHDUO\WR\OLNH*8,DQGJUDSKLFVWRRONLWV ZLWKVRSKLVWLFDWHGDQGVFDODEOHYHUVLRQVWKDWFRPHDORWFORVHUWRWKHSURPLVHRI´:ULWHRQFH 5XQDQ\ZKHUHµWKDQWKHLUSUHGHFHVVRUV

Features in Java 7KLVVHFWLRQEULHIO\GLVFXVVHVWKHW\SLFDOIHDWXUHVRI-DYDZKLFKKDVKHOSHGLWEHFRPHDUHOHJDWH LWWRWKHSRVLWLRQRIEHLQJDGLVWLQJXLVKHGSURJUDPPLQJODQJXDJHRIWRGD\·VWHFKQRORJ\ Java is an easy programming language

-DYD LV WKH RQH RI WKH HDVLHVW SURJUDPPLQJ ODQJXDJHV LQ WKH ZRUOG QRZ 1R SURJUDPPLQJ ODQJXDJHDVSRZHUIXODV-DYDLVDQ\HDVLHU6LQFH-DYDLVREMHFWRULHQWHGSURJUDPPLQJLQ-DYDLV YHU\VLPSOH,WKDVDOOWKHPRGHUQIHDWXUHVWKDWZHZDQWLQDSURJUDPPLQJODQJXDJH,WZLOOPDNH DVPRRWKUHSODFHPHQWRI&DQG&LQGXHFRXUVHRIWLPHEXWWKDWLVQRWWKHRQO\WKLQJ,Q DGGLWLRQZHFDQXVHWKH-DYDSUHGHILQHGOLEUDULHVDQGSDFNDJHVLQRXUSURJUDP$OVRLQ-DYD WKHUHDUHQRUHVWULFWLRQVUHODWHGWRV\QWD[DQGSURJUDPPLQJFRQVWUXFWVFRPSDUHGWRDQ\RWKHU SURJUDPPLQJODQJXDJHV Java is portable and architecturally neutral

:ULWHRQFHDQGUXQDQ\ZKHUHLVWKHVORJDQIRU-DYD$OUHDG\ZHKDYHVHHQWKHFRQFHSWRIE\WH FRGH%HFDXVHRIWKLVE\WHFRGH-DYDLVFDOOHGDSODWIRUPLQGHSHQGHQWSURJUDPPLQJODQJXDJH DUFKLWHFWXUDOO\ QHXWUDO D VLQJOH SURJUDP FDQ UXQ RQ DQ\ W\SH RI PDFKLQH 7KLV PDNHV WKH FRQFHSW RI SRUWLQJ IURP RQH SODWIRUP WR DQRWKHU UHGXQGDQW 7KH VDPH YHUVLRQ RI WKH DSSOLFDWLRQ UXQV RQ DOO SODWIRUPV 6XFK SODWIRUP LQGHSHQGHQW ODQJXDJH LV QRW RQO\ XVHIXO IRU QHWZRUNVEXWDOVRIRUVLQJOHV\VWHPVRIWZDUHGLVWULEXWLRQ Java is a Distributed language

,Q D GLVWULEXWHG V\VWHP REMHFWV FDQ EH RQ D ORFDO RU D UHPRWH V\VWHP -DYD DSSOHWV DQG DSSOLFDWLRQVFDQRSHQDQGDFFHVVREMHFWVDFURVVWKHQHWDVHDVLO\DVWKH\FDQDFFHVVDILOHIURPD ORFDOILOHV\VWHP7KHH[WHQVLYHOLEUDU\RIURXWLQHVEXLOWLQWRWKHODQJXDJHDOORZV-DYDDSSOLFDWLRQ DQGDSSOHWWRHDVLO\ZRUNZLWK7&3,3SURWRFROVOLNH+773DQG)737KHEHDXW\RI-DYDEHLQJ

4

Comp-U-Learn

JAVA-An Introduction

DGLVWULEXWHGV\VWHPLVWKDWPDQ\GHVLJQHUVDWGLIIHUHQWUHPRWHORFDWLRQVFDQFROODERUDWHRQD VLQJOHSURMHFWEHFDXVHWKHE\WHFRGHLVLQWHUSUHWHGLQZHESDJHVDORQJZLWK-DYDDSSOHWV7KRXJK WKLVPDNHVWKHZHESDJHVWDNHDORQJHUWLPHWRORDG Java provides security

-DYD SURJUDPV DUH UHODWLYHO\ VDIH EHFDXVH WKH\ GR QRW KDYH SHUPLVVLRQ WR DFFHVV DOO RI RXU FRPSXWHU·V PHPRU\ DQG GLVF VSDFH -DYD KDV D EXLOWLQ PHFKDQLVP WR VDIHJXDUG RXU PDFKLQH IURPYLUXVHV6R-DYDLVLQWHQGHGWREHXVHGLQQHWZRUNHGGLVWULEXWHGHQYLURQPHQWV Java is Robust

-DYD EDVHG DSSOLFDWLRQV RU DSSOHWV DUH ZHOO EHKDYHG DQG ZLOO QRW OHW D V\VWHP FUDVK 7KH\ DOVR EHKDYHXQLIRUPO\DFURVVGLIIHUHQWSODWIRUPV7KLVIHDWXUHLVDOVRYHU\XVHIXO7KH-DYDFRPSLOHU GHWHFWV PDQ\ SUREOHPV GXULQJ FRPSLODWLRQ WLPH LWVHOI ZKLFK LQ RWKHU ODQJXDJHV ZRXOG EH VKRZQXSRQO\DWUXQWLPH$OVR-DYDGRHVQRWVXSSRUWSRLQWHUDULWKPHWLF6RDQ\RQHFDQZULWH D-DYDSURJUDPZLWKRXWKDYLQJWRZRUU\DERXWWKHPHPRU\OHDNDJHRUPHPRU\FRUUXSWLRQWKDW LVXVXDOO\DIHDWXUHRIEDGSRLQWHUPDQDJHPHQW ([FHSWLRQ FRQGLWLRQV LQ WUDGLWLRQDO HQYLURQPHQWV RIWHQ DULVH LQ VLWXDWLRQV VXFK DV GLYLVLRQ E\ ]HUR RU ILOH QRW IRXQG DQG PXVW EH PDQDJHG ZLWK FOXPV\ DQG KDUG WR UHDG FRQVWUXFWV -DYD KHOSV LQ WKLV DUHD E\ SURYLGLQJ REMHFW RULHQWHG H[FHSWLRQ KDQGOLQJ ,Q D ZHOOZULWWHQ -DYD SURJUDPDOOUXQWLPHHUURUVFDQDQGVKRXOGEHPDQDJHGE\RXUSURJUDP Java is a Multithreaded Language

-DYD ZDV GHVLJQHG WR PHHW WKH UHDOZRUOG UHTXLUHPHQW RI FUHDWLQJ LQWHUDFWLYH QHWZRUNHG SURJUDPV 7R DFFRPSOLVK WKLV -DYD VXSSRUWV PXOWLWKUHDGHG SURJUDPPLQJ ZKLFK DOORZV XV WR ZULWH SURJUDPV WKDW GR PDQ\ WKLQJV DW RQFH 7KH -DYD UXQ WLPH FRPHV ZLWK DQ HOHJDQW \HW VRSKLVWLFDWHG VROXWLRQ IRU PXOWLSURFHVV V\QFKURQL]DWLRQ WKDW PDNHV LW SRVVLEOH WR FRQVWUXFW VPRRWKO\ UXQQLQJ LQWHUDFWLYH V\VWHPV -DYD LV DQ HDV\ WR DSSURDFK PXOWLWKUHDGLQJ ODQJXDJH ,W DOORZVXVWRWKLQNDERXWWKHVSHFLILFEHKDYLRURIRXUSURJUDPQRWWKHPXOWLWDVNLQJVXEV\VWHP DVDZKROH Java is dynamic

-DYD LV D PRUH G\QDPLF ODQJXDJH WKDQ WKH RWKHU ODQJXDJHV ,W ZDV GHVLJQHG WR DGDSW WR DQ HYROYLQJ HQYLURQPHQW -DYD SURJUDPV FDUU\ ZLWK WKHP VXEVWDQWLDO DPRXQWV RI UXQ WLPH LQIRUPDWLRQWKDWDUHXVHGWRYHULI\WKHREMHFWDWUXQWLPH7KLVPDNHVLWSRVVLEOHWRG\QDPLFDOO\ OLQNFRGHLQDVDIHDQGH[SHGLHQWPDQQHU

Comp-U-Learn

5

Java Programming I

Java and the Internet %\XVLQJ-DYDXVHUVZLOOGRZQORDG-DYDE\WHFRGHIURPWKH,QWHUQHWDQGUXQWKHPRQWKHLURZQ PDFKLQHV-DYDSURJUDPVWKDWZRUNRQZHESDJHVDUHFDOOHGDSSOHWV7RXVHWKLVDSSOHWZHQHHG D-DYDHQDEOHGEURZVHUZKLFKLQWHUSUHWVWKHE\WHFRGHIRUXV6LQFH6XQOLFHQVHVWKH-DYDVRXUFH FRGHLWLQVLVWVWKDWWKHUHEHQRFKDQJHVLQWKHODQJXDJHDQGEDVLFOLEUDU\VWUXFWXUHV'XHWRWKLV ZHDUHVXUHWKDWDQDSSOHWUXQVRQDQ\EURZVHUWKDWLVDGYHUWLVHGDV-DYDHQDEOHG 7KH ,QWHUQHW KHOSHG FDWDSXOW -DYD WR WKH IRUHIURQW RI SURJUDPPLQJ 7KH UHDVRQ LV WKDW -DYD H[SDQGVWKHXQLYHUVHRIREMHFWVWKDWFDQPRYHDERXWIUHHO\LQF\EHUVSDFH,QDQHWZRUNWKHUH DUH WZR YHU\ EURDG FDWHJRULHV RI REMHFWV WKDW DUH WUDQVPLWWHG EHWZHHQ WKH VHUYHU DQG RXU SHUVRQDOFRPSXWHUQDPHO\SDVVLYHDQGDFWLYHSURJUDPV :KHQZHUHDGRXUHPDLOZHDUHYLHZLQJWKHSDVVLYHGDWD(YHQZKHQZHGRZQORDGDSURJUDP WKHFRGHIRUWKHSURJUDPLVVWLOORQO\SDVVLYHXQWLOZHH[HFXWHLW+RZHYHULQWKHVHFRQGW\SHRI REMHFWWKDWFDQEHWUDQVPLWWHGWRRXUFRPSXWHUDVDG\QDPLFVHOIH[HFXWLQJSURJUDPLWLVFDOOHG DVDQDFWLYHSURJUDP $SSOHWVFDQEHXVHGWRDGGEXWWRQVDQGLQSXWILHOGVWRZHESDJH+RZHYHUGRZQORDGLQJWKRVH DSSOHWVRYHUDGLDOXSOLQHLVVORZDQGZHFDQGRPXFKWKHVDPHZLWK'\QDPLF+70/+70/ IRUPV DQG D VFULSWLQJ ODQJXDJH VXFK DV -DYD6FULSW ,Q HDUO\ GD\V DSSOHWV ZHUH XVHG IRU DQLPDWLRQV OLNH VSLQQLQJ JOREHV FDUWRRQV +RZHYHU DQLPDWHG *,) FDQ GR PXFK RI WKLV DQG '\QDPLF+70/FRPELQHGZLWKVFULSWLQJFDQGRHYHQPRUHRIZKDW-DYDDSSOHWVZHUHXVHGIRU

Java- An OOP Language 7KHREMHFWRULHQWHGFRQFHSWKDVSURYHQLWVZRUWKLQWKHODVWWKLUW\\HDUV,WLVRQHRIWKHPRVW SRSXODUWHFKQRORJLHV0DQ\RIXVPLJKWKDYHKHDUGWKLVZRUGPD\EHSHUKDSVZLWKRXWNQRZLQJ ZKDWLWPHDQV:KDWHYHULWPD\EH223LVRQHRIWKHVLPSOHVWDQGSODLQWKLQJVZHFDQFRPH DFURVV LQ RXU SURJUDPPLQJ FDUHHU 223 ODQJXDJH SURYLGHV VLPSOH FRQVWUXFWV WR HQDEOH XV WR H[SUHVVRXUQDWXUDOLGHDVHIILFLHQWO\7KLVDOORZVXVWRWDONDERXWYDULRXVREMHFWV 6LQFH-DYDLVDQREMHFWRULHQWHGSURJUDPPLQJODQJXDJHZHFDQXVHPRVWRIWKHREMHFWRULHQWHG FRQFHSWV LQ RXU -DYD SURJUDPPLQJ -DYD IRFXVHV RQ GHILQLQJ GDWD DQG IXQFWLRQV WKDW PD\ EH DSSOLHGWRWKRVHREMHFWV7KLVIDFLOLWDWHVSURJUDPGHYHORSPHQWXVLQJQDWXUDOSDUDGLJPV,Q-DYD ZHFDQFRQVWUXFWDSURJUDPXVLQJWKHIROORZLQJREMHFWRULHQWHGFRQFHSWV ♦ ♦ ♦ ♦

6

Encapsulation Inheritance Polymorphism Interfaces

Comp-U-Learn

JAVA-An Introduction

$OWKRXJK -DYD VXSSRUWV WKH REMHFWRULHQWDWLRQ LW GRHV QRW VXSSRUW PXOWLSOH LQKHULWDQFH ,W VXSSRUWVVLQJOHLQKHULWDQFHZKHUHRQHFODVVFDQLQKHULWIURPRQO\RQHRWKHUFODVV2QWKHRWKHU KDQG-DYDVXSSRUWVDEVWUDFWFODVVHVLQWHUIDFHVXVLQJZKLFKSURJUDPPHUVFDQVLPXODWHPXOWLSOH LQKHULWDQFH7KHDEVWUDFWEDVHFODVVIRUDOO-DYDFODVVHVLVDFODVVFDOOHGREMHFW

C++ vs. Java $OWKRXJK-DYDLVREMHFWRULHQWHGWKHUHDUHVRPHGLIIHUHQFHVEHWZHHQ-DYDDQG&DQREMHFW RULHQWHG SURJUDPPLQJ ODQJXDJH LWVHOI $SDUW IURP WKH REMHFWRULHQWHG FRQFHSWV -DYD GLIIHUV IURP&LQYDULRXVZD\V7KHIROORZLQJOLVWVWKHGLIIHUHQFHV ♦ Java omits header files, pre-processor, goto statement and multi dimensional arrays. ♦ Like C, C++, Java does not support the pointer arithmetic. In addition, Java omits the important elements, union and structures. ♦ Java does not support the multiple inheritance. Through interfaces, we can simulate multiple inheritance. ♦ Java does not support stand-alone functions. All Java functions including the main function should be declared within the class. ♦ Although Java supports polymorphism, it does not support the operator overloading. ♦ In Java, the main function should take one parameter, which is a string type variable. The String class object itself determines the number of arguments. ♦ Java has an auto garbage collection mechanism. Therefore, we do not need to worry about freeing memory. ♦ In Java we can comment the lines by using the “/**” and “*/”. It can be used by the javadoc tool, which will be discussed later. ♦ The boolean data types, unlike in C++, are not an interpretation of the integers 0 and 1. Therefore in Java, Java boolean cannot be typecast into integers. They can have values either true or false.

Java Tools -DYDLVDFRPSOHWHSURJUDPPLQJHQYLURQPHQWDQGFRPHVZLWKLWVRZQVHWRI WRROV(DFK-DYD WRROKDVDVLJQLILFDQWIHDWXUH7KHIROORZLQJDUHWKH-DYDWRROVXVHGIRU-DYDSURJUDPPLQJ JDK

6WDQGVIRU-DYD'HYHORSHUV.LWDYDLODEOHIRULWVVXSSRUWHGSODWIRUPVRQZKLFKZHKDYHWRZULWH RXU-DYDSURJUDP,WLQFOXGHVIROORZLQJWRROVIRUIXUWKHUIDFLOLWLHV

Comp-U-Learn

7

Java Programming I Javac

6WDQGVIRU-DYDFRPSLOHUE\ZKLFKZHFRPSLOHRXU-DYDDSSOLFDWLRQDVZHOODVWKHDSSOHW$IWHU FRPSLOLQJ RXU -DYD SURJUDP D FODVV ILOH ZLOO DXWRPDWLFDOO\ EH FUHDWHG LQ WKH VDPH GLUHFWRU\ ZKLFKFRQWDLQVWKHE\WHFRGHRIWKHSURJUDP7KHV\QWD[WRFRPSLOHWKHSURJUDPLV javac

< type our Java file here with the .Java extension.>

E.g.: C:/jdk1.2/bin/javac example.java

Java

7KLV LV WKH -DYD LQWHUSUHWHU 8VLQJ WKLV ZH ZLOO EH DEOH WR UXQ RXU DSSOLFDWLRQ SURJUDP LQ WKH FRPPDQG OLQH 7KLV VKRXOG EH GRQH DIWHU FRPSLOLQJ WKH -DYD ILOH %HFDXVH ZKHQ ZH UXQ RXU -DYDILOHWKH-DYDLQWHUSUHWHUZLOOORRNIRUWKHFODVVILOHRIWKDWSDUWLFXODUSURJUDPWRH[HFXWHWKH RXWSXW7KHV\QWD[WRUXQRXUDSSOLFDWLRQSURJUDPLV Java

< Java file without the .Java extension.>

Example 1.1 C:/jdk1.2/bin/java example

Appletviewer

:HFDQUXQRXUDSSOHWSURJUDPXVLQJWKLVVWDQGDORQHEURZVHUDQGJHWRXURXWSXWLQDZLQGRZ :HFDQDOVRXVHDQ\RWKHUEURZVHUOLNH,QWHUQHW([SORUHU7KHV\QWD[DWFRPPDQGOLQHLV Appletviewer < HTML file.html extension.>

$QDSSOHWLVW\SLFDOO\YLHZHGOLNHWKLV Example 1.2 C:/jdk1.2/bin/appletviewer example.html

javadoc

7KLV WRRO UHFRJQL]HV WKH WKLUG FRPPHQW GHOLPLWHU ´

µ DQG XVHV LW WR DXWRPDWLFDOO\ JHQHUDWH GRFXPHQWDWLRQ 7KLV WRRO XVHV WKHVH W\SH RI FRPPHQWV -DYDGRF XQGHUVWDQGV D QXPEHU RI SDUDPHWHUVWKDWZHFDQHPEHGLQWKHVHFRPPHQWV7KHMDYDGRFRQO\ZRUNVRQSXEOLFFODVVHV 8

Comp-U-Learn

JAVA-An Introduction Jdb

7KLV WRRO LV FDOOHG -DYD GHEXJJHU ZKLFK LV XVHG WR GHEXJ RXU SURJUDP ,I ZH KDYH DQ\ FRPSLODWLRQHUURUVZHFDQHDVLO\ILQGRXWWKHHUURUORFDWLRQE\XVLQJWKH-DYDGHEXJJHUWRRO $OVRWKH-DYDHQYLURQPHQWKDVVRPHRWKHUWRROVOLNHMDYDSURIZKLFKLVWRJHQHUDWHSURILOHIRU RXUSURJUDPMDYDKZKLFKLVXVHGWRJHQHUDWH WKH KHDGHUILOHVIRULQWHJUDWLQJ&LQWR RXU-DYD FRGH

Application Programming -DYDDSSOLFDWLRQVDUHVLPLODUWRRWKHUSURJUDPPLQJODQJXDJHV,Q-DYDWKHUHDUHWZRSDUWVLQWKH SURJUDPPLQJHQYLURQPHQWDSSOLFDWLRQDQGDSSOHW,QDQDSSOLFDWLRQZHFDQZULWHRXUSURJUDP DQG LW UXQV VWDQG DORQH RQ WKH -DYD 9LUWXDO 0DFKLQH 7KDW PHDQV WKDW ZH FDQ UXQ RXU -DYD DSSOLFDWLRQSURJUDPLQRXUVWDQGDORQHPDFKLQH7KHMDYDFFRPSLOHULVXVHGWRFRPSLOHWKH-DYD DSSOLFDWLRQ7KH-DYDLQWHUSUHWHULVXVHGWRUXQWKH-DYDDSSOLFDWLRQLQWKHFRPPDQGOLQH 7KH DSSOLFDWLRQ LV ORDGHG IURP WKH ORFDO ILOH V\VWHP EHFDXVH LW LV DVVXPHG WKDW XVHUV ORDG DSSOLFDWLRQ IURP WKH ORFDO ILOH V\VWHP 7KHUH DUH IHZHU ILOHV DQG QHWZRUN VHFXULW\ UHVWULFWLRQV LPSRVHG $QLPSRUWDQWDGYDQWDJHIRUODUJHDSSOLFDWLRQVLVWKDWWKHPHPRU\VSDFHFDQEHFRQWUROOHG)URP WKH -90 ZH FDQ FRQWURO LQLWLDO OLPLWV IRU WKH VWDFN DQG KHDS ,I RXU DSSOLFDWLRQ XVHV D ODUJH DPRXQWRIPHPRU\ZHZLOOKDYHFRPSOHWHFRQWURORIWKHVHVHWWLQJV :LQGRZV DSSOLFDWLRQV DUH VLPLODU WR UXQQLQJ DQ DSSOHW IURP ZLWKLQ D ZHE EURZVHU 7KH PDLQ GLIIHUHQFH LV WKDW WKHUH DUH IHZHU ILOH DQG QHWZRUN VHFXULW\ UHVWULFWLRQV 6WDQGDORQH ZLQGRZ DSSOLFDWLRQVPXVWDOVRSURYLGHWKHLURZQFRQQHFWLRQWRUHVRXUFHVVXFKDVSLFWXUHVDQGVRXQG 7KH\GLIIHUIURPDSSOHWVLQWKDWWKH\GRQRWUXQIURP:HEEURZVHUV

Creating an Application ,Q-DYDFUHDWLQJDQDSSOLFDWLRQSURJUDPFRQVLVWVRIWKHIROORZLQJVWHSV ♦ Create a Java Source file with .Java extension. ♦ Compile this source file by using javac compiler. ♦ Run this application by using Java interpreter. 7KH IROORZLQJ H[DPSOH LOOXVWUDWHV WKH SUHOLPLQDU\ WKLQJV DERXW FUHDWLRQ RI DQ DSSOLFDWLRQ SURJUDP

Comp-U-Learn

9

Java Programming I

Example 1.3 class first_program public static void main(String args[]) { System.out.println(“Welcome to Comp-U-Learn!”); } }

$-DYDDSSOLFDWLRQVKRXOGFRQWDLQWKHIROORZLQJVWHSV &ODVV GHILQLWLRQ 7KH ILUVW OLQH VKRXOG FRQWDLQ WKH NH\ZRUG FODVV DQG WKH FODVV QDPH ILUVWBSURJUDPLVWKHVRXUFHILOHQDPH 0DLQPHWKRG,QWKHVHFRQGOLQHZHVKRXOGGHILQHWKHPDLQPHWKRG,QWKLVOLQHZHDOVRVSHFLI\ WKHDFFHVVPRGHUHWXUQW\SHDQGWKHPDLQNH\ZRUGZLWKWKHVLQJOHSDUDPHWHU,QDGGLWLRQZH FDQ KDYH DQ\ QXPEHU RI FODVV PHWKRGV DQG YDULDEOHV ZLWKLQ D FODVV GHILQLWLRQ ,Q WKH DERYH SURJUDP ♦ 3XEOLFLQGLFDWHVWKDWWKHPDLQPHWKRGFDQEHFDOOHGE\DQ\REMHFW ♦ 6WDWLFLQGLFDWHVWKDWWKHPDLQPHWKRGLVLQWKHFODVVGHILQLWLRQ,Q-DYDDSSOLFDWLRQ WKH PDLQPHWKRGVKRXOGEHLQVLGHWKHFODVVGHILQLWLRQ ♦ 9RLGGHQRWHVWKDWWKHPDLQPHWKRGKDVQRUHWXUQW\SH ♦ 7KHPDLQPHWKRGWDNHVDVLQJOHDUJXPHQWDVDQDUUD\RIVWULQJV7KHVHVWULQJVZKHQ JLYHQ DV DUJXPHQWV WR WKH SURJUDP DW FRPPDQG OLQH DUH FDOOHG FRPPDQG OLQH DUJXPHQWV

Note In Java the source file name should be same as the class name. When we run our program, the interpreter will look for the .class file of that source file name 1RZW\SHLQWKHDERYHSURJUDPLQ1RWHSDG'26HGLWRU DQGVDYHLWDVILUVWBSURJUDPMDYDLQ -DYD·VELQGLUHFWRU\IROORZWKHVWHSVJLYHQEHORZLQWKHFRPPDQGOLQHWRJHWWKHRXWSXW 1. Compile the program using javac ( javac first_program.java) 2. Press Enter and wait until the compilation is over without any errors. 3. Then run the program using the interpreter ( java first_program) 1RZZHFDQJHWWKHRXWSXWLQWKHFRPPDQGOLQHDVIROORZV

10

Comp-U-Learn

JAVA-An Introduction

Fig 1.1

Applet Programming $QDSSOHWLVDG\QDPLFDQGLQWHUDFWLYHSURJUDPWKDWFDQUXQLQVLGHDZHESDJHGLVSOD\HGE\D -DYDHQDEOHGEURZVHUVXFKDV+RW-DYDRU1HWVFDSH-DYDDSSOHWVKDYHUHVWULFWLRQVWRHQVXUH VHFXULW\WRSUHYHQWWKHPIURPEHLQJDIIHFWHGE\YLUXVHV $SSOHWV DUH D FRPPRQ ZD\ RI ZULWLQJ LQWHUDFWLYH XVHU LQWHUIDFH -DYD DSSOLFDWLRQV ,QWHJUDWLQJ ZHE EDVHG VRXQG DQG JUDSKLFV LQWR DSSOLFDWLRQV LV VLPSOLILHG E\ XVLQJ PHWKRGV LQ WKH DSSOHW FODVV$SSOHWVDUHHVVHQWLDOO\SURJUDPVWKDWUXQIURPZLWKLQDZHEEURZVHU7KH\DSSHDUDVSDUW RI +70/ GRFXPHQWV LQ WKH VDPH ZD\ WKDW SLFWXUHV DUH UHSUHVHQWHG $SSOHWV RQO\ UXQ IURP ZLWKLQ-DYDHQDEOHGEURZVHUVVXFKDV1HWVFDSH+RW-DYDDQGWKH,QWHUQHW([SORUHU

Creating an Applet ,QWKLVVHFWLRQZHDUHJRLQJWROHDUQDERXWWKHFUHDWLRQRIDVLPSOHDSSOHWSURJUDP7KHGHWDLOV UHJDUGLQJDSSOHWVZLOOEHGLVFXVVHGLQWKHVXFFHHGLQJVHVVLRQV7KHFUHDWLRQRIDQDSSOHWFRQVLVWV RIWKHIROORZLQJIRXUVWHSV ♦ ♦ ♦ ♦

Importing the necessary built-in Java packages Defining applet subclasses Applet implementation Passing this Java applet’s .class file into HTML file.

&RQVLGHU WKH IROORZLQJ DSSOHW H[DPSOH  VD\ ILUVWBDSSOHWMDYD  ,W ZLOO JLYH WKH GHWDLOV WR FUHDWHDQDSSOHW Comp-U-Learn

11

Java Programming I

Example 1.4 import java.awt.*; import java.applet.*; public class first_applet extends Applet { public void paint(Graphics g) { g.drawString("Welcome to Comp-U-Learn!",50,20); } }

,QWKHDERYHSURJUDPWKHILUVWWZROLQHVDUHXVHGWRLPSRUWVRPHSDFNDJHVDQGFODVVHVZKLFK DUH EHLQJ XVHG ZLWKLQ WKH DSSOHW /LNH DSSOLFDWLRQV KHUH WR ZH KDYH WR VSHFLI\ WKH FODVV GHFODUDWLRQ DW WKH EHJLQQLQJ 7KH H[WHQGV NH\ZRUG LV XVHG KHUH WR H[WHQG VRPH SUHGHILQHG FODVVHVWRRXUSURJUDP 7KHQZHKDYHWRLPSOHPHQWWKHDSSOHWE\PHDQVRIWKHDSSOHWPHWKRGV,QWKLVSURJUDPWKH SDLQWPHWKRGRIDSSOHWLVXVHGWRSULQWVRPHWH[WLQWKHZLQGRZ)LQDOO\ZHKDYHWRSDVVWKLV VRXUFHILOH ILUVWBDSSOHWFODVV LQWRDQ+70/ILOH)RUWKDWZHKDYHWRFUHDWHDQ+70/ILOH VD\ ILUVWBDSSOHWKWPO ZKLFKVKRXOGFRQWDLQWKHIROORZLQJFRGH

1RZFRPSLOHWKLVILUVWBDSSOHWMDYDILOHRQWKHFRPPDQGOLQHXVLQJMDYDF7KHQUXQWKLV ILUVWBDSSOHWKWPOILOHXVLQJDSSOHWYLHZHU 7KH IROORZLQJ ILJXUH VKRZV  WKH RXWSXW RI WKH DERYH DSSOHWSURJUDP

Fig 1.2

12

Comp-U-Learn

JAVA-An Introduction

$IWHU FRPSLOLQJ WKH -DYD ILOH ZH JHW WKH RXWSXW IRU WKH DERYH SURJUDP E\ EURZVLQJ WKH ILUVWBDSSOHWKWPOILOHLQWKH,QWHUQHWH[SORUHU

Fig 1.3

Overview of Java 6RIDUZHKDYHGLVFXVVHGDERXW-DYDLWVIHDWXUHVDQGLWVVLPSOHSURJUDPPLQJHQYLURQPHQW7KLV VHFWLRQLVDTXLFNRYHUYLHZRI-DYD -DYDDVRIWRGD\LVSRSXODUGXHLWV,QWHUQHWIDFLOLWLHVEURZVLQJHWFEXWLWKDVPRUHSRWHQWLDOWR EHFRPHDVHULRXVSURJUDPPLQJODQJXDJHLQIXWXUH7RGD\PDQ\SHRSOHIDLOWRYLVXDOL]HWKLVEXW ZHFDQEHFRQILGHQWWKDWLWZLOOSURYHWREHVR,QIDFWWKLVLVWKHPDMRUUHDVRQZK\-DYDDWWUDFWV PDQ\ SHRSOH ,W KDV DOO WKH JRRG SRLQWV RI D ZHOOWKRXJKW RXW ODQJXDJH OLNH 3DVFDO WKDW LV D VWUXFWXUDO ODQJXDJH ,WV V\QWD[ ORRNV VLPLODU WR & EXW LW KDV YHU\ FDUHIXOO\ DYRLGHG DOO WKH SUREOHPDWLFFRQVWUXFWVRI&OLNHSRLQWHUVVWUXFWXUHVDQGXQLRQV ,QDGGLWLRQWKHPDMRUPLVWDNHPDGHLQWKH&GHVLJQWRSDWFKXS&ZLWKWKH223IDFLOLWLHV KDVEHHQDYRLGHGLQ-DYD,Q&DQ\&SURJUDPFDQEHDFFHSWHGDVD&SURJUDPWKXV HYHQWXDOO\DOOWKHDGYDQWDJHVRI223JRWNLOOHG-DYDGRHVQRWDOORZWKLVDQGIRUFHVWKHVRIWZDUH SURJUDPPHUWRGHYHORSFRGHLQDV\VWHPDWLFVWUXFWXUHGWRSGRZQDQG223PDQQHU )RUDOOWKHVHUHDVRQV-DYDZRXOGEHWKHODQJXDJHRIIXWXUH$IWHU\HDUVPRVWSUREDEO\SHRSOH ZLOO VD\ WKDW ´ LW DOVR KDV DOO WKH IDFLOLW\µ +HUH LW UHPLQGV XV RI VRPHWKLQJ VLPLODU WKDW KDG KDSSHQHGZLWK&DURXQG7KDWWLPHHYHU\ERG\UHJDUGHGLWWREHWKH ´6\VWHPVSURJUDPPLQJµODQJXDJHDQGPDQ\H[SHUWVDOVRIDLOHGWRVHHLWVRWKHUSRWHQWLDOVDVD JHQHUDOSURJUDPPLQJODQJXDJH$IWHU\HDUVLQHYHU\RQHXQGHUVWRRGLWDVDGHYHORSPHQW ODQJXDJH DQG DGGHG D OLQH VD\LQJ ´LW LV EHWWHU VXLWHG WR GR ORZOHYHO V\VWHPRULHQWHG SURJUDPPLQJµ 7KXV -DYD ZLOO EHFRPH D SRZHUIXO JHQHUDO SXUSRVH SURJUDPPLQJ ODQJXDJH LQ WKHQH[WFHQWXU\ Comp-U-Learn

13

Java Programming I

Summary In this session, we learnt about the Java language and how Java is an objectoriented language. Now we can appreciate the relationship between the Java and the Internet. In this session we also learnt how Java differs from the other programming languages. After this Java preliminary, we learnt about Java tools and its uses. We also learnt to write a simple Java application program and create a simple applet.

Going Over It Again I. Fill in the Blanks

 -DYDLVRIILFLDOO\UHOHDVHGLQBBBBBBBBBBBBB  ,Q D QHWZRUN WKHUH DUH WZR YHU\ EURDG FDWHJRULHV RI REMHFWV WKH\ DUH BBBBBBBBB DQG BBBBBBBBBBBB  7KURXJKBBBBBBBBBBBZHFDQVLPXODWHPXOWLSOHLQKHULWDQFH  ,Q-DYDWKHVRXUFHILOHQDPHVKRXOGEHVDPHDVWKHBBBBBBBQDPH  $IWHUFRPSLOLQJRXU-DYDSURJUDPDBBBBBBBILOHZLOOEHDXWRPDWLFDOO\FUHDWHGLQWKHVDPH GLUHFWRU\E\BBBBBBBFRPSLOHU

II. State True or False

 -DYDLVDVWUXFWXUDODQGREMHFWRULHQWHGODQJXDJH  -DYDVXSSRUWVDOOWKHSRO\PRUSKLVPFRQFHSWV  :HFDQUXQ$SSOHWVE\WKHVWDQGDORQHLQWHUSUHWHU  ,QDSSOHWVWKHUHLVQRQHHGIRUPDLQPHWKRG  :HFDQXVHWKHMDYDFWRROIRUGHEXJJLQJRXUSURJUDP

14

Comp-U-Learn

JAVA-An Introduction III. One line Answers

 :KDWDUHWKHWZRSURJUDPPLQJW\SHVRIIHUHGE\-DYD"  :KDWLV-90"  /LVWRXWWKH-90WRROV  +RZGRZHLPSOHPHQWPXOWLSOHLQKHULWDQFHLQ-DYD"  :KDWLVDQDSSOHW" IV. Match the following

$SSOHW



DPXOWLSOHLQKHULWDQFH

-DYDGRF



EE\WHFRGH

LQWHUIDFHV



FEURZVHU

+773)73



GGRFXPHQWDWLRQ

-DYDF



H,QWHUQHWSURWRFROV

Comp-U-Learn

15

Session 2

Fundamentals of Java

On Completion of this Session We will be able to understand...

) Java Syntax & Identifiers ) Java variables and its scope ) About commenting in Java ) Java programming constructs ) Arrays & Strings in Java

In This Session...



Data types & Variables in Java



Literals, Keywords & Identifiers



Operators in Java



Expression Evaluations & Operator Precedence



Scope of Variables



Commenting in Java



Decision Making



For Loop



While & Do… While Loop



Switch & Break Statements



Arrays in Java



Strings in Java

Fundamentals of Java

Data types & Variables in Java ,Q WKLV VHFWLRQ ZH ZLOO EH GLVFXVVLQJ DERXW WKH GDWD W\SHV DQG YDULDEOHV XVHG LQ -DYD ,Q -DYD WKHUHDUHWZRW\SHVRIGDWDNLQGV7KH\DUH ♦ Primitive data types ♦ Reference data types 7KHSULPLWLYHGDWDW\SHVFRQWDLQDVLQJOHYDOXH,QWHJHUIORDWFKDUDFWHUDQGERROHDQGDWDW\SHV FRPHXQGHUWKLVW\SH7KHUHIHUHQFHW\SHVDUHFDOOHGVXFKEHFDXVHWKHYDOXHRIUHIHUHQFHYDULDEOH LVDUHIHUHQFHWRDQDFWXDOYDOXHUHSUHVHQWHGE\DQRWKHUYDULDEOH)RUH[DPSOHDUUD\VFODVVHVDQG LQWHUIDFHV IDOO XQGHU WKLV FDWHJRU\ ,Q DGGLWLRQ ZKHQ D FODVV LV FUHDWHG LQ HVVHQFH D QHZ GDWD W\SHLVFUHDWHG:H·OOVHHWKHVHGDWDW\SHVLQGHWDLO 7KHIROORZLQJWDEOHOLVWVWKHPRVWRISULPLWLYHGDWDW\SHVWKHLUVL]HDQGUDQJH Type Byte Short Int Long Float Double Char Boolean

Size 1 2 4 8

Range -128 to 127 -32,768 to 32, 767 -2,147,483,648 to 2,147,483,647 -9,223,372,036,854,775,808 To 9,223,372,036,854,775,807 approx. ±3.40282347E+38F approx. ±1.79769313486231570E+308 true or false

4 8 2 -

Variables in Java

,Q -DYD ZH KDYH WR GHFODUH WKH W\SH RI YDULDEOH ZH DUH JRLQJ WR XVH 7KH YDULDEOH GHFODUDWLRQ DOZD\VFRQWDLQVWZRSDUWV2QHLVGDWDW\SHDQGDQRWKHULVYDULDEOHQDPH7KHIROORZLQJV\QWD[ VKRXOGEHXVHGWRGHFODUHDYDULDEOH



(e.g.: int

no;)

,Q-DYDZKLOHGHFODULQJDYDULDEOHZHKDYHVRPHUHVWULFWLRQV ♦ A variable name must be a legal identifier of a series of Unicode characters. ♦ A variable name should not be the same as any keywords or literals. Comp-U-Learn

19

Java Programming I

♦ They must not have the same name as another variable. ♦ Java is case sensitive. So int Myint, myInt, MyInt, and myint are different variables. Variable initialization

/RFDO YDULDEOHV  ZKLFK DUH YDULDEOHV GHFODUHG LQ PHWKRGV  PXVW EH LQLWLDOL]HG EHIRUH WKH\ DUH XVHG,IQRWDFRPSLOHWLPHHUURUZLOORFFXU$YDOXHDVVLJQHGWRWKHYDULDEOHPXVWPDWFKWKH YDULDEOHW\SH E.g.:

int

number = 0;

Using Variables

7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKHXVHRIYDULDEOHVLQ-DYD Example 2.1 class var_usage { public static void main(String args[]) { int a=10; double b=4.5; char c='n'; System.out.println(" This is the Usage of System.out.println(" The value of a is: " System.out.println(" The value of b is: " System.out.println(" The value of c is: " } }

Variables"); +a); +b); +c);

,QWKLVH[DPSOHWKH 6\VWHPRXWSULQWOQ VWDWHPHQW LV XVHG WR SULQW VRPH WH[W RQ WKH VFUHHQ ,Q DGGLWLRQKHUHZHDUHSULQWLQJWKHLQLWLDOL]HGYDULDEOHVVRZHKDYHWRXVH´µRSHUDWRUDORQJZLWK WKHYDULDEOHQDPH$IWHUUXQQLQJWKHDERYHSURJUDPZHJHWWKHRXWSXWDVIROORZV This is the Usage of Variables The value of a is: 10 The value of b is: 4.5 The value of c is: n

Note For printing text on consecutive lines, System.out.println statement is used. If we use the System.out.print statement, the text will be printed in the same line. 20

Comp-U-Learn

Fundamentals of Java

Literals, Keywords & Identifiers ,Q -DYD WKHUH DUH VRPH OLWHUDOV DQG UHVHUYHG ZRUGV $ OLWHUDO UHSUHVHQWV WKH YDOXH RI D FHUWDLQ W\SHZKHUHWKHW\SHGHVFULEHVKRZWKDWYDOXHEHKDYHV7KHUHDUHGLIIHUHQW W\SHVRIOLWHUDOYL] QXPHULFFKDUDFWHUERROHDQDQGVWULQJ Number

,QWKLVW\SHZHFDQKDYHOLWHUDOVOLNHLQWORQJRFWDOKH[DGHFLPDOHWFDQXPEHUEHJLQQLQJZLWK LVFDOOHGRFWDOQXPEHU$OHDGLQJ[QXPEHULVFDOOHGKH[DGHFLPDOQXPEHU8VLQJWKHOHWWHU(RU HIROORZHGE\WKHH[SRQHQWFDQXVHWKHH[SRQHQWVZLWKIORDWLQJSRLQWOLWHUDOV Boolean

7KHUHDUHRQO\WZRW\SHVRIERROHDQOLWHUDOV7KH\DUHWUXHDQGIDOVH Character

$VLQJOHFKDUDFWHUHQFORVHGZLWKLQVLQJOHTXRWHVH[SUHVVHVWKHFKDUDFWHUOLWHUDOV7KHVHDUHVWRUHG DV8QLFRGHFKDUDFWHUV Escape Sequences

7KHVH DUH DOVR D IRUP RI FKDUDFWHU OLWHUDO EXW DUH QRW SULQWHG RQ WKH VFUHHQ7KH\ FRXOG EH FRPELQHGZLWKDQ\RWKHUOLWHUDO7KHIROORZLQJWDEOHVKRZVHVFDSHVHTXHQFHVXVHGLQ-DYD Literals \n \t \b \r \f \\ \” \ddd \xdd \udddd

Usage To insert a new line (line feed) For tab control To give backspace For carriage return To give form feed For backslash to print a “ symbol For octal For Hexadecimal For Unicode character

Key words

.H\ZRUGVDUHDOVRFDOOHGUHVHUYHGZRUGV+HUHLVDFRPSOHWHOLVWRIWKHNH\ZRUGVLQ-DYDIRU RXUIXUWKHUUHIHUHQFH$OORIWKHPDUHQRWFXUUHQWO\LQXVHVRPHRIWKHPDUHUHVHUYHGIRUIXWXUH HQKDQFHPHQWV Comp-U-Learn

21

Java Programming I

DEVWUDFWERROHDQEUHDNE\WH FDVHFDVWFDWFKFKDUFODVVFRQVWFRQWLQXH GHIDXOWGRGRXEOHHOVHH[WHQGVILQDOILQDOO\IORDWIXWXUH JHQHULFLILPSOHPHQWVLPSRUWLQQHULQVWDQFHRILQWLQWHUIDFH ORQJQDWLYHQHZQXOORSHUDWRURXWHU SDFNDJHSXEOLFSURWHFWHGDQGSULYDWH UHVWUXQUHWXUQVKRUWVWDWLFVXSHUVZLWFKV\QFKURQL]HG WKLVWKURZWUDQVLHQWWU\YDUYRLGYRODWLOHZKLOH Identifiers

7KHLGHQWLILHUVDUHWKHV\PEROVXVHGLQD-DYDSURJUDP,GHQWLILHUVFDQQRWVWDUWZLWKDQXPEHU DOWKRXJKQXPEHUVDUHDOORZHGLQVLGHLGHQWLILHUV7KHV\PEROVWKDWFDQEHXVHGDVLGHQWLILHUVLQ -DYDDUH #A    ?^`>@aa_ !"´DQGHWF.

Operators in Java ,Q -DYD RSHUDWRUV FRPH LQ VHYHUDO W\SHV 7KH\ FDQ EH XVHG ZLWK YDULDEOHV WR LQGLFDWH PDWKHPDWLFDOUHODWLRQVKLSEHWZHHQWZRRUPRUHLWHPVWRFUHDWHORJLFDOVWUXFWXUHVRUWRSHUIRUP FRPSXWDWLRQV 7KH RSHUDWRUV VXSSRUWHG E\ -DYD DUH $ULWKPHWLF $VVLJQPHQW /RJLFDO DQG &RPSDULVRQ $ULWKPHWLFRSHUDWRUV $OOEDVLFDULWKPHWLFRSHUDWRUVVXFKDV DQGXQDU\RSHUDWRUVFRPHVXQGHUWKLVW\SH 7KHIROORZLQJWDEOHOLVWVWKH$ULWKPHWLFRSHUDWRUV Description Multiplication Division Addition Subtraction Modulus Increment Decrement Bit-wise complement

22

Operators * / + % ++ -~

Function Multiply the given two numbers Divide two numbers Add two numbers Subtract two numbers Determine the remainder in a division operation Increase the value of a specified variable by one Decrease the value of a specified variable by one Change the bit values of a specified variable, Converting all ones to zeros and vice versa

Comp-U-Learn

Fundamentals of Java

7KHIROORZLQJH[DPSOHVKRZVWKHXVDJHRIWKHDULWKPHWLFRSHUDWRUVLQ-DYD Example 2.2 class arithmetic { public static void main(String { int a=20; int b=10; double c=4.5; System.out.println(" The Usage System.out.println(" The value System.out.println(" The value System.out.println(" The value System.out.println(" The value System.out.println(" The value a++; b--; System.out.println(" System.out.println(" System.out.println(" System.out.println(" } }

Now, Now, Now, Now,

the the the the

args[])

of of of of of of

Arithmetic operators"); (a+b) is: " +(a+b)); (a-b) is: " +(a-b)); (a*b) is: " +(a*b)); (b+c) is: " +(b+c)); (a*c) is: " +(a*c));

second value of a is: " +a); second value of b is: " +b); final value of a is: " +(--a)); final value of b is: " +(++b));

$IWHUVDYLQJWKLVILOHDVDULWKPHWLFMDYDUXQWKHSURJUDP:HJHWWKHIROORZLQJRXWSXW 7KH8VDJHRI$ULWKPHWLFRSHUDWRUVDUHVKRZQEHORZ The value of (a+b) is: 30 The value of (a-b) is: 10 The value of (a*b) is: 200 The value of (b+c) is: 14.5 The value of (a*c) is: 90.0 Now, the second value of a is: 21 Now, the second value of b is: 9 Now, the final value of a is: 20 Now, the final value of b is: 10 Assignment operators

,Q-DYDWKHDVVLJQPHQWRSHUDWRUDSSOLHVWKHYDOXHRIWKHH[SUHVVLRQIURPWKHULJKWVLGHWRWKH YDULDEOHLQWKHOHIWVLGH:HFDQDOVRXVHWKHVH$VVLJQPHQWRSHUDWRUVLQWKHVKRUWFXWIRUPV)RU H[DPSOHWKHIROORZLQJWZRH[SUHVVLRQVZLOOJLYHWKHVDPHUHVXOW Comp-U-Learn

23

Java Programming I int int

xy = xy + 10 xy += 10

//using normal assignment // using shortcut assignment

7KHIROORZLQJWDEOHOLVWVWKHDVVLJQPHQWRSHUDWRUVDQGIXQFWLRQV Description Assign Addition Subtraction Multiplication Division Bitwise right Bitwise left Bitwise and Bitwise xor Bitwise or

Operator = += -= *= /= >>= <<= &= ^= |=

Function Assign right operand to left operand Add right from left & assign the value Subtract right from left & assign the value Multiply two values & assign it to left operand Divide two values & assign it to left operand Perform bitwise right shift Perform bitwise left shift Perform bitwise and operation Perform bitwise xor operation Perform bitwise or operation

Logical operators

/RJLFDORSHUDWRUVDUHXVHGWRHYDOXDWHDQH[SUHVVLRQWRFKHFNZKHWKHUWKHH[SUHVVLRQLVWUXHRU IDOVH6RWKHVHORJLFDORSHUDWRUVSHUIRUPWKHHYDOXDWLRQDQGUHWXUQWKHYDOXHDVD%RROHDQW\SH Description And Or

Operator && ||

Not

!

Function returns true if both operands are true returns true if any one of operands are true. returns reverse Boolean value of the expression

Comparison operators

7KHVHDUHXVHGWRFRPSDUHWKHRSHUDQGV$%RROHDQYDOXHLVUHWXUQHGZKHQXVLQJYDULDEOHVRU OLWHUDOV ZLWK WKH FRPSDULVRQ RSHUDWRUV &RQGLWLRQDO RSHUDWLRQ LV DOVR D VSHFLDO W\SH RI FRPSDULVRQ WKDW LV RQO\ ZLWK WKH DVVLJQPHQW RSHUDWRUV 7KH WDEOH JLYHQ EHORZ OLVWV WKH FRPSDULVRQRSHUDWRUV Description Less than Greater than Equal to 24

Operator < > ==

Function return true when result is less than return true when result is greater than the compared return true when result is equal Comp-U-Learn

Fundamentals of Java

Description Less than or equal to Greater than or equal to Not equal to Conditional

Operator <= >=

Function return true when result is less than or equal return true when result is greater than or equal

!= ?:

return true when result is not equal return first value of expression when result is true.

:H FDQ XVH WKHVH ORJLFDO ELWZLVH DQG FRPSDULVRQ RSHUDWRUV LQ WKH FRQGLWLRQDO VWDWHPHQWV ([DPSOHVLQWKHFRPLQJVHFWLRQVZLOOJLYHWKHXVDJHRIWKHVHRSHUDWRUV

Expression Evaluation & Operator Precedence $QH[SUHVVLRQLVDFROOHFWLRQRIYDULDEOHVDQGRSHUDWRUVWKDWVSHFLI\DFRPSXWDWLRQ([SUHVVLRQV DUHXVHGWRSHUIRUPRSHUDWLRQVRQWKHGDWDLQDSURJUDP7KHH[SUHVVLRQVDUHQRWVWDWHPHQWV )RUH[DPSOHFRQVLGHUWKHH[SUHVVLRQ int a= 20 * 3 + 7

,QWKHDERYHH[SUHVVLRQLQWHJHUDZLOOJHWDYDOXHRI:K\FDQ·WLWJHW"7KLVLVEHFDXVHWKH RSHUDWRUVKDYHSUHFHGHQFHLQWKLVH[SUHVVLRQ-DYDZLOOWUHDWWKHDERYHH[SUHVVLRQDV    ,IZHZDQWWKHYDOXHZHKDYHWRJLYHWKHH[SUHVVLRQDV int a= 20 * (3 + 7)

7KH RSHUDWRUV  DQG ² ZLOO KDYH VDPH SUHFHGHQFH $QG    KDYH HTXDO SUHFHGHQFH &RPSDULQJ WKHVH WZR JURXSLQJV RI SUHFHGHQFH WKH RSHUDWRUV   DQG  HQMR\ KLJKHU SUHFHGHQFHWKDQWKHRSHUDWRUVDQG

Scope of Variables ,QWKLVVHFWLRQZHZLOOOHDUQDERXWWKHVFRSHRIYDULDEOHVZLWKLQDSURJUDP$YDULDEOH·VVFRSHLV WKHEORFNRIFRGHZLWKLQZKLFKWKHYDULDEOHLVDFFHVVLEOH$OVRWKHVFRSHRIDYDULDEOHGHWHUPLQHV ZKHQWKHYDULDEOHLVFUHDWHGDQGGHVWUR\HG:HFDQHVWDEOLVKWKHVFRSHRIDSDUWLFXODUYDULDEOHDW WKHWLPHRIGHFODUDWLRQ7KHIROORZLQJDUHWKHPDLQW\SHRIVFRSHRIDYDULDEOH ♦ Local variable ♦ Member variable 7KH ORFDO YDULDEOHV DUH GHFODUHG ZLWKLQ D PHWKRG RU EORFN RI FRGH LQ D PHWKRG &RQVLGHU WKH H[DPSOH:HFDQVHHWKHYDULDEOHVDEDQGF7KH\DUHGHFODUHGZLWKLQWKHPDLQPHWKRG6R Comp-U-Learn

25

Java Programming I

ZH FDQ XVH WKHVH YDULDEOHV ZLWKLQ WKH PDLQ PHWKRG RQO\ ,Q JHQHUDO D  ORFDO YDULDEOH FDQ EH DFFHVVHGIURPLWVGHFODUDWLRQSDUWWRWKHHQGRIWKHFRGHEORFNLQZKLFKLWZDVGHFODUHG $ PHPEHU YDULDEOH LV D PHPEHU RI D FODVV RU DQ REMHFW DQG LV GHFODUHG ZLWKLQ D FODVV %XW LW VKRXOGQRWEHZLWKLQDQ\RIWKHFODVVPHWKRGV,IZHGHFODUHDYDULDEOHLQVLGHDPHWKRGZHFDQ DFFHVV WKDW YDULDEOH ZLWKLQ WKDW PHWKRG RQO\ :KLFK PHDQV LW ZLOO EH FRQVLGHUHG DV D ORFDO YDULDEOHRIWKDWPHWKRG7KHVWDWLFPHWKRGRIDFODVVFDQDFFHVVRQO\VWDWLFYDULDEOHVWKH\FDQ·W DFFHVVWKHYDULDEOHVZKLFKDUHGHFODUHGRWKHUZLVH

Commenting in Java ,Q -DYD SURJUDPV ZH FDQ FRPPHQW OLQHV E\ XVLQJ VLQJOH RU PXOWLSOH OLQH FRPPHQWLQJ V\QWD[ 8VLQJWKHIROORZLQJSURJUDPZHFDQXQGHUVWDQGWKHFRPPHQWLQJV\QWD[ Example 2.3: class comment { public static void main(String args[]) { int a=20; int b=10; // The following lines give us an idea about operators System.out.println(" The Usage of Arithmetic operators"); System.out.println(" The value of (a+b) is: " +(a+b)); System.out.println(" The value of (a-b) is: " +(a-b)); // Now a, b are going to be changed a++; b--; /* In the next two lines we are going to use the changed value of a, b and c */ System.out.println(" Now, the second value of a is: " +a); System.out.println(" Now,the second value of b is: " +b); } }

5XQWKHDERYHSURJUDPDQGVHHWKHRXWSXW2QO\SULQWVWDWHPHQWVJLYHQLQWKHSURJUDPZLOOEH SULQWHGLQWKHRXWSXW$Q\WKLQJWKDWDSSHDUVDIWHU´µXQWLOWKHHQGRIWKDWVLQJOHOLQHLVFDOOHG DVLQJOHOLQHFRPPHQWDQGLVLJQRUHGE\WKHMDYDFFRPSLOHU ,QDGGLWLRQDQ\WKLQJWKDWDSSHDUVDIWHU XSWR LVFDOOHGDVPXOWLSOHOLQHFRPPHQWLQJ:H FDQJLYHDQ\QXPEHURIOLQHVLQEHWZHHQWKH DQG 7KH-DYDFRPSLOHUZLOOLJQRUHDOOWKHVH OLQHV,QWKHDERYHH[DPSOHZHFDQVHHWZRW\SHVRIFRPPHQWLQJ

26

Comp-U-Learn

Fundamentals of Java

&RPPHQWVDUHDGGHGIRUWKHUHDGHUWRXQGHUVWDQGWKHSURJUDPEHWWHUWKH\DUHRIQRXVHWRWKH PDFKLQH7KHFRPSLOHULJQRUHVWKHVHFRPPHQWV:HFDQDOVRIROORZWKLVVW\OHLQRXUSURJUDPV WRPDNHRXU SURJUDP DQXQGHUVWDQGDEOHRQH:KHQZHZULWHDUHODWLYHO\ ELJJHU SURJUDP DQG UHDG LW DIWHU VL[ PRQWKV FRPPHQWV ZLOO SURYLGH D ORW RI LQIRUPDWLRQ WKDW ZRXOG RWKHUZLVH EH GLIILFXOWWRJXHVVIURPWKHSURJUDPDORQH

Decision Making /LNH DOO RWKHU SURJUDPPLQJ ODQJXDJHV -DYD KDV LWV RZQ SURJUDPPLQJ FRQVWUXFWV ,Q WKH IROORZLQJ VHFWLRQV ZH FDQ VHH YDULRXV -DYD SURJUDPPLQJ FRQVWUXFWV 7KHVH SURJUDPPLQJ FRQVWUXFWV LQFOXGHV WKH FRQGLWLRQDO VWDWHPHQWV FRQWURO VWDWHPHQWV DQG YDULRXV ORRSV %HIRUH JRLQJWRWKHVHWKLQJVZHKDYHWRXQGHUVWDQGWKHFRQFHSWRIGHFLVLRQPDNLQJ &RPSXWHUVDUHXVHIXOQRWRQO\EHFDXVHWKH\KDYHWKHDELOLW\WRVWRUHDQGPDQLSXODWHQXPEHUV EXW DOVR EHFDXVH WKH\ KDYH WKH DELOLW\ WR SLFN XS WKH ULJKW DOWHUQDWLYH E\ PHDQV RI GHFLVLRQ PDNLQJ(YHU\SURJUDPPLQJODQJXDJHRIIHUVDIDFLOLW\WRZULWHGRZQDOWHUQDWLYHVWREHIROORZHG ,Q -DYD WKHUH LV QR H[FHSWLRQ WR WKDW -DYD SURYLGHV WKH WZR SURJUDPPLQJ FRQVWUXFWV LI DQG VZLWFKVWDWHPHQWV 8VLQJ WKH ORJLFDO RSHUDWRUV DQG FRPSDULVRQ RSHUDWRUV ZH FDQ FUHDWH D FRQVWUXFW IRU GHFLVLRQ PDNLQJ0RVWRIWKHVHGHFLVLRQPDNLQJLVGRQHGHSHQGLQJXSRQWKHUHWXUQYDOXHWKDWLVHLWKHU WUXHRUIDOVH :KHQ LVXVHGWKHULJKWGHFLVLRQZLOOEHFDUULHGRXWGHSHQGLQJRQWKHIROORZLQJUHWXUQW\SH LIERWKVWDWHPHQWVDUHWUXH True && true = true True && false = false False && true = false False && false = false :KHQ__ $1' RSHUDWRULVXVHGLQRXUFRQGLWLRQDOVWDWHPHQWVWKHULJKWGHFLVLRQZLOOEHGRQH LIDQ\RQHWKHVWDWHPHQWVLVWUXH7KHGHVFULSWLRQIROORZV True || true = true True || false = true False || true = true False || false = false

Comp-U-Learn

27

Java Programming I

$OVRZHFDQXVHWKHVHFRQGLWLRQVMRLQWO\OLNH WUXH IDOVH __WUXH 7KHUHWXUQW\SHRIWKH DERYHFRQGLWLRQZLOOEHWUXH7KHRWKHURSHUDWRUZLOOZRUNDVIROORZV (true) = ! true = false !(false) = ! false = true if… and If.. else statements

7KLV LV D FRQGLWLRQDO VWDWHPHQW WKDW H[HFXWHV WKH ILUVW VHW RI VWDWHPHQWV LI WKH FRQGLWLRQ LV WUXH DQGWKHVWDWHPHQWIROORZLQJHOVHLIWKHFRQGLWLRQLVIDOVH7KHVHLIHOVHFDQEHQHVWHGDWDQ\OHYHO 7KHV\QWD[LV if (condition) { statements } else { statements }

7KHIROORZLQJH[DPSOHZLOOJLYHWKHXVDJHRIWKHLIDQGLI«HOVHVWDWHPHQWV Example 2.4 class sample { public static void main(String args[]) { int mark1=73; int mark2=60; { if ((mark1>=75) && (mark2>=75)) { System.out.println("Grade A"); } else if (((mark1>=50) && (mark2>=50)) && ((mark1<=74) && (mark2<=74))) { System.out.println("Grade B"); } else { System.out.println("Grade C"); } } } }

28

Comp-U-Learn

Fundamentals of Java

7KHRXWSXWRIWKHDERYHSURJUDPZLOOEH*UDGH%%HFDXVHWKHJLYHQPDUNDQGPDUNEHORQJV WRWKHVHFRQGFRQGLWLRQ

For loop ,QDIRUORRSZHKDYHWRSDVVWKUHHSDUDPHWHUVVHSDUDWHGE\VHPLFRORQVIROORZHGE\WKHVHWRI VWDWHPHQWVWREHH[HFXWHGGXULQJWKHORRSRSHUDWLRQ The syntax is for (initialization; condition; increment ) { Statements }

♦ In the initialization part, we have to initialize the variable, which can be a new one declared as any of the datatypes. ♦ In second part, we have to give an expression as a condition. The return value of this expression may be true or false. Depending upon the return value, the loop statements will be executed. ♦ Last part is used to increase/decrease the counter variable. It is also optional and can be updated programmatically within the loop statements. ♦ The loop will be terminated when the condition becomes false. The following example illustrates the use of for loop. Example 2.5 class loop_example { public static void main(String args[]) { for (int i=1; i<=5;i++) { System.out.println("This is No: " +i +" execution!"); } System.out.println("Loop terminated!"); } }

7KHRXWSXWZLOOEH This is No: This is No:

1 execution! 2 execution!

Comp-U-Learn

29

Java Programming I This is No: 3 execution! This is No: 4 execution! This is No: 5 execution! For Loop terminated!

While & Do… While Loop :KLOHORRSH[HFXWHVWKHVWDWHPHQWVXQWLODQH[SUHVVLRQLVWUXH:KHQWKHFRQGLWLRQLVQRORQJHU WUXHH[HFXWLRQFRQWLQXHVIURPWKHILUVWVWDWHPHQWDIWHUWKHZKLOHVWDWHPHQWV 7KHV\QWD[LV while (condition)

{ statements } ,QDGRZKLOHORRSWKHH[SUHVVLRQLVHYDOXDWHGRQO\DIWHUDOOWKHVWDWHPHQWVDUHH[HFXWHGDWOHDVW RQFH7KHV\QWD[LV do { statements } while(condition);

7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKHXVDJHRIZKLOHORRS:H·OOJHWWKHRXWSXWVLPLODUWRWKH SUHYLRXVRQH Example 2.6 class loop1 { public static void main(String args[]) { int i=1; // Initialization while(i<=5) // Condition { System.out.println("This is No: " +i +" execution!"); i++; // Incrementation } System.out.println("While Loop terminated!"); } }

30

Comp-U-Learn

Fundamentals of Java

Switch & Break Statements 7KRXJKZHFDQXVH,I«HOVHVWDWHPHQWVWRGHDOZLWKPXOWLSOHFRQGLWLRQVZHFDQXVHWKHVZLWFK VWDWHPHQWVEHFDXVHWKH\DUHPRUHHIILFLHQWVLPSOHHDV\DQGUHDGDEOH7KLVRSHUDWRUDOORZVXVWR JURXS WRJHWKHU WKH FRQGLWLRQ DQG DVVRFLDWHG DFWLRQ WR SHUIRUP  :KHQ WKH EUHDN NH\ZRUG LV HQFRXQWHUHGWKHUHVWRIWKHFRQGLWLRQVRIWKHVZLWFKDUHQRWHYDOXDWHG7KHV\QWD[IRUWKHVZLWFK VWDWHPHQWLV switch (variable) { case(value1): statements break; case(value2): statements break; default: statements break; }

Break

7KLV EUHDN NH\ZRUG WHUPLQDWHV WKH FXUUHQW IRU ZKLOH DQG VZLWFK SDVVHV WKH FRQWURO WR WKH ILUVW VWDWHPHQWDIWHUWKHORRS7KHPDLQXVHRIEUHDNLVWREUHDNWKHORRSDQGFRQWLQXHWKHH[HFXWLRQ RIWKHUHPDLQLQJVWDWHPHQWVDIWHUWKHORRS 7KHV\QWD[LV While(condition) { statements break; /* After executing the above the loop will be terminated.*/ }

statements

Continue

,QFRQWLQXHWKHFRQWUROSDVVHVWRWKHFRQGLWLRQLQDZKLOHORRSDQGWRWKHXSGDWHH[SUHVVLRQLQD IRUORRS

Note The important difference between the break and continue is that the loop is not terminated in continue. 7KHIROORZLQJH[DPSOHEULHIO\LOOXVWUDWHVWKHVZLWFKVWDWHPHQWZLWKXVLQJEUHDNNH\ZRUG,WDOVR JLYHVWKHRXWSXWDV´7KXUVGD\µ Comp-U-Learn

31

Java Programming I

Example 2.7 class var_usage { public static void main(String args[]) { int i=5; switch(i) { case 1: System.out.println("Sunday!"); break; case 2: System.out.println("Monday!"); break; case 3: System.out.println("Tuesday!"); break; case 4: System.out.println("Wednesday!"); break; case 5: System.out.println("Thursday!"); break; case 6: System.out.println("Friday!"); break; case 7: System.out.println("Saturday!"); break; default: System.out.println("Holiday!"); break; } } }

Arrays in Java $QDUUD\LQ-DYDLVDQHIIHFWLYHPHDQVRIVWRULQJDFROOHFWLRQRUVHULHVRUDJURXSRIYDULDEOHVDQG UHIHUULQJWRWKHPE\DFRPPRQQDPH7KHQXPEHURIYDOXHVWKDWFDQEHVWRUHGLQDQDUUD\LV FDOOHGDUUD\VL]H(DFKYDULDEOHLVFDOOHGDVDUUD\HOHPHQWRULWHP7KHUHDUHWKUHHVWHSVWRFUHDWH DQDUUD\GHFODUDWLRQPHPRU\DOORFDWLRQDQGLQLWLDOL]DWLRQ Array declaration

/LNHDYDULDEOHZHKDYHWRGHFODUHDQDUUD\XVLQJWKHIROORZLQJV\QWD[7KHDUUD\PD\EHRIDQ\ GDWDW\SH

32

Comp-U-Learn

Fundamentals of Java <array type> <array name>

Example: int [] array1; double [] array2;

Memory allocation

$IWHU GHFODULQJ DQ DUUD\ ZH KDYH WR DOORFDWH WKH PHPRU\ IRU WKDW DUUD\ 2QO\ WKHQ DUH ZH DFWXDOO\FUHDWLQJDQDUUD\7KHQHZNH\ZRUGLVXVHGIRUWKLV7KHV\QWD[LV <array name> = new <array type with no of items> e.g.:array1 = new int[4]; array2 = new double[7];

Array initialization

$IWHUWKHGHFODUDWLRQDQGWKHPHPRU\DOORFDWLRQZHFDQLQLWLDOL]HWKHDUUD\HOHPHQWVLQGLYLGXDOO\ RUWRWDOO\:HFDQLQLWLDOL]HDQDUUD\XVLQJWKHLQGH[YDOXHZKLFKVWDUWVIURPWRODVWEXWEHIRUH WKHDUUD\HOHPHQW7RDFFHVVDSDUWLFXODUDUUD\HOHPHQWZHKDYHWRXVHWKHFRUUHVSRQGLQJLQGH[ YDOXH7KHV\QWD[LV array1[0]=1; array1[1]=2; and so on upto n-1 th element.

$OVRZHFDQGRDOOWKUHHRSHUDWLRQVDWWKHVDPHWLPHDVSHUWKHIROORZLQJH[DPSOHFRGH

int[]

array1 = new int[4]; double array2[] = new double[7];

Multidimensional Array

-DYDGRHVQRWVXSSRUWPXOWLGLPHQVLRQDODUUD\+RZHYHUDQDUUD\RIDUUD\VFDQEHFUHDWHG7KLV FDQEHGRQHZLWKDQLQGLYLGXDODUUD\LQLWLDOL]DWLRQ)RUH[DPSOHDWZRGLPHQVLRQDODUUD\FDQEH FUHDWHGDV VD\$UUD\ Array1[0][0]=20; Array1[0][1]=34; Array1[1][0]=23; Array1[1][1]=45;

DQGVRRQ

Comp-U-Learn

33

Java Programming I

Strings in Java 6WULQJV DUH VHTXHQFHV RI FKDUDFWHUV ,Q -DYD 6WULQJV DUH LQVWDQFHV RI WKH FODVV 6WULQJ :KHQ D VWULQJ OLWHUDO LV XVHG LQ WKH SURJUDP -DYD DXWRPDWLFDOO\ FUHDWHV DQ REMHFW RI WKH 6WULQJ FODVV 6WULQJVDUHXQXVXDOLQWKLVDVSHFW 7KHUHDUHYDULRXVPHWKRGVDYDLODEOHLQ6WULQJFODVV)UHTXHQWO\XVHGRQHVDUHHTXDOVOHQJWKDQG VXEVWULQJ7KHHTXDOVFRPSDUHVD6WULQJREMHFWZLWKWKHJLYHQREMHFWDQGUHWXUQVWUXHLIWKH\DUH HTXDO7KHQH[WRQHLVXVHGWRUHWXUQWKH6WULQJOHQJWK7KHVXEVWULQJLVXVHGIRUH[WUDFWLRQ 7KHIROORZLQJ H[DPSOH LOOXVWUDWHV DOO WKH GHWDLOV UHJDUGLQJ DQ DUUD\ EDVLFV DQG DERXW WKH 6WULQJ FODVV Example 2.8 class exarray { public static void main(String args[]) { int array1[] = {10,20,30}; // integer type array declaration and initialization // The following are the String type array declaration and initialization String array2[] = {"First","Second","Third"}; String sample=”Hai! Students!”; for (int i=0; i<=2; i++) { System.out.println("The " +array2[i] +" element is: " +array1[i]); } System.out.println("The Extracted String is: " +(sample.substring(0,4))); } }

7KHRXWSXWZLOOEHDVIROORZV The First element is: 10 The Second element is: 20 The Third element is: 30 The Extracted String is: Hi!

34

Comp-U-Learn

Fundamentals of Java

Summary In this session we have learnt various Java data types, literals, reserved words and identifiers. Now we have a brief idea about operators and expression evaluation using operator precedence. We also tried our hands on decision making using if.. else statement, switch statement and various loops such as for/while. At the end of this session, we learnt all the concepts regarding arrays and strings in Java. We have a full-fledged knowledge about Java fundamentals and Java programming constructs.

Going Over It Again I. Fill in the Blanks

 BBBBBBBBBBBVWDWHPHQWLVXVHGWRSULQWVRPHWH[WRQWKHVFUHHQ  7KHERROHDQOLWHUDOVDUHBBBBBBBBBBBDQGBBBBBBBBBBBB  ,QIRUORRSBBBBBBBBBBBBBBBBBBBBDQGBBBBBBBBBBBDUHWKHSDUDPHWHUV  7KHVXEVWULQJPHWKRGLVXVHGIRUVWULQJBBBBBBBBBBB  ,QGHFLVLRQPDNLQJWKHULJKWGHFLVLRQZLOOEHWDNHQGHSHQGLQJRQWKHBBBBBBBBW\SH

II. State True or False

 $YDULDEOHFDQKDYHWKHVDPHQDPHDVWKDWRIDQ\UHVHUYHGZRUG  ([SUHVVLRQHYDOXDWLRQGHSHQGVRQWKHRSHUDWRUSUHFHGHQFH  ,Q-DYDPXOWLSOHOLQHFRPPHQWFDQEHGRQHE\ DQG   :KHQWKHEUHDNNH\ZRUGLVHQFRXQWHUHGWKHUHVWRIWKHFRQGLWLRQVRIWKHVZLWFKZLOOQRWEH H[HFXWHG  $UUD\VDUHSULPLWLYHGDWDW\SHV  -DYDVXSSRUWVPXOWLGLPHQVLRQDODUUD\V

Comp-U-Learn

35

Java Programming I III. One line Answers

 :KDWDUHWKHWZRGDWDW\SHVDYDLODEOH"  :KDWLVDOLWHUDOLQ-DYD"  ([SODLQORFDOYDULDEOHV  :KDWLVWKHXVHRI RSHUDWRU"  /LVWRXWWKHPHWKRGVDYDLODEOHLQ6WULQJFODVV IV. Define the Following

 3ULPLWLYHGDWDW\SH  5HIHUHQFHGDWDW\SHV  ,GHQWLILHUV  $UUD\V  0HPEHUYDULDEOH

36

Comp-U-Learn

Session 3

OOPs In Java

On Completion of this Session We will be able to understand...

) Traditional Programming Model ) Object Oriented Programming Approach ) Basic concepts of OOPs and its features ) Java Programming using OOPs ) Understanding various modifiers in Java ) Super and Sub classes ) Constructors and overloaded constructors ) Garbage collection in

In This Session...



Traditional Programming Model



Object Oriented Programming Approach



Features of Object Oriented Programming



Basic concepts of OOPS



Creating Classes and Objects in Java



Constructors



Garbage Collection



Finalize Method



Inheritance



Polymorphism



Recursion



Advantages of OOPs in Java

OOPs In Java

Traditional Programming Model %HIRUHDSSO\LQJWKHSURJUDPPLQJFRQVWUXFWVLQ-DYDZKLFKZHKDYHVHHQLQWKHODVWVHVVLRQZH QHHG WR NQRZ DERXW WKH FRQFHSWV RI 2EMHFW 2ULHQWHG 3URJUDPPLQJ ,Q WKLV VHFWLRQ DQG WKH VXFFHHGLQJRQHVZHDUHJRLQJWROHDUQDERXW223DQGLWVKLVWRU\,QODWHUVHVVLRQVZH·OODSSO\ WKHVH223FRQFHSWVLQ-DYD ,Q HDUOLHU GD\V WUDGLWLRQDO SURJUDPPLQJ XVLQJ KLJK OHYHO ODQJXDJHV VXFK DV &2%2/ )2575$1DQG&ZHUHFRPPRQO\NQRZQDVSURFHGXUHRULHQWHGSURJUDPPLQJ7KLVPHWKRGRI SURJUDPPLQJWKRXJKVWUXFWXUHGZDVQRWPHHWLQJPRVWRIWKHUHTXLUHPHQWVRISURJUDPPHUV,Q WKLV DSSURDFK WKH LPSHWXV LV JLYHQ RQO\ WR WKH VHTXHQFH RI WKLQJV WR EH GRQH ZKLFK LV DFFRPSOLVKHG WKURXJK D QXPEHU RI IXQFWLRQV ,W DOVR DLPV WR SURYLGH D WRS GRZQ PRGXODU DSSURDFKLQSURJUDPPLQJPHWKRGRORJ\$W\SLFDOVWUXFWXUHRIDSURFHGXUHRULHQWHGSURJUDPLV VKRZQEHORZ

Main Program

Function 1

Function 2

Function 3

Function 4

Fig 3.1

7KHIROORZLQJDUHWKHFRQVWUDLQWVWKDWZHUHHQFRXQWHUHGLQWKHSURFHGXUDODSSURDFK ♦ Greater emphasis is laid on the process of the application (Sequences involved to do the task). This means that more stress is enforced on the function or methods and not on the data.

Comp-U-Learn

39

Java Programming I

♦ The procedural approach does not model real world problems very well because the functions are action oriented. They don’t really correspond to the elements of the problem. ♦ Modules are tightly inter-woven, inter dependent and difficult to separate. As a result of this inter-dependency between modules, modification of one program could affect all other programs that depend on it. This led to the complexity of code especially for huge programs. ♦ Most often, applications with almost similar features have to be re-written and recompiled resulting in higher software maintenance costs as the applications lack portability to run in multiple servers and in heterogeneous environments. ♦ Most functions use global data resulting in the data moving around the system openly throughout all modules. When functions transform data from one form to another, the true state and nature of the data is not available throughout all the modules. 7KHPDMRUPRWLYDWLQJIDFWRULQWKHLQYHQWLRQRI2EMHFW2ULHQWHGDSSURDFKLVWRVDOYDJHVRPHRI WKHIODZVHQFRXQWHUHGLQWKHSURFHGXUDODSSURDFK223ODQJXDJHVVXFKDV&6PDOOWDON-DYD HWFRYHUFRPHWKHVHGUDZEDFNV7KH\DUHPRGHOHGDIWHUUHDOZRUOGFKDUDFWHULVWLFVDQGKHQFHDUH VLPSOHDQGHDV\WRXQGHUVWDQG

Object Oriented Programming Approach 223WUHDWVGDWDDVDFULWLFDOHOHPHQWLQWKHSURFHVVRISURJUDPGHYHORSPHQWDQGGRHVQRWDOORZ LWWRIORZIUHHO\DURXQGWKHV\VWHP,WWLHVGDWDPRUHFORVHO\WRWKHIXQFWLRQVWKDWRSHUDWHRQLW DQG SURWHFWV LW IURP DFFLGHQWDO PRGLILFDWLRQV IURP RXWVLGH IXQFWLRQV 223 DOORZV XV WR GHFRPSRVH D SUREOHP LQWR D QXPEHU RI HQWLWLHV FDOOHG REMHFWV DQG WKHQ EXLOGV GDWD DQG IXQFWLRQV DURXQG WKHVH HQWLWLHV 7KH RUJDQL]DWLRQ RI GDWD DQG IXQFWLRQV LQ REMHFW RULHQWHG SURJUDPVLVVKRZQEHORZ

40

Comp-U-Learn

OOPs In Java

Object A

Object B

Data

Data

Function

Function

Functio

Data

Object C

Fig. 3.2

Features of Object Oriented Programming 1. 2. 3. 4. 5. 6. 7. 8.

Emphasis is more on data rather than procedure. Programs are divided into what are known as objects. Data structures are designed so that they characterize objects. Functions that operate on data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be easily added whenever necessary. Follows bottom-up approach in program design.

Note

2EMHFW RULHQWHG SURJUDPPLQJ LV DQ DSSURDFK WKDW SURYLGHV D ZD\ RI PRGXODUL]LQJSURJUDPVE\FUHDWLQJSDUWLWLRQHGPHPRU\DUHDIRUERWKGDWDDQG IXQFWLRQVWKDWFDQEHXVHGDVWHPSODWHVIRUFUHDWLQJFRSLHVRIVXFKPRGXOHVRQ GHPDQG

Comp-U-Learn

41

Java Programming I

+HUHZH FRQVLGHU DQ REMHFW WR DFFHVV DQG RSHUDWH RQ D SDUWLWLRQHG DUHD RI FRPSXWHU PHPRU\ WKDWVWRUHVGDWDDQGDVHWRIRSHUDWLRQVWKDWFDQDFFHVVWKDWGDWD6LQFHPHPRU\SDUWLWLRQV DUH LQGHSHQGHQWWKHREMHFWVFDQEHXVHGLQDYDULHW\RIGLIIHUHQWSURJUDPVZLWKRXWPRGLILFDWLRQV

Basic Concepts of OOPS $Q\223ODQJXDJHVKRXOGVXSSRUWWKHIROORZLQJIHDWXUHV-DYDVXSSRUWVWKHVH223VFRQFHSWV H[FHSWIHZRILWVLQWHUQDOSURSHUWLHV ♦ Classes ♦ Objects ♦ Data Abstraction ♦ Data Encapsulation ♦ Inheritance ♦ Polymorphism Classes

$ FODVV LV D WHPSODWH WKDW GHILQHV WKH YDULDEOHV DQG WKH PHWKRGV FRPPRQ WR DOO REMHFWV RI D FHUWDLQNLQG)RUH[DPSOHOHWXVFRQVLGHUGLIIHUHQWNLQGVRIRUQDPHQWVVXFKDVULQJVEDQJOHV EUDFHOHWVFKDLQVVWXGVHWF$OORIWKHPKDYHDJHQHUDOEHKDYLRUDQGVWDWH$OOWKHVHMHZHOVFDQ EHSXWXSLQWRDEURDGHUFDWHJRU\FDOOHGMHZHOVRURUQDPHQWV+HQFHLQWKLVFDVHZHFDOO-HZHOV RURUQDPHQWVDVDFODVV

Note A class is a user-defined datatype that encompasses the entire set of data and code of an object. Objects

2EMHFWV FDQ EH UHDO RU LPDJLQDU\ 7KH\ DUH WKH LQVWDQFHV RI FODVVHV 2EMHFWV DUH WKH EDVLF UXQ WLPHHQWLWLHVLQDQREMHFWRULHQWHGV\VWHP7KH\PD\EHDSHUVRQDSODFHDEDQNDFFRXQWDWDEOH RI GDWD RU DQ\ LWHP WKDW WKH SURJUDP PXVW KDQGOH ,Q VRIWZDUH WHUPV DQ REMHFW LV D VRIWZDUH EXQGOH RI YDULDEOHV DQG UHODWHG PHWKRGV 3UREOHPV LQ SURJUDPPLQJ DUH DQDO\]HG LQ WHUPV RI REMHFWV DQG WKH QDWXUH RI FRPPXQLFDWLRQ EHWZHHQ WKHP 3URJUDP REMHFWV VKRXOG EH FKRVHQ VXFKWKDWWKH\PDWFKFORVHO\ZLWKWKHUHDOZRUOGREMHFWV

42

Comp-U-Learn

OOPs In Java

Note Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code. Examples of objects are 5HDOREMHFWV²0DUXWKL9DQRXUFODVVURRPEDOOHWF ,PDJLQDU\²5HFRUG2UJDQL]DWLRQHWF &RPSOH[²'DWDEDVHVSUHDGVKHHWVSDFNDJHVHWF 2QFH D FODVV LV GHILQHG ZH FDQ FUHDWH DQ\ QXPEHU RI REMHFWV EHORQJLQJ WR WKDW FODVV (DFK REMHFW LV DVVRFLDWHG ZLWK WKH GDWD RI W\SH FODVV ZLWK ZKLFK WKH\ DUH FUHDWHG )RU H[DPSOH PDQJRDSSOHDQGRUDQJHDUHPHPEHUVRIWKHFODVVIUXLW&ODVVHVDUHXVHUGHILQHGGDWDW\SHVDQG EHKDYHOLNHWKHEXLOWLQW\SHVRIDSURJUDPPLQJODQJXDJH7KHV\QWD[XVHGWRFUHDWHDQREMHFWLV QRGLIIHUHQWWKDQWKHV\QWD[XVHGWRFUHDWHDQLQWHJHUREMHFWLQ&,IIUXLWKDVEHHQGHILQHGDVD FODVVWKHQWKHVWDWHPHQW )UXLWPDQJR ZLOO FUHDWH DQ REMHFW PDQJR EHORQJLQJ WR WKH FODVV IUXLW 7KLV FRXOG EH H[SODLQHG IXUWKHU E\ FRPSDULQJZLWK int k;

+HUHNLVDQREMHFWRILQWHJHUGDWDW\SHDQGKDVDOOWKHSURSHUWLHVSHUWDLQLQJWRDQLQWHJHU Data Abstraction

$EVWUDFWLRQUHIHUVWRWKHDFWRIUHSUHVHQWLQJHVVHQWLDOIHDWXUHVZLWKRXWLQFOXGLQJWKHEDFNJURXQG GHWDLOV RU H[SODQDWLRQV &ODVVHV XVH WKH FRQFHSW RI DEVWUDFWLRQ DQG DUH GHILQHG DV D OLVW RI DEVWUDFWDWWULEXWHVVXFKDVVL]HZHLJKWFRVWDQGIXQFWLRQVWRRSHUDWHRQWKHVHDWWULEXWHV7KH\ HQFDSVXODWHDOOWKHHVVHQWLDOSURSHUWLHVRIWKHREMHFWVWKDWDUHWREHFUHDWHG6LQFHWKHFODVVHVXVH WKHFRQFHSWRIGDWDDEVWUDFWLRQWKH\DUHNQRZQDV$EVWUDFW'DWD7\SHV $'7 )RUH[DPSOH LIZHWDNHPDQJRDVDQREMHFWWKHQWKHSURSHUWLHVVXFKDVFRORUWDVWHYDULHW\FRVWVL]HHWFDUH QRW H[SOLFLWO\ TXRWHG RQ WKH IDFH RI PHUHO\ VD\LQJ LW DV D )UXLW 7KHVH SURSHUWLHV DUH WRWDOO\ HQFDSVXODWHGLQ)UXLW+HQFHZHFDOOLWRQO\DV)UXLWDQGWKHLQKHUHQWSURSHUWLHVRIWKHIUXLWDUH WRWDOO\KLGGHQLQVLGHE\PDNLQJWKHWHUP)UXLWDEVWUDFW 7KHUHDUHWZRNLQGVRI$EVWUDFWLRQ ♦ Data Abstraction ♦ Functional abstraction Comp-U-Learn

43

Java Programming I

,IZHWDNHDFDUDVDQH[DPSOHIRUDFODVVWKHQ Data Abstraction

(QJLQHQXPEHUVSHHGHWF Functional Abstraction

6WDUW6WRSHWF Data Encapsulation

7KH ZUDSSLQJ XS RI GDWD DQG IXQFWLRQV LQWR D VLQJOH XQLW FDOOHG FODVV  LV NQRZQ DV HQFDSVXODWLRQ 'DWD HQFDSVXODWLRQ LV WKH PRVW VWULNLQJ IHDWXUH RI D FODVV 7KH GDWD LV QRW DFFHVVLEOH WR WKH RXWVLGH ZRUOG DQG RQO\ WKRVH IXQFWLRQV ZKLFK DUH ZUDSSHG LQ WKH FODVV FDQ DFFHVVLW7KHVHIXQFWLRQVSURYLGHWKHLQWHUIDFHEHWZHHQWKHREMHFW·VGDWDDQGWKHSURJUDP7KLV LQVXODWLRQ RI WKH GDWD IURP GLUHFW DFFHVV E\ WKH SURJUDP LV FDOOHG GDWD KLGLQJ (QFDSVXODWLRQ HPERGLHVLQIRUPDWLRQKLGLQJ

Creating Classes and Objects in Java ,Q-DYDZHFDQFUHDWHDQREMHFWE\FUHDWLQJDQLQVWDQFHRIDFODVV)RUH[DPSOH Date today=new Date(); Rectangle rect=new Rectangle();

+HUH'DWHLVDEXLOWLQFODVVDYDLODEOHLQWKHMDYDXWLOSDFNDJHWRGD\LVDYDULDEOHRIW\SH'DWH DQGLVLQLWLDOL]HGXVLQJWKHQHZRSHUDWRU1RWHWKDWWKHQHZRSHUDWRULQVWDQWLDWHGWKH'DWHFODVV E\FUHDWLQJDQHZREMHFWIRU'DWHDQGWKHQLQLWLDOL]HVLW ,WLVQRWHVVHQWLDOWKDWHYHU\WLPHDQREMHFWFUHDWLRQVKRXOGKDYHVLPXOWDQHRXVLQLWLDOL]DWLRQDOVR ,WLVSRVVLEOHWRKDYHRQO\REMHFWFUHDWLRQDORQH Example 3:1 Date

today;

7KHJHQHUDOV\QWD[LV Classname Objectname;

/HWXVWDNHDQRWKHUH[DPSOH 796HWV6RQ\3KLOLSV 44

Comp-U-Learn

OOPs In Java

+HUHZHKDYHFUHDWHGWZRREMHFWVRIWKHFODVV796HWV7KH\FDQEHLQLWLDOL]HGRUWKH\FDQEHVHW WRQXOO +RZWR,QLWLDOL]H" Sony=new TVSets; Philips=Sony;

2EMHFWV FDQ HLWKHU EH LQLWLDOL]HG WKURXJK WKH QHZ RSHUDWRU RU LW FDQ DOVR EH LQLWLDOL]HG XVLQJ DQRWKHU LQVWDQFH 7KH QHZ RSHUDWRU LV XVHG IRU DOORFDWLQJ PHPRU\ WR WKH REMHFW ,Q WKLV FDVH ERWK 6RQ\ DQG 3KLOLSV UHIHU WR WKH VDPH REMHFW 1RZ DVVXPLQJ WKH PHWKRGV 3OD\ 0XWH &RQWUDVWDUHLQWKH796HWVFODVVWKH\FDQEHLQYRNHGDV Sony.Play(); Philips.Contrast();

+RZWR,QLWLDOL]HWR1XOO Sony=null;

Note Local object variables are not automatically initialized to null. We must initialize them, either by calling new or by setting them to null. Creating a Class in Java

$ FODVV LV D EOXHSULQW RU SURWRW\SH WKDW FDQ EH XVHG WR FUHDWH PDQ\ REMHFWV 7KH FODVV FRQVWUXFWLRQKDVWZRSKDVHV ♦ Class Declaration ♦ Class Body Class Declaration

$ FODVV GHFODUDWLRQ PXVW FRQWDLQ WKH FODVV NH\ZRUG DQG WKH QDPH RI WKH FODVV WKDW LV WR EH GHILQHG class ClassName { ........... .......... ........... }

Comp-U-Learn

45

Java Programming I

$W\SLFDOFODVVGHFODUDWLRQZLOOEHOLNHWKLV >PRGLILHUV@FODVV&ODVV1DPH>H[WHQGVVXSHU&ODVV1DPH@>LPSOHPHQWV,QWHUIDFH1DPHV@ { ............................ ....................... };

7KH LWHPV EHWZHHQ > DQG @ DUH RSWLRQDO &ODVV QDPHV PXVW EH D OHJDO -DYD LGHQWLILHU DQG E\ FRQYHQWLRQ EHJLQ ZLWK D FDSLWDO  OHWWHU :H ZLOO VHH HDFK RQH RI WKHP LQ GHWDLO 2I WKH DERYH PHQWLRQHG FODVV GHFODUDWLRQ IRUPDW RQO\ WKH FODVV  NH\ZRUG DQG WKH FODVV QDPH DUH YHU\ LPSRUWDQW DQG PRVW UHTXLUHG 7KH RWKHU LWHPV DUH RSWLRQDO ,I ZH GRQ·W PDNH DQ H[SOLFLW GHFODUDWLRQIRUWKHRSWLRQDOLWHPVWKH-DYDFRPSLOHUDVVXPHVFHUWDLQGHIDXOWVDQRQILQDOQRQ SXEOLFQRQDEVWUDFWVXEFODVVHVRI2EMHFWWKDWLPSOHPHQWVQRLQWHUIDFHV

Class Modifiers

$PRGLILHULVRWKHUZLVHFDOOHGDQDFFHVVVSHFLILHU7KH\GHILQHWKHVFRSHRIWKHFODVVDQGDOVRWKH XVDJHRIWKH REMHFWV RIWKDWSDUWLFXODUFODVV $ FODVV FDQ KDYH DQ\ RI WKUHH PRGLILHUV ² SXEOLF DEVWUDFWRUILQDO 7KHSXEOLFPRGLILHUGHFODUHVWKDWWKHFODVVFDQEHXVHGE\REMHFWVRXWVLGHWKHFXUUHQWSDFNDJH %\GHIDXOWDFODVVFDQRQO\EHXVHGE\RWKHUFODVVHVLQWKHVDPHSDFNDJHLQZKLFKLWLVGHFODUHG

Note Package is a collection of classes grouped together. Packages are convenient for organizing our work and separating our code libraries provided with others. 7KHDEVWUDFWPRGLILHUGHFODUHVWKDWWKHFODVVLVDQDEVWUDFWFODVV$QDEVWUDFWFODVVLVXVHGZKHQ ZHQHHGDPRUHJHQHULFFODVVDQGSUREDEO\PRUHDEVWUDFW$EVWUDFWFODVVHVDUHQRWLQVWDQWLDWHG 7KDWLVLIDFODVVLVGHFODUHGDVDEVWUDFWQRREMHFWVRIWKDWFODVVFDQEHFUHDWHG:HZLOOKDYHWR H[WHQGWKDWFODVVLQRUGHUWRFUHDWHDQLQVWDQFHRIWKHFODVV$EVWUDFWFODVVHVFDQKDYHFRQFUHWH GDWDIXQFWLRQVDQGDOVRPD\FRQWDLQVRPHDEVWUDFWPHWKRGVDOVR$QDEVWUDFWFODVVPXVWKDYH DWOHDVWRQHDEVWUDFWPHWKRG &ODVVHVWKDWFDQQRWEHSDUHQWFODVVHVDUHFDOOHGILQDOFODVVDQGZHXVHWKHILQDOPRGLILHULQWKH GHILQLWLRQRIWKHFODVVWRLQGLFDWHWKLV)LQDONH\ZRUGLVXVHGWRSUHYHQWLQKHULWDQFH&ODVVHVDUH PDGHILQDOIRUWKHSXUSRVHRIHIILFLHQF\DQGIRUVHFXULW\UHDVRQV

46

Comp-U-Learn

OOPs In Java

Super Class and Sub Classes

6XSHUFODVVHVDQG6XEFODVVHVDUHWKHPHDQVWKURXJKZKLFKLQKHULWDQFHLVLPSOHPHQWHGLQ-DYD 7KHSDUHQWRUWKHEDVHFODVVLVFDOOHGD6XSHUFODVV7KHGHULYHGFODVVLVFDOOHGD6XEFODVV-DYD XVHV WKH H[WHQGV NH\ZRUG LQ RUGHU WR LPSOHPHQW LQKHULWDQFH ,QKHULWDQFH LQ -DYD LV SXEOLF LQ QDWXUH Example 3.2 class Employee { ........ .......... } class Manager extends Employee { ............ ............. }

+HUHWKHFODVV0DQDJHULVDGHULYHGFODVVDQGFODVV(PSOR\HHLVDEDVHFODVV Object Class – The universal Super Class

7KHREMHFWFODVVLVWKHXOWLPDWHDQFHVWRUYHU\FODVVLQ-DYDH[WHQGV2EMHFW+RZHYHUWKHUHLV QRQHHGWRVD\ class Employee extends Object

6LQFHWKHXOWLPDWHSDUHQWFODVV2EMHFWLVWDNHQIRUJUDQWHGLIQRSDUHQWLVH[SOLFLWO\PHQWLRQHG 2EMHFWFODVVLVORFDWHGLQWKHSDFNDJHMDYDODQJ(YHU\FODVVLQ-DYDH[WHQGVIURP2EMHFW6RPH PHWKRGVLQWKH2EMHFWFODVVDUHDVIROORZV public Boolean equals(Object obj)

7KLV PHWKRG WHVWV ZKHWKHU RU QRW RQH REMHFW LV HTXDO WR DQRWKHU 7KH HTXDOV PHWKRG DV LW LV LPSOHPHQWHG LQ WKH 2EMHFW SDUHQW FODVV GHWHUPLQHV ZKHWKHU RU QRW WZR REMHFWV SRLQW WR WKH VDPHDUHDRIPHPRU\ $QRWKHU LPSRUWDQW PHWKRG LQ 2EMHFW LV WKH WR6WULQJ PHWKRG WKDW UHWXUQV D VWULQJ WKDW UHSUHVHQWV WKH YDOXH RI WKLV REMHFW 7KH WR6WULQJ PHWKRG LV XQLTXH IRU DQ LPSRUWDQW UHDVRQ  ZKHQHYHU DQ REMHFW LV FRQFDWHQDWHG ZLWK D VWULQJ XVLQJ WKH ´µ RSHUDWRU WKH -DYD FRPSLOHU

Comp-U-Learn

47

Java Programming I

DXWRPDWLFDOO\LQYRNHVWKHWR6WULQJPHWKRGWRREWDLQDVWULQJUHSUHVHQWDWLRQRIWKHREMHFW)RU H[DPSOH Date today=new today(1998,12,26); String last=“ Today date is “ + today; //automatically invokes today.toString public Object clone()

7KLV LV XVHG WR FORQH WKH REMHFW E\ DOORFDWLQJ PHPRU\ DQG FRS\LQJ WKH FXUUHQW REMHFW LQWR LW &ORQLQJLVQRWKLQJEXWPDNLQJDELWE\ELWFRS\,WLVVLPSO\DQRWKHUREMHFWZLWKWKHVDPHEDVH W\SHVDQGILHOGV The class called Class

-DYD PDLQWDLQV D 5XQ 7LPH 7\SH ,GHQWLILFDWLRQ ZKLFK NHHSV WUDFN RI WKH FODVV WR ZKLFK HDFK REMHFW EHORQJV 7KLV HQVXUHV WKDW WKH FXUUHQW PHWKRGV DUH VHOHFWHG DW UXQWLPH 7KH FODVV WKDW KROGVWKLVLQIRUPDWLRQLVFDOOHG&ODVV7KHJHW&ODVV PHWKRGRI2EMHFWUHWXUQVDQLQVWDQFHRI WKLVFODVV Class Body

7KHFODVVERG\FRPSRQHQWRIDFODVVLPSOHPHQWDWLRQFDQLWVHOIFRQWDLQWZRGLIIHUHQWVHFWLRQV 9DULDEOHGHFODUDWLRQV 0HWKRGV class ClassName { Membervariable Declarations Method Declarations }

Member Variable Declarations

$PHPEHUYDULDEOHGHFODUDWLRQORRNVOLNHWKLV >DFFHVVVSHFLILHU@>VWDWLF@>ILQDO@>WUDQVLHQW@>YRODWLOH@GDWDW\SHYDULDEOH1DPH $PHPEHUYDULDEOHGHFODUDWLRQGHILQHVWKHIROORZLQJDVSHFWVRIDYDULDEOH $FFHVVVSHFLILHUGHILQHVZKLFKRWKHUFODVVHVKDYHDFFHVVWRWKHYDULDEOH7KHIROORZLQJLVWKHOLVW RIPRGLILHUVWKDWFDQEHXVHGZLWKWKHPHWKRGVDQGPHPEHUYDULDEOHGHFODUDWLRQVLQ-DYD

48

Comp-U-Learn

OOPs In Java

Public

7KHNH\ZRUGSXEOLFPHDQVWKDWDQ\FODVVLQDQ\SDFNDJHFDQ DFFHVVWKHYDULDEOHVRUPHWKRGV 0HWKRGVGHFODUHGDVSXEOLFDUHDFFHVVLEOHWRDOO Example 3:3 public void shape() { }

Protected

$Q\FODVVLQWKHVDPHSDFNDJHDVWKHFODVVLQZKLFKLWLVGHFODUHGFDQDFFHVVSURWHFWHGYDULDEOHV RUPHWKRGV)RUH[DPSOHLQSDFNDJH3DFN class A { protected int min; }

+HUHPLQFDQEHXVHGE\DQ\FODVVLQWKHSDFNDJH3DFNLUUHVSHFWLYHRIZKHWKHUWKH\KDYHEHHQ GHULYHGRUQRW$OVRZKHQWKHUHDUHDQ\RWKHUFODVVHVWKDWKDYHEHHQGHULYHGIURPFODVV$WKH\ FDQPDNHXVHRIWKHSURWHFWHGGDWD´LQWPLQµHYHQWKRXJKWKHVXEFODVVHVPD\UHVLGHLQRWKHU SDFNDJHV QRWLQ3DFN Private

3ULYDWH YDULDEOHV RU PHWKRGV FDQ RQO\ EH DFFHVVHG ZLWKLQ WKH FRQILQHV RI  WKH GHFODULQJ FODVV 2QO\ WKH PHPEHUV DQG PHWKRGV RI WKDW SDUWLFXODU FODVV FDQ DFFHVV WKH SULYDWH GDWD 1R RWKHU PHWKRGVFODVVHVDQGQRWHYHQVXEFODVVHVZKHWKHULQVLGHRURXWVLGHWKHSDFNDJHFDQKDYHDFFHVV WRWKHSULYDWHGDWD class Hour { private int hr, min, sec; private void input(); }

+HUHWKHPHWKRGLQSXWFDQPDNHXVHRIWKHSULYDWHGDWDKUPLQDQGVHF Static

:KHQZHZDQWDPHWKRGWREHDFODVVPHWKRGXVHWKHVWDWLFNH\ZRUGLQWKHPHWKRGGHFODUDWLRQ 6WDWLFILHOGVGRQRWFKDQJHIURPRQHLQVWDQFHRIDFODVVWRDQRWKHU6WDWLFPHWKRGVEHORQJWRD

Comp-U-Learn

49

Java Programming I

FODVVDQGGRQRWRSHUDWHRQDQ\LQVWDQFHRIDFODVV6WDWLFPHWKRGVFDQRQO\DFFHVVVWDWLFILHOGV 6WDWLFLQLWLDOL]DWLRQRFFXUVZKHQWKHFODVVLVILUVWORDGHG6WDWLFPHWKRGVFDQQRWEHRYHUORDGHG 6WDWLFPHWKRGVEHORQJWRDFODVVDQGGRQRWRSHUDWHRQDQ\LQVWDQFHRIWKHFODVV Example 3.4 class Myclass { static private int i; static public int output() { return i; } static public void input(int j) { i=j; } }

Note Overloading refers to the existence of more than one function with the same name but with different function signature. The parameters passed to a method is called its signature. Final

9DULDEOHV RU PHWKRGV GHFODUHG DV ILQDO FDQQRW EH RYHUORDGHG RU FKDQJHG &ODVV YDULDEOHV DUH RIWHQ XVHG ZLWK WKH NH\ZRUG ILQDO WR GHILQH FRQVWDQWV 7KLV RIIHUV EHWWHU PHPRU\ HIILFLHQF\ WKDQ ILQDO LQVWDQFH YDULDEOHV EHFDXVH FRQVWDQWV FDQQRW FKDQJH $ ILQDO PHWKRG KDV DQ LPSOHPHQWDWLRQ WKDW ZLOO QRW EH FKDQJHG DQ\ZKHUH LQ  WKH PRGXOH DQG LV FULWLFDO WR WKH FRQVLVWHQWVWDWHRIWKHREMHFW)LQDOPHWKRGVFDQQRWEHRYHUULGGHQLQWKHVXEFODVVHV Transient

7UDQVLHQW YDULDEOHV DUH QRW SDUW RI WKH REMHFWV SHUVLVWHQW VWDWH ,W PDUNV WKH GDWD  QRW WR EH SHUVLVWHQW 0HPEHU YDULDEOHV WKDW DUH SDUW RI WKH SHUVLVWHQW VWDWH RI DQ REMHFW PXVW EH VDYHG ZKHQWKHREMHFWLVDUFKLYHG:HXVHWKHWUDQVLHQWNH\ZRUGWRLQGLFDWHWKDWWKHSDUWLFXODUYDULDEOH LVQRWSDUWRIWKHSHUVLVWHQWVWDWHRIWKHREMHFW class Some { transient int hai; }

50

Comp-U-Learn

OOPs In Java

Volatile

7KLVPHDQVWKDWWKHYDULDEOHLVPRGLILHGLQYDULDEO\E\GLIIHUHQWPHWKRGVZLWKRXWDQ\FRUUHODWLRQ ,WLVQRWXVHGFRPPRQO\7KHIROORZLQJYDULDEOHGHFODUDWLRQLVDQH[DPSOHRIKRZWRGHFODUH WKDWDYDULDEOHFDQEHPRGLILHGDV\QFKURQRXVO\ Example 3.5 class Anything { volatile int r; }

Implementing Methods in Java

$PHWKRGLPSOHPHQWDWLRQFRQWDLQVWZRSDUWV ♦ Method declaration ♦ Method body Method Declaration

$PHWKRGGHFODUDWLRQSURYLGHVDORWRILQIRUPDWLRQDERXWWKHPHWKRGWRWKHFRPSLOHUWKHUXQ WLPHV\VWHPDQGWRRWKHUFODVVHVDQGREMHFWV7KLVFRQWDLQVWKHQDPHRIWKHPHWKRGWKHUHWXUQ W\SHRIWKHPHWKRGWKHW\SHRIDUJXPHQWVUHTXLUHGE\WKHPHWKRGDQGWKHPRGLILHUVIRUWKDW PHWKRG Method body

7KLV FRQWDLQV WKH FRGH VHJPHQW WR EH H[HFXWHG E\ WKH PHWKRG ,Q FDVH WKH SDUWLFXODU PHWKRG UHWXUQVDQ\YDOXHWKHQWKHERG\ZLOOFRQWDLQWKHUHWXUQNH\ZRUG Example 3.6 class some { public int dummy(int a) { int b=a+5; return b; } }

7KHUHWXUQYDOXHYRLGVLJQLILHVWKDWWKHPHWKRGZLOOQRWUHWXUQDQ\YDOXH,QWKHDERYHH[DPSOH WKH PHWKRG GXPP\ DFFHSWV DQ LQWHJHU YDULDEOH DV DQ DUJXPHQW -DYD VXSSRUWV PHWKRG RYHUORDGLQJ 7KH PHWKRG WKDW KDV D VDPH QDPH DV WKDW RI WKH FODVV LV FDOOHG WKH FRQVWUXFWRU 0HWKRGVFDQDOVREHRYHUULGGHQ Comp-U-Learn

51

Java Programming I

7KLVPHDQVWKDWWKHPHWKRGVLQWKHVXSHUFODVVHVFDQEHZULWWHQLQWKHVXEFODVVHVZLWKUHOHYDQW FKDQJHVWRPHHWWKHQHHGVRIWKHVXEFODVV%XWLQWKLVFDVHWKHRYHUULGLQJPHWKRGPXVWKDYH WKHVDPHQDPHUHWXUQW\SHDQGSDUDPHWHUOLVWLVWKHPHWKRGLWRYHUULGHV,Q-DYDDUJXPHQWVDUH SDVVHG E\ YDOXH RQO\ WR WKH PHWKRGV 3DVVLQJ YDULDEOHV E\ YDOXHV DVVXUHV WKDW WKH PHWKRGV XQLQWHQWLRQDOO\FDQQRWPRGLI\DYDULDEOH·VYDOXHWKDWLVRXWVLGHLWVVFRSH

Note When a method returns a value, the datatype of the value returned by the return statement must match the datatype that the method is actually returning. There cannot be a mismatch in the declaration and in the actual return statement. $VLPSOHH[DPSOHKHUHWRVKRZKRZWRFDOODPHWKRGLQ-DYD class ex2 { public static void main(String args[]) { System.out.println(" We are in the main function "); System.out.println(); System.out.println("Call to the method sample "); sample(); System.out.println(); System.out.println("Back to main function "); } static void sample() { int a= 10; a= a* 10; System.out.println("Now we are in the sample method "); System.out.println(a); } }

2XWSXW2IWKHSURJUDP We are in the main function Call to the method sample Now we are in the sample method 100 Back to main function

Note A method is a collection of statements that performs a series of operations. In languages like C, they are called functions.

52

Comp-U-Learn

OOPs In Java

Constructors &RQVWUXFWRUVDUHVSHFLDOPHWKRGVSURYLGHGLQHDFK-DYDFODVVWKDWDUHUHVSRQVLEOHIRULQLWLDOL]LQJ QHZREMHFWVRIWKDWW\SH7KHQHZRSHUDWRUFUHDWHVWKHREMHFWDQGWKHFRQVWUXFWRULQLWLDOL]HVLW$ FODVV PD\ SURYLGH PXOWLSOH FRQVWUXFWRUV WR SHUIRUP GLIIHUHQW NLQGV RI LQLWLDOL]DWLRQ RQ QHZ REMHFWV$FRQVWUXFWRUWKDWWDNHVQRDUJXPHQWVLVFDOOHGDGHIDXOWFRQVWUXFWRU7KLVLVLQYRNHG DXWRPDWLFDOO\ZKHQWKHREMHFWLVLQLWLDOL]HG Example 3.7 Date today=new Date(); TVSets Philips=new TVSets(); TVSets Sony=new Sony();

:KHQ WKH FRQVWUXFWRU WDNHV DUJXPHQWV LW LV FDOOHG DQ RYHUORDGHG FRQVWUXFWRU 7KH FRPSLOHU PDNHV WKH GHFLVLRQ UHJDUGLQJ LQYRFDWLRQ RI WKH DSSURSULDWH FRQVWUXFWRU GHSHQGLQJ XSRQ WKH W\SHDQGWKHQXPEHURIDUJXPHQWVSDVVHGWRLW7KLVFRQFHSWLVFDOOHGRYHUORDGLQJ

Note Overloading refers to the concept where there are more than one function with the same name but with different parameters. These parameters may differ in number, sequence and data type of the arguments. Calls to the functions are bound according to the nature of the arguments passed. Examples 3.8 Date today = new Date(1998,10,28); TVSets Sony = new Sony(14,Portable); Rectangle rect = new Rectangle(10,10,200,200);

+HUH WRGD\ REMHFW LV LQLWLDOL]HG ZLWK DUJXPHQWV \HDU PRQWK DQG GD\ 7KH FRQVWUXFWRU  ZLWK WKUHHDUJXPHQWVDYDLODEOHLQ'DWHFODVVLVLQYRNHG$QHZUHFWDQJOHUHFWRIVL]H ZLOOEHFUHDWHGDQGLQLWLDOL]HG Referring an Object variable

/HWXVVD\WKDWZHZDQWWRPRYHWKHUHFWDQJOHWRDQHZORFDWLRQ&KDQJLQJ WKHUHFWDQJOHWRD QHZORFDWLRQFRXOGEHGRQHE\WKHIROORZLQJPHWKRGV ♦ Manipulate the object’s variables directly rect.x=80; rect.y=100;

Comp-U-Learn

53

Java Programming I

ZKHUH[\DUHWKHQHZORFDWLRQVRIWKHUHFWDQJOH *HQHUDOV\QWD[ ObjectReference.Variable

♦ Call the move method which is available in the Rectangle class rect.move(80,100);

7KLVVWDWHPHQWZLOOPRYHWKHREMHFWUHFWWRDQHZORFDWLRQ0HWKRGFDOOVDUHGLUHFWHGDWD VSHFLILF REMHFW WKH REMHFW VSHFLILHG LQ WKH PHWKRG FDOO LV WKH REMHFW WKDW UHVSRQGV WR WKH LQVWUXFWLRQ 0HWKRG FDOOV DUH NQRZQ DV PHVVDJHV ,Q WKH H[DPSOH RQ 3RO\PRUSKLVP ZKLFK LV JRLQJWREHGHDOWODWHUZLOOH[SODLQWKHEDVLFFRQFHSWVRI&RQVWUXFWRUV

Garbage Collection 0DQ\REMHFWRULHQWHGODQJXDJHVUHTXLUHWKDWZHNHHSWUDFNRIDOOWKHREMHFWVZHFUHDWHDQGFDQ GHVWUR\ WKHP ZKHQ ZH QR ORQJHU QHHG WKHP :ULWLQJ FRGH WR PDQDJH PHPRU\ LQ WKLV ZD\ LV WHGLRXVDQGRIWHQHUURUSURQH-DYDWDNHVFDUHRIWKLVPHPRU\PDQDJHPHQWWHFKQLTXH7KH-DYD UXQWLPHHQYLURQPHQWGHOHWHVREMHFWVZKHQLWGHWHUPLQHVWKDWWKH\DUHQRORQJHUEHLQJXVHG7KLV SURFHVVLVNQRZQDVJDUEDJHFROOHFWLRQ$QREMHFWLVHOLJLEOHIRUJDUEDJHFROOHFWLRQZKHQWKHUH DUH QR PRUH UHIHUHQFHV WR WKDW REMHFW 5HIHUHQFHV WKDW DUH KHOG LQ D YDULDEOH DUH QDWXUDOO\ GURSSHGZKHQWKHYDULDEOHJRHVRXWRIVFRSH7KHJDUEDJHFROOHFWRUUXQVV\QFKURQRXVO\ZKHQ WKHV\VWHPUXQVRXWRIPHPRU\RULQUHVSRQVHWRDUHTXHVWIURPD-DYDSURJUDP-DYD3URJUDPV FDQDVNIRUWKHJDUEDJHFROOHFWRUWRUXQDWDQ\WLPHE\FDOOLQJ6\VWHPJF  7KHILQDOL]H PHWKRGZLOOEHFDOOHGEHIRUHWKHJDUEDJHFROOHFWRUVZHHSVDZD\WKHREMHFW&DOOWKH VWDWLFPHWKRG6\VWHPUXQ)LQDOL]HUV2Q([LW 758( WRJXDUDQWHHWKDWILQDOL]HUPHWKRGVDUHFDOOHG EHIRUH -DYD VKXWV GRZQ $VNLQJ WKH JDUEDJH FROOHFWLRQ WR UXQ GRHV QRW JXDUDQWHH WKDW RXU REMHFWVZLOOEHJDUEDJHFROOHFWHG

Finalize Method %HIRUHDQREMHFWLVJDUEDJHFROOHFWHGWKHUXQWLPHV\VWHPFDOOVLWVILQDOL]HPHWKRG,WLVLQWHQGHG WRUHOHDVHV\VWHPUHVRXUFHVVXFKDVRSHQILOHVRURSHQVRFNHWVEHIRUHJHWWLQJFROOHFWHG2XUFODVV FDQSURYLGHIRUILQDOL]DWLRQVLPSO\E\GHFODUDWLRQRIDPHWKRGFDOOHGILQDOL]HDQGLPSOHPHQWLQJ LW)RU([DPSOH protected void finalize() { … statements }

54

Comp-U-Learn

OOPs In Java

Inheritance ,Q UHDO OLIH ZH FDQ REVHUYH LQKHULWDQFH DOPRVW HYHU\ZKHUH $ FKLOG IRU H[DPSOH WDNHV RQ WKH FKDUDFWHULVWLFV RI WKH SDUHQWV ,QKHULWDQFH LV WKH PHFKDQLVP WKURXJK ZKLFK D FODVV FDQ EH GHILQHG LQ WHUPV RI DQ H[LVWLQJ FODVV ,QKHULWDQFH LV WKH SURFHVV E\ ZKLFK REMHFWV RI RQH FODVV DFTXLUH WKH SURSHUWLHV RI REMHFWV RI DQRWKHU FODVV ,W VXSSRUWV WKH FRQFHSW RI KLHUDUFKLFDO FODVVLILFDWLRQ7KHIROORZLQJH[DPSOHVKRZVWKHSURSHUW\LQKHULWDQFHRIREMHFWV

Vehicles Attributes: Have engine Carry people Carry luggage Used for transport

Four Wheelers

Two Wheelers

Attributes :

Attributes :

Cars

Jeep

Motor Bikes

Scooters

Attributes:

Attributes:

Attributes:

Attributes:

Fig 3.3 ,Q2236WKHFRQFHSWRILQKHULWDQFHSURYLGHVWKHLGHDRIUHXVDELOLW\7KLVPHDQVWKDWZHFDQ DGGDGGLWLRQDOIHDWXUHVWRDQH[LVWLQJFODVVZLWKRXWPRGLI\LQJLW7KLVLVSRVVLEOHE\GHULYLQJD QHZ FODVV IURP WKH H[LVWLQJ RQH 7KH QHZ FODVV ZLOO KDYH WKH FRPELQHG IHDWXUHV RI ERWK WKH FODVVHV)RUH[DPSOHKHUH9HKLFOHVLVDEURDGFDWHJRU\ZKLFKH[SODLQVWKHYDULRXVDWWULEXWHVRI DOOWKHYHKLFOHVFRPPRQO\7KLVFRXOGEHIXUWKHUGLYLGHGLQWRWZRVSHFLILFFDWHJRULHVOLNH7ZR Comp-U-Learn

55

Java Programming I

ZKHHOHUV DQG )RXU ZKHHOHUV %RWK WKHVH FODVVHV ZLOO KDYH WKH SURSHUWLHV RI WKH JHQHUDO FODVV ´9HKLFOHVµ$JDLQWZRZKHHOHUVFODVVFRXOGEHGHULYHGRUEURNHQLQWRFODVV´0RWRU%LNH´DQG FODVV´6FRRWHUV´ZKLFKKDYHWKHVSHFLILFDWWULEXWHVRIWKHVHWZRW\SHVRIYHKLFOHV7KXVWKURXJK LQKHULWDQFHZHDUHDEOHWRJHQHUDWHDQHZFODVVIURPDQH[LVWLQJRQH7KHSURSHUWLHVFRPPRQWR ERWK WKHVH FODVVHV DUH QRW UHZULWWHQ EXW DUH UHXVHG ,QKHULWDQFH HQDEOHV WKH UHILQHPHQW RU VSHFLDOL]DWLRQRIDQH[LVWLQJFODVV7KRXJKDFKLOGLQKHULWVWKHFKDUDFWHULVWLFVIURPLWVSDUHQWVLW DOVRKDVLWVRZQIHDWXUHV $ FODVV FDQ LQKHULW WKH DWWULEXWHV RI WZR RU PRUH FODVVHV 0XOWLSOH LQKHULWDQFH DOORZV XV WR FRPELQHWKHIHDWXUHVRIVHYHUDOH[LVWLQJFODVVHVDVDVWDUWLQJSRLQWIRUGHILQLQJQHZFODVVHV,WLV OLNHDFKLOGLQKHULWLQJWKHFRORURIWKHIDWKHUDQGWKHIDFHFXWRIWKHPRWKHU

Mammals

Birds

Platypus

Fig 3.4 ,QWKLVH[DPSOHLIPDPPDOVDQGELUGVDUHWZRFODVVHVWKHQSODW\SXVH[KLELWVWKHFKDUDFWHULVWLFV RIERWKWKHVHFODVVHV Note Java does not support multiple inheritance due to difficulty in maintaining and keeping track of the code. ,Q-DYDZHFDQLQKHULWDVXSHUFODVVE\WKH.H\ZRUGH[WHQGV7KHIROORZLQJH[DPSOHLOOXVWUDWHV LQKHULWDQFHLQ-DYD class base { public String name="Peter"; public int age=23; }

56

Comp-U-Learn

OOPs In Java class base1 extends base { private int acc_no=4566; public void disp() { System.out.println("The name is : " +name); System.out.println("The Age is : " +age); System.out.println("The account No. is : " +acc_no); } public static void main(String args[]) { base1 b = new base1(); b.disp(); } }

6DYHWKHILOHDVEDVHMDYD7KHRXWSXWLVDVIROORZV The name is : Peter The Age is : 23 The account No. is : 4566

Polymorphism 3RO\PRUSKLVPLV\HWDQRWKHULPSRUWDQW223FRQFHSW3RO\PHDQVPDQ\0RUSKPHDQVIRUPV 3RO\PRUSKLVPPHDQVWKHDELOLW\WRWDNHPRUHWKDQRQHIRUP)RUH[DPSOHLIZHWDNHPRYHDV DQRSHUDWLRQWKHQWKHPDQZDONVILVKVZLPVELUGVIO\DQGZRUPVFUDZO7KLVLVQRWKLQJEXWDQ RSHUDWLRQ H[KLELWLQJ GLIIHUHQW EHKDYLRU LQ GLIIHUHQW LQVWDQFHV 7KH EHKDYLRU GHSHQGV XSRQ WKH W\SHVRIGDWDXVHGLQWKHRSHUDWLRQ )RUH[DPSOHFRQVLGHUWKHRSHUDWLRQRIGUDZLQJ)RUGUDZLQJYDULRXVVKDSHVZHFDQXVHVDPH GUDZ  PHWKRG E\ JLYLQJ WKH FRUUHVSRQGLQJ SDUDPHWHUV 7KLV LV FDOOHG 2YHUORDGLQJ %DVLFDOO\ 223 VXSSRUWV )XQFWLRQ RYHUORDGLQJ DQG 2SHUDWRU RYHUORDGLQJ %XW -DYD GRHV QRW VXSSRUW 2SHUDWRURYHUORDGLQJ 3RO\PRUSKLVPLVH[SODLQHGFOHDUO\LQWKHIROORZLQJGLDJUDP

Comp-U-Learn

57

Java Programming I Shape Draw()

Circle Object

Box Object

Triangle Object

Draw(Circle)

Draw(Box)

Draw(Triangle)

Fig 3.5 /HWXVORRNDWDFRPSOHWHH[DPSOHRIDFODVVLQ-DYD7KLVH[SODLQVWKHFRQFHSWRI&RQVWUXFWRUV DQG2YHUORDGLQJFRQFHSWRI3RO\PRUSKLVP Example 3.9 // Creation of a

Class called AddSub

class AddSub { int num1,num2; public AddSub() { num1=20; num2=10; System.out.println("Default constructor invoked "); } public AddSub(int x, int y) { num1=x; num2=y; System.out.println("Overloaded Constructor Invoked "); } public int AddNum() { int num3; num3=num1 + num2; return num3; } public int SubNum()

58

Comp-U-Learn

OOPs In Java { int num3; num3=num1-num2; return num3; } } public class ex3 { public static void main(String args[]) { AddSub a=new AddSub(); AddSub b=new AddSub(60,50); System.out.println(" The value of num1 of object a is "+ a.num1); System.out.println(" The value of num2 of object a is "+ a.num2); System.out.println(); System.out.println(" The result of addition of object a is "+a.AddNum()); System.out.println(); System.out.println(" The result of subtraction of object a is "+a.SubNum()); System.out.println(); System.out.println(" The value of num1 of object b is "+ b.num1); System.out.println(" The value of num2 of object b is "+ b.num2); System.out.println(); System.out.println(" The result of addition of object b is "+b.AddNum()); System.out.println(); System.out.println(" The result of subtraction of object b is "+b.SubNum()); } }

2XWSXWRIWKH3URJUDPLVVKRZQEHORZ Default constructor invoked Overloaded Constructor Invoked The value of num1 in object a is 20 The value of num2 in object a is 10 The The The The The The

result of addition of object a is result of subtraction of object a value of num1 in object b is 60 value of num2 in object b is 50 result of addition of object b is result of subtraction of object b

30 is 10

110 is 10

Comp-U-Learn

59

Java Programming I Keywords this & super

,QDPHWKRGWKHNH\ZRUGWKLVUHIHUVWRWKHREMHFWRQZKLFKWKHPHWKRGRSHUDWHV:KHQWKLVLV XVHGLQVLGHDFRQVWUXFWRUWKHQWKHFRQVWUXFWRUFDOOVDQRWKHUFRQVWUXFWRURIWKHVDPHFODVV7KLV LVDFDOOWRRQHRIWKHFXUUHQWREMHFWV$JDLQLWLVUHTXLUHGRQO\ZKHQWKHUHLVDQDPELJXLW\LQWKH PHWKRGQDPHDQGLVRIWHQXVHGWRPDNHWKHLQWHQWRIWKHFRGHFOHDUHU)RUH[DPSOH class Book { int NoPages; int Weight; Book(int NoPages, int Weight) { this.NoPages=NoPages; this.weight=Weight; } }

Super

7KHNH\ZRUGVXSHUDOZD\VUHIHUVWRWKHVXSHUFODVV Example 3.10 class Employee { int salary; Employee(int i) { this.salary=i; } } class Manager extends Employee { Manager(int l) { super(l); }

+HUHWKHVXSHULVXVHGWRFDOOWKHFRQVWUXFWRURIWKHEDVHFODVV,QVKRUWWKHVXSHUUHIHUVWKHEDVH FODVV,QFDVHRIRYHUULGLQJWKHEDVHFODVVPHWKRGVLQWKHVXEFODVVHVWKHVXEFODVVHVPD\FDOOWKH EDVHFODVVPHWKRGXVLQJ Super.BaseClassMethodName();

60

Comp-U-Learn

OOPs In Java

Recursion 5HFXUVLRQLVDJHQHUDOPHWKRGZKHUHE\DIXQFWLRQFDOOVLWVHOILQDUHSHDWHGIDVKLRQ7KLVFRXOG EH H[SODLQHG DV D UHFXUVLYH PHWKRG UHSHDWHGO\ FDOOLQJ LWVHOI XQWLO D VSHFLILF FULWHULRQ LV PHW :KHQ WKH FRQGLWLRQ EHFRPHV IDOVH WKH UHFXUVLRQ WHUPLQDWHV 7KHUH DUH DFWXDOO\ WZR W\SHV RI UHFXUVLRQSRVVLEOH 'LUHFW5HFXUVLRQ+HUHWKHVXESURJUDPVFDOOVRQO\LWVHOI ,QGLUHFW5HFXUVLRQ+HUHDVXESURJUDPFDOOVDQRWKHUVXESURJUDPZKLFKLQWXUQFDOOVWKHILUVW VXESURJUDP Example 3.11 Direct Recursion Static int recu(int x) { if (x=1) return x; else return x * recursion(x-1); } Indirect Recursion Static int even (int x) { if )x=0) return true; else return odd(x-1); } static int odd(int x) { if(x=0) return false; else return even(x-1); }

Accessor and Mutator Methods

0HWKRGV WKDW FKDQJH LQVWDQFH ILHOGV DUH FDOOHG PXWDWRU PHWKRGV DQG WKRVH WKDW ZLOO DFFHVV LQVWDQFH ILHOGV ZLWKRXW PRGLI\LQJ WKHP DUH FDOOHG DFFHVVRU PHWKRGV 7KH FRQYHQWLRQ XVHG LQ -DYDLVWRXVHWKHORZHUFDVHSUHIL[JHWIRUDFFHVVRUPHWKRGVDQGVHWIRUPXWDWRUPHWKRGV

Comp-U-Learn

61

Java Programming I

Example of Accessor methods are as follows : int getDate() int getMonth() int getYear()

Example of Mutator methods are as follows : void setDate(int) void setMonth(int) void setYear(int)

Message Communication

$QREMHFWRULHQWHGSURJUDPFRQVLVWVRIDVHWRIREMHFWVWKDWFRPPXQLFDWHZLWKHDFKRWKHU7KH SURFHVV RI SURJUDPPLQJ LQ DQ REMHFWRULHQWHG ODQJXDJH WKHUHIRUH LQYROYHV WKH IROORZLQJ EDVLF VWHSV &UHDWLQJFODVVHVWKDWGHILQHREMHFWVDQGWKHLUEHKDYLRU &UHDWLQJREMHFWVIURPFODVVGHILQLWLRQV (VWDEOLVKLQJFRPPXQLFDWLRQDPRQJREMHFWV $PHVVDJHIRUDQREMHFWLVDUHTXHVWIRUH[HFXWLRQRIDSURFHGXUHDQGWKHUHIRUHZLOOLQYRNHD IXQFWLRQ SURFHGXUH  LQ WKH UHFHLYLQJ REMHFW WKDW JHQHUDWHV WKH GHVLUHG UHVXOW 0HVVDJH SDVVLQJ LQYROYHV VSHFLI\LQJ WKH QDPH RI WKH REMHFW WKH QDPH RI WKH IXQFWLRQ PHVVDJH  DQG WKH LQIRUPDWLRQWREHVHQW

Note Message passing supports all possible interactions between objects. Objects that send and receive messages need not be in the same process or even in the same machine

Advantages of OOPS in Java 7KURXJKLQKHULWDQFHZHFDQHOLPLQDWHUHGXQGDQWFRGHDQGH[WHQGWKHXVHRIH[LVWLQJFODVVHV :HFDQPDNHXVHRIWKHH[LVWLQJPRGXOHVWREXLOGRWKHUSURJUDPVLIWKH\ZDQWWRFRPPXQLFDWH ZLWKRQHDQRWKHUUDWKHUWKDQGHYHORSLQJWKHPRGXOHIURPWKHVFUDWFK 7KH SULQFLSOH RI GDWD KLGLQJ KHOSV WKH SURJUDPPHU WR EXLOG VHFXUH SURJUDPV WKDW FDQQRW EH WDPSHUHGE\RWKHUSURJUDPVRUHYHQWKHRWKHUFRGHLQWKHVDPHSURJUDP 62

Comp-U-Learn

OOPs In Java

,WLVSRVVLEOHWRKDYHPXOWLSOHLQVWDQFHVRIDQREMHFWWRFRH[LVWZLWKRXWDQ\LQWHUIHUHQFH ,WLVHDV\WRSDUWLWLRQWKHZRUNLQDSURMHFWEDVHGRQSURMHFWV 2EMHFWRULHQWHGV\VWHPVFDQEHHDVLO\XSJUDGHGIURPVPDOOWRODUJHV\VWHPV 0HVVDJH SDVVLQJ WHFKQLTXHV IRU FRPPXQLFDWLRQ EHWZHHQ REMHFWV PDNHV WKH LQWHUIDFH GHVFULSWLRQVZLWKH[WHUQDOV\VWHPVPXFKVLPSOHU $OOFODVVHVDQGREMHFWVWKHUHRIFDQEHWUHDWHGDVVHSDUDWHPRGXOHV7KLVPDNHVGHVLJQLQJVLPSOHU ,QKHULWDQFHHQDEOHVXVLQUHXVDELOLW\RIDFRGH 7KHVRIWZDUHV\VWHPEDVHGRQ223LVFORVHWRUHDOZRUOGDQGKHQFHVLPSOHWRXQGHUVWDQG Summary In this session, we learnt basic concepts, advantages and features of OOP. We are able to apprise the traditional programming model with the Object oriented approach. The application of OOP in Java, the concept of super and sub classes tries to bring forth inheritance in Java. Also the usage of the various modifiers like public, private, abstract, final, static, volatile, transient will enable the programmer to achieve an absolute proficiency and have an concrete knowledge of OOP. The garbage collection in Java frees the programmer from worrying about the pains of memory leakage.

Going Over It Again I. Fill in the Blanks

 $FODVVFRQWDLQVBBBBBBBBBBBBBBBBBBBDQGBBBBBBBBBBBBBBBBBBBBBBBBB  BBBBBBBBBBBBBBBBBVSHFLILHUSUHYHQWVLQKHULWDQFHLQ-DYD  BBBBBBBBBBBBBBBBBBBDQGBBBBBBBBBBBBBBBBBBBBBDUHWKHWZRNLQGVRIDEVWUDFWLRQ  7KHBBBBBBBBLVXVHGWRLQLWLDOL]HDQGDOORFDWHPHPRU\WRWKHREMHFWV  BBBBBBBBBBBBBBBBBLVWKHXQLYHUVDOVXSHUFODVVLQ-DYDIRUDOOREMHFWV  7KHWZRW\SHVRIUHFXUVLRQDUHBBBBBBBBBBBBBBBBBBBBDQGBBBBBBBBBBBBBBBBBBBBBB

Comp-U-Learn

63

Java Programming I II. State True or False

 7KHWUDGLWLRQDOPRGHOGRHVQRWVLPXODWHUHDOZRUOGSUREOHPV  -DYDVXSSRUWVPXOWLSOHLQKHULWDQFH  &RQVWUXFWRUVDUHLQYRNHGDWWKHHQGRIWKHFODVV  7KHPHWKRGWR6WULQJ LVDYDLODEOHLQWKH'DWHFODVV  3ULYDWHDFFHVVVSHFLILHGGDWDDQGPHWKRGVFDQEHDFFHVVHGDQ\ZKHUHLQWKHSDFNDJH III. One line Answers

 'HILQHLQKHULWDQFH  :KDWLVSRO\PRUSKLVP"  'HILQHUHFXUVLRQ  %ULHIO\H[SODLQWKHXVDJHRIVXSHUPHWKRG  ([SODLQSUHFLVHO\WKHQHHGIRUILQDOL]HPHWKRG  %ULHIO\GHVFULEHWKHJDUEDJHFROOHFWRULQ-DYD  :KDWLVIXQFWLRQRYHUORDGLQJ"

64

Comp-U-Learn

Session 4

Interfaces and Packages

On Completion of this Session We will be able to understand...

) Introduction to Interfaces ) Implementing the Interfaces ) Cloneable Interface ) About Inner classes ) Importance of packages ) Creating packages ) Access Protection ) Overview of Java Built in Packages

In This Session...



Introduction to Interfaces



What is an interface?



Intricacies in an Interface



Interface References



Extending the Interface



The Cloneable Interface



Inner Classes



Packages



Need for Packages



CLASSPATH Variable



Access Protection



Overview of Java Built-in Packages

Interfaces and Packages

Introduction to Interfaces ,QWKHHDUOLHUVHVVLRQVZHIRXQGWKDWZHFDQFUHDWHVXEFODVVHVLQ-DYDE\H[WHQGLQJDQDOUHDG\ GHILQHG FODVV ,Q -DYD PXOWLSOH LQKHULWDQFH LV QRW SRVVLEOH 8VLQJ WKH NH\ZRUG H[WHQGV LW LV SRVVLEOHWRLQKHULWWKHSURSHUWLHVRIMXVWDFODVVRQO\7KHUHPD\EHVRPHFLUFXPVWDQFHVZKLFK UHTXLUHWKHSURSHUWLHVRIWZRFODVVHVWREHLQKHULWHG /HW XV WDNH DQ H[DPSOH &RQVLGHU D FODVV FDOOHG FRRUGLQDWH ZKLFK WDONV DERXW [ DQG \ FRRUGLQDWHV RI SRLQWV DQG D FODVV FDOOHG SURSHUWLHV WKDW WDONV DERXW WKH IRUHJURXQG DQG EDFNJURXQGFRORUVXVHGWRGUDZVKDSHV1RZLIZHZDQWWRGHILQHVRPHJHRPHWULFILJXUHVD\ VTXDUHZHZRXOGQDWXUDOO\OLNHWRWDONDERXWLWVFRRUGLQDWHVDVZHOODVFRORUV6RLWLVUHTXLUHGWR LQKHULW IURP ERWK WKHVH FODVVHV $Q DOWHUQDWH ZD\ RI LPSOHPHQWLQJ WKH PHWKRG RI D GLIIHUHQW FODVVLVWKURXJKDQLQWHUIDFH7KLVVHVVLRQSURYLGHVDQRYHUYLHZRILQWHUIDFHV

What is an interface? $Q LQWHUIDFH LV YHU\ PXFK OLNH D FODVV ZLWK FRQVWDQW YDOXHV DQG PHWKRG GHFODUDWLRQV 7KH GLIIHUHQFHLVWKDWPHWKRGVLQDQLQWHUIDFHDUHRQO\GHFODUHGEXWQRWLPSOHPHQWHG$QLQWHUIDFHLV H[DFWO\ OLNH D FODVV EXW ZLWK WKH NH\ZRUG FODVV EHLQJ UHSODFHG E\ WKH NH\ZRUG LQWHUIDFH  $Q LQWHUIDFH LV VLPLODU WR DQ DEVWUDFW FODVV ZLWK D UHVWULFWLRQ WKDW DOO PHWKRGV LQ DQ LQWHUIDFH DUH DEVWUDFW7KHIROORZLQJH[DPSOHH[SODLQVGHFODUDWLRQRIDQLQWHUIDFH interface ExampleInterface { void xx(); // abstract by default; no body void yy(); }

7KH DERYH H[DPSOH VXJJHVWV WKDW WKHUH DUH WZR SDUWV LQ DQ LQWHUIDFH WKH LQWHUIDFH GHFODUDWLRQ DQG WKH LQWHUIDFH ERG\ 7KH GHFODUDWLRQ SDUW FRQVLVWV RI QDPH RI WKH LQWHUIDFH DQG ZKHWKHU LW LQKHULWV IURP DQ\ RWKHU LQWHUIDFH 7KH LQWHUIDFH ERG\ FRQVLVWV RI WKH FRQVWDQW YDOXHV LQ WKH LQWHUIDFHDQGWKHGHFODUDWLRQRIWKHPHWKRGVRIWKHLQWHUIDFH1RZWRXVHWKHLQWHUIDFHDFODVV PXVWLPSOHPHQWWKHFRUUHVSRQGLQJDEVWUDFWIXQFWLRQV:HPD\GHILQHDFODVVFDOOHGVRPHDV public class some implements ExampleInterface { void xx(); // write the code here void yy(); // write the code here7 }

Comp-U-Learn

67

Java Programming I

+HUHWKHFODVVVRPHFDQLPSOHPHQWPRUHWKDQRQHLQWHUIDFHEXWLWFDQQRWH[WHQGPRUHWKDQRQH FODVV,Q-DYDDQLQWHUIDFHLVDUHIHUHQFHGDWDW\SHDQGDVVXFKFDQEHXVHGLQDOOSODFHVZKHUHD W\SHFDQEHXVHG:HZLOOVHHWKLVLQGHWDLOXQGHUWKHKHDGLQJ´8VLQJDQ,QWHUIDFHDVD7\SHµ

Intricacies in an Interface ,QWHUIDFHV DUH XVHG WR GHILQH D SURWRFRO RI EHKDYLRU WKDW FDQ EH LPSOHPHQWHG E\ DQ\ FODVV DQ\ZKHUH LQ WKH FODVV KLHUDUFK\ /HW XV WU\ WR GLIIHUHQWLDWH EHWZHHQ LQWHUIDFHV DQG DEVWUDFW FODVVHV$EVWUDFWFODVVHVDUHXVHGRQO\ZKHQWKH\DUHVXSHUFODVVHVDQGWKHVXEFODVVHVLPSOHPHQW WKHPHWKRGV

Note In the case of interfaces, the methods can be implemented even by classes, which are not inherited. 2IWHQLQWHUIDFHVDUHWKRXJKWRIDVDQDOWHUQDWLYHWRPXOWLSOHFODVVLQKHULWDQFH:KLOHLQWHUIDFHV PD\VROYHVRPHRIWKHVDPHSUREOHPVWKDWPXOWLSOHFODVVLQKHULWDQFHGRWKH\DUHTXLWHGLIIHUHQW ,QSDUWLFXODU ♦ We cannot inherit variables from an interface ♦ We cannot inherit method implementations from an interface. ♦ The interface hierarchy is independent of the class hierarchy- classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance. 7KHVWUHQJWKRIWKHLQWHUIDFHOLHVLQWKHIDFWWKDWDQXQUHODWHGFODVVZKLFKGRHVQRWEHORQJWRWKH KLHUDUFK\ FDQ LPSOHPHQW WKH PHWKRGV RI DQ LQWHUIDFH 7KHUHIRUH LQKHULWDQFH GRHV QRW WDNH SODFHLQWKLVFRQFHSW+HUHLVDQH[DPSOHWKDWWHOOVPRUHDERXWDQLQWHUIDFH Example 4.1 interface one { public void xx(); } interface two extends { public void yy(); }

one

class cl1 implements one { public void xx() {

68

Comp-U-Learn

Interfaces and Packages System.out.println(“The function xx of class cl1 implements interface one“); } public void yy() { System.out.println(“Original yy in class but not in interface “); } } class cl2 implements two { public void xx() { System.out.println(“The function xx of class cl2 implements interface two “); } public void yy() { System.out.println(“The function yy of class cl2 implements interface two “); } }

$QLQWHUIDFHFDQH[WHQGDQRWKHULQWHUIDFH OLNHWZRH[WHQGVRQHDQGKDVWZRPHWKRGV[[DQG\\ EXW DQ LQWHUIDFH FDQQRW H[WHQG D FODVV DQG D FODVV FDQQRW H[WHQG DQ LQWHUIDFH D FODVV FDQ LPSOHPHQWDQLQWHUIDFH $FODVVFDQMXVWLPSOHPHQWDOOPHWKRGVRIDQLQWHUIDFH FOLPSOHPHQWV WZR RULWFDQKDYHLWVRZQPHWKRGVDOVRLQDGGLWLRQWRWKHPHWKRGVRIWKHLQWHUIDFH FOKDVLWV RZQPHWKRG\\ZKLFKLVQRWDPHWKRGRIWKHLQWHUIDFHRQH 

Note All methods in an interface are always public, static, final and abstract; even if we do not use the word public, they are public in one and two above. But for their implementations within a class, omitting the word public creates problems. An interface can extend multiple interfaces. 7KHVWHSVLQYROYHGLQFUHDWLQJDQLQWHUIDFHDUH 'HFODUHWKHLQWHUIDFH $GGDEVWUDFWPHWKRGVWRWKHLQWHUIDFHERG\ 6DYHWKHILOHZLWKDMDYDH[WHQVLRQ &RPSLOHWKHLQWHUIDFHFUHDWHG 7KHVWHSVLQYROYHGLQLPSOHPHQWLQJDQLQWHUIDFHDUH 'HFODUHWKHFODVVDQGXVHWKHLPSOHPHQWNH\ZRUGIROORZHGE\WKHQDPHRIWKHLQWHUIDFH ,PSOHPHQWHYHU\DEVWUDFWPHWKRGWKDWKDVEHHQGHFODUHGZKLOHFUHDWLQJWKHLQWHUIDFH 6DYHWKHILOHZLWKDMDYDH[WHQVLRQ &RPSLOHWKHDSSOHWRUDSSOLFDWLRQFUHDWHG

Comp-U-Learn

69

Java Programming I

7KH IROORZLQJ DUH VRPH RI WKH JXLGHOLQHV WR EH IROORZHG ZKLOH FUHDWLQJ DQG LPSOHPHQWLQJ LQWHUIDFHV ♦ An interface can be declared as public, whereby it can be implemented even outside a package. ♦ An interface cannot be considered a substitute for multiple inheritance, which is not supported by Java. ♦ While declaring members in an interface, we may not use the private and protected access specifiers. ♦ Constants declared in an interface are implicitly public, static and final. ♦ All methods declared in an interface are implicitly public and abstract. ♦ A class can implement as many interfaces as required with each interface name being separated by a comma(,).

Note If the parent class already implements an interface, its subclasses do not need to explicitly use the implement keyword. $VDPSOHSURJUDPWRVKRZWKHZRUNLQJRIDQLQWHUIDFH Example 4.2 package Display; public interface DisplayInterface { public String GetDlsplayText(); //no implementation of this method } // This applet implements the method declared in the interface import java.awt.*; import java.applet.*; import java.lang.*; import Display.DisplayInterface; public class ex13 extends Applet implements DisplayInterface { public void paint(Graphics g) { String str=GetDisplayText(); g.drawString(str,80,100); } public String GetDisplayText() { return " Display Text "; } }

70

Comp-U-Learn

Interfaces and Packages

Note Member declarations in an interface disallow some of the use of declaration modifiers and discourage the use of others. We may not use transient, volatile or synchronized in a member declaration in an interface. Also, we may not use the private and protected specifiers when declaring members of an interface.

Interface References :HFDQGHFODUHYDULDEOHVDVREMHFWUHIHUHQFHVWKDWXVHDQLQWHUIDFHUDWKHUWKDQDFODVVW\SH$Q\ LQVWDQFHRIDFODVVWKDWLPSOHPHQWVWKHGHFODUHGLQWHUIDFHFDQEHVWRUHGLQVXFKDYDULDEOH:KHQ ZHFDOODPHWKRGWKURXJKRQHRIWKHVHUHIHUHQFHVWKHFRUUHFWYHUVLRQZLOOEHFDOOHGEDVHGRQWKH DFWXDOLQVWDQFHRIWKHLQWHUIDFHEHLQJUHIHUUHGWR7KLVLVRQHRIWKHNH\IHDWXUHVRILQWHUIDFHV 7KHPHWKRGWREHH[HFXWHGLVORRNHGXSG\QDPLFDOO\DWUXQWLPHDOORZLQJFODVVHVWREHFUHDWHG ODWHU WKDQ WKH FRGH ZKLFK FDOOV PHWKRGV RQ WKHP 7KH FDOOLQJ FRGH FDQ GLVSDWFK WKURXJK DQ LQWHUIDFHZLWKRXWKDYLQJWRNQRZDQ\WKLQJDERXWWKHFDOOHGFRGH Example 4.3 interface Iface { void callfn(int i); } class One implements Iface { public void callfn(int a) { System.out.println(“Calling the callfn with “ + a); } } class Two implements Iface { public void callfn(int a) { System.out.println(“Call from class two of method of callfn”); System.out.println(“a squared is “ + (a * a)); } } class ex12 { public static void main(String args[]) { Iface i=new One(); Two j=new Two(); i.callfn(100);

Comp-U-Learn

71

Java Programming I i=j; i.callfn(100); } }

Extending the Interface $QLQWHUIDFHFDQLQKHULWDQRWKHUE\XVHRIWKHNH\ZRUGH[WHQGV7KHV\QWD[LVWKHVDPHDVIRU LQKHULWLQJFODVVHV:KHQDFODVVLPSOHPHQWVDQLQWHUIDFHWKDWLQKHULWVDQRWKHULQWHUIDFHLWPXVW SURYLGHLPSOHPHQWDWLRQVIRUDOOPHWKRGVGHILQHGZLWKLQWKHLQWHUIDFHLQKHULWDQFHFKDLQ7KLVFDQ EHLOOXVWUDWHGWKURXJKDQH[DPSOH Example 4.4 interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class cl1 implements B { public void meth1() { System.out.println(“implementing method 1 in Interface A”); } public void meth2() { System.out.println(“implementing method 2 in Interface A”); } public void meth3() { System.out.println(“implementing method 3 in Interface B”); } } class ex14 { public static void main(String args[]) { cl1 obj=new cl1(); obj.meth1(); obj.meth2(); obj.meth3(); } }

72

Comp-U-Learn

Interfaces and Packages

$VDQH[SHULPHQWZKHQZHWU\WRUHPRYHWKHLPSOHPHQWDWLRQIRUPHWKRGPHWK LQWKHFODVV FO LW ZLOO FDXVH D FRPSLODWLRQ HUURU EHFDXVH DQ\ FODVV WKDW LPSOHPHQWV DQ LQWHUIDFH PXVW LPSOHPHQWDOOPHWKRGVGHILQHGE\WKDWLQWHUIDFH

The Cloneable Interface :KHQ ZH PDNH D FRS\ RI WKH YDULDEOH WKH RULJLQDO DQG WKH FRS\ DUH UHIHUHQFHV WR WKH VDPH REMHFW7KLVPHDQVDFKDQJHWRHLWKHUYDULDEOHDOVRDIIHFWVWKHRWKHU Day Bday=new Day(1998,8,16); Day d=Bday; d.advance(100); //Oops will also change Bday

7KLVLVGHSLFWHGEHORZ

Bday

Day

D

Day 16 Month 8 Year 1998

Fig. 4.1 ,IZHZRXOGOLNH'WREHDQHZREMHFWWKDWEHJLQVLWVOLIHEHLQJLGHQWLFDOWR%GD\EXWZKRVHVWDWH FDQGLYHUJHRYHUWLPHWKHQZHXVHWKHFORQH PHWKRG Day Bday=new Bday(1998,8,16); Day d=(Day)Bday.clone(); // must cast because clone() returns an Object d.advance(100); //Bday will not be changed.

7KHFORQHPHWKRGLVDSURWHFWHGPHWKRGRI2EMHFWZKLFKPHDQVWKDWRXUFRGHFDQQRWVLPSO\ FDOO LW 7KH FORQH PHWKRG LV LPSOHPHQWHG WKURXJK WKH &ORQHDEOH LQWHUIDFH 7KH FORQH PHWKRG ZLOOPDNHDELWZLVHFRS\RIWKHFODVV·VREMHFWV

Comp-U-Learn

73

Java Programming I

Day

Bday

Day 16 Month 8 Year 1998

Day

D

Day 16 Month 8 Year 1998

Fig. 4.2

Inner Classes $QLQQHUFODVVLVDFODVVWKDWLVGHILQHGLQVLGHDQRWKHUFODVV7KHQHHGIRULQQHUFODVVHVFDQEH VWDWHGDVIROORZV ♦ An object of an inner class can access the implementation of the object that created it – including data that would otherwise be private. ♦ Inner classes can be hidden from other classes in the same package. ♦ Anonymous inner classes are handy when we want to define callbacks on the fly. ♦ Inner classes are very convenient when we are writing event-driven programs. Example 4.5 class LinkedList { ............ ............. ................... private: class Node

74

Comp-U-Learn

Interfaces and Packages { public Node *Next; int data; } class Iterator { public : void insert(int x); int erase(); } ................. }

+HUH WKH /LQNHG /LVW FODVV LV WKH RXWHU FODVV DQG WKH FODVVHV 1RGH DQG ,WHUWRU DUH WZR LQQHU FODVVHV 1RWH WKDW WKH H[DPSOH VKRZQ DERYH LV ZULWWHQ LQ & 7KLV LV MXVW WR VKRZ WKH VLPLODULWLHVDQGWKHGLIIHUHQFHEHWZHHQ-DYDDQG&

Note An object that comes from an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to the total state of the outer object. A static inner class can be used whenever the inner class does not need to access an outer class.

Packages ,Q-DYDHYHU\WKLQJLVGHVFULEHGLQWHUPVRIFODVVHVDQGVRWKHQXPEHURIFODVVHVXVHGE\DVLQJOH SURJUDPLVYHU\ODUJH7KHUHIRUHLWEHFRPHVLQHYLWDEOHWRSURSHUO\RUJDQL]HWKHVHFODVVHVIURP WKH SRLQW RI WKHLU UHXVDELOLW\ LQ PXOWLSOH SURJUDPV -DYD SURYLGHV VXFK D IDFLOLW\ WKURXJK SDFNDJHV $ SDFNDJH LV D JURXS RI FODVVHV ,W FRXOG EH FRPSDUHG WR WKH OLEUDULHV RIIHUHG E\ SURJUDPPLQJ ODQJXDJHV OLNH & DQG & 7KH FODVVHV RIIHUHG E\ -DYD DUH RUJDQL]HG LQWR SDFNDJHVZKLFKPD\EHLPSRUWHGLQDQDSSOLFDWLRQZLWKWKHLPSRUWVWDWHPHQWDVLOOXVWUDWHGLQ WKHH[DPSOHEHORZ import java.awt.*; import java.applet.*; import java.awt.Button;

%\UXOHHYHU\FODVVLQ-DYDEHORQJVWRVRPHSDFNDJH,IZHGRQ·WPHQWLRQDERXWDSDFNDJHWKH FRPSLOHUDVVXPHVWKDWZHDUHSXWWLQJWKHFODVVHVLQWKHGHIDXOWSDFNDJH7KLVGHIDXOWSDFNDJHKDV QRQDPHLQ-DYD

Comp-U-Learn

75

Java Programming I

Need for Packages /HW XV VHH WKH QHHG IRU SDFNDJHV EHIRUH WU\LQJ WR GHILQH D SDFNDJH ,I WKH FRQFHSW RI LPSRUW VWDWHPHQWGRHVQRWH[LVWLQ-DYDZHDQGKDGWRIRUH[DPSOHFUHDWHD%XWWRQREMHFWZHZRXOG KDYHWRVD\ java.awt.Button MyButton=new java.awt.Button(“sample”);

7KLVLVDYHU\WHGLRXVZD\RIFUHDWLQJD%XWWRQZLWKWKHDGGLWLRQDORYHUORDGRIQHHGLQJWRNQRZ WKHIXOO\TXDOLILHGQDPHVZKHQUHIHUULQJWRDFODVVRI-DYD7KHVDPHWKLQJFRXOGEHDSSURDFKHG LQDVWUDLJKWIRUZDUGPDQQHU import java.awt.button; ............................................. ............................................. Button MyButton = new Button(“sample”);;

7RFUHDWHSDFNDJHVVLPSO\LQFOXGHDSDFNDJHFRPPDQGDVWKHILUVWVWDWHPHQWLQD-DYDVRXUFH ILOH $Q\ FODVV GHFODUHG ZLWKLQ WKDW ILOH ZLOO EHORQJ WR WKH VSHFLILHG SDFNDJH 7KH SDFNDJH VWDWHPHQWGHILQHVDQDPHVSDFHLQZKLFKFODVVHVDUHVWRUHG,IZHRPLWWKHSDFNDJHVWDWHPHQW WKHQWKHFODVVQDPHVDUHSXWLQWRDGHIDXOWSDFNDJHZKLFKKDVQRQDPH$WWKHEHJLQQLQJRIWKH FODVVGHFODUDWLRQDGGWKHIROORZLQJFRGH package Packagename;

Example package pkg;

+HUH SNJ LV WKH QDPH RI WKH SDFNDJH -DYD XVHV ILOH V\VWHP GLUHFWRULHV WR VWRUH SDFNDJHV )RU H[DPSOHWKHFODVVILOHVIRUDQ\FODVVHVWKDWDUHGHFODUHGWREHSDUWRIWKHSDFNDJHSNJPXVWEH VWRUHGLQDGLUHFWRU\FDOOHGSNJ0RUHWKDQRQHILOHFDQLQFOXGHWKHVDPHSDFNDJHVWDWHPHQW7KH SDFNDJHVWDWHPHQWVLPSO\VSHFLILHVWRZKLFKSDFNDJHVWKHFODVVHVGHILQHGLQDILOHEHORQJ Creation of a Package The following are the steps involved in the creation of a package

,GHQWLI\WKHKLHUDUFK\LQZKLFKZHZRXOGOLNHWRSODFHWKHFODVVILOHV &UHDWHDGLUHFWRU\ZKLFKKDVWKHVDPHQDPHDVWKDWRIWKHSDFNDJH ,QFOXGHSDFNDJHVWDWHPHQWDORQJWKHSDFNDJHQDPHDVWKHILUVWVWDWHPHQWLQWKHSURJUDP 'HFODUHWKHFODVVHVUHTXLUHGLQWKHSDFNDJH

76

Comp-U-Learn

Interfaces and Packages

6DYHWKHILOHQRZZLWKWKHQDPHRIWKHFODVVDORQJZLWKMDYDH[WHQVLRQ &RPSLOHWKHILOHXVLQJMDYDFWRFUHDWHWKHFODVVILOHLQWKHVDPHGLUHFWRU\ LHWKHGLUHFWRU\WKDW KDVWKHQDPHRIWKHSDFNDJH ([HFXWHWKHFODVVILOH

CLASSPATH Variable :KHQZHDUHZULWLQJVPDOOSURJUDPVLWGRHVQRWPDWWHULIWKHSDFNDJHQDPHLVQRWPHQWLRQHG %HFDXVHLWZLOOEHLQWKHGHIDXOWSDFNDJH-DYDFRPSLOHUDQGLQWHUSUHWHUVHDUFKHVWKHFODVVILOHVLQ WKH SDWK VSHFLILHG LQ &/$663$7+ YDULDEOH 7KH FXUUHQW ZRUNLQJ GLUHFWRU\ LV E\ GHIDXOW LQFOXGHG LQ WKLV YDULDEOH +HQFH LW LV SRVVLEOH WR FRPSLOH DQG H[HFXWH ILOHV IURP WKH H[LVWLQJ FXUUHQWGLUHFWRU\,QFDVHRIFUHDWLQJDSDFNDJHLWVKRXOGEHHQVXUHGWKDWWKHURRWGLUHFWRU\RI WKHSDFNDJHLVLQFOXGHGLQWKH&/$663$7+YDULDEOH7KLVLVEHFDXVHWKHVSHFLILFORFDWLRQWKDW WKH -DYD FRPSLOHU ZLOO FRQVLGHU DV WKH URRW RI DQ\ SDFNDJH KLHUDUFK\ LV FRQWUROOHG E\ &/$663$7+ 6LQFHFODVVHVFRXOGEHDQ\ZKHUHZHPXVWLQGLFDWHWRWKH-DYDLQWHUSUHWHUZKHUHLWFDQILQGWKH FODVVHVWKDWZHDUHWU\LQJWRUXQ7KLVLVGRQHWKURXJKWKH&/$663$7+HQYLURQPHQWYDULDEOH 7KH&/$663$7+YDULDEOHFRPSULVHVDOLVWRIGLUHFWRU\QDPHVWKDWFRQWDLQ-DYDFRPSLOHG-DYD FODVVHV 7KH DFWXDO FRQVWUXFW RI &/$663$7+ GHSHQGV RQ WKH V\VWHP ZH DUH UXQQLQJ 7KH FODVVHV LQFOXGHG ZLWK WKH -DYD GHYHORSPHQW HQYLURQPHQW DUH DXWRPDWLFDOO\ DYDLODEOH WR XV EHFDXVHWKHLQWHUSUHWHUDXWRPDWLFDOO\DSSHQGVWKHFRUUHFWGLUHFWRU\WRRXU&/$663$7+ZKHQLW VWDUWVXS Snapshot on Packages

♦ As default, every class belongs to some package in Java. ♦ A package statement before the class statement is necessary. ♦ Two or more packages can be grouped. This creates a hierarchy of packages. ♦ Package hierarchy is denoted by writing the dot (.) after every level; aaa.bbb.ccc means that the package ccc is in the bbb package which is in the aaa package. ♦ Java restriction is that we should keep the packages/classes into corresponding directories/files. ♦ It is possible to create a class called cla in ccc as well as in bbb or in ttt. There is no conflict; they actually have different full names to be qualified. ♦ A package can contain only one public class.

Comp-U-Learn

77

Java Programming I

Example 4.6 package mainpack; public class Class1 { public static void meth1() { System.out.println(“Hello Friends”); } }

&UHDWHDGLUHFWRU\FDOOHGPDLQSDFNXQGHUELQDQGVDYHWKLVILOHDV&ODVVMDYD package mainpack.child; public class Class2 { public static void meth2() { System.out.println(“Good Bye Friends”); } }

1RZFUHDWHDVXEGLUHFWRU\FDOOHGFKLOGXQGHUWKHGLUHFWRU\PDLQSDFN6DYHWKLVILOHDV&ODVVMDYD LQWKHVXEGLUHFWRU\FKLOG1RZXQGHUELQGLUHFWRU\RSHQDQHZILOHDQGZULWHWKHIROORZLQJFRGH import mainpack.*; import mainpack.child.*; class ex14 { public static void main(String args[]) { Class1.meth1(); Class2.meth2(); } }

6DYHWKLVILOHDVH[MDYDFRPSLOHXVLQJMDYDFDQGH[HFXWHWKHFODVVILOH

Note The star form may increase compilation time especially if we import several large packages. For this reason it is a good idea to explicitly name the classes that we want to use rather importing whole packages. $OORIWKHVWDQGDUG-DYDFODVVHVLQFOXGHGZLWK-DYDDUHVWRUHGLQDSDFNDJHFDOOHGMDYD7KHEDVLF ODQJXDJHIXQFWLRQVDUHVWRUHGLQDSDFNDJHLQVLGHRIWKHMDYDSDFNDJHFDOOHGMDYDODQJ1RUPDOO\ ZHKDYHWRLPSRUWHYHU\SDFNDJHRUFODVVWKDWZHZDQWWRXVHEXWVLQFH-DYDLVXVHOHVVZLWKRXW PXFKRIWKHIXQFWLRQDOLW\LQMDYDODQJWKHFRPSLOHUIRUDOOSURJUDPVLPSOLFLWO\LPSRUWVLW

78

Comp-U-Learn

Interfaces and Packages

Access Protection &ODVVHVDQGSDFNDJHVDUHERWKPHDQVRIHQFDSVXODWLQJDQGFRQWDLQLQJWKHQDPHVSDFHDQGVFRSH RI YDULDEOHV DQG PHWKRGV 3DFNDJHV DFW DV FRQWDLQHUV IRU FODVVHV DQG RWKHU VXERUGLQDWH SDFNDJHV &ODVVHV DFW DV FRQWDLQHUV IRU GDWD DQG FRGH 7KH FODVV LV -DYD·V VPDOOHVW XQLW RI DEVWUDFWLRQ %HFDXVH RI WKH LQWHUSOD\ EHWZHHQ FODVVHV DQG SDFNDJHV -DYD DGGUHVVHV IRXU FDWHJRULHVRIYLVLELOLW\IRUFODVVPHPEHUV ♦ ♦ ♦ ♦

Subclasses in the same package Non subclasses in the same package Sub classes in different packages Classes that are neither in the same package nor subclasses

7KHWKUHHDFFHVVVSHFLILHUVSULYDWHSXEOLFDQGSURWHFWHGSURYLGHDYDULHW\RIZD\VWRSURGXFH WKHPDQ\OHYHOVRIDFFHVVUHTXLUHGE\WKHVHFDWHJRULHV7KHIROORZLQJWDEOHVKRZVWKHXVDJHRI YDULRXVDFFHVVVSHFLILHUVDQGWKHLUVFRSHLQWKHSDFNDJHV Description Same class Same package Subclass Same package Non subclass Different package Sub class Different package Non Sub class

Private Yes No No

No modifier Yes Yes Yes

Protected Yes Yes Yes

Public Yes Yes Yes

No

No

Yes

Yes

No

No

Yes

Yes

$FODVVKDVRQO\WZRSRVVLEOHDFFHVVOHYHOVGHIDXOWDQGSXEOLF:KHQDFODVVLVGHFODUHGDVSXEOLF LWLVDFFHVVLEOHE\DQ\RWKHUFRGH,IDFODVVKDVGHIDXOWDFFHVVWKHQLWFDQRQO\EHDFFHVVHGE\ RWKHUFRGHZLWKLQLWVVDPHSDFNDJH Access Control Rules

$OOWKHFODVVHVDUHSXWLQWRWKHVHFDWHJRULHV This class (T). Subclasses of this class in the same package (SP) Non subclasses of this class in the same package (NP) Subclasses of this class in the other package (SO) Non subclasses of this class in other packages (NO) As the access attributes, Java provides these five alternatives

Comp-U-Learn

79

Java Programming I

1RQH QRWVSHFLI\LQJDQ\WKLQJ Private Public Private protected Protected 7KHUXOHVIRUXVLQJWKHVHDWWULEXWHVDUHDVIROORZV ,I ZH GRQ·W VSHFLI\ DQ\WKLQJ  WKLV FODVV DQG WKH GDWDPHWKRGV GHILQHG LQVLGH LW DUH YLVLEOH DFFHVVLEOH WKURXJKRXWWKHSDFNDJHFRQWDLQLQJWKLVFODVV YLVLEOHDFFHVVLEOHWR76313 ,IZHGHFODUHVRPHWKLQJ WKLVFODVVRUWKHGDWDPHWKRGVGHILQHGLQVLGHLW DVSULYDWHLWLVYLVLEOH DFFHVVLEOH  RQO\ LQ WKLV FODVV YLVLEOH WR 7  7KH ZRUG SULYDWH LV JHQHUDOO\ XVHG IRU KLGLQJ LQIRUPDWLRQIURPRWKHUFODVVHV ,IZHGHFODUHVRPHWKLQJDVSULYDWHSURWHFWHGLWLVYLVLEOH DFFHVVLEOH LQVLGHDOOWKHVXEFODVVHVLQ WKLVSDFNDJHDVZHOODVLQRWKHUSDFNDJHV YLVLEOHWR76362 ,I ZH GHFODUH VRPHWKLQJ DV SURWHFWHG LW LV YLVLEOH LQVLGH DOO FODVVHV RI WKLV SDFNDJH DQG DOVR LQVLGHWKHVXEFODVVHV RIRWKHUSDFNDJHV YLVLEOHWR 763136R ,WLVQRWYLVLEOHRQO\IRUWKH QRQVXEFODVVHVRIRWKHUSDFNDJHV QRWYLVLEOHWR12  ,IZHGHILQHVRPHWKLQJSXEOLFLWLVYLVLEOHHYHU\ZKHUH YLVLEOHWR763136212 

Overview of Java Built-in Packages 7KH-'.$3,FRQVLVWVRISDFNDJHVDOORIZKLFKDUHLQWKH&RUH$3,2IWKH&RUH$3, SDFNDJHV  DUH SDUW RI WKH -DYD )RXQGDWLRQ &ODVVHV -)&  7KH &RUH $3, JUHZ VLJQLILFDQWO\ IURP-'.WR2IWKH&RUH$3,SDFNDJHVWKDWZHUHDUHDGGHGLQ-'.DUHLQ WKH-)&6ZLQJDQG1RQVZLQJ DUH-DYD,'/ &25%$DQG&RV1DPLQJ DUHVHFXULW\ DUH XWLOLW\ SDFNDJHV -$5 DQG 0,0( VXSSRUW   LV -DYD %HDQV  LV 50, DQG  LV 2EMHFW 5HIHUHQFHV MDYDODQJUHI 7KHEXONRIWKHQHZ-'.SDFNDJHVDUH-)&DQG&25%$ &RUH$3,SDFNDJHVDUHOLVWHGKHUHXQGHU ♦ ♦ ♦ ♦ ♦ 80

Java.applet Java.awt Java.beans Java.io Java.lang Comp-U-Learn

Interfaces and Packages

♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦

Java.math Java.net Java.rmi Java.security Java.sql Java.text Java.util Com.sun.java.swing Com.sun.java.image.codec.jpeg Com.sun.java.accessibility Org.omg.CORBA

The java.applet

7KHMDYDDSSOHWSDFNDJHLVRQHRIWKHVPDOOHVWSDFNDJHVLQWKHFRUH$3,,WFRQVLVWVRIRQHFODVV DQGWKUHHLQWHUIDFHVWKDWSURYLGHWKHEDVLFIXQFWLRQDOLW\QHHGHGWRLPSOHPHQWDSSOHWV7KHDSSOHW FODVV SURYLGHV PHWKRGV WR GLVSOD\ LPDJHV SOD\ DXGLR ILOHV UHVSRQG WR HYHQWV DQG REWDLQ LQIRUPDWLRQ DERXW DQ DSSOHW·V H[HFXWLRQ HQYLURQPHQW 7KH $SSOHW&RQWH[W LQWHUIDFH GHILQHV PHWKRGV WKDW DOORZ DQ DSSOHW WR DFFHVV WKH FRQWH[W LQ ZKLFK LW LV EHLQJ UXQ 7KH $SSOHW6WXE LQWHUIDFHVXSSRUWVFRPPXQLFDWLRQEHWZHHQDQDSSOHWDQGLWVEURZVHUHQYLURQPHQWDQGLVXVHG WR GHYHORS FXVWRP DSSOHW YLHZHUV 7KH $XGLR&OLS LQWHUIDFH SURYLGHV PHWKRGV WKDW VXSSRUW SOD\LQJDXGLRFOLSV The java.awt

7KH MDYDDZW SDFNDJH LPSOHPHQWV WKH FRUH FODVVHV DQG LQWHUIDFHV RI WKH $EVWUDFW ZLQGRZ 7RRONLW,WLVDODUJHSDFNDJHFRQWDLQLQJFODVVHVDQGLQWHUIDFHV7KHVHFODVVHVDQGLQWHUIDFHV SURYLGHWKHVWDQGDUG$:7*8,FRQWUROVDVZHOODVGUDZLQJSULQWLQJDQGRWKHUFDSDELOLWLHV The Javabeans

7KLVSDFNDJHKDVEHHQDGGHGWRVXSSRUWWKHLPSOHPHQWDWLRQIRUDEHDQFRQWDLQHUWKDWSURYLGHV DQH[HFXWLRQFRQWH[WIRUEHDQVGXULQJGHVLJQDQGUXQWLPHH[HFXWLRQ7KLVSDFNDJHFRQWDLQV FODVVHVDQGHLJKWLQWHUIDFHVWKDWSURYLGHWKHEDVLF-DYD%HDQVIXQFWLRQDOLW\ The java.io

7KLV SURYLGHV D VHW RI LQSXW DQG RXWSXW VWUHDPV XVHG WR UHDG DQG ZULWH GDWD WR ILOHV RU RWKHU LQSXWDQGRXWSXWVRXUFHV Comp-U-Learn

81

Java Programming I

The java.lang

7KHMDYDODQJSDFNDJHSURYLGHVFODVVHVDQGWKUHHLQWHUIDFHVWKDWLPSOHPHQWIXQGDPHQWDO-DYD REMHFWV %HFDXVH RI LWV LPSRUWDQFH WKH MDYDODQJ SDFNDJH LV LQFOXGHG ZLWK DOO -DYD SODWIRUPV UDQJLQJIURP(PEHGGHG-DYDWRWKHIXOOEORZQ-'. The java.math

7KH -DYDPDWK SDFNDJH SURYLGHV WZR FODVVHV %LJ'HFLPDO DQG %LJ,QWHJHU WKDW SURYLGH WKH FDSDELOLW\ WR SHUIRUP DUELWUDU\ SUHFLVLRQ DULWKPHWLF ,W SURYLGHV D OLEUDU\ RI PDWK URXWLQHV DQG YDOXHVVXFKDV3, The java.net

7KHMDYDQHWSDFNDJHKDVFODVVHVDQGILYHLQWHUIDFHVIRU7&3,3QHWZRUNSURJUDPPLQJ The java.rmi

7KH 5HPRWH 0HWKRG ,QYRFDWLRQ SDFNDJHV SURYLGH WKH FDSDELOLW\ WR XVH GLVWULEXWHG REMHFWV ZLWKLQ-DYD7KLVLVDQHZDGGLWLRQWR-'.,WVXSSRUWVSHUVLVWHQWUHPRWHREMHFWUHIHUHQFHV DQGDXWRPDWLFREMHFWDFWLYDWLRQ The java.security

7KHILYHMDYDVHFXULW\SDFNDJHVVXSSRUWLPSOHPHQWDWLRQRI-'.FRQILJXUDEOHVHFXULW\SROLF\ DQG FU\SWRJHQLF VHFXULW\ PHFKDQLVPV ,W SURYLGHV VSHFLDO VSHFLILFDWLRQV IRU WKH NH\V XVHG LQ FRPPRQFU\SWRJUDSKLFDOJRULWKPV 7KLV SDFNDJH KDV  FODVVHV DQG HLJKW LQWHUIDFHV WKDW IRUP WKHIRXQGDWLRQIRUWKH6HFXULW\$3, The Swing

6ZLQJ LV D  MDYD H[WHQVLRQ WR WKH $:7 WKDW SURYLGHV PDQ\ QHZ *8, FRPSRQHQWV LPSURYHPHQWVWRH[LVWLQJFRPSRQHQWVDQGWKHFDSDELOLW\WRVHOHFWIURPDYDULHW\RI*8,ORRN DQG IHHOV VXFK DV 0HWDO :LQGRZV 0RWLI DQG 0DFLQWRVK ,W SURYLGHV FODVVHV WR LPSOHPHQW ERUGHUVDQGERUGHUVW\OHVWKHWDEOHFRPSRQHQWWH[WSURFHVVLQJFRPSRQHQWV The java.utility

7KLVFRQWDLQVDFROOHFWLRQRIXWLOLW\FODVVHV$PRQJWKHPDUHWKHVHYHUDOJHQHULFGDWDVWUXFWXUHV OLNH 'LFWLRQDU\ 6WDFN 9HFWRU DQG +DVKWDEOH  ,W DOVR FRQWDLQV FODVVHV WR PDQLSXODWH FDOHQGDU GDWHV7KH-DYDXWLOSDFNDJHDOVRFRQWDLQVWKH2EVHUYHULQWHUIDFHDQG2EVHUYDEOHFODVVZKLFK DOORZREMHFWVWRQRWLI\RQHDQRWKHUZKHQWKH\FKDQJH 82

Comp-U-Learn

Interfaces and Packages

Summary Interfaces are declared like classes but using the keyword interface. Interface has two parts the interface declaration and the interface body. Any class outside the hierarchy can implement interfaces. Interfaces are mainly used to draw a similarity between unrelated classes. Interfaces are not a substitute for multiple inheritance. All the methods declared in the interface are abstract. Implementing the interface results in the implementation of the methods declared in the interface. A package is a group of classes similar to the libraries offered by most programming languages. Packages help simplify programming and remove the overhead of remembering fully qualified package names to refer a class. The keyword package identifies the package. The import statement is used to import classes of a package in other programs. Some of the standard Java packages are java.applet, java.lang, java.net, java.util, java.awt and java.io.

Going Over It Again I. Fill in the Blanks

 $QLQWHUIDFHLVGHFODUHGXVLQJBBBBBBBBBNH\ZRUG  $OOWKHPHWKRGVLQDQLQWHUIDFHDUHBBBBBBBB  $SDFNDJHDOZD\VFRQWDLQBBBBBBBSXEOLFFODVV  BBBBBBBSDFNDJHSURYLGHVDOLEUDU\RIPDWKURXWLQHV  BBBBBBBBSDFNDJHSURYLGHVDVHWRILQSXWDQGRXWSXWVWUHDPVXVHGWRUHDGDQGZULWHGDWD WRILOHVRURWKHULQSXWDQGRXWSXWVRXUFHV II. State True or False

 ,QWHUIDFHLVDQDOWHUQDWLYHWRPXOWLSOHLQKHULWDQFH  $FODVVFDQH[WHQGPRUHWKDQRQHFODVV  0HWKRGLPSOHPHQWDWLRQVDQGYDULDEOHVDUHLQKHULWHGIURPDQLQWHUIDFH  $QLQWHUIDFHFDQQRWH[WHQGRWKHULQWHUIDFHV  3URWHFWHGGDWDFDQEHDFFHVVHGE\WKHQRQVXEFODVVHVRIRWKHUSDFNDJHV

Comp-U-Learn

83

Java Programming I

III. One line Answers

 'HILQHLQWHUIDFH  'LIIHUHQWLDWHPXOWLSOHLQKHULWDQFHDQGLQWHUIDFH  'HILQHLQQHUFODVVHV  :KDWLVWKHDGYDQWDJHRILPSOHPHQWLQJFORQH PHWKRG"  :ULWHDVKRUWQRWHRQSDFNDJHV

84

Comp-U-Learn

Session 5

Streams and File Handling

On Completion of this Session We will be able to understand...

) Stream class and its functions ) System Properties ) Input Stream and its methods ) Output Streams and its methods ) Directory Structure ) File Input and Output Streams ) Buffered Streams & Filtered Streams

In This Session...



Java Stream Class



Print Stream



System Properties



Input and Output Streams



Files and Directories



File Input and Output Streams



Data Input and Output Streams



Filtered Streams



Buffered Streams



Pushback Input Streams



Random Access File



Reader and Writer Classes

Streams and File Handling

Java Stream Class 6WUHDP LQ -DYD LV D JHQHUDO DEVWUDFWLRQ RI WKH GDWD WUDQVIHU PHFKDQLVP 6HSDUDWH VWUHDPV DUH SURYLGHGIRULQSXWDQGRXWSXW$OOLQSXWRXWSXWRSHUDWLRQVLQ-DYDDUHGRQHXVLQJWKHEDVLFW\SH E\WH&KDUDFWHUVDUHGHDOWWKURXJKWKHLUVSHFLILFFRGHZKRVHYDOXHVDUHE\WHW\SH-DYDSURJUDPV DOO UHDG IURP DQG ZULWH WR VWUHDPV $ VWUHDP LV D IORZLQJ VHTXHQFH RI FKDUDFWHUV 7KH LQSXW VRXUFH FDQ EH IURP D NH\ERDUG D ILOH RU WKH QHWZRUN DQG WKH RXWSXW GHVWLQDWLRQ FDQ EH WKH VFUHHQRUDILOHRUWKHQHWZRUN7KHGDWHLVVHQWRUUHFHLYHGDVDVHTXHQFHRIE\WHV The Stream Classes

-DYDLPSOHPHQWVVWUHDPVZLWKLQDFODVVKLHUDUFK\GHILQHGLQWKHMDYDLRSDFNDJH$WWKHWRS RI WKHKLHUDUFK\DUHWZRDEVWUDFWFODVVHV,QSXW6WUHDPDQG2XWSXW6WUHDP-DYDKDVVHYHUDOFRQFUHWH VXEFODVVHVRIHDFKWRKDQGOHWKHGLIIHUHQFHVEHWZHHQYDULRXVGHYLFHVVXFKDVGLVNILOHVQHWZRUN FRQQHFWLRQVDQGHYHQPHPRU\EXIIHUV

Print Stream 7KH3ULQW6WUHDPFODVVSURYLGHVDOORI WKHIRUPDWWLQJ FDSDELOLWLHVZH KDYH EHHQ XVLQJ IURP WKH 6\VWHP ILOH KDQGOH 6\VWHPRXW -DYD·V 3ULQW6WUHDP  REMHFWV VXSSRUW WKH SULQW  DQG SULQWOQ PHWKRGV IRU DOO W\SHV LQFOXGLQJ REMHFWV  7KH PHWKRGV RI WKLV FODVV DUH ZLGHO\ XVHG LQ -DYD DSSOLFDWLRQV 7KH WZR PHWKRGV WKDW DUH YHU\ IDPLOLDU WR XV DUH 6\VWHPRXWSULQWOQ  DQG 6\VWHPRXWSULQW  7KH6\VWHPHUUPHWKRGLVXVHGWRSULQWHUURUPHVVDJHVDQG6\VWHPLQLVDQ ,QSXW6WUHDP Print, println and write methods

7KHSULQWDQGSULQWOQPHWKRGVDUHHVVHQWLDOO\WKHVDPHWKH\ERWKZULWHWKHLUVWULQJDUJXPHQWWR WKHVWUHDP7KHRQHGLIIHUHQFHEHWZHHQWKHWZRLVWKDWSULQWOQDGGVDQHZOLQHFKDUDFWHUWRWKH HQGRILWVRXWSXWZKHUHDVSULQWGRHVQ·W System.out.println(“welcome to Java streams “);

,VWKHVDPHDV System.out.print(“Welcome to Java steams \n”);

7KHZULWHPHWKRGLVOHVVIUHTXHQWO\XVHGWKDQSULQWRUSULQWOQFRPPDQGV:ULWHLVXVHGWRZULWH E\WHVWRWKHVWUHDP7KH\DUHXVHGWRZULWH1RQ$6&,,GDWD Comp-U-Learn

87

Java Programming I Java’s Stream Input Output Classes

Stream Class BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutput Stream File File Descriptor FileInputStream FileOutputStream FilterInputStream FilterOutputStream InputStream LineNumberInputStream OutputStream PipedInputStream PipedOutputStream PrintStream PushbackInputStream RandomAccessFile SequenceInputStream

Stream Tokenizer String BufferInputStream

Definition Buffered input stream Buffered output stream Input stream that reads from a byte array Output stream that writes to a byte array An input stream that contains methods for reading Java standard data types An output stream that contains methods for writing Java standard data types Deals directly with files and the file system Deals with record pointers, file descriptions and file access mechanisms Input stream that reads from a file Output stream that writes to a file Implements Input Stream Implements Output Stream Abstract class that describes stream input Input stream that counts lines Abstract class that describes stream output Input pipe Output pipe Output stream that contains print() and println() Input stream that supports one-byte “unget” which returns a byte to the input stream Supports random access file I/O Input stream that is a combination of two or more input streams which will be read sequentially, one after the other Tokenizing input stream Input streams that read from a string

Built-in streams in Java

$OO-DYDSURJUDPVDXWRPDWLFDOO\LPSRUWWKHMDYDODQJSDFNDJH7KLVSDFNDJHGHILQHVDFODVVFDOOHG 6\VWHPZKLFKHQFDSVXODWHVVHYHUDODVSHFWVRIWKHUXQWLPHHQYLURQPHQW,WDOVRFRQWDLQVWKUHH SUHGHILQHGYDULDEOHVFDOOHGLQRXWDQGHUU7KHVHILHOGVDUHGHFODUHGDVSXEOLFDQGVWDWLFZLWKLQ 6\VWHP 7KLV PHDQV WKDW WKH\ FDQ EH XVHG E\ DQ\ RWKHU SDUW RI RXU SURJUDP DQG ZLWKRXW UHIHUHQFHWRDVSHFLILF6\VWHPREMHFW 88

Comp-U-Learn

Streams and File Handling

6\VWHPRXWUHIHUVWRWKHVWDQGDUGRXWSXWVWUHDP%\GHIDXOWWKLVUHIHUVWRWKHPRQLWRU6\VWHPLQ UHIHUVWRWKHVWDQGDUGLQSXWVWUHDPZKLFKLVE\GHIDXOWWKHNH\ERDUG6\VWHPHUUUHIHUVWRWKH VWDQGDUG HUURU VWUHDP ZKLFK LV DOVR WKH VFUHHQ E\ GHIDXOW +RZHYHU WKHVH VWUHDPV FDQ EH UHGLUHFWHGWRDQ\FRPSDWLEOH,2GHYLFH

System Properties 7KH6\VWHPFODVVPDLQWDLQVDVHWRISURSHUWLHVNH\YDOXHSDLUVWKDWGHILQHWUDLWVRUDWWULEXWHVRI WKH FXUUHQW ZRUNLQJ HQYLURQPHQW :KHQ WKH UXQWLPH V\VWHP ILUVW VWDUWV XS WKH V\VWHP SURSHUWLHV DUH LQLWLDOL]HG WR FRQWDLQ LQIRUPDWLRQ DERXW WKH UXQWLPH HQYLURQPHQW LQFOXGLQJ LQIRUPDWLRQ DERXW WKH FXUUHQW XVHU WKH FXUUHQW YHUVLRQ RI WKH -DYD UXQWLPH DQG HYHQ WKH FKDUDFWHU XVHG WR VHSDUDWH FRPSRQHQWV RI D ILOH QDPH 7KH 6\VWHP FODVV SURYLGHV VHYHUDO PHWKRGV WR UHDG DQG ZULWH V\VWHP SURSHUWLHV ,W LV SRVVLEOH WR FKDQJH WKH VHW RI V\VWHP SURSHUWLHVFRPSOHWHO\7KH6\VWHPFODVVFRQWDLQVWZRSURSHUWLHVJHW3URSHUW\DQGJHW3URSHUWLHV 7KH*HW3URSHUW\PHWKRGUHWXUQVDVWULQJFRQWDLQLQJWKHYDOXHRIWKHSURSHUW\3URYLGHGDVDQ DUJXPHQW)RUH[DPSOH System.getProperty(“home.name”);

,IWKHDUJXPHQWGRHVQRWKDYHDYDOXHRUWKHSURSHUW\GRHVQRWH[LVWWKHQ1XOO3RLQWHU([FHSWLRQ ZLOOEHUDLVHG7RDYRLGWKLVZHFDQXVHOLNH System.getProperty(“home.name”,”Nothing “);

7KLV PHWKRG ZLOO UHWXUQ WKH YDOXH ´1RWKLQJµ LI WKH DUJXPHQW KRPHQDPH GRHV QRW KDYH DQ\ YDOXH 7KH JHW3URSHUWLHV PHWKRG UHWXUQV D 3URSHUWLHV REMHFW WKDW FRQWDLQV D FRPSOHWH VHW RI V\VWHPSURSHUW\NH\YDOXHSDLUV 7KHVHW3URSHUWLHV PHWKRGLVXVHGWRPRGLI\WKHH[LVWLQJVHWRIV\VWHPSURSHUWLHV7KLVPHWKRG WDNHV D 3URSHUWLHV REMHFW WKDW KDV EHHQ LQLWLDOL]HG WR FRQWDLQ WKH NH\YDOXH SDLUV IRU WKH SURSHUWLHVWKDWKDVWREHVHW7KLVPHWKRGUHSODFHVWKHHQWLUHVHWRIV\VWHPSURSHUWLHVZLWKWKH QHZ VHW UHSUHVHQWHG E\ WKH 3URSHUWLHV REMHFW 7KH VHW3URSHUWLHV PHWKRG FKDQJHV WKH VHW RI V\VWHP SURSHUWLHV IRU WKH FXUUHQW UXQQLQJ DSSOLFDWLRQ 7KHVH FKDQJHV DUH QRW SHUVLVWHQW &KDQJLQJV\VWHPSURSHUWLHVZLWKLQDQDSSOLFDWLRQZLOOQRWDIIHFWIXWXUHLQYRFDWLRQVRIWKH-DYD LQWHUSUHWHU IRU WKLV RU DQ\ RWKHU DSSOLFDWLRQ 7KH UXQ WLPH V\VWHP UHLQLWLDOL]HV WKH V\VWHP SURSHUWLHV HDFK WLPH LWV VWDUWV XS $Q ([DPSOH WR VKRZ WKH JHW3URSHUWLHV DQG VHW3URSHUWLHV 0HWKRGVLVJLYHQEHORZ

Comp-U-Learn

89

Java Programming I

Example 5.1 import java.io.FileInputSteeam; import java.util,Properties; class PropertiesTest { public static void main(String args[]) { try { FileInputStream pfile=new FileInputStream(“MyProps.txt”); Properties p=new Properties(System.getProperties()); p.load(pfile); System.setProperties(p); System.getProperties().list(System.out); } catch(java.io.FileNotFoundException e) { System.err.println(“Cannot find the file MyProps.txt”); } catch(java.io.IOException e) { System.err.printlln(“Input Output Error “); } } }

+HUHWKHJHW3URSHUWLHV PHWKRGZLOOUHWXUQD3URSHUWLHVREMHFWZLWKWKHFXUUHQWVHWRIV\VWHP SURSHUWLHV LQLWLDOL]HG E\ WKH UXQWLPH V\VWHP DORQJ ZLWK WKH SURSHUWLHV DYDLODEOH LQ WKH ILOH ´0\3URSVW[Wµ2QFHGRQHWKHVHSURSHUWLHVDUHVHWXVLQJWKHVHW3URSHUW\PHWKRG

Note Finalization can be forced to occur by the method System.runFinalization and the garbage collector can be made to run at anytime using System.gc(). Method read()

7KHORZHVWOHYHOLQSXWPHWKRGLVUHDG ,WFRPHVLQVHYHUDOIRUPV(DFKWLPHUHDG LVFDOOHGLW UHDGVDVLQJOHE\WHIURPWKHLQSXWVWUHDPDQGUHWXUQVLWDVDQLQWHJHUYDOXH,WUHWXUQV²ZKHQ WKH HQG RI WKH VWUHDP LV HQFRXQWHUHG ,W FDQ WKURZ DQ ,2([FHSWLRQ ([FHSWLRQV UHIHU WR QRQ KDQGOHGHUURUVDQGDEQRUPDOLWLHVRFFXULQJGXULQJDSURJUDPH[HFXWLRQVXFKDVGLYLVLRQE\]HUR ILOH QRW IRXQG HWF ([FHSWLRQV DUH KDQGOHG LQ GHWDLO LQ WKH IROORZLQJ VHVVLRQ 7KH IROORZLQJ SURJUDPGHPRQVWUDWHVUHDG ,WUHDGVFKDUDFWHUVIURPWKHVWDQGDUGLQSXWXQWLOWKHXVHUW\SHVD ´Tµ

90

Comp-U-Learn

Streams and File Handling

Example 5.2 import java.io.*; class ex22 { public static void main(String args[]) throws IOException { char c; System.out.println("enter characters, q to quit. "); do{ c=(char)System.in.read(); System.out.println(c); }while(c!='q'); } }

7KHRXWSXWLVGLIIHUHQWEHFDXVH6\VWHPLQLVOLQHEXIIHUHGE\GHIDXOW 7KHRXWSXWRIWKHSURJUDPLV enter characters, q to quit. 123456q 1 2 3 4 5 6

Reading a String

-DYD SURYLGHV D EXLOW LQ PHWKRG FDOOHG UHDG/LQH  ZKLFK DXWRPDWLFDOO\ UHDGV D VHTXHQFH RI FKDUDFWHUVIURPWKHLQSXWVWHDPDQGUHWXUQVWKHPLQ DQREMHFW RIW\SH6WULQJ 7KLVPHWKRG LV SDUW RI WKH 'DWD,QSXW6WUHDP FODVV ZKLFK SURYLGHV PHWKRGV IRU UHDGLQJ DOO RI -DYD·V VLPSOH W\SHVSOXVOLQHVRIWH[W7KHJHQHUDOIRUPRIUHDG/LQH LV Final String readLine() throws IOException

UHDG/LQH  UHWXUQV D VWULQJ REMHFW %HIRUH XVLQJ UHDG/LQH  ZH PXVW REWDLQ D 'DWD,QSXW6WUHDP REMHFWWKDWLVOLQNHGWRDQLQSXWVWUHDP7KHJHQHUDOIRUPLV DataInputStream(InputStream istream)

+HUHLVWUHDPLVWKHVWUHDPWKDWLVOLQNHGWRWKHLQVWDQFHRI'DWD,QSXW6WUHDPEHLQJFUHDWHG7R UHDG FRQVROH LQSXW ZH FDQ XVH 6\VWHPLQ IRU WKLV SDUDPHWHU $Q H[DPSOH WR GHPRQVWUDWH WKH DERYHFRQFHSWLVJLYHQEHORZ

Comp-U-Learn

91

Java Programming I

Example 5.3 import java.io.*; class ex23 { public static void main(String args[]) throws IOException { DataInputStream in=new DataInputStream(System.in); String str; System.out.println("Enter lines of text "); System.out.println("Enter 'End' to quit"); do{ str=in.readLine(); System.out.println(str); }while(!str.equals("End")); } }

7KHRXWSXWRIWKHSURJUDPZLOOEH Enter lines of text Enter ‘End’ to quit Ba ba Black Sheep Ba ba Black Sheep Have you any wool Have you any wool End End

$QRWKHUH[DPSOHWRVKRZWKHEHKDYLRURI,2VWUHDPVLVJLYHQEHORZ Example 5.4 import java.io.*; class ex24 { public static void main(String args[]) throws IOException { DataInputStream in=new DataInputStream(System.in); String str[]=new String[50]; System.out.println("Enter lines of text "); System.out.println("Enter 'End' to quit"); for(int i=0;i<50;i++) { str[i]=in.readLine(); if(str[i].equals("End")) break;

92

Comp-U-Learn

Streams and File Handling } System.out.println("The file is for(int i=0;i<50;i++) { if(str[i].equals("end")) break; System.out.println(str[i]); } } }

");

7KHRXWSXWRIWKHSURJUDP Enter lines of text Enter ‘End’ to quit Ba ba black sheep Have you any wool End The file is Ba ba black sheep Have you any wool End

Input and Output Streams Input Stream

7KH ,QSXW6WUHDP FODVV KDQGOHV DQ\ NLQG RI LQSXW $OO WKH PHWKRGV RI WKLV FODVV WKURZ DQ ,2([FHSWLRQ LI DQ\ HUURU RFFXUV 7KH VXPPDU\ RI WKH PHWKRGV DYDLODEOH LQ WKLV FODVV LV OLVWHG KHUHXQGHU read()

Returns an int representation of the next available byte. read(byte b[])

$WWHPSWV WR UHDG V E\WHV LQWR WKH DUUD\ E ZKHUH V LV WKH VL]H RI WKH DUUD\ E V EOHQJWK  ,W UHWXUQVDQLQWWHOOLQJKRZPDQ\E\WHVDUHDFWXDOO\UHDG WKHDFWXDOE\WHVUHDGPD\EHOHVVWKDQWKH DUUD\VL]H  read(byte b[],int off,int len)

$WWHPSWV WR UHDG XS WR FK E\WHV DQG VWRUHV WKHP LQ E IURP E>RII@ RQZDUGV ,W UHWXUQV DQ LQW WHOOLQJKRZPDQ\E\WHVDUHDFWXDOO\UHDG

Comp-U-Learn

93

Java Programming I skip(long n)

:LOOVNLSQQH[WE\WHVDQGZLOOUHWXUQWKHQXPEHURIDFWXDOE\WHVVNLSSHG available()

5HWXUQVWKHQXPEHURIE\WHVFXUUHQWO\DYDLODEOHIRUUHDGLQJ WKHVHDUHMXVWWKHUHPDLQLQJXQUHDG E\WHV close()

&ORVHVWKHFXUUHQW,QSXW6WUHDP)XUWKHUDWWHPSWWRUHDGWKURHVDQ,2([FHSWLRQ mark(int rr)

3ODFHVDPDUNDWWKHFXUUHQWSRVLWLRQ7KLVPDUNZLOOUHPDLQYDOLGXQWLOQH[WUUE\WHV DUHUHDG 8VLQJWKLVPDUNZHPD\FRPHEDFNWRWKLVSRVLWLRQDQGVWDUWDIUHVKUHDGLQJ reset()

5HWXUQVWKHLQSXWSRLQWHUWRWKHSUHYLRXVO\PDUNHGSRVLWLRQ mark supported()

5HWXUQVWUXHLIPDUN DQGUHVHW PHWKRGVDUHVXSSRUWHGRQWKLVVWUHDP Output Stream

/LNH ,QSXW6WUHDP -DYD GHILQHV 2XWSXW6WUHDP DV DQ DEVWUDFW FODVV WR GHDO ZLWK DOO NLQGV RI RXWSXWV $OO PHWKRGV RI WKLV FODVV UHWXUQ YRLG DQG WKURZ DQ ,2([FHSWLRQ LQ FDVH RI IDLOXUHV +HUHLVWKHOLVWRILWVPHWKRGV write(int b)

:ULWHVDVLQJOHE\WHWRDQRXWSXWVWUHDP DIWHUFRQYHUWLQJLWWRE\WHW\SH 6LQFHWKHW\SHRIELV LQW ZH FDQ FRQVWUXFW H[SUHVVLRQV RI DOUHDG\ GHILQHG LQW YDULDEOHV IRU SDVVLQJ DV WKH GXPP\ SDUDPHWHUE write(byte b[])

:LOOZULWHDFRPSOHWHDUUD\RIE\WHVRQWKHRXWSXWVWUHDP

94

Comp-U-Learn

Streams and File Handling write(byte b[]. Int off, int len)

:ULWHOHQE\WHVIURPWKHDUUD\EVWDUWLQJIURPE>RII@ flush()

)OXVKHVDQ\E\WHVWKDWKDYHEHHQZULWWHQWRWKHORJLFDO2XWSXW6WUHDPEXWKDYHQRWUHDFKHGWR WKHDFWXDOGHYLFH OLNHDILOHRQWKHGLVN  close()

&ORVHVWKHVWUHDP)XUWKHUDWWHPSWWRZULWHZLOOJHQHUDWHDQHUURU

Files and Directories )LOHVDUHWKHSULPDU\VRXUFHDQGGHVWLQDWLRQIRUGDWDZLWKLQPRVWSURJUDPV)LOHLQSXWRXWSXW RSHUDWLRQLVFRPPRQLQDQ\ODQJXDJH-DYDGHYRWHVDZKROHUDQJHRIPHWKRGVIRXQGLQDFODVV FDOOHG)LOHLQWKHMDYDLRSDFNDJHWRGRWKHVHRSHUDWLRQV)LOHLVDVXEFODVVRI6WUHDPLQ-DYD7KLV LV WKH RQO\ VXEFODVV WKDW GHDOV ZLWK WKH ILOHV LQ WKH GLVN ILOH V\VWHP 8VDJH RI ILOHV KDV VHYHUH UHVWULFWLRQVLQDSSOHWVWRHQVXUHWKDWWKHGLVNRIWKHGHVWLQDWLRQ UXQWLPHHQYLURQPHQW LVQRW FRUUXSWHG E\ DQ\ FKDQFH %XW ILOHV DUH UHTXLUHG IRU DQ\ RWKHU DSSOLFDWLRQ SURJUDP WKDW GRHV VRPHWKLQJXVHIXOIRUWKHDYDLODEOHGDWDDQGSURGXFHVUHVXOWVRISHUPDQHQW QDWXUH-DYDWHDWVD GLUHFWRU\DOVRDVDILOHEXWFHUWDLQPHWKRGVIRUILOHVDQGGLUHFWRULHVDUHGLIIHUHQW$)LOHREMHFWLV XVHGWRREWDLQRUPDQLSXODWHWKHLQIRUPDWLRQDVVRFLDWHGZLWKDGLVNILOHVXFKDVWKHSHUPLVVLRQV WLPHDQGGDWHDQGGLUHFWRU\SDWKDQGWRQDYLJDWHVXEGLUHFWRU\KLHUDUFKLHV6LQFH)LOHGRHVQRW RSHUDWH RQ VWUHDPV LW LV QRW D VXEFODVV RI ,QSXW6WUHDP RU 2XWSXW6WUHDP 7KH IROORZLQJ FRQVWUXFWRUVDUHXVHGWRFUHDWH)LOHREMHFWV ♦ File(String dirpath) ♦ File(String dirpath, String filename) ♦ File(File dirObj, String filename) +HUHWKHGLUSDWKLVWKHSDWKQDPHRIWKHILOHILOHQDPHLVWKHQDPHRIWKHILOHDQGGLU2EMLVDILOH REMHFWWKDWVSHFLILHVDGLUHFWRU\ 7KHIROORZLQJH[DPSOHFUHDWHVWKUHHILOHVILIDQGI7KHILUVW)LOHREMHFWLVFRQVWUXFWHGZLWKD GLUHFWRU\SDWKDVWKHRQO\DUJXPHQW7KHVHFRQGLQFOXGHVWZRDUJXPHQWV²WKHSDWKDQGWKHILOH QDPH7KHWKLUGLQFOXGHVWKHILOHSDWKDVVLJQHGWRIDQGDILOHQDPHIUHIHUVWRWKHVDPHILOHDV I 7KH QH[W LQFOXGHV WKH GLUHFWRU\ XQGHU ZKLFK WKH SDUWLFXODU ILOH ´DXWRH[HFEDWµ KDV WR EH FUHDWHG Comp-U-Learn

95

Java Programming I File File File File

f1=new f2=new f3=new f3=new

File(“/”); File(“/”, “autoexec.bat”); File(f1,”autoexec.bat”); File(“user”,”autoexec.bat”);

Note The Java convention is to use the UNIX and URL style forward slash for path separators. Methods of File Class

7KHIROORZLQJDUHVRPHRIWKHLPSRUWDQWPHWKRGVDYDLODEOHLQWKH)LOHFODVV getName()

7KLVPHWKRGLVXVHGWRREWDLQWKHQDPHRIWKHILOHVSHFLILHG getPath()/ getAbsolutePath()

7KHVH PHWKRGV KHOS WR JHW WKH SDWK RI WKH ILOH VSHFLILHG DQG WKH DEVROXWH SDWK RI WKH ILOH VSHFLILHGUHVSHFWLYHO\ exists()

7KLVPHWKRGLVXVHGWRFKHFNLIWKHQDPHGILOHH[LVWVLQWKDWGLUHFWRU\RUQRW isFile()/isDirectory()

7KHVHDUHXVHGWRFKHFNLIWKHQDPHGILOHLVDQRUGLQDU\ILOHRUDGLUHFWRU\UHVSHFWLYHO\ canRead()/canWrite()

7KHVH PHWKRGV DUH XVHG WR FKHFN LI WKH VSHFLILHG ILOH LV UHDGDEOHZULWDEOH UHVSHFWLYHO\ 7KHVH PHWKRGVUHWXUQD%RROHDQYDOXHGHSHQGLQJRQWKHLUUHDGDELOLW\ZULWDELOLW\ lastModified()

7KLVPHWKRGUHWXUQVWKHODVWPRGLILFDWLRQWLPHRIWKHILOH length()

7KLVPHWKRGLVXVHGWRNQRZWKHILOHVL]HLQE\WHV

96

Comp-U-Learn

Streams and File Handling delete()

7KLVPHWKRGLVXVHGWRGHOHWHWKHVSHFLILHGILOH renameTo()

7KLVPHWKRGLVXVHGWRUHQDPHDVSHFLILHGILOH,WWDNHVDILOHREMHFWWKDWEHFRPHVWKHGHVWLQDWLRQ ILOHRUWKHUHQDPHGILOHDVLWVSDUDPHWHU isFile()

7KLVUHWXUQVWUXHPRVWRIWKHWLPHEXWVRPHVSHFLDOILOHVVXFKDVGHYLFHGULYHUVDQGQDPHGSLSHV PD\QRWEHKDYHOLNHQRUPDOILOHVVRWKLVPHWKRGFDQEHXVHGWRPDNHVXUHWKDWWKHHQWLW\ZH DFFHVVLVDILOH isAbsolute()

7KLVPHWKRGUHWXUQVWUXHLIWKHILOHKDVDQDEVROXWHSDWKIDOVHLIUHODWLYH $QH[DPSOHWRVKRZWKHZRUNLQJRIYDULRXVPHWKRGV&UHDWHDVLPSOHWH[WILOHFDOOHGGXPP\W[W XQGHUF?H[DPSOHWRUXQWKLVSURJUDP Example 5.5 import java.io.File; class ex25 { static void a(String s) { System.out.println(s); } public static void main(String args[]) { File f1=new File("c:/example/dummy.txt"); a("File Name : " + f1.getName()); a("Path : "+f1.getPath()); a("Absolute Path is :" + f1.getAbsolutePath()); a("Parent : " +f1.getParent()); a(f1.exists() ? "File exists " : "File does not exist "); a(f1.canWrite() ? "is writable " : " is not writable "); a(f1.canRead() ? "readable " : " is not readable"); a("is" +(f1.isDirectory() ? "" : "not" +" a directory")); a(f1.isFile() ? "is normal file" : "is not a normal file"); a(f1.isAbsolute() ? "is absolute " : "is not absolute "); a("file last modified : " + f1.lastModified()); a("file size : " + f1.length() + "Bytes "); } }

Comp-U-Learn

97

Java Programming I

7KHRXWSXWRIWKHSURJUDPLV File name : dummy.txt Path : c:\example\dummy.txt Absolute Path : c:\example\dummy.txt Parent : c:\example File exists is writable readable isnot a directory is normal file is absolute file last modified : 934007788000 file size : 217 Bytes

Directories

$ GLUHFWRU\ LV D )LOH WKDW FRQWDLQV D OLVW RI RWKHU ILOHV DQG GLUHFWRULHV :KHQ ZH FUHDWH D )LOH REMHFWDQGLWLVDGLUHFWRU\WKHLV'LUHFWRU\ PHWKRGZLOOUHWXUQWUXH,QWKLVFDVHZHFDQFDOOWKH OLVWPHWKRGRQWKDWREMHFWWRH[WUDFWWKHOLVWRIRWKHUILOHVDQGGLUHFWRULHVLQVLGH7KHOLVWRIILOHV LVUHWXUQHGLQDQDUUD\RI6WULQJREMHFWV7KHSURJUDPVKRZQKHUHZLOOGHPRQVWUDWHWKHXVDJHRI OLVWPHWKRGWRH[DPLQHWKHFRQWHQWVRIDGLUHFWRU\&DOOLQJWKHOLVWPHWKRGRQD)LOHREMHFWWKDW LVQRWDGLUHFWRU\ZLOOFDXVHUXQWLPH1XOO3RLQWHU([FHSWLRQ Example 5.6 import java.io.File; class ex26 { public static void main(String args[]) { int i; String dname="C:/jdk1.2"; File f1=new File(dname); if(f1.isDirectory()) { System.out.println("Directory contents of "+dname); String s[]=f1.list(); for(i=0;i<s.length;i++) { File f=new File(dname + "/" + s[i]); if (f.isDirectory()) System.out.println(s[i] + " is a Directory"); else System.out.println(s[i] + " is a file"); } } else

98

Comp-U-Learn

Streams and File Handling System.out.println(dname+ " is not a Directory"); } }

7KHRXWSXWRIWKHSURJUDP C:\jdk1.2\bin>java ex26 Directory contents of C:/jdk Uninst.isuis a file binis a Directory READMEis a file LICENSEis a file COPYRIGHTis a file README.htmlis a file jreis a Directory libis a Directory includeis a Directory include-oldis a Directory demois a Directory src.jaris a file

FilenameFilter

7KLVLVXVHGWROLPLWWKHQXPEHURIILOHVUHWXUQHGE\WKHOLVW PHWKRGWRLQFOXGHRQO\WKRVHILOHV ZKLFKPDWFKDFHUWDLQILOHQDPHSDWWHUQRUILOWHU7KHQOLVWPHWKRGLVXVHGDVIROORZV String[] list(FilenameFilter ffobject);

)LOHQDPHILOWHULVDQLQWHUIDFH DQGIIREMHFWLVDQREMHFWRIWKLVLQWHUIDFH7KLVLQWHUIDFH GHILQHV RQO\DVLQJOHPHWKRGFDOOHGDFFHSW ZKLFKLVFDOOHGRQFHIRUHDFKILOHLQDOLVW7KLVPHWKRGLV XVHGIRUH[WUDFWLQJILOHVZLWKDSDUWLFXODUH[WHQVLRQ7KHJHQHUDOV\QWD[IRUDFFHSW LV Boolean accept(File dir,String filename)

7KHDFFHSW PHWKRGUHWXUQVWUXHIRUILOHVLQWKHGLUHFWRU\E\GLUWKDWVKRXOGEHLQFOXGHGLQWKH OLVWWKDWLVWKRVHPDWFKWKHILOHQDPHDUJXPHQWDQGIDOVHIRUWKRVHWKDWVKRXOGEHH[FOXGHG$Q H[DPSOHWRVKRZWKHZRUNLQJRI)LOHQDPH)LOWHUIROORZV Example 5.7 import java.io.*; public class OnlyExt implements FilenameFilter { String ex; public OnlyExt(String ex) { this.ex="." +ex;

Comp-U-Learn

99

Java Programming I } public boolean accept(File dir,String fname) { return fname.endsWith(ex); } }

6DYHWKLVILOHZLWKWKHH[WHQVLRQ2QO\([WMDYDXQGHUELQ import java.io.*; class ex27 { public static void main(String args[]) { String dirname="C:/example"; File f1=new File(dirname); FilenameFilter ff=new OnlyExt("doc"); String s[]=f1.list(ff); for(int i=0; i<s.length;i++) System.out.println(s[i]); } }

7KHRXWSXWRIWKHSURJUDPH[MDYDLVDVIROORZV C:\jdk1.2\bin>javac ex27.java C:\jdk1.2\bin>java ex27 OOPs In Java.doc ~$ided tour-3 qns.doc ~$terfaces.doc ~$treams.doc Answers to guide tour-3.doc guided tour-3 qns.doc Interfaces.doc Streams.doc Cover Page.doc C:\jdk1.2\bin>

File Input and Output Streams FileInput Stream

)LOH VWUHDP FRQVLVWV RI WKH )LOH,QSXW6WUHDP DQG )LOH2XWSXW6WUHDP 7KH )LOH,QSXW6WUHDP FODVV FUHDWHVDQ,QSXW6WUHDPWKDWZHFDQXVHWRUHDGWKHFRQWHQWVRIDILOH7KLVFODVVUHDGVGDWDIURP WKHDFWXDOGLVNILOHV7KHWZRPRVWFRPPRQFRQVWUXFWRUVDUH 100

Comp-U-Learn

Streams and File Handling

FileInputStream(String filepath) FileInputStream(File fileobj) (LWKHUFDQWKURZXSD)LOHQRW)RXQG([FHSWLRQ+HUHILOHSDWKLVWKHIXOOQDPHRIDILOHDQGILOHREM LVD)LOHREMHFWWKDWGHVFULEHVWKHILOH 7KHIROORZLQJH[DPSOHFUHDWHVWZR)LOH,QSXW6WUHDPVWKDWXVHWKHVDPHGLVNILOHDQGHDFKRIWKH WZRFRQVWUXFWRUV FileInputStream f1=new FileInputStream(“c:/jdk1.2/bin/ex27.java”); File f=new File(“c:/jdk1.2/bin/ex27.java”); FileInputStream f1=new FileInputStream(f);

$OWKRXJKWKHILUVWFRQVWUXFWRULVSUREDEO\PRUHFRPPRQO\XVHGWKHVHFRQGDOORZVXVWRFORVHO\ H[DPLQH WKH ILOH XVLQJ WKH )LOH PHWKRGV EHIRUH ZH DWWDFK LW WR DQ LQSXW VWUHDP :KHQ D )LOH,QSXW6WUHDP LV FUHDWHG LW LV RSHQHG IRU UHDGLQJ )LOH,QSXW6WUHDP RYHUULGHV VL[ RI WKH PHWKRGVLQWKHDEVWUDFWFODVV,QSXW6WUHDP7KHPDUN DQGUHVHW PHWKRGVDUHQRWRYHUULGGHQ DQGDQ\DWWHPSWWRXVHWKHVHPHWKRGVRQD)LOH,QSXW6WUHDPZLOOJHQHUDWHDQ,2([FHSWLRQ FileOutput Stream

)LOH2XWSXW6WUHDP FUHDWHV DQ 2XWSXW6WUHDP WKDW ZH FDQ XVH WR ZULWH WR D ILOH ,WV WZR PRVW FRPPRQFRQVWUXFWRUVDUH FileOutputStream(String filePath) FileOutputStream(File fileObj) (LWKHUFDQWKURZDQ,2([FHSWLRQRUDVHFXULW\H[FHSWLRQ+HUHILOH3DWKLVWKHIXOOSDWKQDPHRI DILOHDQGILOH2EMLVD)LOHREMHFWWKDWGHVFULEHVWKHILOH&UHDWLRQRID)LOH2XWSXW6WUHDPLVQRW GHSHQGHQWRQWKHILOHDOUHDG\H[LVWLQJ)LOH2XWSXW6WUHDPZLOOFUHDWHWKHILOHEHIRUHRSHQLQJLWIRU RXWSXWZKHQZHFUHDWHWKHREMHFW,QFDVHZKHQZHWU\WRRSHQDUHDGRQO\ILOHDQ,2([FHSWLRQ ZLOO EH WKURZQ 7KH IROORZLQJ H[DPSOH LOOXVWUDWHV  WKH XVDJH RI  )LOH,QSXW6WUHDP DQG )LOH2XWSXW6WUHDP Example 5.8 import java.io.*; class ex28 { public static byte[] getInput() throws Exception { byte inp[]=new byte[150]; System.out.println("enter text"); System.out.println("only 150 bytes ");

Comp-U-Learn

101

Java Programming I System.out.println("Press enter after each line to get input into the program "); for(int i=0;i<150;i++) inp[i]=(byte)System.in.read(); return inp; } public static void main(String args[]) throws Exception { byte input[]=getInput(); OutputStream f=new FileOutputStream("c:/jdk1.2/bin/new.txt"); for(int i=0;i<150;i++) f.write(input[i]); f.close(); int size; InputStream fi=new FileInputStream("c:/jdk1.2/bin/new.txt"); size=fi.available(); for(int i=0;i<size;i++) System.out.print((char)fi.read()); f.close(); } }

2XWSXWRIWKHSURJUDP C:\jdk1.2\bin>java ex28 enter text only 10 bytes Press enter after each line to get input into the program Serialized Serialized C:\jdk1.2\bin>

Data Input and Output Streams 7KLVFODVVFRQWDLQVDVHWRIPHWKRGVWRDFFHSWYDULRXVW\SHVRIGDWD6RPHRIWKHPDUH Int readInt throws IOException Char readChar throws IOException $ VHW RI PHWKRGV H[LVWV LQ WKLV FODVV WR  ZULWH WKH GDWD WR WKH RXWSXW VRXUFH 6RPH RI WKH PHWKRGVDUH void writeBytes(String s) void writeInt(int k) void writeChar(char c) $OO WKHVH PHWKRGV WKURZ ,2([FHSWLRQ $Q H[DPSOH WR VKRZ 'DWD,QSXW DQG 'DWD2XWSXW VWUHDPVLVJLYHQKHUHXQGHU 102

Comp-U-Learn

Streams and File Handling

Example 5.9 import java.io.*; class ex31 { public static void main(String args[]) throws IOException { BufferedReader d=new BufferedReader (new InputStreamReader(new FileInputStream("c:/example/dummy.txt"))); DataOutputStream o=new DataOutputStream (new FileOutputStream("c:/uma/dummy1.txt")); String l; while((l=d.readLine())!= null) { String a=l.toUpperCase(); System.out.println(a); o.writeBytes(a+ "\r\n"); } d.close(); o.close(); } }

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>java ex31 DUMMY FILE CONTENTS THIS IS USED AS TEST FILE FOR ALL EXAMPLES ROSE IS A BEAUTIFUL FLOWER TIGER IS A MAJESTIC ANIMAL BE GOOD DO GOOD

ByteArrayInputStream

%\WH$UUD\,QSXW6WUHDP LV DQ LPSOHPHQWDWLRQ RI DQ LQSXW VWUHDP WKDW XVHV D E\WH DUUD\ DV WKH VRXUFH7KLVFODVVKDVWZRFRQVWUXFWRUVHDFKRIZKLFKUHTXLUHVDE\WHDUUD\WRSURYLGHWKHGDWD VRXUFH %\WH$UUD\,QSXW6WUHDP E\WHDUUD\>@ %\WH$UUD\,QSXW6WUHDP E\WHDUUD\>@LQWVWDUWLQWQXP%\WHV +HUHDUUD\LVWKHLQSXWVRXUFH7KHVHFRQGFRQVWUXFWRUFUHDWHVDQ,QSXW6WUHDPIURPDVXEVHWRI WKHE\WHDUUD\WKDWEHJLQVZLWKWKHFKDUDFWHUDWWKHLQGH[VSHFLILHGE\VWDUWDQGLVQXP%\WHVORQJ $ %\WH$UUD\,QSXW6WUHDP LPSOHPHQWV RQH DGGLWLRQDO PHWKRG WKDW LV QRW VXSSRUWHG E\ D )LOH,QSXW6WUHDPUHVHW  7KLV PHWKRG UHVHWV WKH VWUHDP SRLQWHU WR UHIHU WR WKH VWDUW RI WKH Comp-U-Learn

103

Java Programming I

VWUHDP ZKLFK LQ WKLV FDVH LV WKH VWDUW RI WKH E\WH DUUD\ SDVVHG WR WKH FRQVWUXFWRU %\WH$UUD\2XWSXW LV DQ LPSOHPHQWDWLRQ RI DQ RXWSXW VWUHDP WKDW XVHV D E\WH DUUD\ DV WKH GHVWLQDWLRQ%\WH$UUD\2XWSXW6WUHDPKDVWZRFRQVWUXFWRUV ByteArrayOutputStream() ByteArrayOutputStream(int numBytes) ,QWKHILUVWIRUPDEXIIHURIE\WHVLVFUHDWHG,QWKHVHFRQGDEXIIHULVFUHDWHGZLWKDVL]H HTXDOWRWKDWVSHFLILHGE\QXP%\WHV7KHEXIIHUVL]HZLOOEHLQFUHDVHGDXWRPDWLFDOO\LIQHHGHG 7KHIROORZLQJH[DPSOHDFFHSWVVSHFLILHGQXPEHURIFKDUDFWHUVDVLQSXWDQGFRQYHUWVWKHPLQWR XSSHUFDVHFKDUDFWHUV Example 5.10 import java.io.*; class ex29 { public static void main(String args[]) throws Exception { ByteArrayOutputStream f=new ByteArrayOutputStream(12); System.out.println("enter 10 chars and then press enter key"); System.out.println("these will be converted into uppercase characters "); while(f.size()!=10) { f.write(System.in.read()); } System.out.println("accepted characters into an array"); byte b[]=f.toByteArray(); System.out.println("displaying characters in the array"); for(int i=0;i
104

Comp-U-Learn

Streams and File Handling

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>java ex29 enter 10 chars and then press enter key these will be converted into uppercase characters Acrobatics accepted characters into an array displaying characters in the array A c r o b a t i c s Converted to upper case characters ACROBATICS

StringBufferInputStream

6WULQJ%XIIHU,QSXW6WUHDPLVVLPLODUWR%\WH$UUD\,QSXW6WUHDPH[FHSWWKDWWKHLQWHUQDOEXIIHULVD 6WULQJ LQVWHDG RI D E\WH DUUD\ DQG WKHUH LV QR FRUUHVSRQGLQJ RXWSXW FODVV ,W KDV RQO\ RQH FRQVWUXFWRU StringBufferInputStream(String str)

,QWKLVFRQVWUXFWRUVWULVWKH6WULQJREMHFWXVHGDVWKHLQSXWVRXUFH

Filtered Streams )LOWHUHG VWUHDPV  DUH VLPSO\ ZUDSSHUV DURXQG XQGHUO\LQJ LQSXW RU RXWSXW VWUHDPV WKDW WUDQVSDUHQWO\SURYLGHVRPHH[WHQGHGOHYHORIIXQFWLRQDOLW\7KHVHVWUHDPVDUHW\SLFDOO\DFFHVVHG E\PHWKRGVWKDW DUHH[SHFWLQJDJHQHULFVWUHDPZKLFKLVDVXSHUFODVVRIWKHILOWHUHGVWUHDPV 7\SLFDOH[WHQVLRQVDUHEXIIHULQJFKDUDFWHUWUDQVODWLRQDQGUDZGDWDWUDQVODWLRQ 7KHVH ILOWHUHG VWUHDPV KDYH WKH DGGLWLRQDO IXQFWLRQ RI SURYLGLQJ V\QFKURQL]DWLRQ $OO RI WKH FRQVWUXFWRUV DQG PHWKRGV SURYLGHG LQ WKHVH FODVVHV DUH LGHQWLFDO WR ,QSXW6WUHDP DQG 2XWSXW6WUHDPH[FHSWWKDWWKH\DUHV\QFKURQL]HG

Comp-U-Learn

105

Java Programming I

Buffered Streams %XIIHUHG VWUHDPV H[WHQG WKH ILOWHUHG VWUHDP FODVVHV E\ DWWDFKLQJ D PHPRU\ EXIIHU WR WKH ,2 VWUHDPV 7KLV EXIIHU DOORZV -DYD WR GR ,2 RSHUDWLRQV RQ PRUH WKDQ D E\WH DW D WLPH KHQFH LQFUHDVLQJSHUIRUPDQFH%HFDXVHWKHEXIIHULVDYDLODEOHVNLSSLQJPDUNLQJDQGUHVHWWLQJRIWKH VWUHDPEHFRPHVSRVVLEOH BufferedInputStream

%XIIHULQJ ,2 LV D YHU\ FRPPRQ SHUIRUPDQFH RSWLPL]DWLRQ -DYD·V %XIIHUHG,QSXW6WUHDP FODVV DOORZV XV WR ZUDS DQ\ ,QSXW6WUHDP LQWR D EXIIHUHG VWUHDP DQG DFKLHYH WKLV SHUIRUPDQFH LPSURYHPHQW %XIIHULQJ DQ LQSXW VWUHDP DOVR SURYLGHV WKH IRXQGDWLRQ UHTXLUHG WR VXSSRUW PRYLQJ  EDFNZDUG LQ WKH VWUHDP RI WKH DYDLODEOH EXIIHU 7KLV FODVV DFFHSWV LQSXW E\ XVLQJ D EXIIHUHG DUUD\ RI E\WHV WKDW DFWV DV D FDFKH DQG LW XWLOL]HV WKH PDUN  DQG UHVHW  PHWKRG $ FKXQNRIE\WHVIURPWKHEXIIHUHGDUUD\FDQEHFKRVHQDQGUHDG BufferedOutputStream

$%XIIHUHG2XWSXW6WUHDPLVVLPLODUWRDQ\2XWSXW6WUHDPZLWKWKHH[FHSWLRQRIDQDGGHGIOXVK PHWKRGWKDWLVXVHGWRHQVXUHWKDWGDWDEXIIHUVDUHSK\VLFDOO\ZULWWHQWRWKHDFWXDORXWSXWVWUHDP 6LQFHWKHSRLQWRID%XIIHUHG2XWSXW6WUHDPLVWRLPSURYHSHUIRUPDQFHE\UHGXFLQJWKHQXPEHU RIWLPHVWKHV\VWHPDFWXDOO\ZULWHVWKHGDWDZHPD\QHHGWRFDOOIOXVK WRFDXVHDQ\GDWDWKDWLV LQ WKH EXIIHU WR EH ZULWWHQ 8QOLNH %XIIHUHG,QSXW6WUHDP EXIIHUHG RXWSXW GRHVQ·W SURYLGH DQ\ DGGLWLRQDOIXQFWLRQDOLW\%XIIHUVIRURXWSXWLQ-DYDDUHPHDQWWRLQFUHDVHWKHSHUIRUPDQFH

Pushback Input Stream 3XVKEDFN LV XVHG RQ DQ LQSXW VWUHDP WR DOORZ D FKDUDFWHU WR EH UHDG DQG WKHQ UHWXUQHG  LH SXVKHGEDFN WRWKHVWUHDP7KH3XVKEDFN,QSXW6WUHDPFODVVLPSOHPHQWVWKLVLGHD,WSURYLGHVD PHFKDQLVPWRSHHNDWZKDWLVFRPLQJIURPDQLQSXWVWUHDPZLWKRXWGLVUXSWLQJLW+RZHYHUDQ\ DWWHPSWWRSXVKEDFNPRUHWKDQDVLQJOHFKDUDFWHUUHVXOWVLQDQ,2([FHSWLRQEHLQJWKURZQ$Q H[DPSOHWRVKRZWKH3XVKEDFN,QSXW6WUHDPDQGXQUHDG Example 5.11 import java.io.*; class ex30 { public static void main(String args[]) throws IOException { String s="if (a== 4) a=0 \n"; byte buf[]=new byte[s.length()]; s.getBytes(0,s.length(),buf,0); ByteArrayInputStream in=new ByteArrayInputStream(buf);

106

Comp-U-Learn

Streams and File Handling PushbackInputStream f=new PushbackInputStream(in); int c; while((c=f.read()) !=-1) { switch(c) { case '=': if((c=f.read())=='=') System.out.print(".eq."); else { System.out.print("<-"); f.unread(c); } break; default: System.out.print((char)c); break; } } } }

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>java ex30 if (a.eq. 4) a<-0

Stream Tokenizer

7KLVFODVVKHOSVLQLGHQWLI\LQJWKHSDWWHUQVLQWKHLQSXWVWUHDP,WLVUHVSRQVLEOHIRUEUHDNLQJXS WKH ,QSXW6WUHDP LQWR WRNHQV ZKLFK DUH GHOLPLWHG E\ D VHW RI FKDUDFWHUV 7KH EHVW XVH RI WKLV FODVVLVWRLGHQWLI\WKHQXPEHURIZRUGVRUOLQHVZLWKLQDILOH

Random Access File 5DQGRP$FFHVV)LOH HQFDSVXODWHV D UDQGRP DFFHVV ILOH ,W LV QRW GHULYHG IURP ,QSXW6WUHDP RU 2XWSXW6WUHDP,QVWHDGLWLPSOHPHQWVWKHLQWHUIDFH'DWD,QSXWDQG'DWD2XWSXWZKLFKGHILQHV WKHEDVLF,2PHWKRGV,WDOVRVXSSRUWVSRVLWLRQLQJUHTXHVWVLHZHFDQSRVLWLRQWKHILOHSRLQWHU ZLWKLQWKHILOH,WKDVWKHIROORZLQJFRQVWUXFWRUV RandomAccessFile(File fObj, string acc) RandomAccessFile(String fname, String acc)

,Q WKH ILUVW IRUP I2EM VSHFLILHV WKH QDPH RI WKH ILOH WR RSHQ DV D )LOH REMHFW ,Q WKH VHFRQG PHWKRGWKHQDPHRIWKHILOHLVSDVVHGDVIQDPH,QERWKWKHFDVHVDFFGHWHUPLQHVZKDWW\SHRI Comp-U-Learn

107

Java Programming I

ILOH DFFHVV LV SHUPLWWHG ,I LW LV ¶U· WKHQ WKH ILOH KDV UHDG DFFHVV DQG LI LW LV ¶UZ· WKHQ WKH ILOH LV RSHQHG LQ UHDGZULWH PRGH 7KH PHWKRG VHHN  LV XVHG WR VHW WKH FXUUHQW SRVLWLRQ RI WKH ILOH SRLQWHUZLWKLQWKHILOH void seek(long newPos)

+HUHQHZSRVVSHFLILHVWKHQHZSRVLWLRQLQE\WHVRUWKHILOHSRLQWHUIURPWKHEHJLQQLQJRUHQG RIWKHILOH$IWHUDFDOOWRWKHVHHNPHWKRGWKHQH[WUHDGRUZULWHRSHUDWLRQVZLOORFFXUDWWKH QHZILOHSRVLWLRQ

Reader and Writer Classes 7KH GLIIHUHQFH EHWZHHQ 5HDGHUV DQG ,QSXW6WUHDPV LV WKDW ZKLOH UHDGHUV DUH DEOH WR UHDG FKDUDFWHUVLQSXWVWUHDPVUHDGE\WHV7KLVLQFUHDVHVWKHSRZHURIWKH-DYD,26WUHDPFODVVHVE\ EHLQJ DEOH WR UHDG DQ\ FKDUDFWHUV DQG WKXV HQDEOLQJ LQWHUQDWLRQDOL]DWLRQ ,Q VLPSOH WHUPV LW LV SRVVLEOH WR ZULWH -DYD SURJUDPV LQ ODQJXDJHV OLNH *HUPDQ -DSDQHVH DQG )UHQFK 7KH IXQFWLRQDOLW\RIWKHZULWHULVVLPLODUWR2XWSXW6WUHDPVDQGLWLVSRVVLEOHWRZULWHRQHEORFN RI E\WHVRUFKDUDFWHUV Reader

7KHIROORZLQJVHFWLRQGHDOVZLWKDIHZVXEFODVVHVRI5HDGHU6RPHRIWKHVXEFODVVHVRI5HDGHU &ODVVDUH 1. FileReader

7KLVFODVVLVVLPLODUWR)LOH,QSXW6WUHDP&ODVV 2. CharArray Reader and StringReader

7KHVH FODVVHV DUH VLPLODU WR %\WH$UUD\,QSXW6WUHDP DQG 6WULQJ%XIIHU,QSXW6WUHDP FODVVHV 7KHLU FRQVWUXFWRUVDUHJLYHQEHORZ public CharArrayReader(char ch[]); public StringReader(String s);

3. InputStreamReader

7KLVFODVVZDVGHVLJQHGIURPE\WHRULHQWHGVLWXDWLRQVWRFKDUDFWHURULHQWHGVLWXDWLRQV,WUHDGV E\WHV IURP DQ ,QSXW6WUHDP5HDGHU DQG FRQYHUWV WKHP WR FKDUDFWHUV DFFRUGLQJ WR D PDSSLQJ DOJRULWKP 7KH GHIDXOW PDSSLQJ LGHQWLILHV E\WHV DV FRPPRQ $6&,, FKDUDFWHUV DQG FRQYHUWV WKHPWR-DYD81,&2'(FKDUDFWHUV

108

Comp-U-Learn

Streams and File Handling 4. BufferedReader Class

7KLVFODVVDFFHSWVDUHDGHUREMHFWDVLWVSDUDPHWHUDQGDGGVDEXIIHURIFKDUDFWHUVWRLW7KLVFODVV LVPDLQO\XVHIXOEHFDXVHRILWVUHDG/LQH  Writer class

$IHZRIWKHVXEFODVVHVRI:ULWHUFODVVDUH 

)LOH:ULWHU



&KDU$UUD\:ULWHU



3ULQW:ULWHU



)LOWHU:ULWHU



%XIIHUHG:ULWHU

$QH[DPSOHWRVKRZ5HDGHUDQG:ULWHUFODVVHV Example 5.12 import java.io.*; public class ex50 { public static void main(String args[]) { try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String s,s1 = new String(); while ((s=in.readLine())!=null) s1+=s+'\n'; in.close(); BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter a Line"); System.out.println("Usage of buffered reader and InputStreamReader"); System.out.println(stdin.readLine()); StringReader intwo = new StringReader(s1); int c; System.out.println("Printing individual chars of a file " + args[0]); while ((c=intwo.read())!=-1) System.out.println((char)c); BufferedReader in4 = new BufferedReader(new StringReader(s1)); PrintWriter p = new PrintWriter (new BufferedWriter(new FileWriter("str1")));

Comp-U-Learn

109

Java Programming I while((s=in4.readLine())!=null) p.println("Output "+s); p.close(); } catch(IOException e) { } } }

2XWSXWRIWKHSURJUDP C:\jdk1.1.5\bin>java ex50 ex41.java Enter a Line Usage of buffered reader and InputStreamReader india is my country // The contents of the file ex41.java will be displayed character by character, also the contents of the file will be stored in “str1”.

Summary The Streaming interface in Java provides a clean abstraction for a complex and often cumbersome task. The composition of the filtered stream classes allow us to dynamically build the custom streaming interface to suit our data transfer requirements. Streams are a method of receiving and sending information. The InputStream, OutputStream, DataStreams, PrintStream, RandomAccessFile Streams, BufferedInputStream and BufferedOutputStream are some of the important File Stream classes in Java. Java programs written to adhere to the abstract, high level InputStream and OutputStream classes will function properly in the future even when new and improved concrete stream classes are invented.

Going Over It Again I. Fill in the Blanks

 BBBBBBBBBBBBBDQGBBBBBBBBKHOSLQUHDGLQJDQGZULWLQJGDWDIURPDFWXDOGLVNILOHV  BBBBBBBBBBBDQGBBBBBBBBBBPDNHXVHRIWKHE\WHDUUD\DVDQLQSXWVRXUFHWRSHUIRUP UHDGLQJDQGZULWLQJRSHUDWLRQVRQWKDWDUUD\  BBBBBBBBKHOSVWREUHDNWKH,QSXW6WUHDPLQWRWRNHQV

110

Comp-U-Learn

Streams and File Handling

 BBBBBBBLVXVHGWRILOWHUILOHVZLWKDVSHFLILHGSDWWHUQDQGWKHQOLVWWKHP  BBBBBBBBBPHWKRGKHOSVLQFOHDULQJWKHEXIIHU  BBBBBBBBBPHWKRGLQ-DYDLVXVHGWRFUHDWH'LUHFWRULHV  BBBBBBBBBH[FHSWLRQLVUDLVHGLQ,QSXWDQG2XWSXW6WUHDPV II. State True or False

 7KH5HDGHUDQGZULWHUFODVVHVDUHXVHGWRUHDGDQGZULWHFKDUDFWHUVLQVWHDGRIE\WHV  )LOH2XWSXW6WUHDPGRHVQRWDOORZDSSHQGLQJGDWDWRDQH[LVWLQJILOH  5HDGLQJRUZULWLQJFDQEHGRQHHYHQDIWHUFORVLQJWKHLQSXWRXWSXWVRXUFH  7KHDFFHSW PHWKRGLVDYDLODEOHLQ)LOHFODVV  ,Q-DYDGLUHFWRULHVDUHQRWILOHV III. One line Answers

 :KDWLVD6WUHDP"  :ULWHVKRUWQRWHVRQ%XIIHUHG6WUHDPV  :ULWHWKHXVDJHRIDFFHSW DQGOLVW   'HILQHD3ULQW6WUHDP  :KDWDUH)LOWHUHG6WUHDPV"

Comp-U-Learn

111

Session 6

Exception Handling and MultiThreading

On Completion of this Session We will be able to understand...

) Concepts of errors ) Need To handle errors ) Error Handling in Java ) Uncaught exceptions ) Usage of try, catch, finally and throw blocks ) The Throwable Class ) About Multithreading

In This Session...



Exception Handling – An Insight



Advantages of Exception Handling



Uncaught Exceptions



Multiple Catch Clauses



Implicit and Explicit Exceptions



Java.lang.Throwable



Finally Clause



Creating Own Exception subclasses



MultiThreading



Thread States



Thread Priority



Daemon Threads

Exception Handling and MultiThreading

Exception Handling – An Insight (UURUV DOZD\V RFFXU DQG LW LV LPSRUWDQW WR SURYLGH PHDQV WR KDQGOH WKHP (UURU KDQGOLQJ EHFRPHV D QHFHVVLW\ ZKLOH GHYHORSLQJ DSSOLFDWLRQV WR DFFRXQW IRU XQH[SHFWHG VLWXDWLRQV OLNH UXQQLQJRXWRIPHPRU\UHVRXUFHDOORFDWLRQHUURUVRULQDELOLW\WRILQGILOHV6WDWLVWLFVUHYHDOWKDW DVDUHVXOWRIHUURUKDQGOLQJWKHVL]HRIDSURJUDPLQFUHDVHVRQDQDYHUDJHE\PRUHWKDQ 7RPDLQWDLQD EDODQFHEHWZHHQ HUURU KDQGOLQJDQGWKHVL]H RIWKHVRXUFHFRGH-DYD RIIHUV DQ ([FHSWLRQ FODVV ZKLFK ZKHQ MXGLFLRXVO\ LPSOHPHQWHG LQ SURJUDPV ZRXOG WDNH FDUH RI WKH XQH[SHFWHGVLWXDWLRQV %DVLFDOO\WKHUHDUHWZRNLQGVRIHUURUV7KH\DUH &RPSLOHWLPHHUURUV7KHHUURUVWKDWRFFXUGXULQJFRPSLODWLRQRIDSURJUDP 5XQWLPHHUURUV²7KHHUURUVWKDWRFFXUGXULQJH[HFXWLRQ Sources of Errors User Input Errors

7KHVHDUHW\SLQJHUURUVV\QWD[HUURUVLQFRUUHFWRUQRQH[LVWHQW85/VHWF Device Errors

7KHVHHUURUVRFFXUZKHQWKHUHDUHSUREOHPVZLWKGHYLFHVVXFKDVSULQWHUVLPSURSHUO\FRQQHFWHG GHYLFHVSULQWHUVRXWRISDSHUVHWF Physical Limitations

7KHVHHUURUVRFFXUZLWKUHVSHFWWRWKHSK\VLFDOHQWLWLHVRUFDSDFLWLHV(J6SDFHLVQRWDYDLODEOH RQGLVNVRUPDLQPHPRU\ Code Errors

(UURUV WKDW RFFXU ZKHQ ORJLF LV ZURQJ SRSSLQJ HPSW\ VWDFN ORFDWLQJ QRQH[LVWHQW ILOHV GDWD VWUXFWXUHVHWF ,Q-DYDWKH5XQWLPHHUURUVDUHFDOOHGH[FHSWLRQVDQGWKHSURFHVVRIGHDOLQJZLWKWKHPLVFDOOHG H[FHSWLRQ KDQGOLQJ 7KH WHUP H[FHSWLRQ LV D VKRUW IRUP IRU H[FHSWLRQDO HYHQWV ,W FRXOG EH GHILQHGDVDQHYHQWWKDWRFFXUVGXULQJWKHH[HFXWLRQRIDSURJUDPWKDWGLVUXSWVWKHQRUPDOIORZ RILQVWUXFWLRQV :KHQ DQ HUURU RFFXUV LQ D -DYD PHWKRG WKH PHWKRG FUHDWHV DQ REMHFW RI W\SH ([FHSWLRQ DQG JLYHVLWWRWKHUXQWLPHV\VWHP7KH([FHSWLRQREMHFWFRQVLVWVRIWKHLQIRUPDWLRQSHUWDLQLQJWR Comp-U-Learn

115

Java Programming I

WKHH[FHSWLRQOLNHLWVW\SHDQGVWDWHRIWKHSURJUDPZKHQWKHH[FHSWLRQRFFXUUHG7KHUXQWLPH V\VWHP ORRNV RXW IRU WKH DSSURSULDWH PHWKRG WKDW ZRXOG KDQGOH WKH HUURU WKDW KDV EHHQ HQFRXQWHUHG 7KH SURFHVV RI FUHDWLQJ DQ ([FHSWLRQ REMHFW DQG KDQGOLQJ LW WR WKH UXQWLPH V\VWHPLVFDOOHGWKURZLQJDQH[FHSWLRQ7KHPHWKRGWKDWKDQGOHVWKHH[FHSWLRQWKURZQLVFDOOHG DQ H[FHSWLRQ KDQGOHU 7KH H[FHSWLRQ KDQGOHU LV XVHG WR FDWFK WKH H[FHSWLRQ WKURZQ 7KH UXQ WLPH V\VWHP VHDUFKHV IRU WKH H[FHSWLRQ KDQGOHU VWDUWLQJ IURP WKH PHWKRG ZKHUH WKH HUURU RFFXUUHG7KHVHDUFKJRHVRQWLOOWKHUXQWLPHV\VWHPILQGVDQDSSURSULDWHH[FHSWLRQKDQGOHU$ PHWKRGLVWHUPHGDQDSSURSULDWHH[FHSWLRQKDQGOHULIWKHW\SHRIWKHH[FHSWLRQFDXJKWE\WKH KDQGOHULVWKHVDPHDVWKHW\SHRIWKHH[FHSWLRQ ,I WKH DSSURSULDWH KDQGOHU LV QRW IRXQG WKHQ WKH UXQWLPH V\VWHP WHUPLQDWHV WKH DSSOLFDWLRQ 7KH H[FHSWLRQ KDQGOLQJ PHFKDQLVP WUDQVIHUV WKH FRQWURO IURP WKH HUURU RFFXUUHG WR WKH H[FHSWLRQKDQGOHUWKDWFDQGHDOZLWKWKHH[FHSWLRQV

Advantages of Exception Handling -DYDSURJUDPVKDYHWKHIROORZLQJDGYDQWDJHRYHUWUDGLWLRQDOHUURUPDQDJHPHQWWHFKQLTXHV ♦ ♦ ♦ ♦ ♦

Separating Error handling Code from Regular Code Propagating Errors Up the Call Stack Grouping Error Types and Error Differentiation Allows fixing the errors It prevents the program from automatic termination

([FHSWLRQV DUH D SDUW RI WKH LQKHULWDQFH KLHUDUFK\ DQG DUH GHULYHG IURP WKH 7KURZDEOH FODVV 7KDWLVDQH[FHSWLRQLVDQLQVWDQFHRI WKH 7KURZDEOH  FODVV 7KH H[FHSWLRQ KLHUDUFK\ LV JLYHQ EHORZ Throwable

Error

Exception

IOException

Fig 6.1 116

Comp-U-Learn

RunTime Exception

Exception Handling and MultiThreading

$OOH[FHSWLRQW\SHVDUHVXEFODVVHVRIWKHEXLOWLQFODVV7KURZDEOH7KXV7KURZDEOHLVDWWKHWRS RIWKHH[FHSWLRQFODVVKLHUDUFK\,PPHGLDWHO\EHORZ7KURZDEOHDUHWZRVXEFODVVHVWKDWSDUWLWLRQ H[FHSWLRQVLQWRWZRGLVWLQFWEUDQFKHV2QHEUDQFKLVKHDGHGE\H[FHSWLRQ7KLVFODVVLVXVHGIRU H[FHSWLRQDOFRQGLWLRQVWKDWXVHUSURJUDPVVKRXOGFDWFK7KLVLVDOVRWKHFODVVWKDWZHZLOOVXE FODVVZKHQZHFUHDWHRXUFXVWRPH[FHSWLRQW\SHV7KHUHLVDQLPSRUWDQWVXEFODVVRIH[FHSWLRQ FDOOHGUXQWLPH ([FHSWLRQ([FHSWLRQVRIWKLVW\SHDUHDXWRPDWLFDOO\GHILQHGIRUWKHSURJUDPV WKDW ZH ZLOO ZULWH DQG LQFOXGH WKLQJV VXFK DV GLYLVLRQ E\ ]HUR DQG LQYDOLG DUUD\ LQGH[LQJ ([FHSWLRQVWKDWLQKHULWIURPWKLVFODVVLQFOXGH ♦ Bad cast ♦ Out of bound array access ♦ Null pointer access 7KHVHSUREOHPVDUHRXWRIZURQJSURJUDPPLQJORJLFDQGPXVWEHFRUUHFWHGE\WKHSURJUDPPHU KLPVHOI6RPHRIWKHVHH[FHSWLRQVDUH ♦ ArithmeticException ♦ NullPointerException ♦ ClassCastException ♦ ArrayIndexOutOfBoundsException

Other exceptions

7KHVHLQFOXGHH[FHSWLRQVIRUPXOWLWKUHDGLQJPDOIRUPHG85/UHDGLQJSDVWHQGRIILOHHWF6RPH RIWKHVXEFODVVHVDUH ♦ IOException ♦ AWTException ♦ ClassNotFoundException ♦ IllegalAccessException 7KH RWKHU EUDQFK LV WRSSHG E\ (UURU ZKLFK GHILQHV H[FHSWLRQV WKDW DUH QRW H[SHFWHG WR EH FDXJKWXQGHUQRUPDOFLUFXPVWDQFHVE\RXUSURJUDP([FHSWLRQVRIW\SH(UURUDUHXVHGE\WKH -DYDUXQWLPHV\VWHPWRLQGLFDWHHUURUVKDYLQJWRGRZLWKWKHUXQWLPHHQYLURQPHQWLWVHOI6WDFN RYHUIORZ LV DQ H[DPSOH RI VXFK DQ HUURU EHFDXVH WKHVH DUH W\SLFDOO\ FUHDWHG LQ UHVSRQVH WR FDWDVWURSKLFIDLOXUHVWKDWFDQQRWXVXDOO\EHKDQGOHGE\RXUSURJUDP Comp-U-Learn

117

Java Programming I

Uncaught Exceptions /RRNDWWKHSURJUDPJLYHQEHORZ,WKDVZLOOIXOO\LQFOXGHGDGLYLVLRQE\]HUR Example 6.1 class ex61 { public static void main(String args[]) { int d=0; int a=42/d; } }

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>javac ex61.java C:\jdk1.2\bin>java ex61 Exception in thread "main" java.lang.ArithmeticException: / by zero at ex61.main(ex61.java:6) C:\jdk1.2\bin>

:KHQ WKH -DYD UXQ WLPH V\VWHP GHWHFWV WKH DWWHPSW WR GLYLGH E\ ]HUR LW FRQVWUXFWV D QHZ H[FHSWLRQ REMHFW DQG WKHQ WKURZV WKLV H[FHSWLRQ 7KLV FDXVHV WKH H[HFXWLRQ RI  H[ WR VWRS EHFDXVH RQFH DQ H[FHSWLRQ KDV EHHQ WKURZQ LW PXVW EH FDXJKW E\ DQ H[FHSWLRQ KDQGOHU DQG GHDOW ZLWK LPPHGLDWHO\ ,Q WKLV H[DPSOH ZH KDYHQ·W VXSSOLHG DQ\ H[FHSWLRQ KDQGOHUV RQ RXU RZQ VR WKH H[FHSWLRQ LV FDXJKW E\ WKH GHIDXOW KDQGOHU SURYLGHG E\ WKH -DYD UXQWLPH V\VWHP 7KH GHIDXOW KDQGOHU ZLOO XOWLPDWHO\ SURFHVV DQ\ H[FHSWLRQ WKDW LV QRW FDXJKW E\ RXU SURJUDP 7KH GHIDXOW KDQGOHU  GLVSOD\V D VWULQJ GHVFULELQJ WKH H[FHSWLRQ SULQWV D VWDFN WUDFH IURP WKH SRLQWDWZKLFKWKHH[FHSWLRQRFFXUUHGDQGWHUPLQDWHVWKHSURJUDP1RWLFHKRZWKHFODVVQDPH H[WKHPHWKRGQDPHPDLQWKHILOHQDPHH[MDYDDQGWKHOLQHQXPEHUDUHDOOLQFOXGHGLQ WKHVLPSOH VWDFN WUDFH 1RWH WKDW WKH W\SH RI WKH H[FHSWLRQ WKURZQ LV D VXEFODVV RI ([FHSWLRQ FDOOHGDULWKPHWLF([FHSWLRQZKLFKPRUHVSHFLILFDOO\GHVFULEHVZKDWW\SHRIHUURUKDVRFFXUUHG -DYD H[FHSWLRQ KDQGOLQJ LV PDQDJHG YLD ILYH NH\ZRUGV WU\ FDWFK WKURZ WKURZV DQG ILQDOO\ 3URJUDPVWDWHPHQWVWKDWZHZDQWWRPRQLWRUIRUH[FHSWLRQVDUHFRQWDLQHGZLWKLQDWU\EORFN,I DQH[FHSWLRQRFFXUVZLWKLQWKHWU\EORFNLWLVWKURZQ2XUFRGHFDQFDWFKWKLVH[FHSWLRQ XVLQJ FDWFK  DQG KDQGOH LW LQ VRPH UDWLRQDO PDQQHU 6\VWHP JHQHUDWHG H[FHSWLRQV DUH DXWRPDWLFDOO\ WKURZQE\WKH-DYDUXQWLPHV\VWHP7RPDQXDOO\WKURZDQH[FHSWLRQXVHWKHNH\ZRUGWKURZ $Q\H[FHSWLRQWKDWLVWKURZQRXWRIDPHWKRGPXVWEHVSHFLILHGDVVXFKE\DWKURZVFODXVH$Q\ FRGHWKDWDEVROXWHO\PXVWEHH[HFXWHGEHIRUHDPHWKRGUHWXUQVLVSXWLQDILQDOO\EORFN 118

Comp-U-Learn

Exception Handling and MultiThreading This is the general form of n exception handling try { //Block of code to monitor for errors } catch(ExceptionType1 exObj) { // exception handler for Exceptiontype 1 } catch(ExceptionType2 exObj2) { //exception handler for exception type 2 } //.......................... ........................... finally { // block of code to be executed before try block ends }

+HUHH[FHSWLRQW\SHLVWKHW\SHRIH[FHSWLRQWKDWKDVRFFXUUHG

Note We can throw many exceptions in one method, but we cannot throw exceptions inherited from Error class and those from RunTimeException $VDPSOHSURJUDPWRLOOXVWUDWHWKHXVDJHRIWKURZLQJDQH[FHSWLRQ Example 6.2 class ex62 { public static void main(String args[]) { System.out.println("enter a character "); char c=(char)System.in.read(); } }

2XWSXWRIWKHSURJUDP C:\jdk1.2\bin>javac ex62.java Ex62a.java:6: Exception java.io.IOException must be caught, or it must be declared in the throws clause of this method. char c=(char)System.in.read(); ^ 1 error

Comp-U-Learn

119

Java Programming I

1RZZHFDPUHZULWHWKHSURJUDPDVVKRZQEHORZDQGVHHWKHRXWSXW class ex62 { public static void main(String args[]) throws java.io.IOException { System.out.println("enter a character "); char c=(char)System.in.read(); } }

7KHRXWSXWRIWKHSURJUDPQRZLV C:\jdk1.2\bin>java ex62 java C:\jdk1.2\bin>java ex62 Enter a character i

1RZZHFDQUHZULWHWKHSURJUDPH[MDYDZKLFKWKURZVDQ$ULWKPHWLF([FHSWLRQ class ex61 { public static void main(String args[]) { int d,a; try { d=0; a=42/d; System.out.println("Test to see the try block } catch (ArithmeticException e) { System.out.println("Division by zero "); System.out.println("Inside catch block "); } System.out.println("After catch block "); } }

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>javac ex61.java C:\jdk1.2\bin>java ex61 Division by zero Inside catch block After catch block C:\jdk1.2\bin>

120

Comp-U-Learn

");

Exception Handling and MultiThreading

1RWLFHWKDWWKHFDOOWRWKHSULQWOQVWDWHPHQWLQVLGHWKHWU\EORFNKDVQ·WJRWH[HFXWHG2QFH DQ H[FHSWLRQLVWKURZQSURJUDPFRQWUROWUDQVIHUVRXWRIWKHWU\EORFNWRWKHFDWFKEORFNWRKDQGOH WKHH[FHSWLRQEHLQJWKURZQRXW7KHWU\EORFNGRHVQRWFDOODFDWFKEORFNDQGKHQFHFRQWUROZLOO QRWJHWWUDQVIHUUHGWRWU\EORFNRQFHPRUHDIWHUWKHH[FHSWLRQLVEHLQJKDQGOHG+HQFHWKHOLQH 6\VWHPRXWSULQOQ ´,QVLGHWU\EORFN ZLOOQRWEHGLVSOD\HGRQWKHVFUHHQ 2QFH WKH FDWFK EORFN LV H[HFXWHG SURJUDP FRQWLQXHV ZLWK WKH QH[W OLQH LQ WKH SURJUDP IROORZLQJ WKH HQWLUH WU\FDWFK EORFNV $ WU\ DQG D FDWFK IRUP D VLQJOH XQLW 7KH VFRSH RI WKH FDWFK VWDWHPHQW LV UHVWULFWHG WR WKRVH VWDWHPHQWV VSHFLILHG E\ WKH LPPHGLDWHO\ SUHFHGLQJ WU\ VWDWHPHQW7KHJRDORIPRVWZHOOFRQVWUXFWHGFDWFKFODXVHVVKRXOGEHWRUHVROYHWKHH[FHSWLRQDO FRQGLWLRQDQGWKHQFRQWLQXHRQDVLIQRHUURUKDVRFFXUUHG

Note Curly braces must surround the statements that are protected in a try statement. That is, they must be within a block. We cannot use try on a single statement. Displaying the description of an Exception

7KURZDEOH RYHUULGHV WKH WR6WULQJ  PHWKRG GHILQHG E\ 2EMHFW  VR WKDW LW UHWXUQV D VWULQJ FRQWDLQLQJ D GHVFULSWLRQ RI WKH H[FHSWLRQ :H FDQ GLVSOD\ WKLV GHVFULSWLRQ LQ D SULQWOQ VWDWHPHQWE\VLPSO\SDVVLQJWKHH[FHSWLRQDVDQDUJXPHQW)RUH[DPSOHWKHFDWFKEORFNLQWKH SUHFHGLQJSURJUDPFDQEHUHZULWWHQDV catch (ArithmeticException e) { System.out.println("Division by zero "); System.out.println("Inside catch block "); System.out.println(“Exception :”+e); }

7KLVZLOOJLYHWKHRXWSXW C:\jdk1.2\bin>java ex62 Division by zero Inside catch block Exception :java.lang.ArithmeticException: / by zero After catch block C:\jdk1.2\bin>

Comp-U-Learn

121

Java Programming I

Multiple Catch Clauses 0RUH WKDQ RQH H[FHSWLRQ FRXOG EH UDLVHG E\ D VLQJOH SLHFH RI FRGH 7R KDQGOH WKLV W\SH RI VLWXDWLRQZHFDQVSHFLI\WZRRUPRUHFDWFKFODXVHVHDFKFDWFKLQJDGLIIHUHQWW\SHRIH[FHSWLRQ :KHQDQH[FHSWLRQLVWKURZQHDFKFDWFKVWDWHPHQWLVLQVSHFWHGLQRUGHUDQGWKHILUVWRQHZKRVH W\SHPDWFKHVWKDWRIWKHH[FHSWLRQH[HFXWHG$IWHURQHFDWFKVWDWHPHQWH[HFXWHVWKHRWKHUVDUH E\SDVVHGDQGH[HFXWLRQFRQWLQXHVDIWHUWKHWU\FDWFKEORFN7KHIROORZLQJH[DPSOHWUDSVWZR GLIIHUHQWH[FHSWLRQW\SHV Example 6.3 class ex63 { public static void main(String args[]) { try{ int a=args.length; System.out.println("a = " +a); int b=42/a; int c[]= {1}; c[42]=99; System.out.println("Test to see the try } catch (ArithmeticException e) { System.out.println("Division by zero " } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index :" + e } System.out.println("After try and catch } }

block

");

+ e);

); block ");

7KHRXWSXWRIWKHSURJUDP C:\jdk1.2\bin>java ex63 a = 0 Division by zero java.lang.ArithmeticException: / by zero After try and catch block C:\jdk1.2\bin>java ex63 neem a = 1

:KHQZHXVHPXOWLSOHFDWFKVWDWHPHQWVLWLVLPSRUWDQWWRUHPHPEHUWKDWH[FHSWLRQVXEFODVVHV PXVW FRPH EHIRUH DQ\ RI WKHLU VXSHU FODVVHV 7KLV LV EHFDXVH D FDWFK VWDWHPHQW WKDW XVHV D VXSHUFODVVZLOOFDWFKH[FHSWLRQVRIWKDWW\SHSOXVDQ\RILWVVXEFODVVHV7KXVDVXEFODVVZRXOG QHYHU EH UHDFKHG LI LW FDPH DIWHU LWV VXSHUFODVV )XUWKHU LQ -DYD XQUHDFKDEOH FRGH LV DQ HUURU 7KHIROORZLQJFRGHZLOOLOOXVWUDWHWKLV 122

Comp-U-Learn

Exception Handling and MultiThreading

Example 6.4 class ex64 { public static void main(String args[]) { int d,a; try{ d=0; a=42/d; System.out.println("Test to see the try block "); } catch(Exception e) { System.out.println("General exception raised in catch " +e); } catch (ArithmeticException e) { System.out.println("Division by zero "); System.out.println("Inside catch block "); System.out.println("Exception :"+e); } System.out.println("After catch block "); } }

7KHRXWSXWRIWKHDERYHSURJUDPLVDVIROORZV C:\jdk1.2\bin>javac ex64.java Ex64.java:15: catch not reached. catch (ArithmeticException e) ^ 1 error C:\jdk1.2\bin>

Implicit and Explicit Exceptions $Q\ H[FHSWLRQ GHULYHG IURP (UURU FODVV RU 5XQ7LPH([FHSWLRQ DUH FDOOHG LPSOLFLW H[FHSWLRQV 7KHVH H[FHSWLRQV DUH EH\RQG RXU FRQWURO RU VKRXOG QRW KDYH RFFXUUHG LQ WKH ILUVW SODFH $OO RWKHU H[FHSWLRQV DUH H[SOLFLW H[FHSWLRQV $ PHWKRG PXVW GHFODUH DOO WKH H[SOLFLW H[FHSWLRQV LW WKURZV,IZHRYHUULGHDPHWKRGIURPDSDUHQWFODVVWKHFKLOGFODVVLQKHULWVWKHSDUHQWPHWKRG XQGHUVWDQGDEO\  EXW WKH FKLOG FDQQRW PDQXDOO\ IRUFH DQ H[FHSWLRQ XVLQJ WKURZ ,I WKH SDUHQW FODVVWKURZVQRH[SOLFLWH[FHSWLRQVDWDOOZHVKRXOGIROORZWKHVHVWHSVWRWKURZDQH[FHSWLRQ Comp-U-Learn

123

Java Programming I



)LQGWKHDSSURSULDWHH[FHSWLRQFODVV



00DNHDQREMHFWRIWKDWFODVV



7KURZWKDWREMHFW

Note We can create our Exception classes when the standard exceptions don’t meet our requirements.

Java.lang.Throwable public Throwable()

7KLVFRQVWUXFWVDQHZ7KURZDEOHREMHFWZLWKRXWDQ\REMHFW public Throwable(String message)

7KLV FRQVWUXFWV D QHZ 7KURZDEOH REMHFW ZLWK WKH PHVVDJH JLYHQ ,W FDQ EH XVHG WR SURYLGH LQIRUPDWLRQ IRU GHEXJJLQJ $OO GHULYHG H[FHSWLRQ FODVVHV VXSSRUW ERWK D GHIDXOW FRQVWUXFWRU ZLWKDGHWDLOHGPHVVDJH public String getMessage()

7KLVPHWKRGREWDLQVWKHGHWDLOHGPHVVDJHRIWKH7KURZDEOHREMHFW 7KHWU\VWDWHPHQWFDQEHQHVWHG7KDWLVDWU\VWDWHPHQWFDQEHLQVLGHWKHEORFNRIDQRWKHUWU\ (DFKWLPHDWU\VWDWHPHQWLVHQWHUHGWKHFRQWH[WRIWKDWH[FHSWLRQLVSXVKHGRQWKHVWDFN,IDQ LQQHU WU\ VWDWHPHQW GRHV QRW KDYH D FDWFK KDQGOHU IRU D SDUWLFXODU H[FHSWLRQ WKH VWDFN LV XQZRXQGDQGWKHQH[WWU\VWDWHPHQW·VFDWFKKDQGOHUVDUHLQVSHFWHGIRUDPDWFK7KLVFRQWLQXHV XQWLORQHRIWKHFDWFKVWDWHPHQWVXFFHHGVRUXQWLODOORIWKHQHVWHGWU\VWDWHPHQWVDUHH[KDXVWHG ,IQRFDWFKVWDWHPHQWPDWFKHVWKHQWKH-DYDUXQWLPHV\VWHPKDQGOHVWKHH[FHSWLRQ+HUHLVDQ H[DPSOHWRVKRZWKHQHVWHGWU\VWDWHPHQWV Example 6.5 class ex65 { public static void main(String args[]) { try { int a=args.length; int b=42/a; System.out.println("a = " + a);

124

Comp-U-Learn

Exception Handling and MultiThreading try{ if (a==1) a=a/(a-a); if (a==2) { int c[]={1}; c[42]=99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bounds : " +e); } }catch(ArithmeticException e) { System.out.println("Divide by 0 : " +e); } } }

7KHRXWSXWRIWKHSURJUDP C:\jdk1.2\bin>java ex65 Divide by 0 : java.lang.ArithmeticException: / by zero C:\jdk1.2\bin>java ex65 Uma a = 1 Divide by 0 : java.lang.ArithmeticException: / by zero C:\jdk1.2\bin>java ex65 Uma Uma2 a = 2 Array index out of bounds : java.lang.ArrayIndexOutOfBoundsException: 42 C:\jdk1.2\bin>

Throw

:KHQZHZDQWWRWKURZDQH[FHSWLRQH[SOLFLWO\ZHKDYHWRXVHDWKURZVWDWHPHQW7KHJHQHUDO IRUPRIWKURZLVVKRZQKHUH throw ThrowableInstance;

+HUH 7KURZDEOH,QVWDQFH PXVW EH DQ REMHFW RI W\SH 7KURZDEOH RU D VXEFODVV RI 7KURZDEOH 6LPSOHW\SHVVXFKDV LQW RU FKDU DV ZHOO DV QRQWKURZDEOH  FODVVHV VXFK DV 6WULQJ DQG REMHFW FDQQRWEHXVHGDVH[FHSWLRQV 7KHUH DUH WZR ZD\V ZH FDQ REWDLQ D 7KURZDEOH REMHFW XVLQJ D SDUDPHWHULQWRDFDWFKFODXVHRUFUHDWLQJRQHZLWKWKHQHZRSHUDWRU 7KHIORZRIH[HFXWLRQVWRSVLPPHGLDWHO\DIWHUWKHWKURZVWDWHPHQWDQ\VXEVHTXHQWVWDWHPHQWV DUHQRWH[HFXWHG7KHQHDUHVWHQFORVLQJWU\EORFNLVLQVSHFWHGWRVHHLILWKDVDFDWFKVWDWHPHQW Comp-U-Learn

125

Java Programming I

WKDW PDWFKHV WKH W\SH RI WKH H[FHSWLRQ ,I LW ILQGV D PDWFK FRQWURO LV WUDQVIHUUHG WR WKDW VWDWHPHQW,IQRWWKHQWKHQH[WHQFORVLQJWU\VWDWHPHQWLVLQVSHFWHGDQGVRRQ,IQRPDWFKLQJLV IRXQGWKHQWKHGHIDXOWH[FHSWLRQKDQGOHUKDOWVWKHSURJUDPDQGSULQWVWKHVWDFNWUDFH 7KHVDPSOHSURJUDPLVJLYHQEHORZ Example 6.6 class ex66 { static void FnA() { try { throw new NullPointerException("demo"); }catch(NullPointerException e) { System.out.println("Caught inside the Function A"); throw e; } } public static void main(String args[]) { try { FnA(); }catch(NullPointerException e) { System.out.println(" Recaught: "+e); } } } The output of the program will be as follows C:\jdk1.2\bin>javac ex66.java C:\jdk1.2\bin>java ex66 Caught inside the Function A Recaught: java.lang.NullPointerException: demo C:\jdk1.2\bin>

Throws

,I D PHWKRG LV FDSDEOH RI FDXVLQJ DQ H[FHSWLRQ WKDW LW GRHV QRW KDQGOH LW PXVW VSHFLI\ WKLV EHKDYLRUVRWKDWFDOOHURIWKHPHWKRGFDQJXDUGKLPVHOIDJDLQVWWKDWH[FHSWLRQ7KLVLVGRQHE\ GHFODULQJ D WKURZV FODXVH LQ WKH PHWKRG·V GHFODUDWLRQ $ WKURZV FODXVH OLVWV WKH W\SHV RI 126

Comp-U-Learn

Exception Handling and MultiThreading

H[FHSWLRQVWKDWDPHWKRGPLJKWWKURZ7KLVLVQHFHVVDU\IRUDOOH[FHSWLRQVH[FHSWWKRVHRIW\SH (UURURU5XQWLPH([FHSWLRQRUDQ\RIWKHLUVXEFODVVHV$OORWKHUH[FHSWLRQVWKDWDPHWKRGFDQ WKURZPXVWEHGHFODUHGLQWKHWKURZVFODXVH,IDUHQRWDFRPSLOHWLPHHUURUZLOOUHVXOW 7KH IROORZLQJ H[DPSOH LOOXVWUDWHV WKLV +HUH WKH SURJUDP ZLOO QRW FRPSLOH EHFDXVH WKH WKURZV FODXVHLVQRWVSHFLILHG Example 6.7 class ex67 { static void demo() { System.out.println("inside the function demo"); throw new IllegalAccessException("demo"); } public static void main(String args[]) { demo(); } }

7KHSURJUDPSURGXFHVDFRPSLODWLRQHUURUOLNHWKLV C:\jdk1.2\bin>javac ex67.java Ex67.java:6: Exception java.lang.IllegalAccessException must be caught, or it must be declared in the throws clause of this method. throw new IllegalAccessException("demo"); ^ 1 error C:\jdk1.2\bin>

7KLVSURJUDPFRXOGEHFRUUHFWHGE\DGGLQJWKHFRGHLQPDLQIXQFWLRQDQGE\DGGLQJWKURZVLQ WKHGHPRIXQFWLRQ class ex67 { static void demo() throws IllegalAccessException { System.out.println("inside the function demo"); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try{ demo(); }catch(IllegalAccessException e) {

Comp-U-Learn

127

Java Programming I System.out.println("Caught" +e); } } }

7KHRXWSXWRIWKHSURJUDPLVDVIROORZV C:\jdk1.2\bin>javac ex67.java C:\jdk1.2\bin>java ex67 inside the function demo Caughtjava.lang.IllegalAccessException: demo C:\jdk1.2\bin

Finally Clause )LQDOO\ FUHDWHV D EORFN RI FRGH WKDW ZLOO EH H[HFXWHG DIWHU D WU\FDWFK EORFN LV FRPSOHWHG DQG EHIRUHWKHFRGHIROORZLQJWKHWU\FDWFKEORFN7KHILQDOO\EORFNZLOOH[HFXWHZKHWKHURUQRWDQ H[HFXWLRQLVWKURZQ,IDQH[HFXWLRQLVWKURZQWKHILQDOO\EORFNZLOOH[HFXWHHYHQLIQRFDWFK VWDWHPHQWPDWFKHVWKHH[FHSWLRQ7KHILQDOO\EORFNZLOOEHH[HFXWHGXQGHUDOOFLUFXPVWDQFHV $FWXDOO\WKHWU\EORFNH[HFXWHVILUVW ♦ If no exception, then finally block executes and then executes the first line after the try block ♦ If an exception occurs, then the catch block executes and then the code in the finally block executes. ,QFDVHWKHUHLVDQH[FHSWLRQEXWWKHUHLVQRPDWFKLQJFDWFKVWDWHPHQWWKHQWKHFRGHH[HFXWLRQ VNLSVUHVWRIWKHFRGHDQGH[HFXWHVWKHILQDOO\EORFN7KLVH[HFXWLRQLVWKURZQEDFNWRWKHFDOOHU RIWKHPHWKRG Guidelines to exceptions

128



8VHH[FHSWLRQVIRUH[FHSWLRQDOFLUFXPVWDQFHVRQO\



$OZD\VSUHIHUWRXVHVLPSOHWHVWVLQSODFHRIH[FHSWLRQKDQGOLQJ



'RQRWKDYHWRRPDQ\WU\FDWFKRSHUDWLRQV



6HSDUDWHQRUPDOSURFHVVLQJIURPHUURUKDQGOLQJ



'RQRWLJQRUHDYRLGH[FHSWLRQVEXWKDQGOHWKHPFRUUHFWO\ Comp-U-Learn

Exception Handling and MultiThreading

Creating Own Exception Subclasses 7KH([FHSWLRQFODVVGRHVQRWGHILQHDQ\PHWKRGVRILWVRZQ,WLQKHULWVWKRVHPHWKRGVSURYLGHG E\ 7KURZDEOH &XVWRPL]HG H[FHSWLRQV DUH QHFHVVDU\ WR KDQGOH DEQRUPDO FRQGLWLRQV RI DSSOLFDWLRQV FUHDWHG E\ WKH XVHU 7KH DGYDQWDJH RI FUHDWLQJ VXFK DQ H[FHSWLRQ FODVV LV WKDW DFFRUGLQJWRVLWXDWLRQVGHILQHGE\WKHXVHUDQH[FHSWLRQFDQEHWKURZQ,WLVDOVRSRVVLEOHWRVHW DQ\ FRQGLWLRQ RU YDOXH WR D YDULDEOH DQG JHQHUDWH XVHUGHILQHG H[FHSWLRQ )RU  H[DPSOH LW LV SRVVLEOH WR  FKHFN LI WKH LQSXW LV JUHDWHU WKDQ HTXDO WR RU OHVV WKDQ D SUHGHILQHG QXPEHU DQG DFFRUGLQJO\JHQHUDWHH[FHSWLRQV7KHIROORZLQJSURJUDPLOOXVWUDWHVWKLV Example 6.8 class except extends Exception { private int detail; except(int a) { detail=a; } public String toString() { return "My Exception [" + detail + "] "; } } class ex68 { static void compute(int a) throws except { System.out.println("Called compute(" + a + ")"); if(a>10) throw new except(a); System.out.println("Normal exit"); } public static void main(String args[]) { try{ compute(1); compute(20); } catch(except e) { System.out.println("caught " + e); } } }

Comp-U-Learn

129

Java Programming I

7KLVH[DPSOHGHILQHVDVXEFODVVRI([FHSWLRQFDOOHGH[FHSW7KLVVXEFODVVLVTXLWHVLPSOHLWKDV RQO\DFRQVWUXFWRUSOXVDQRYHUORDGHGWR6WULQJ PHWKRGWKDWGLVSOD\VWKHYDOXHRIWKHH[FHSWLRQ 7KH FODVV H[MDYD  GHILQHV D PHWKRG QDPHG FRPSXWH  WKDW WKURZV DQ H[FHSW REMHFW 7KH H[FHSWLRQLVWKURZQZKHQFRPSXWH ·VLQWHJHUSDUDPHWHULVJUHDWHUWKDQ7KHPDLQPHWKRG VHWVXSDQH[FHSWLRQKDQGOHUIRUH[FHSWWKHQFDOOVWKHFRPSXWH ZLWKDOHJDOYDOXH OHVVWKDQ DQGDQLOOHJDORQHWRVKRZERWKSDWKVWKURXJKWKHFRGH+HUHLVWKHUHVXOW 7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>java ex68 Called compute(1) Normal exit Called compute(20) caught My Exception [20] C:\jdk1.2\bin>

$QRWKHU([DPSOHWRVKRZWKHZRUNLQJRIXVHUFUHDWHGH[FHSWLRQV Example 6.9 class ex69 { static void FnA() { try{ System.out.println("inside function A"); throw new RuntimeException("demo"); }finally{ System.out.println(" Proc A finally method"); } } static void FnB() { try{ System.out.println("inside function B"); return; }finally{ System.out.println(" Proc B finally method"); } } static void FnC() { try{ System.out.println("inside function C"); }finally{ System.out.println(" Proc C finally method");

130

Comp-U-Learn

Exception Handling and MultiThreading } } public static void main(String args[]) { try{ FnA(); }catch(Exception e) { System.out.println("Execution Caught "); } FnB(); FnC(); } }

7KHRXWSXWRIWKHSURJUDP C:\jdk1.2\bin>javac ex69.java C:\jdk1.2\bin>java ex69 inside function A Proc A finally method Execution Caught inside function B Proc B finally method inside function C Proc C finally method C:\jdk1.2\bin>

Quick View of Exceptions and their meanings

Exception ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitorStateExceptionIllegal IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException

Meaning Arithmetic error such as divide by zero. Array index is out of bounds Assignment to an array element of an incompatible type Invalid cast Illegal argument used to invoke a method. monitor operation, such as waiting on an unlocked thread Requested operation not compatible with current thread state Some type of index is out-of bounds. Array created with a negative size

Comp-U-Learn

131

Java Programming I

Exception NullPointerException NumberFormatException

Meaning Invalid use of a null reference. Invalid conversion of a string to a numeric format

Exception

Meaning

SecurityException ClassNotfoundException CloneNotSupportedException

Attempt to violate security Class not found Attempt to clone an object that does not implement the Cloneable interface Access to a class is denied Attempt to create an object of an abstract class or interface One thread has been interrupted by another thread

IllegalAccessException InstantiationException InterruptedException

MultiThreading Thread

$ WKUHDG FDQ EH GHILQHG DV D VLQJOH VHTXHQWLDO IORZ RI FRQWURO 7KUHDGV DUH DOVR NQRZQ DV H[HFXWLRQFRQWH[WVRUOLJKWZHLJKWSURFHVVHV$SURJUDPLVQRUPDOO\EURNHQLQWRVPDOOFKXQNV FDOOHG WDVNV DQG WDVNV DUH IXUWKHU  EURNHQ GRZQ LQWR VPDOOHU FKXQNV FDOOHG WKUHDGV /HW XV FRQVLGHUWKHSURFHVVLQYROYHGIRUSUHSDUDWLRQRIWHD,QRUGHUWRSUHSDUHWHDVRPHVPDOOWDVNV DUHLQYROYHG7KHVHDUH 

%RLOLQJWKHWHDOHDYHVLQZDWHU



%RLOLQJPLON



)LOWHULQJWKHIURPWKHWHDOLTXHXUWHDOHDYHV



3RXULQJWHDDGGLQJVXJDUDQGPLONLQDFXS



6WLUULQJWKHFRQWHQWV

(DFKRIWKHDERYHWDVNVLVUHTXLUHGWRSUHSDUHWHDDQGFRXOGEHFRQVLGHUHGDVDWKUHDG6RPHRI WKHWDVNVFRXOGEHSHUIRUPHGVLPXOWDQHRXVO\6RZHFDQVD\WKDWSUHSDULQJWHDLQYROYHVYDULRXV WKUHDGV WR EH H[HFXWHG ,Q FRPSXWHU WHUPLQRORJ\ LI PRUH WKDQ RQH WKUHDG H[HFXWHV VLPXOWDQHRXVO\ WKHQ LW LV FDOOHG PXOWLWKUHDGLQJ $ WKUHDG LV WKH VPDOOHVW XQLW RI FRGH WKDW DQ RSHUDWLQJV\VWHPFDQH[HFXWH7KUHDGVUXQZLWKLQDSURFHVV ,WLVSRVVLEOHWRZRUNLQPRUHWKDQRQHDSSOLFDWLRQVLPXOWDQHRXVO\LQZLQGRZVHQYLURQPHQW,W LVSRVVLEOHWRZRUNLQ0LFURVRIW:RUGGRLQJVRPHIRUPDWWLQJRIWKHWH[WZKLOHDWWKHVDPHWLPH IURP ,QWHUQHW ([SORUHU GRZQORDGLQJ D :HE SDJH 7KDW LV KHUH ZH DUH ZRUNLQJ LQ PRUH WKDQ 132

Comp-U-Learn

Exception Handling and MultiThreading

RQHZLQGRZFRQFXUUHQWO\RULQPRUHWKDQRQHDSSOLFDWLRQ7KLVLVVDLGWREHPXOWLWDVNLQJ/HWV VHHZKDWLVPXOWLWKUHDGLQJ1RZLWLVLPSRUWDQWWRXQGHUVWDQGZKDWLVDSURFHVV 7KHUXQQLQJLQVWDQFHRIDSURJUDPLVFDOOHGDSURFHVV,WLVDSURJUDPLQH[HFXWLRQ1RZWKH V\VWHP UHVRXUFHV DQG WKH &38 WLPH DUH DOORFDWHG WR WKH YDULRXV UXQQLQJ SURFHVVHV :KHQ WKH WLPH VOLFH LV DOORFDWHG WR D SURFHVV WKH YDULRXV WKUHDGV LQ WKH SURFHVV PDNH XVH RI WKH RI WKH DYDLODEOH &38 WLPH ,Q RWKHUV ZRUGV WKH WKUHDGV DUH WKH XOWLPDWH XQLWV WKDW XVH D &38 WLPH 7KRXJKWKH\PDNHXVHRIWKHV\VWHPUHVRXUFHVWKH\DUHQRWDOORWWHGZLWKDQ\7KHWKUHDGVLQD SURFHVV PDNH XVH RI WKH V\VWHP UHVRXUFHV DOORFDWHG WR WKDW SDUWLFXODU SURFHVV 7KH GLIIHUHQFH EHWZHHQDWKUHDGDQGDSURFHVVLVWKDWDWKUHDGFDQQRWH[LVWRQLWVRZQZKHUHDVDSURFHVVFDQ 7KUHDGV DUH ZLWKLQ D SURFHVV 3URFHVV LV DOORFDWHG ZLWK WKH V\VWHP UHVRXUFHV DQG &38 WLPH 7KUHDGV PDNH XVH RI WKHP 7KH HQG XVHU GRHV QRW H[HFXWH D WKUHDG GLUHFWO\ $ SURFHVV FDQ FRQWDLQDVLQJOHWKUHDGRUPRUH3URFHVVWKDWLVPDGHRIDVLQJOHWKUHDGLVFDOOHGVLQJOHWKUHDGHG DSSOLFDWLRQDQGDSURFHVVKDYLQJPRUHLVFDOOHGPXOWLWKUHDGHG$QH[DPSOHRIPXOWLWKUHDGLQJLV WKH DELOLW\RI,QWHUQHW([SORUHUWR GRZQORDG ILOHV GLVSOD\ D :HE3DJHV $OVR WKH FRS\LQJ ILOHV IURPRQHIROGHUWRDQRWKHULVPXOWLWKUHDGHG7KHPDLQDGYDQWDJHRIPXOWLWKUHDGLQJLVWKHVSHHG RIH[HFXWLRQRIWKHSURJUDP /HWXVXQGHUVWDQGWKLVE\DQH[DPSOH$VVXPHWKDWZHKDYHWRSHUIRUPDFDOFXODWLRQOLNH (a+b) – (b*a)

1RZLIZHKDYHPXOWLSOHWKUHDGVWKHQFDOFXODWLQJDEZLOOEHGRQHE\DWKUHDGDQGFDOFXODWLQJ E DZLOO EH GRQH E\ DQRWKHU WKUHDG +HQFH H[HFXWLRQ RI WKLV SURFHVV LV IDVWHU 0XOWLWKUHDGLQJ DOORZVXVWRZULWHHIILFLHQWSURJUDPVWKDWPDNHPD[LPXPXVHRIWKH&38EHFDXVHLGOHWLPHFDQ EHNHSWWRWKHPLQLPXP:KHQDSURJUDPUHTXLUHVXVHULQSXWPXOWLWKUHDGLQJHQDEOHFUHDWLRQRI DVHSDUDWH WKUHDG IRU WKLV WDVN DORQH 7KH PDLQ WKUHDG FDQ FRQWLQXH ZLWK WKH H[HFXWLRQ RI WKH UHVWRIWKHSURJUDP3URJUDPVQRWXVLQJPXOWLWKUHDGLQJZLOOKDYHWRZDLWXQWLOWKHXVHUKDVLQSXW DYDOXHIRUWKHFRQWLQXDWLRQRIWKHSURJUDP 7KH EHQHILW RI -DYD·V PXOWLWKUHDGLQJ LV WKDW RQH WKUHDG WKDW FDQ SDXVH ZLWKRXW VWRSSLQJ RWKHU SDUWV RI WKH SURJUDP )RU H[DPSOH WKH LGOH WLPH FUHDWHG ZKHQ D WKUHDG UHDGV GDWD IURP D QHWZRUNRUZDLWVIRUWKHXVHULQSXWFDQEHXWLOL]HGHOVHZKHUH7KH-DYDUXQWLPHV\VWHPGHSHQGV RQ WKUHDGV IRU PDQ\ WKLQJV DQG DOO RI WKH FODVV OLEUDULHV DUH GHVLJQHG ZLWK PXOWLWKUHDGLQJ LQ PLQG The advantages of using threads are as follows

♦ ♦ ♦ ♦ ♦

Can be created faster Requires less overhead Interprocess communication ids are faster Context switching is faster Uses CPU time optimally. Comp-U-Learn

133

Java Programming I

Note Java assigns a priority to each thread. A higher priority thread does not run faster than a lower priority thread, if it is the only thread running. Instead a thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. 7KH7KUHDGFODVVLPSOHPHQWVWKUHDGVLQ-DYD7KH7KUHDGFODVVLVSDUWRIWKHSDFNDJHMDYDODQJ DQG KHOSV WR LPSOHPHQW -DYD WKUHDGV ZKLFK DUH LQGHSHQGHQW 7KHUH DUH WZR ZD\V WR FUHDWH D FODVVWKDWFDQEHPXOWLWKUHDGHG ♦ Create a class that extends the Thread class ♦ Create a class that implements the Runnable interface. 7KHIROORZLQJDUHWKHWKUHDGVLQ7KUHDGFODVV public thread()

&RQVWUXFWVDQHZWKUHDG7KHWKUHDGPXVWKDYHDUXQPHWKRGDQGDVWDUWPHWKRGWRDFWLYDWHWKH UXQPHWKRG public void run()

7KLV PHWKRG ZKLFK PXVW EH RYHUULGGHQ VKRXOG FRQWDLQ WKH FRGH RI WKH WKUHDG 7KH WKUHDG·V ERG\LVLPSOHPHQWHGLQLWVUXQPHWKRG public void start()

6WDUWVWKHWKUHDG7KLVZLOOFDXVHWKHUXQ PHWKRGWREHFDOOHGDQGUHWXUQLPPHGLDWHO\VRWKDW WKHWKUHDGFDQUXQFRQFXUUHQWO\ public static void sleep(long millesecs)

7KH FXUUHQWO\ H[HFXWLQJ WKUHDG ZDLWV VOHHS  IRU WKH VSHFLILHG WLPH LQ PLOOLVHFRQGV DQG WKHQ SHUPLWWLQJRWKHUWKUHDGVWRWDNHRYHUFRQWURO public void interrupt()

6HQGVDQLQWHUUXSWUHTXHVWWRDWKUHDG public static boolean interrupted()

5HWXUQVZKHWKHUDWKUHDGKDVEHHQLQWHUUXSWHGRUQRW

134

Comp-U-Learn

Exception Handling and MultiThreading

public static void yield()

7KHFXUUHQWWKUHDG\LHOGVWKHH[HFXWLRQWRWKHQH[WUXQQDEOHWKUHDG getName()

2EWDLQVDWKUHDGQDPH getPriority()

2EWDLQVDWKUHDG·VSULRULW\ isAlive()

'HWHUPLQHVLIDWKUHDGLVVWLOOUXQQLQJ join()

:DLWVIRUDWKUHDGWRWHUPLQDWH resume()

5HVXPHVH[HFXWLRQRIDVXVSHQGHGWKUHDG7KLVLVYDOLGRQO\LIVXVSHQG LVLQLWLDWHG suspend()

6XVSHQGVDWKUHDG public final void stop()

.LOOVDWKUHDG activeCount()

5HWXUQVWKHFXUUHQWQXPEHURIDFWLYHWKUHDGVLQWKLVWKUHDGJURXS currentThread()

5HWXUQVDUHIHUHQFHWRWKHFXUUHQWO\H[HFXWLQJ7KUHDGREMHFWDQGLVDVWDWLFPHWKRG setName(String)

6HWVWKHWKUHDG·VQDPH

Comp-U-Learn

135

Java Programming I

setPriority(int)

6HWVWKHWKUHDGSULRULW\ $QH[DPSOHRIFUHDWLQJWKUHDGXVLQJ7KUHDGFODVVLVVKRZQDVIROORZV Example 6.10 class mythread extends Thread { String name; Thread t; mythread(String s) { t=new Thread(this,s); System.out.println("New thread : " +t); t.start(); } public void run() { try { for(int i=5;i>0;i--) { System.out.println(name + i); Thread.sleep(500); } }catch(InterruptedException e) { } System.out.println(name+ "existing ........"); } } class ex610 { public static void main(String args[]) { mythread m1=new mythread("One"); mythread m2=new mythread("Two"); System.out.println("thread m1 is alive " + m1.t.isAlive()); System.out.println("thread m2 is alive " + m2.t.isAlive()); try{ System.out.println("Waiting ");

136

Comp-U-Learn

Exception Handling and MultiThreading m1.t.join(); m2.t.join(); }catch(InterruptedException e) { } System.out.println("thread m1 is alive " + m1.t.isAlive()); System.out.println("thread m2 is alive " + m2.t.isAlive()); System.out.println("Existing main thread "); } }

2XWSXWRIWKHSURJUDP C:\jdk1.2\bin>java ex610 New thread : Thread[One,5,main] New thread : Thread[Two,5,main] thread m1 is alive true null5 null5 thread m2 is alive true Waiting null4 null4 null3 null3 null2 null2 null1 null1 nullexisting ........ nullexisting ........ thread m1 is alive false thread m2 is alive false Existing main thread

Comp-U-Learn

137

Java Programming I

Thread States

Runnable

Start( ) or run expires

Dead

Not Runnable Start( )

Stop( ) New Thread Stop( )

New Thread

Fig 6.2 :KHQHYHU DQ LQVWDQFH RI WKH 7KUHDG FODVV LV FUHDWHG WKH WKUHDG HQWHUV LQWR WKH QHZ 7KUHDG 6WDWH7KHFRGHWKDWIROORZVLOOXVWUDWHVWKHLQVWDQWLDWLRQRIWKH7KUHDGFODVV Thread nThread=new Thread(this);

7KLV FUHDWHV D QHZ WKUHDG 1RZ QR UHVRXUFHV DUH DOORFDWHG WR WKH WKUHDG ,W LV RQO\ DQ HPSW\ REMHFW$VDUHVXOWRIWKLVRQO\WKHVWDUWDQGVWRSPHWKRGVFDQEHLQYRNHG,IDQDWWHPSWLVPDGH WRLQYRNHRWKHUPHWKRGVRIWKH7KUHDGFODVVWKHQLWZLOOWKURZ,OOHJDO7KUHDG6WDWH([FHSWLRQ Runnable

2QFHWKHWKUHDGUHFHLYHVWKHVWDUWPHWKRGLWHQWHUVLQWRWKHUXQQDEOHVWDWHDQGQRWUXQQLQJVWDWH 7KHWKUHDGPLJKWQRWEHH[HFXWLQJDWWKHUXQQDEOHVWDJH6LQFHDVLQJOHSURFHVVRUFDQQRWH[HFXWH PRUH WKDQ RQH WKUHDG DW RQH WLPH WKHUH LV D ZD\ RI VFKHGXOLQJ WKH SULRULWLHV IRU WKH WKUHDGV 7KLVLVFDOOHG7KUHDGSULRULW\

138

Comp-U-Learn

Exception Handling and MultiThreading

Not Runnable

$WKUHDGLVVDLGWREHLQWKHQRWUXQQDEOHVWDWHLILW ♦ ♦ ♦ ♦

Has been suspended Is sleeping Is waiting Is being blocked by another thread

$WKUHDGFDQEHVXVSHQGHGE\LQYRNLQJWKHVXVSHQGPHWKRGRIWKH7KUHDGFODVVZKHUHE\WKH WKUHDGLVQRWH[HFXWDEOH7RH[HFXWHWKHWKUHDGWKHUHVXPH KDVWREHLQYRNHG7KHVXVSHQG KRZHYHUGRHVQ·WNLOOWKHWKUHDG $WKUHDGLVSXWWRVOHHSZKHQWKHVOHHSPHWKRGLVLQYRNHG7KHWLPHLVJLYHQDVPLOOLVHFRQGVWR WKH VOHHS  $ VOHHSLQJ WKUHDG ZLOO HQWHU LQWR WKH UXQQDEOH VWDWH DIWHU WKH VSHFLILHG WLPH KDV HODSVHG8QWLOWKDWWLPHWKUHDGZLOOQRWH[HFXWH7KHVOHHSLQJWKUHDGFDQQRWEHH[HFXWHGXVLQJ WKHUHVXPH  $ WKUHDG FDQ EH PDGH WR ZDLW RQ D FRQGLWLRQDO YDULDEOH PDNLQJ LW ZDLW XQWLO WKH FRQGLWLRQ LV VDWLVILHG 7KH WKUHDG LV QRW UXQQDEOH WLOO WKH FRQGLWLRQ EHFRPHV WUXH 7KH FRQGLWLRQ FDQ EH QRWLILHGWRWKHWKUHDGE\LQYRNLQJQRWLI\  Dead

$WKUHDGFDQHLWKHUGLHQDWXUDOO\RULWFDQEHNLOOHG$WKUHDGXQGHUJRHVDQDWXUDOGHDWKZKHQWKH ORRSLQWKHUXQPHWKRGLVFRPSOHWHG$WKUHDGFDQEHNLOOHGE\LQYRNLQJWKHVWRSPHWKRG7KH LV$OLYH PHWKRGFDQEHXVHGWRILQGRXWZKHWKHUDWKUHDGKDVEHHQVWDUWHGRUVWRSSHG

Thread Priority (DFK WKUHDG KDV D SULRULW\ ZKLFK DIIHFWV WKH RUGHU LQ ZKLFK LW LV UXQ 7KUHDGV ZLWK D KLJKHU SULRULW\ VXSHUVHGH WKUHDGV ZLWK D ORZHU SULRULW\ $ WKUHDG LQKHULWV LWV SULRULW\ IURP WKH WKUHDG WKDW FUHDWHG LW 7KH SULRULW\ RI D WKUHDG FDQ EH VHW E\ XVLQJ WKH VHW3ULRULW\  RI WKH 7KUHDG IXQFWLRQ7KHSDUDPHWHUVWRWKLVPHWKRGDUH ♦ MIN_PRIORITY ♦ MAX_PRIORITY ♦ NORM_PRIORITY :KHQPRUHWKDQRQHWKUHDGLVUHDG\IRUH[HFXWLRQ-DYDUXQWLPHV\VWHPFKRRVHVWKHRQHZLWK WKH KLJKHVW SULRULW\ DQG H[HFXWHV LW :KHQ RQH WKUHDG LV EHLQJ H[HFXWHG DQG -DYD HQFRXQWHUV

Comp-U-Learn

139

Java Programming I

DQRWKHUZLWKDKLJKHUSULRULW\WKHQ-DYDSXVKHVWKHFXUUHQWO\H[HFXWLQJWKUHDGDQGWKHRQHZLWK DKLJKHUSULRULW\ZLOOEHH[HFXWHG

Daemon Threads $GDHPRQWKUHDGFDQEHFRQVLGHUHGWREHDWDVNPDQDJHUWKUHDGWKDWVXSSRUWVRWKHUWKUHDGV,WLV LQGHSHQGHQW LQ DQ DSSOLFDWLRQ DQG SURYLGHV VHUYLFHV WR RWKHU REMHFWV LQ WKH VDPH DSSOLFDWLRQ 7KHUXQPHWKRGRIDGDHPRQWKUHDGLVXVXDOO\DQLQILQLWHORRSZKLFKZDLWVIRUDVHUYLFHUHTXHVW 7RVSHFLI\WKDWDWKUHDGLVGDHPRQVHW'DHPRQ PHWKRGLVLQYRNHGZLWKWKHERROHDQSDUDPHWHU WUXH7KHLV'DHPRQ PHWKRGLVXVHGWRFKHFNZKHWKHUDWKUHDGLVD'DHPRQRUQRW 7KH IROORZLQJ SURJUDP  LOOXVWUDWHV WKH ZRUNLQJ RI WKUHDGV +HUH WKH WKUHDG LV PDGH WR WLFN FRQWLQXRXVO\LUUHVSHFWLYHRIZKHWKHUWKHDSSOHWLVEHLQJPLQLPL]HGRUPD[LPL]HG Example 6.11 import java.awt.Graphics; import java.util.Date;import java.applet.*; public class time extends Applet implements Runnable { Thread t1; public void start() { if(t1==null) { t1=new Thread(this); t1.start(); } } public void run() { while(t1!=null) { repaint(); try { t1.sleep(1000); } catch(InterruptedException e) { } } } public void paint(Graphics g) { Date d=new Date();

140

Comp-U-Learn

Exception Handling and MultiThreading g.drawString(d.getHours() +":"+d.getMinutes()+":"+d.getSeconds(),5,10); } public void stop() { t1.stop(); t1=null; } }

7KHRXWSXWRIWKHSURJUDPLVDVIROORZV

Fig 6.3 $QRWKHUH[DPSOHWRVKRZWKHZRUNLQJRIWKUHDGVXVLQJDSSOLFDWLRQ Example 6.12 class mythread implements Runnable { Thread t; mythread() { t=new Thread(this," Demo Thread"); System.out.println("child thread : " +t); t.start(); } public void run() { try { for(int i=5;i>0;i--) {

Comp-U-Learn

141

Java Programming I System.out.println("Child Thread : " + i); Thread.sleep(500); } }catch(InterruptedException e) { System.out.println("Child Thread interrupted ."); } System.out.println("Existing child thread "); } } class ex54 { public static void main(String args[]) { new mythread(); try{ for(int i=6;i>0;i--) { System.out.println("Main Thread : " + i); Thread.sleep(1000); } }catch(InterruptedException e) { System.out.println("Main thread Interrupted "); } System.out.println("Existing main thread "); } }

,QVLGHWKHFRQVWUXFWRUP\WKUHDGZHDUHFUHDWLQJDQHZWKUHDGXVLQJWKHVWDWHPHQW T=new Thread(this,”Demo Thread”);

7KLVREMHFWKHUHVSHFLILHVWKDWWKHQHZO\FUHDWHGWKUHDGFUHDWHGZLOOFDOOWKHUXQ PHWKRG1H[W VWDUW LV FDOOHG ZKLFK VWDUWV WKH WKUHDG DQG EHJLQV H[HFXWLQJ WKH UXQ PHWKRG 7KLV FDXVHV WKH FKLOGWKUHDG·VIRUORRSWREHJLQDIWHUFDOOLQJWKHVWDUWPHWKRGP\WKUHDG·VFRQVWUXFWRUUHWXUQVWR PDLQ 7KHPDLQWKUHDGQRZHQWHUVLQWRWKHIRUORRS %RWK WKH WKUHDGV UXQQLQJ VLPXOWDQHRXVO\ VKDULQJ WKH &38 WLPH XQWLO WKH XSSHU ERXQG RI WKH ORRSLVUHDFKHG 7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.2\bin>javac ex54.java C:\jdk1.2\bin>java ex54 child thread : Thread[ Demo Thread,5,main] Main Thread : 6

142

Comp-U-Learn

Exception Handling and MultiThreading Child Thread : 5 Child Thread : 4 Main Thread : 5 Child Thread : 3 Child Thread : 2 Main Thread : 4 Child Thread : 1 Existing child thread Main Thread : 3 Main Thread : 2 Main Thread : 1 Existing main thread C:\jdk1.2\bin>

Summary Exception handling provides a powerful mechanism to control complex programs that have many dynamic run time characteristics. Errors and abnormal situations arising while executing a program needs to be handled. Java provides well-defined methods for exception handling. There are various exception handling classes which are subclasses of Exception. The try, catch ,throw, finally and throws are the keywords involved in exception handling. Multithreading enables the program to make optimum utilization of the available CPU time. It is a feature of the programming environment to make best use of the available resources. Multithreading in Java is offered through Thread class and Runnable interface. The start(), run(), sleep(), stop(), suspend() and resume() are some of the important methods related to threading in Java.

Going Over It Again I. Fill in the Blanks

 ([FHSWLRQVDUHGHULYHGIURPBBBBBBBBBBBFODVV  0DQXDOO\FUHDWHGH[FHSWLRQVDUHUDLVHGXVLQJBBBBBBBBBBBBBBNH\ZRUG  ([FHSWLRQV WKDW DUH WKURZQ RXW RI D PHWKRG PXVW EH VSHFLILHG XVLQJ BBBBBBBBBBBBB FODXVH  7KHDELOLW\WRSHUIRUPPRUHWKDQRQHSURFHVVVLPXOWDQHRXVO\LVFDOOHGBBBBBBBBBBBB  BBBBBBBBBBBBBBPHWKRGLVXVHGWRGHWHUPLQHWKHSULRULW\RIDWKUHDG  BBBBBBBBBBBBBBBBBBBLVWRNQRZZKHWKHUDWKUHDGKDVEHHQVWDUWHGRUVWRSSHG Comp-U-Learn

143

Java Programming I

II. State True or False

 ([FHSWLRQKDQGOLQJDOORZV\RXWRIL[HUURUV  (UURUFODVVKDQGOHVWKHHUURUVWKDWDUHQRWFDXJKWXQGHUQRUPDOFLUFXPVWDQFHV  'LYLVLRQE\]HURFDXVHV1XOO3RLQWHU([FHSWLRQ  7U\FDQEHXVHGRQDVLQJOHVWDWHPHQWZLWKRXWFXUO\EUDFHV  7KUHDGVFDQH[LVWLQGHSHQGHQWO\  7KHVXVSHQG NLOOVDWKUHDG III. One line Answers

 /LVWWKHVRXUFHVRIHUURUV  :KDWLVH[FHSWLRQKDQGOLQJ"  :KDWZLOOKDSSHQLIDQH[FHSWLRQWKURZQGRHVQRWKDYHDQKDQGOHU"  ([SODLQWKHXVDJHRIILQDOO\EORFN  ([SODLQ'DHPRQ7KUHDG  :KDWLVLPSOLFLWDQGH[SOLFLWH[FHSWLRQ"  :KDWLVDWKUHDG"

144

Comp-U-Learn

Session 7

Java Applets

On Completion of this Session We will be able to understand...

) Java Applet ) Applet in Html ) Basic methods of Applet ) Various Applet classes ) Image class in Applet ) Animation in Applet

In This Session...



Introduction to Applet



Applet vs Application



Applet Architecture



Developing an Applet



Applet in HTML



Basic Methods in Applet



Parameter passing to Applets



Graphics Class



Font Class



Color Class



Images



Animation using Images

Java Applets

Introduction to Applet 7KHPDLQIHDWXUHWKDW-DYDSURYLGHVRYHURWKHUODQJXDJHVLVWKHIDFLOLW\WRZULWHDSSOHWV$SSOHWLV DSURJUDPWKDWFDQEHGRZQORDGHGDQGH[HFXWHGRQDQ\PDFKLQHLQWKHZRUOG7KHDGYDQWDJHV RIIHUHGE\WKHDSSOHWVDUHPXFKPRUHWKDQRQHFDQWKLQNRI$SSOHWVRSHQXSWKHSRVVLELOLW\RI FUHDWLQJDQLPDWLRQRQZHESDJHV:LWKRXWDSSOHWVWKHZHESDJHVDUHMXVWOLNHPDJD]LQHSDJHV ZLWKDSSOHWVWKH\EHFRPHOLNHPRYLHVDQGFRPPXQLFDWHPXFKPRUHHIIHFWLYHO\ ,Q DGGLWLRQ WR WKH DSSOHW LWVHOI WKH ZHE SDJH FDQ FRQWDLQV DOO RWKHU +70/ HOHPHQWV ZH KDYH OHDUQW$SSOHWVDUHMXVWRQHSDUWRIWKHK\SHUWH[WSDJH,WLVDOZD\VZRUWKNHHSLQJLQPLQGWKDW -DYDLVQRWDWRROIRUGHVLJQLQJ+70/SDJHV$FWXDOO\DSSOHWVDUHWKHWRROIRUEULQJLQJWKHPWR OLIH7KLVLVQRWWRVD\WKDWWKH*8,GHVLJQHOHPHQWVLQD-DYDDSSOHWDUHQRWLPSRUWDQWEXWWKH\ PXVWZRUNZLWKWKHXQGHUO\LQJ+70/GHVLJQRIWKHZHESDJH 7KLV VHVVLRQ ILUVW VKRZV KRZ WR FUHDWH D -DYD DSSOHW DQG YLHZ WKHP LQ RXU WHUPLQDO XVLQJ DSSOHWYLHZHU RU DQ\ RWKHU EURZVHUV ZLWK GLIIHUHQW YLVXDO HIIHFWV OLNH IRQWV FRORUV DQG YDULRXV VKDSHV7KHVXFFHHGLQJVHVVLRQVZLOOGLVFXVVKRZWRFRSHZLWKZLQGRZLQJUHTXLUHPHQWVDQGDOO WKHLPSRUWDQWDVSHFWVRI-DYDDSSOHWV

Applet vs Application -DYDDSSOLFDWLRQVDUHVLPSOHVWDQGDORQHSURJUDPVWKDWFDQEHUXQE\WKHMDYDLQWHUSUHWHU:HJHW WKH RXWSXW RI WKH DSSOLFDWLRQ SURJUDPV LQ WKH FRPPDQG OLQH RQO\ %XW MDYD DSSOHWV FDQ UXQ LQVLGHWKH:RUOG:LGH:HEEURZVHUDQGZHJHWRXUDSSOHWRXWSXWLQD*8,IRUPDW$SSOHWVFDQ EHORDGHGRYHUWKHQHWZRUNDQGKDYHPRUHFDSDELOLWLHVWKDQWKHMDYDDSSOLFDWLRQSURJUDPV $SDUWIURPWKDWDSSOHWVKDYHWKHIROORZLQJDGYDQWDJHVWKDWQRWHYHQWKHMDYDDSSOLFDWLRQVKDYH 7KH\DUH ♦ Applets have built-in support for multimedia. ♦ Applets running within a Web browser can easily be embedded in a Web page. ♦ Applets can make use of the GUI based pre-defined packages. ♦ Applet provides a frame, event-handling facility and graphics context. ♦ Applets can invoke public methods of other applets on the same page. (YHQWKRXJKWKHDSSOHWVKDYHWKHDERYHIDFLOLWLHVWKH\KDYHKDVVHFXULW\UHVWULFWLRQVWRSUHYHQW WKHPIURPEHLQJDIIHFWHGE\YLUXVHV-DYDDSSOHWVGRHVQ·WVXSSRUWWKHIROORZLQJDVSHFWVGXHWR VHFXULW\UHVWULFWLRQV Comp-U-Learn

147

Java Programming I

♦ ♦ ♦ ♦

Applets cannot load libraries or define native methods. An applet cannot ordinarily read or write files on the host that is executing it. An applet cannot make network connections except to the host that it came from. An applet cannot read certain system properties.

Applet Architecture :H  KDYH DOUHDG\ VHHQ WKDW DQ DSSOHW LV D VLPSOH MDYD FODVV WKDW XOWLPDWHO\ H[WHQGV WKH MDYDDSSOHW$SSOHWFODVV1RWHWKDWWKHDSSOHWSDFNDJHLVQRWSDUWRIWKH$:7FRPSRQHQW7KH DUFKLWHFWXUHVKRZQLQWKHIROORZLQJILJXUHLOOXVWUDWHVWKLV ,QWKHVXFFHHGLQJVHVVLRQVZHZLOOXVHWKH6ZLQJVHWWRLPSOHPHQWDSSOHWV$OORIWKHDSSOHWVZLOO H[WHQGWKH$SSOHWFODVVWKHVXSHUFODVVIRU6ZLQJDSSOHWV$VZHFDQVHHLQWKHIROORZLQJILJXUH $SSOHWLVDQLPPHGLDWHVXEFODVVRIWKHRUGLQDU\$SSOHWFODVV Object

Component

Container

Window

Panel

Frame

Applet

JFrame

JApplet

Fig 7.1.

148

Comp-U-Learn

Java Applets

Developing an Applet ,QWKLVVHFWLRQZHDUHJRLQJWROHDUQDERXWWKHFUHDWLRQRIDVLPSOHDSSOHWSURJUDP7KHFUHDWLRQ RIDQDSSOHWFRQVLVWVRIWKHIROORZLQJIRXUVWHSV ♦ ♦ ♦ ♦

Importing the necessary built-in java packages Defining applet subclasses Applet implementation Passing this Java applet’s .class file into HTML file.

&RQVLGHUWKHIROORZLQJDSSOHWH[DPSOH VD\ VDPSOHMDYD ,WLOOXVWUDWHVWKHGHWDLOVWRFUHDWH DQDSSOHW Example 7.1 import java.awt.*; import java.applet.*; public class sample extends Applet { public void paint(Graphics g) { g.drawString("Java Applet Welcomes You!",100,100); } }

,QWKHDERYHSURJUDPWKHILUVWWZROLQHVDUHXVHGWRLPSRUWVRPHSDFNDJHVDQGFODVVHVZKLFKDUH EHLQJXVHGZLWKLQRXUDSSOHW $VLQDQDSSOLFDWLRQKHUHWRRZHKDYHWRVSHFLI\WKHFODVVGHFODUDWLRQDWWKHEHJLQQLQJ+HUH WKHH[WHQGVNH\ZRUGLVXVHGWRH[WHQGVRPHSUHGHILQHGFODVVHVWRRXUSURJUDP 7KHQZHKDYHWRLPSOHPHQWWKHDSSOHWE\PHDQVRIDSSOHWPHWKRGV,QWKLVSURJUDPWKHSDLQW PHWKRGRIDSSOHWLVXVHGWRSULQWVRPHWH[WLQWKHZLQGRZ7KHGUDZ6WULQJPHWKRGRIWKHFODVV *UDSKLFVLVXVHGIRUSDLQWLQJWKHWH[WLQWKHVFUHHQ )LQDOO\ZHKDYHWRSDVVWKLVVRXUFHILOH VDPSOHFODVV LQWRDQ+70/ILOH)RUWKDWZHKDYHWR FUHDWHDQRWKHU+70/ILOH VD\VDPSOHKWPO ZKLFKVKRXOGFRQWDLQWKHIROORZLQJFRGH

1RZFRPSLOHWKLVVDPSOHMDYDILOHRQWKHFRPPDQGOLQHXVLQJMDYDF7KHQUXQWKLVVDPSOHKWPO ILOHXVLQJDSSOHWYLHZHU7KHIROORZLQJILJXUHVKRZVWKHRXWSXWRIWKLVDSSOHW Comp-U-Learn

149

Java Programming I

Fig 7.2 $IWHUFRPSLOLQJRXUMDYDILOHZHFDQDOVRJHWWKHRXWSXWIRUWKHDERYHSURJUDPE\EURZVLQJWKH VDPSOHKWPO ILOH LQ WKH ,QWHUQHW H[SORUHU 7KH IROORZLQJ ILJXUH  VKRZV WKH RXWSXW RI WKH VDPSOHSURJUDPLQWKHLQWHUQHWH[SORUHU

Fig 7.3

Note Look at the applet code. There is no main method. Applets don’t need it. The main method is actually in the browser or the appletviewer, not in the Applet itself.

Applet in HTML %HIRUH-DYDZHXVHG+70/WRGHVFULEHWKHOD\RXWRIDZHESDJH+70/LVDVLPSOHYHKLFOHWR LQGLFDWHHOHPHQWVRIDK\SHUWH[WSDJH7KH+70/SDJHPXVWWHOOWKHEURZVHUZKLFKDSSOHWVWR ORDGDQGZKHUHWRSXWHDFKDSSOHWRQWKHZHESDJH7KH$33/(7!DQG$33/(7!WDJV DUHFDOOHG+70/MDYDWDJV7KHMDYDHQDEOHGEURZVHUVZLOOXQGHUVWDQGWKDWFRGHEHWZHHQWKHVH WDJVDUHWKHMDYDFRGH)RUWKDWZLWKLQWKHVHWDJVZHPXVWSDVVWKHIROORZLQJ

150

Comp-U-Learn

Java Applets

♦ The name of the class files ♦ The location of the class files ♦ How the applet sits on the web page )RUWKHDERYHUHTXLUHPHQWVWKH$33/(7!WDJKDVWKHIROORZLQJDWWULEXWHV:HFDQXVHWKHVH DWWULEXWHVDFFRUGLQJWRRXUUHTXLUHPHQWV <APPLET>

7KLVWDJWKDWLVXQGHUVWRRGE\WKHDSSOHWYLHZHURUDQ\%URZVHU <EMBED>

7KLVWDJWKDWLVXQGHUVWRRGE\WKH1HWVFDSH1DYLJDWRU

7KLVWDJWKDWLVXQGHUVWRRGE\WKH,QWHUQHW([SORUHUDQGWKHODWHVWYHUVLRQRIWKH1DYLJDWRU

This tag is to pass some parameter into the HTML file while using Java programs. CODE

7RVSHFLI\WKHQDPHRIWKHFODVVILOH CODEBASE

7RVSHFLI\WKHSDWKRIWKHFODVVILOH ARCHIVE

7KLVRSWLRQDODWWULEXWHOLVWVWKH-DYDDUFKLYHILOHV UHVRXUFHILOHV  OBJECT

7KLVLVWRVSHFLI\WKHQDPHRIWKHILOHWKDWFRQWDLQVVHULDOL]HGDSSOHWREMHFWV NAME

7KH1$0(DWWULEXWHJLYHVDQDPHIRUDQDSSOHWWREHUHIHUUHGE\WKHFRGH Comp-U-Learn

151

Java Programming I ALIGN

6SHFLI\WKHDOLJQPHQWRIWKHRXWSXWZLQGRZWRWKHDSSOHWYLHZHU WIDTH

6SHFLI\WKHZLGWKRIWKHRXWSXWZLQGRZWRWKHDSSOHWYLHZHU HEIGHT

6SHFLI\WKHKHLJKWRIWKHRXWSXWZLQGRZWRWKHDSSOHWYLHZHU 1RZ REVHUYH VDPSOHKWPO FRGH LQ WKH H[DPSOH  :LWKLQ WKH $33/(7! WDJ WKH &2'( DWWULEXWH VSHFLILHV WKH VDPSOHFODVV ILOH WKH ZLGWK DQG KHLJKW DWWULEXWHV VSHFLI\LQJ WKH VL]H RI WKHRXWSXWZLQGRZ

Basic Methods in Applet 7KHUHDUHIRXUPHWKRGVLQWKHDSSOHWFODVVWKDWJLYHWKHIUDPHZRUNE\ZKLFKRQHFDQEXLOGDQ\ VHULRXV DSSOHW 7KH\ DUH LQLW  VWDUW  VWRS  GHVWUR\  ,Q WKLV VHFWLRQ ZH FDQ  JHW D VKRUW GHVFULSWLRQDERXWWKHVHPHWKRGV7KHVHPHWKRGVH[LVWLQWKHDSSOHWFODVVDQGDUHRYHUULGGHQWR H[HFXWHWKHPHWKRGVLQDJLYHQFODVV init() method

7KHLQLW PHWKRGLVXVHGWRLQLWLDOL]HWKHDSSOHW7KLVPHWKRGLVFDOOHGDVVRRQDVDQDSSOHWLV VWDUWHG,QLWLDOL]DWLRQRIDOOWKHYDULDEOHVFUHDWLRQRIREMHFWVVHWWLQJRISDUDPHWHUVHWFFDQEH GRQHLQWKLVPHWKRG:HQHYHUQHHGWRFDOOWKLVPHWKRGGLUHFWO\,WLVFDOOHGDXWRPDWLFDOO\E\WKH V\VWHPRQFHWKHDSSOHWLVFUHDWHG $SSOHWFDQKDYHDGHIDXOWFRQVWUXFWRUEXWLWLVFXVWRPDU\WRSHUIRUPDOOWKHLQLWLDOL]DWLRQLQWKH LQLW PHWKRGLQVWHDGRIWKHGHIDXOWFRQVWUXFWRU start() method

7KLV PHWKRG LV DXWRPDWLFDOO\ FDOOHG RQFH WKH LQLW  PHWKRG LV H[HFXWHG $OVR LW LV DOVR FDOOHG ZKHQHYHU WKH XVHU UHWXUQV WR WKH SDJH FRQWDLQLQJ WKH DSSOHW DIWHU KDYLQJ YLVLWHG RWKHU SDJHV 7KLV VWDUW  PHWKRG FDQ EH FDOOHG UHSHDWHGO\ XQOLNH WKH LQLW  PHWKRG :H QHHG QRW  FDOO WKLV PHWKRG GLUHFWO\ DV LW LV FDOOHG ZKHQ WKH DSSOHW·V GRFXPHQW LV YLVLWHG RU LWV ZLQGRZ EHFRPHV YLVLEOH,QDQXWVKHOOZHFDQVD\WKHVWDUW PHWKRGLVXVHGWRVWDUWWKHH[HFXWLRQRIWKHDSSOHW

152

Comp-U-Learn

Java Applets stop() method

7KHVWRS PHWKRGLVXVHGWRKDOWWKHUXQQLQJRIWKHDSSOHWLHVWRSWKHH[HFXWLRQRIWKHDSSOHW 7KLVPHWKRGLVDXWRPDWLFDOO\FDOOHGZKHQWKHXVHUPRYHVRIIWKHZHESDJHRQZKLFKWKHDSSOHW VLWV ,W FDQ WKHUHIRUH EH UXQ UHSHDWHGO\ LQ WKH VDPH DSSOHW :H QHHG QRW FDOO WKLV PHWKRG GLUHFWO\ destroy() method

7KHGHVWUR\ PHWKRGLVXVHGWRIUHHWKHPHPRU\DOORFDWHGIRUYDULDEOHVDQGREMHFWVLQLWLDOL]HGLQ WKHDSSOHW$Q\FOHDQXSDFWLYLW\WKDWQHHGVWREHSHUIRUPHGFDQEHGRQHLQWKLVPHWKRG-DYD FDOOVWKHVWRS PHWKRGEHIRUHFDOOLQJWKHGHVWUR\ PHWKRGLIWKHDSSOHWLVVWLOODFWLYH

Note The destroy() method is different from the finalize() method. The destroy() method applies only to applets and the finalize() method is used generally to clean up a single object. $SDUWIURPWKHVHEDVLFPHWKRGVLQWKHDSSOHWFODVVVRPHPRUHPHWKRGVLQWKHZLQGRZFODVVDUH DOVRXVHGWRFUHDWHDFWLYHDSSOHWV7KH\DUHGLVFXVVHGEHORZ paint() method

7KLVPHWKRGKHOSVLQGUDZLQJZULWLQJDQGFUHDWLQJDFRORUHGEDFNJURXQGRUDQLPDJHRQWRWKH DSSOHW,WWDNHVDQDUJXPHQWZKLFKLVDQLQVWDQFHRIWKH*UDSKLFFODVV7RXVHWKLVPHWKRGLWLV QHFHVVDU\WRLPSRUWWKH*UDSKLFVFODVVDVLPSRUWMDYDDZW  repaint() method

7KH UHSDLQW PHWKRG LV XVHG ZKHQ DQ DSSOHW LV WR EH UHSDLQWHG 7KLV PHWKRG FDOOV RQH PRUH PHWKRGXSGDWH WRFOHDUWKHVFUHHQRIDQ\H[LVWLQJFRQWHQW7KHXSGDWH PHWKRGLQWXUQVFDOOV WKH SDLQW PHWKRGWKDW WKHQGUDZV WKHFRQWHQWVRIWKHFXUUHQWIUDPH 7KH UHSDLQW  LV XVXDOO\ FDOOHGLQDQLPDWLRQSURJUDPVLQYROYLQJPXOWLWKUHDGLQJ The following example is designed to give us some feel of the methods in the applet class that we are likely to encounter. Example 7.2 import import public { public

java.applet.*; java.awt.*; class sample_methods extends Applet void init()

Comp-U-Learn

153

Java Programming I { System.out.println("This is the } public void start() { System.out.println("This is the } public void paint(Graphics g) { System.out.println("This is the } public void stop() { System.out.println("This is the } public void destroy() { System.out.println("This is the } }

INIT() method");

START() method");

PAINT() method");

STOP() method");

DESTROY() method");

:ULWH WKH DERYH FRGH DQG VDYH LW DV VDPSOHBPHWKRGVMDYD 7KHQ FRPSLOH LW XVLQJ MDYDF 7KHQ ZULWHWKHIROORZLQJFRGHRI+70/IRUWKHDERYHH[DPSOHDQGUXQLWXVLQJDSSOHWYLHZHU

,Q WKH RXWSXW ZKHQHYHU WKH PHWKRGV DUH FDOOHG WKH DSSOHW UHVSRQGV E\ SULQWLQJ WKH FRUUHVSRQGLQJWH[WRIWKHPHWKRGDWRXUXVXDOFRPPDQGOLQH%HIRUHWKHDSSOHWLVFUHDWHGZH FDQ JHW LQLW  VWDUW  DQG SDLQW  PHWKRG DFWLRQV LQ WKH FRPPDQG OLQH 7KHQ ZH FDQ JHW RXU DSSOHW ZLQGRZ $IWHU FORVLQJ WKH DSSOHW ZLQGRZ ZH FDQ JHW WKH DFWLRQV LQ WKH VWRS  DQG WKH GHVWUR\ PHWKRG

Parameter passing to Applets ,QWKHH[DPSOHZHSDVVHGSDUDPHWHUVLQD-DYDDSSOLFDWLRQ7RSDVVSDUDPHWHUVWRDQDSSOHW ZHKDYHWRXVHWKHWDJ3$5$0!DORQJZLWKDWWULEXWHVWKDWZHGHILQH,WKDVWZRDWWULEXWHVYL] 1$0( DQG 9$/8( 7KH LQLW  PHWKRG RI WKH DSSOHW GHDOW ODWHU FRQWDLQV D PHWKRG FDOOHG JHW3DUDPHWHU 7KLVPHWKRGWDNHV RQHDUJXPHQWWKDWLVDVWULQJUHSUHVHQWLQJ WKH QDPHRI WKH SDUDPHWHU EHLQJ ORRNHG IRU DQG UHWXUQV D VWULQJ FRQWDLQLQJ WKH FRUUHVSRQGLQJ YDOXH RI WKDW SDUDPHWHU 7RGHPRQVWUDWHWKLVZHZLOOFRQYHUW´-DYD$SSOHWV:HOFRPHV
154

Comp-U-Learn

Java Applets

Example 7.3 import java.applet.*; import java.awt.*; public class parameter extends Applet { String input; public void init() { input=getParameter("String"); } public void paint(Graphics g) { g.drawString(input,100,100); } }

7KH IROORZLQJ FRGH LV UHTXLUHG WR SDVV D SDUDPHWHU WR WKH DSSOHW +HUH ZH SDVV WKH LQSXW DV 6WULQJW\SHE\WKH9$/8(DWWULEXWH7KH1$0(LQGLFDWHVWKHSDUDPHWHUQDPHLQWKH-DYDFRGH <param name="String" value="This is the demo for Parameter in Applet">

Fig 7.4 1RZ UXQ WKLV SURJUDP XVLQJ DSSOHWYLHZHU WR JHW WKH DSSOHW ZLQGRZ ZLWK WKH WH[W ZKLFK LV SDVVHGLQWKH9$/8(DWWULEXWHDVVKRZQLQWKHILJXUH,IZHZDQWWRFKDQJHWKHSDUDPHWHU YDOXHZHFDQFKDQJHWKHYDOXHRIWKH9$/8(DWWULEXWHLQ+70/ILOHLWVHOIDQGJHWWKHRXWSXWE\ UXQQLQJ WKH +70/ ILOH DORQH 7KHUH LV QR QHHG RI FRPSLOLQJ WKH SURJUDP DJDLQ 7KLV LV WKH PDLQDGYDQWDJHRIWKLVSDUDPHWHUSDVVLQJ Comp-U-Learn

155

Java Programming I

Graphics class ,Q-DYDXVLQJWKHPHWKRGVGHILQHGLQWKH*UDSKLFVFODVVZHFDQGRDOOWKHJUDSKLFVRSHUDWLRQV 7KLV *UDSKLFV FODVV LV SDUW RI WKH MDYDDZW SDFNDJH $OO WKH GUDZLQJ PHWKRGV KDYH DUJXPHQWV SDVVHGWRWKHP7KH\PD\EHHQGSRLQWVFRUQHUVRUVWDUWLQJSRLQWV7KHVHWKLQJVDUHUHIHUUHGE\ WKHFRRUGLQDWHV\VWHP$OOWKHFRRUGLQDWRUVDUHLQWHJHUV 7KHIROORZLQJ WDEOHOLVWVWKHPHWKRGVDYDLODEOHLQWKH *UDSKLFVFODVVZLWKWKH SDUDPHWHUV WKH\ WDNH Method DrawLine() DrawRect()/fillRect() DrawRoundRect()/fillRou ndRect() DrawPolygon/fillPloygon DrawOval()/fillOval() DrawArc() FillArc()

Parameters int x1, int y1, int x2, int y2 int x1, int y1, int width, int height int x1, int y1, int width,int height,int width of an angle, int height of the angle of corner. int x1, int y1, int total no. of points. int x1, int y1, int width, int height int x1, int y1, int width, int height, angle1, angle2 int x1, int y1, int width, int height, angle1, angle2

,QWKHDERYHWDEOHWKH[DQG\FRRUGLQDWHVGHQRWHWKHWRSFRRUGLQDWHVRIWKHGUDZLQJ$SDUW IURPWKDWZHFDQXVHGUDZ6WULQJ PHWKRGWRGLVSOD\VRPHWH[WLQWKHDSSOHWZLQGRZ,WZLOO WDNHWKUHHDUJXPHQWVWKHVWULQJWREHSULQWHGDQGWKHFRRUGLQDWHVRIWKHOHIWPRVWHGJHRIWKH WH[W$QGWKHGUDZ&KDU PHWKRGLVDOVRDYDLODEOH7KLVPHWKRGZLOOWDNHILYHSDUDPHWHUV²DQ DUUD\RIFKDUDFWHUVWREHGLVSOD\HGDQLQWHJHUUHSUHVHQWLQJWKHILUVWFKDUDFWHULQDQDUUD\WRGUDZ DQRWKHULQWHJHUIRUWKHODVWFKDUDFWHUWRGUDZDQGWKH[\FRRUGLQDWHV Clipping

,WLVWKHWHFKQLTXHE\ZKLFKWKHGUDZLQJDUHDFDQEHUHVWULFWHGWRDVPDOOSRUWLRQRIWKHVFUHHQ $FOLSSLQJUHJLRQLVDQDUHDZKHUHWKHGUDZLQJVDUHDOORZHG$Q\GUDZLQJVRXWVLGHWKHFOLSSLQJ UHJLRQ LV FOLSSHG RII DQG QRW GLVSOD\HG )RU WKDW FOLS5HFW  PHWKRG LV XVHG &OLSSLQJ UHJLRQ VKRXOGDOZD\VEHDUHFWDQJOH7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKH*UDSKLFVFODVVPHWKRGVDQG WKHFOLSSLQJWHFKQLTXH Example 7.4 import import public { public {

156

java.awt.*; java.applet.*; class drawings extends Applet void paint(Graphics g)

Comp-U-Learn

Java Applets //g.clipRect(10,10,250,150); g.drawRect(70,50,60,40); g.fillRect(240,50,60,40); g.fillRoundRect(240,120,60,60,10,10); g.drawOval(70,200,60,60); g.fillOval(240,200,60,60); g.drawString("This is the Graphics class!",50,20); } }

$IWHUFRPSLOLQJWKHGUDZLQJVMDYDUXQWKHIROORZLQJGUDZLQJVKWPOILOHXVLQJDSSOHWYLHZHU:H JHWWKHRXWSXWDVVKRZQLQWKHILJXUH

Fig 7.5

Fig. 7.6 Comp-U-Learn

157

Java Programming I

$IWHU UHPRYLQJ WKH FRPPHQW LQ WKH  OLQH  &RPSLOH WKH GUDZLQJVMDYD DJDLQ DQG WKHQ UXQ GUDZLQJVKWPOILOH1RZZHJHWWKHRXWSXWZLWKWKHFOLSSHGUHJLRQDVVKRZQLQWKHDERYHILJXUH

Font Class :HPD\ILQGWKDWWKHGHIDXOWIRQWIRURXUDSSOHWLVQRWYHU\LQWHUHVWLQJ7KHIRQWFODVVSURYLGHV WKHIDFLOLW\WRVHOHFWRXUIRQWIURPDOLVWRIIRQWV7KHVHIRQWVOHDYHWKHSRWHQWLDOWRYDU\IURP V\VWHP WR V\VWHP OHDGLQJ WR SRUWDELOLW\ LVVXHV LQ WKH IXWXUH ,Q DGGLWLRQ WR VHOHFWLQJ EHWZHHQ PXOWLSOHIRQWVZHPD\DOVRVHOHFWDQXPEHURIIRQWVW\OHV6RPHRIWKHIRQWVW\OHVDYDLODEOHDUH %2/' 3/$,1 ,7$/,& 7KHVH DUH LQWHJHU FRQVWDQWV DQG WKH\ FDQ EH DGGHG  OLNH )RQW%2/')RQW,7$/,& 7KHUH DUH VRPH LPSRUWDQW PHWKRGV  DYDLODEOH LQ )RQW FODVV 7KH\ DUH OLVWHG LQ WKH IROORZLQJ WDEOH Method getName() getSize() getStyle() GetFontList()

Use Returns the current Font name. Returns the current Font size. Returns the current Font style Returns the available Fonts.

Note The getFontList() method is available only in the java.awt.Toolkit class.

FontMetrices Class

7KH)RQW0HWULFHVFODVVOHWVXVH[DPLQHWKHYDULRXVFKDUDFWHUPHDVXUHPHQWVIRUDSDUWLFXODUIRQW 7KH JHW)RQW0HWULFHV PHWKRG LQ WKH *UDSKLFV FODVV UHWXUQV DQ LQVWDQFH RI )RQW0HWULFHV IRU D SDUWLFXODUIRQW2QHRIWKHPRVWLPSRUWDQWFRPPRQXVHVRIWKH)RQW0HWULFHVFODVVLVWRJHWWKH ZLGWKRUKHLJKWRIVWULQJFKDUDFWHUV7KHIROORZLQJDUHWKHPHWKRGVDYDLODEOHLQWKLVFODVV Methods StringWidth() charWidth() getHeight()

158

Uses returns the width of the string passed. returns the width of character passed. returns the total height of the Font.

Comp-U-Learn

Java Applets

Color Class ,Q DQ DSSOHW ZH FDQ GUDZ GLDJUDPV DQG GLVSOD\ WH[W LQ GLIIHUHQW FRORUV XVLQJ WKH &RORU FODVV -DYDSURYLGHVGLIIHUHQWPHWKRGVDQGEHKDYLRUVIRUGHDOLQJZLWKFRORUV7KLVFODVVFRPHVXQGHU WKH MDYDDZW SDFNDJH 7KH IRUHJURXQG DQG EDFNJURXQG FRORUV FDQ DOVR EH VHW IRU DQ DSSOHW &RORUVDUHUHSUHVHQWHGE\PHDQVRIFRPELQDWLRQRIUHGEOXHDQGJUHHQ&RORUVQRWDYDLODEOHLQ WKHVWDQGDUGFRORUREMHFWVFDQEHFUHDWHGXVLQJWKHQHZNH\ZRUG7KHIROORZLQJWDEOHOLVWVWKH PHWKRGVDYDLODEOHZLWKLQWKH*UDSKLFVFODVV Methods setColor() setBackground() setForeground() getBackground() getForeground()

Uses sets a color to a specified object. sets the background color of the applet window. sets the foreground color of the applet window. returns background color of the applet window. returns foreground color of the applet window

7KHIROORZLQJH[DPSOHGHPRQVWUDWHVWKHXVHRIWKH*UDSKLFV)RQWDQG&RORUFODVVHV Example 7.5 import java.awt.*; import java.applet.*; public class colorful extends Applet { public void paint(Graphics g) { Font f1= new Font("Arial",Font.BOLD+Font.ITALIC,10); g.setFont(f1); g.setColor(Color.black); g.drawString("Applet For You!",5,35);

Font f2= new Font("Courier",Font.ITALIC,15); g.setFont(f2); g.setColor(Color.red); g.drawString("Applet For You!",5,75);

Font f3= new Font("TimesRoman",Font.BOLD,20); g.setFont(f3); g.setColor(Color.blue);

Comp-U-Learn

159

Java Programming I g.drawString("Applet For You!",5,155);

Font f4= new Font("Helvitica",Font.PLAIN,15); g.setFont(f4); g.setColor(Color.orange); g.drawString("Applet For You!",5,215); } }

:ULWH WKH DERYH FRGH VDYH LW DV FRORUIXOMDYD DQG FRPSLOH LW E\ XVLQJ WKH MDYDF 5XQ WKH IROORZLQJ FRORUIXOKWPO ILOH ZH JHW WKH FRORUIXO DSSOHW ZLQGRZ DV VKRZQ LQ WKH IROORZLQJ ILJXUH

Fig 7.7

Images ,QWKHIROORZLQJVHFWLRQVZHDUHJRLQJWROHDUQDERXWXVLQJELWPDSLPDJHVVXFKDV*,)RU-3(* ILOHV JHWWLQJ WKHP IURP WKH VHUYHU ORDGLQJ WKHP LQWR -DYD GLVSOD\LQJ WKHP LQ WKH DSSOHW DQG FUHDWLQJDQLPDWLRQXVLQJLPDJHV 160

Comp-U-Learn

Java Applets Using images

%DVLFLPDJHKDQGOLQJLQ-DYDLVHDV\7KH ImageFODVVLQWKH java.awtSDFNDJHSURYLGHVDEVWUDFW PHWKRGVWRUHSUHVHQWFRPPRQLPDJHEHKDYLRU6SHFLDOPHWKRGVGHILQHGLQ AppletDQG Graphics JLYH ZH HYHU\WKLQJ RQH QHHGV WR ORDG DQG GLVSOD\ LPDJHV LQ DQ DSSOHW DV HDVLO\ DV GUDZLQJ D UHFWDQJOH Getting Images

7R GLVSOD\ DQ LPDJH LQ RXU DSSOHW ILUVW ZH VKRXOG ORDG WKDW LPDJH RYHU WKH QHW LQWR RXU -DYD SURJUDP,PDJHVDUHVWRUHGDVVHSDUDWHILOHVIURP-DYDFODVVILOHVVRZHKDYHWRILQGWKHP 7KH AppletFODVVSURYLGHVDPHWKRGFDOOHG getImage()ZKLFKORDGVDQLPDJHDQGDXWRPDWLFDOO\ FUHDWHVDQLQVWDQFHRIWKHImageFODVV7RXVHLWDOORQHKDVWRGRLVWRLPSRUWWKH java.awt.Image FODVVLQWRWKH-DYDSURJUDPDQGWKHQJLYHWKH85/RIWKHLPDJH7KHUHDUHWZRZD\VRIGRLQJ WKHODWHUVWHS ♦ The getImage() method with a single argument (an object of type URL) retrieves the image at that URL. ♦ The getImage() method with two arguments: the base URL (also a URL object) and a string representing the path or filename of the actual image (relative to the base). 7KH Applet FODVV SURYLGHV WZR PHWKRGV WKDW ZLOO KHOS ZLWK WKH EDVH 85/ DUJXPHQW WR getImage() ♦ The getDocumentBase() method returns a URL object representing the directory of the HTML file that contains this applet. So, for example, if the HTML file is located at http://www.myserver.com/htmlfiles/javahtml/, getDocumentBase() returns a URL pointing to that path. ♦ The getCodeBase() method returns a string representing the directory in which this applet is contained, which may or may not be the same directory as the HTML file, depending on whether the CODEBASE attribute in <APPLET> is set or not. 7KHXVDJHRIgetDocumentBase()RUgetCodeBase()GHSHQGVRQZKHWKHUWKHLPDJHVDUHUHODWLYHWR WKH+70/ILOHVRUUHODWLYHWR-DYDFODVVILOHV8VLQJHLWKHU getDocumentBase()RU getCodeBase() HQDEOHVPRYLQJWKH+70/ILOHVDQGDSSOHWVDURXQGDQG-DYDFDQVWLOOILQGWKHUHTXLUHGLPDJHV +HUHDUHDIHZH[DPSOHVRIgetImageWRJHWDQLGHD7KLVILUVWFDOOWRgetImage()UHWULHYHVWKHILOH DWWKDWVSHFLILF85/ http://www.server.com/ files/image.gif ,IDQ\SDUWRIWKDW85/FKDQJHVZH KDYHWRUHFRPSLOHWKH-DYDDSSOHWWRWDNHWKHQHZSDWKLQWRDFFRXQW Comp-U-Learn

161

Java Programming I Image img = getImage( new URL("http://www.server.com/files/image.gif"));

,QWKHIROORZLQJIRUPRIgetImageWKHimage.gifILOHLVLQWKHVDPHGLUHFWRU\DVWKH+70/ ILOHVWKDWUHIHUWRWKLVDSSOHW Image img = getImage(getDocumentBase(), "image.gif")

,QWKHIRUPPHQWLRQHGEHORZWKHILOHimage.gifLVLQWKHVDPHGLUHFWRU\DVWKHDSSOHWLWVHOI Image img = getImage(getCodeBase(), "image.gif")

,IRQHKDVORWVRILPDJHILOHVLW VFRPPRQWRSXWWKHPLQWRWKHLURZQVXEGLUHFWRU\7KLVIRUPRI getImage()ORRNVIRUWKHILOH image.gifLQWKHGLUHFWRU\ imagesZKLFKLQWXUQLVLQWKH VDPHGLUHFWRU\DVWKH-DYDDSSOHW Image img = getImage(getCodeBase(), "images/image.gif")

Drawing Images

:KHQZHUHWULHYHDQLPDJHXVLQJ getImage()WKDWPHWKRGDFWXDOO\VSDZQVDWKUHDGWRORDGWKH LPDJHDQGUHWXUQVDOPRVWLPPHGLDWHO\ZLWK WKH ImageREMHFW 7KLVJLYHVWKHLOOXVLRQRIDOPRVW LQVWDQWDQHRXVO\KDYLQJWKHLPDJHWKHUH,WPD\WDNHVRPHWLPHKRZHYHUIRUWKHDFWXDOLPDJHWR GRZQORDGDQGGHFRPSUHVVZKLFKPD\FDXVHLPDJHDSSOHWVWRGUDZZLWKRQO\SDUWLDOLPDJHVRU IRUWKHLPDJHWREHGUDZQRQWKHVFUHHQLQFUHPHQWDOO\DVLWORDGV:HFDQFRQWUROKRZZHZDQW RXUDSSOHWWREHKDYHLQDSDUWLDOLPDJHVLWXDWLRQ IRUH[DPSOHLIZHZDQWLWWRZDLWXQWLOLW VDOO WKHUHEHIRUHGLVSOD\LQJLW E\WDNLQJDGYDQWDJHRIWKHImageObserverLQWHUIDFH 7KHPRVWOLNHO\WKLQJZHZRXOGOLNHWRGRZLWKDQLPDJHLVWRGLVSOD\LWDVZHZRXOGGRIRUD UHFWDQJOHRUDWH[WVWULQJ7KH GraphicsFODVVSURYLGHVWZRPHWKRGVWRGRMXVWWKLVERWKFDOOHG drawImage7KHIROORZLQJH[DPSOHVKRZVWKHXVDJHRI,PDJHFODVV Example 7.6 import java.awt.*; import java.applet.*; public class image_sample extends Applet { Image img; public void init() { img = getImage(getCodeBase(),"mygif.gif"); } public void paint(Graphics g) { g.drawImage(img,10,10,this); } }

162

Comp-U-Learn

Java Applets

The following is the corresponding HTML code for the above program.

In this example, the instance variable img holds the mygif image, which is loaded in the init() method. The paint() method then draws that image on the screen. In figure 7.8 we can see the loaded .gif file.

Fig 7.8 7KH VHFRQG IRUP RI drawImage() WDNHV VL[ DUJXPHQWV WKH LPDJH WR GUDZ WKH x DQG y FRRUGLQDWHV RI WKH WRSOHIW FRUQHU D ZLGWK DQG KHLJKW RI WKH LPDJH ERXQGLQJ ER[ DQG this object,IWKH ZLGWK DQG KHLJKW DUJXPHQWVIRUWKHERXQGLQJER[DUHVPDOOHU RUODUJHUWKDQWKH DFWXDO LPDJH WKH LPDJH LV DXWRPDWLFDOO\ VFDOHG WR ILW %\ XVLQJ WKRVH H[WUD DUJXPHQWV ZH FDQ VTXHH]H DQG H[SDQG LPDJHV LQWR ZKDWHYHU VSDFH ZH QHHG WKHP WR ILW LQ 7KH WZR PHWKRGV GHILQHG IRU WKH Image FODVV FDQ JLYH WKH DFWXDO VL]H RI WKH LPDJH getWidth() DQG getHeight() %RWKWDNHDVLQJOHDUJXPHQWDQLQVWDQFHRIImageObserverZKLFKLVXVHGWRWUDFNWKHORDGLQJRI DQ LPDJH 7KHQ ZH FDQ VFDOH WKH LPDJH WR D VSHFLILF SHUFHQWDJH DQG DYRLG GLVWRUWLRQ LQ HLWKHU GLUHFWLRQZKHQUHILWWLQJLWLQDUHFWDQJOH Image Observers

,PDJH REVHUYHUV DUH XVHG WR ZDWFK WKH SURJUHVV RI KRZ IDU DORQJ DQ LPDJH LV LQ WKH ORDGLQJ SURFHVVDQGWRPDNHGHFLVLRQVZKHQWKHLPDJHLVRQO\IXOO\RUSDUWLDOO\ORDGHG7KHAppletFODVV ZKLFKDQDSSOHWLQKHULWVIURPFRQWDLQVGHIDXOWEHKDYLRUIRULPDJHREVHUYDWLRQ ZKLFKLWLQKHULWV IURP WKH Component VXSHUFODVV  WKDW VKRXOG ZRUN LQ WKH PDMRULW\ RI FDVHV +HQFH WKH this DUJXPHQWVKRXOGEHVXSSOLHGWRdrawImage()getWidth()DQG getHeight()7KHRQO\UHDVRQWRXVH DQDOWHUQDWHDUJXPHQWLQLWVSODFHLVPRUHFRQWURORYHUZKDWDQDSSOHWZLOOGRLQFDVHVZKHUHDQ LPDJHPD\RQO\EHSDUWLDOO\ORDGHGRULIWUDFNLQJORWVRILPDJHVORDGLQJDV\QFKURQRXVO\ Comp-U-Learn

163

Java Programming I Modifying Images

,QDGGLWLRQWRWKHEDVLFVRIKDQGOLQJLPDJHVGHVFULEHGLQWKLVVHFWLRQWKHjava.awt.imageSDFNDJH SURYLGHVPRUHFODVVHVDQGLQWHUIDFHVWKDWHQDEOHPRGLI\LQJLPDJHVDQGWKHLULQWHUQDOFRORUVRU WRFUHDWHELWPDSLPDJHVE\KDQG

Animation using Images $QLPDWLRQLVDWHFKQLTXHE\ZKLFKDQREMHFWLVPRYHGRQWKHVFUHHQ7KHREMHFWWREHPRYHG FDQ EH D VLPSOH GUDZLQJ RU D FRPSOH[ LPDJH ORDGHG IURP DQ LPDJH ILOH $QLPDWLRQ W\SLFDOO\ LQYROYHVIROORZLQJVWHSV ♦ The object is drawn at a location ♦ The object location is changed and object at the old location erased. ♦ The object is repainted at the new location. ,I ZH JR IRU DQ DQLPDWLRQ ORDGLQJ YDULRXV LPDJH ILOHV ZH PXVW PDNH VXUH DOO LPDJHV DUH LQ D VXEGLUHFWRU\ZKHUHRXUFODVVILOHVZLOOEHVWRUHG)RUDQDQLPDWLRQORDGLQJWKHYDULRXVLPDJHV ZHFDQIROORZWKHIROORZLQJVWHSV Organize and Load the Images in Our Applet

7KHEDVLFLGHDKHUHLVWKDWZHKDYHDVHWRILPDJHVDQGZHGLVSOD\WKHPRQHDWDWLPHUDSLGO\VR WKDWWKH\JLYHWKHDSSHDUDQFHRIPRYHPHQW7KHHDVLHVWZD\WRPDQDJHWKLVLQ-DYDLVWRVWRUH WKHLPDJHVLQDQDUUD\RIFODVV ImageDQGWKHQWRKDYH DVSHFLDOYDULDEOHWRNHHSWUDFNRI WKH FXUUHQW LPDJH $V ZH LWHUDWH RYHU WKH VORWV LQ WKH DUUD\ XVLQJ D for ORRS  ZH FDQ FKDQJH WKH DUUD\LQGH[IRUHYHU\LWHUDWLRQ Animate the Images

:LWKWKHLPDJHVORDGHGWKHQH[WVWHSLVWRVWDUWDQLPDWLQJWKHELWVRIWKHDSSOHW,WLVGRQHLQVLGH WKHDSSOHWWKUHDG V run()PHWKRGDQGPRYHWKHPDFURVVWKHVFUHHQ7KHPRYLQJSDUWLVDVLPSOH forORRSEHWZHHQWKH startDQG endDUJXPHQWVVHWWLQJWKH xSRVLWLRQWRWKHFXUUHQWORRSYDOXH 6ZDSSLQJWKHLPDJHVPHDQVPHUHO\WHVWLQJWRVHHZKLFKRQHLVDFWLYHDWDQ\WXUQRIWKHORRSDQG DVVLJQLQJWKHRWKHURQHWRWKHFXUUHQWLPDJH)LQDOO\DWHDFKQHZIUDPH\RX OOFDOOrepaint()DQG sleep()IRUDELWWRSDXVHWKHDQLPDWLRQ$FWXDOO\JLYHQWKDWGXULQJWKLVDQLPDWLRQWKHUHZLOOEHD ORWRISDXVLQJRIYDULRXVLQWHUYDOVLWPDNHVVHQVHWRFUHDWHDXWLOLW\PHWKRGWKDWGRHVMXVWWKDW SDXVHIRUDJLYHQDPRXQWRIWLPH7KHpause()PHWKRGWKHUHIRUHWDNHVRQHDUJXPHQW DQXPEHU RIPLOOLVHFRQGV  7KHpaint()PHWKRGLVWULYLDOO\VLPSOHDOOit does is SDLQWLQJWKHFXUUHQWLPDJHDWWKHFXUUHQWxDQG ySRVLWLRQV$OOWKDWLQIRUPDWLRQLVVWRUHGLQLQVWDQFHYDULDEOHV+RZHYHUZHGRZDQWWRPDNH 164

Comp-U-Learn

Java Applets

VXUHWKDWWKHLPDJHVDFWXDOO\H[LVWEHIRUHZHGUDZWKHP WKHLPDJHVPLJKWEHLQWKHSURFHVVRI ORDGLQJ  7KHUH VRQHPRUHWKLQJOHIWWRGRWRILQLVKWKHDSSOHW$OOWKHVHLPDJHVIRUWKHDQLPDWLRQKDYH ZKLWH EDFNJURXQGV 'UDZLQJ WKRVH LPDJHV RQ WKH GHIDXOW DSSOHW EDFNJURXQG D PHGLXP JUD\ PHDQVDQ XQVLJKWO\ ZKLWH ER[ DURXQG HDFK LPDJH 7R JHW DURXQG WKH SUREOHP PHUHO\ VHW WKH DSSOHW VEDFNJURXQGWRwhiteDWWKHVWDUWRIWKHrun()PHWKRG 7KHIROORZLQJH[DPSOHH[SODLQVWKHFRQFHSWVDQGXVDJHRIDQLPDWLRQZLWKPXOWLWKUHDGLQJ Example 7.7 import java.awt.Graphics; import java.awt.Image; import java.awt.Color; public class animation extends java.applet.Applet implements Runnable { Image img; Thread runner; int xpos=0; int ypos=50; public void init() { img=getImage(getCodeBase(),"T1.GIF"); } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void run() { // initialize while(true) { for(xpos=0; xpos< getSize().width; xpos+=5) { repaint();

Comp-U-Learn

165

Java Programming I try{ runner.sleep(100); } catch(InterruptedException e){} } } } public void paint(Graphics g) { g.drawImage(img, xpos+10, ypos,this); } }

$IWHU FRPSLOLQJ WKLV DQLPDWLRQMDYD UXQ WKH IROORZLQJ DQLPDWLRQKWPO XVLQJ DSSOHWYLHZHU DQG VHHWKHDSSOHWZLQGRZ

Using Sound

-DYDKDVEXLOWLQVXSSRUWIRUSOD\LQJVRXQGFOLSSLQJVLQFRQMXQFWLRQZLWKUXQQLQJDQLPDWLRQRU IRUVRXQGVRQWKHLU RZQ ,Q IDFW VXSSRUW IRU VRXQG OLNH VXSSRUW IRU LPDJHV LV EXLOW LQWR WKH AppletDQGawtFODVVHVVRXVLQJVRXQGLQRXU-DYDDSSOHWVLVDVHDV\DVORDGLQJDQGXVLQJLPDJHV &XUUHQWO\WKHRQO\VRXQGIRUPDWWKDW-DYDVXSSRUWVLV6XQ V$8IRUPDWVRPHWLPHVFDOOHG—ODZ IRUPDW$8ILOHVWHQGWREHVPDOOHUWKDQVRXQGILOHVLQRWKHUIRUPDWVEXWWKHVRXQGTXDOLW\LV QRWYHU\JRRG,IZH UHHVSHFLDOO\FRQFHUQHGZLWKVRXQGTXDOLW\ZHPD\ZDQWRXUVRXQGFOLSVWR EHUHIHUHQFHVLQWKHWUDGLWLRQDO+70/ZD\ DVOLQNVWRH[WHUQDOILOHV UDWKHUWKDQLQFOXGHGLQD -DYDDSSOHW 7KHVLPSOHVWZD\WRUHWULHYHDQGSOD\DVRXQGLVWKURXJKWKH play()PHWKRGSDUWRIWKH Applet FODVVDQGWKHUHIRUHDYDLODEOHLQDSSOHWV7KHplay()PHWKRGLVVLPLODUWRWKHgetImage()PHWKRGLQ WKDWLWWDNHVRQHRIWZRIRUPV ♦ play() with one argument, a URL object, loads and plays the given audio clip at that URL. ♦ play() with two arguments, one a base URL and one a pathname, loads and plays that audio file. The first argument can most usefully be either a call to getDocumentBase() or getCodeBase(). Summary In this first session of our applet programming, we learnt to write applets using a simple example. We understood the relation between Java applet and HTML. We came to know that an applet consists of certain basic methods like init(), start(), stop() and destroy(). Then we moved on to learn Graphics, Font and Color classes. Finally, we created animations using images. 166

Comp-U-Learn

Java Applets

Going Over it Again I. Fill in the Blanks

 7KHBBBBBBBBBBBBBBWDJLVXVHGIRUSDVVLQJSDUDPHWHUWRDQDSSOHW  7KHBBBBBBBBBBBPHWKRGLVXVHGWRFOHDQXSWKHPHPRU\  ,WLVSRVVLEOHWRXSGDWHDSDUWRIWKHVFUHHQXVLQJBBBBBBBBBPHWKRG  BBBBBBBBBBPHWKRGLVXVHGWRPRYHWKHLPDJHLQWKHVFUHHQ  7KHJHW)RQW/LVW PHWKRGLVLQWKHBBBBBBBBBBBBBFODVV II. State True or False

 7KH3$5$0!WDJFRQWDLQVRQO\RQHDWWULEXWH  $SSOHWVFDQEHUXQXVLQJ-DYDLQWHUSUHWHU  $OOWKHGUDZLQJVPDGHRXWVLGHWKHLPDJHVXUIDFHDUHFOLSSHG  7KHVOHHS PHWKRGLQWKH7KUHDGFODVVGHVWUR\VWKHWKUHDG  7KHJHW)RQW0HWULFHVFODVVLVXVHGWRJHWWKHLQIRUPDWLRQRQDVSHFLILFIRQW III. One line Answers

 /LVWRXWWKHGLIIHUHQFHVEHWZHHQWKH$SSOLFDWLRQDQG$SSOHW  :KDWDUHWKHDWWULEXWHVLQWKH$33/(7!WDJ"  ([SODLQDSSOHW·VEDVLFPHWKRGV  :KDWLVDQ$QLPDWLRQ"  :KDWLVDQLPDJHREVHUYHU"  :KDWDUHWKHPHWKRGVDYDLODEOHLQWKH*UDSKLFVFODVV" IV. Define the Following

    

3$5$0!WDJ UXQ PHWKRG UHSDLQW PHWKRG &OLSSLQJ GUDZ&KDU PHWKRG Comp-U-Learn

167

Session 8

Abstract Windowing Toolkit (AWT)

On Completion of this Session We will be able to understand...

) AWT ) AWT Architecture ) AWT components ) AWT Canvas

In This Session...



An AWT Overview



AWT Architecture



Basic UI Components



Buttons



Checkboxes



Radio Buttons



Choices



TextFields



TextAreas



Lists



Scrollbars and Sliders



Canvases

Abstract Windowing Toolkit (AWT)

An AWT Overview $SSOHWV DQG DSSOLFDWLRQV FRPPRQO\ SUHVHQW LQIRUPDWLRQ WR WKH XVHU DQG LQYLWH WKH XVHU·V LQWHUDFWLRQ XVLQJ *8, WRROV 7KLV $EVWUDFW :LQGRZLQJ 7RRONLW $:7  LV SDUW RI WKH -DYD SURJUDPPLQJHQYLURQPHQWWKDWFRQWDLQVDFRPSOHWHVHWRIFODVVHVDQGFRPSRQHQWVIRUFUHDWLQJ *8,EDVHGSURJUDPV 7KH EDVLF LGHD EHKLQG $:7 LV WKDW D JUDSKLFDO -DYD SURJUDP LV D VHW RI QHVWHG FRPSRQHQWV VWDUWLQJ IURP WKH RXWHUPRVW ZLQGRZ DOO WKH ZD\ GRZQ WR WKH VPDOOHVW 8, FRPSRQHQW &RPSRQHQWVFDQLQFOXGHWKLQJVZHFDQDFWXDOO\VHHRQWKHVFUHHQVXFKDVZLQGRZVPHQXEDUV EXWWRQVDQGWH[WILHOGVDQGWKH\FDQDOVRLQFOXGHFRQWDLQHUVZKLFKLQ WXUQFDQFRQWDLQRWKHU FRPSRQHQWV

AWT Architecture 7KH KLHUDUFK\ RI FRPSRQHQWV GHWHUPLQH WKH DUUDQJHPHQW RI LWHPV RQ WKH VFUHHQ DQG LQVLGH RWKHU LWHPV WKH RUGHU LQ ZKLFK WKH\ DUH SDLQWHG DQG KRZ HYHQWV DUH SDVVHG IURP RQH FRPSRQHQWWRDQRWKHU7KHVHDUHWKHPDMRUFRPSRQHQWVRQHFDQZRUNZLWKLQWKH$:7 Containers &RQWDLQHUV DUH JHQHULF $:7 FRPSRQHQWV WKDW FRQWDLQ RWKHU FRPSRQHQWV LQFOXGLQJ RWKHU FRQWDLQHUV7KHPRVWFRPPRQIRUPRIFRQWDLQHULVWKHSDQHOZKLFKUHSUHVHQWVDFRQWDLQHUWKDW FDQEHGLVSOD\HGRQVFUHHQ$SSOHWVDUHDIRUPRISDQHO LQIDFWWKH AppletFODVVLVDVXEFODVV RIWKHPanelFODVV 7KHFRQWDLQHULVWKHDEVWUDFWEDVHFODVVWKDWIRUPVWKHURRWRIWKHFRQWDLQHU KLHUDUFK\ :H FDQ DGG FRPSRQHQWV WR WKH FRQWDLQHU ZLWK WKH DGG  PHWKRG 7R UHPRYH D FRPSRQHQWODWHUUHPRYH PHWKRGLVXVHG Canvases $FDQYDVLVDVLPSOHGUDZLQJVXUIDFHWKDWUHSUHVHQWVDUHFWDQJXODUDUHDRIWKHVFUHHQ,WSURYLGHV DQDUHDWRGUDZXSRQDIUDPHZRUNIRUKDQGOLQJLQSXWHYHQWV$OWKRXJKRQHFDQGUDZRQSDQHOV DV ZH YH EHHQ GRLQJ DOO DORQJ  FDQYDVHV DUH JRRG IRU SDLQWLQJ LPDJHV RU SHUIRUPLQJ RWKHU JUDSKLFRSHUDWLRQV&DQYDVFDQEHXVHGWRFUHDWHFXVWRPFRPSRQHQWV UI components 7KHVH LQFOXGH EXWWRQV OLVWV VLPSOH SRSXS PHQXV FKHFN ER[HV WHVW ILHOGV DQG RWKHU W\SLFDO HOHPHQWVRIDXVHULQWHUIDFH

Comp-U-Learn

171

Java Programming I

Window construction components 7KHVH LQFOXGH ZLQGRZV IUDPHV PHQX EDUV DQG GLDORJ ER[HV 7KH\ DUH OLVWHG VHSDUDWHO\ IURP WKHRWKHU8,FRPSRQHQWVEHFDXVHWKH\DUHXVHGOHVVRIWHQ²SDUWLFXODUO\LQDSSOHWV,QDSSOHWV WKH EURZVHU SURYLGHV PDLQ ZLQGRZ DQG PHQX EDU VR ZH GRQ W KDYH WR XVH WKHVH 7KH DSSOHW PD\FUHDWHDQHZZLQGRZKRZHYHURUZHPD\ZDQWWRZULWHRXURZQ-DYDDSSOLFDWLRQWKDWXVHV WKHVHFRPSRQHQWV 7KHIROORZLQJILJXUHVKRZVDSDUWLDO$:7FODVVKLHUDUFK\

Fig 8.1 $:7LQFOXGHVDVHWRIOD\RXWPDQDJHUV/D\RXWPDQDJHUVGHWHUPLQHKRZYDULRXVFRPSRQHQWV DUH DUUDQJHG ZKHQ WKH\ DUH GLVSOD\HG RQVFUHHQ DQG WKH\ DUH RI YDULRXV VL]HV UHODWLYH RI HDFK RWKHU 6LQFH -DYD DSSOHWV DQG DSSOLFDWLRQV WKDW XVH $:7 FDQ UXQ RQ GLIIHUHQW V\VWHPV ZLWK GLIIHUHQW GLVSOD\V GLIIHUHQW IRQWV DQG GLIIHUHQW UHVROXWLRQV ZH FDQQRW MXVW VWLFN D SDUWLFXODU FRPSRQHQWDWDSDUWLFXODUVSRWRQWKHZLQGRZ/D\RXWPDQDJHU·VKHOSWRFUHDWH8,OD\RXWVWKDW DUHG\QDPLFDOO\DUUDQJHGDQGFDQEHGLVSOD\HGDQ\ZKHUHWKHDSSOHWRUDSSOLFDWLRQPLJKWUXQ

Basic UI Components 7KH VLPSOHVW IRUP RI $:7 FRPSRQHQW LV WKH EDVLF 8, FRPSRQHQW 6LQFH DQ DSSOHW LV D FRQWDLQHU ZH FDQ SXW RWKHU $:7 FRPSRQHQWV ² VXFK DV 8, FRPSRQHQWV RU RWKHU FRQWDLQHUV LQWRLW%DVLF8,FRPSRQHQWVLQFOXGHODEHOVEXWWRQVFKHFNER[HVFKRLFHPHQXVDQGWH[WILHOGV :HILUVWFUHDWHWKHFRPSRQHQWDQGWKHQDGGLWWRWKHSDQHOWKDWKROGVLWDWWKHSRLQWZKHUHLWLV GLVSOD\HGRQWKHVFUHHQ7RDGGDFRPSRQHQWWRDSDQHO VXFKDVDQDSSOHWIRUH[DPSOH XVH WKHadd()PHWKRG

172

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

Labels $ ODEHO LV DQ XQHGLWDEOH WH[W VWULQJ WKDW DFWV DV D GHVFULSWLRQ IRU RWKHU $:7 FRPSRQHQWV 7R FUHDWHDODEHOXVHRQHRIWKHIROORZLQJFRQVWUXFWRUV ♦ Label() creates an empty label, with its text aligned left. ♦ Label(String) creates a label with the given text string, also aligned left. ♦ Label(String, int) creates a label with the given text string and the given alignment. The available alignment numbers are stored in class variables in Label, making them easier to remember: Label.RIGHT, Label.LEFT, and Label.CENTER. ♦ :HFDQFKDQJHWKHODEHO VIRQWZLWKWKH setFont()PHWKRGHLWKHUFDOOHGRQWKHODEHOLWVHOIWR FKDQJHWKHLQGLYLGXDOODEHORURQWKHHQFORVLQJFRPSRQHQWWRFKDQJHDOOWKHODEHOV Label Methods 2QFHZHKDYHD LabelREMHFWZHFDQXVHPHWKRGVGHILQHGLQWKH LabelFODVVWRJHWDQGVHW WKHYDOXHVRIWKHWH[WDVVKRZQLQ7DEOHEHORZ Method GetText() setText(String) GetAlignment() SetAlignment(int)

Action Returns a string containing this label's text. Changes the text of this label . 5HWXUQVDQLQWHJHUUHSUHVHQWLQJWKHDOLJQPHQWRIWKLVODEHO  LV/DEHO/()7LV/DEHO&(17(5LV/DEHO5,*+7 &KDQJHVWKHDOLJQPHQWRIWKLVODEHOWRWKHJLYHQLQWHJHUXVH WKHFODVVYDULDEOHVOLVWHGLQWKHJHW$OLJQPHQW 

7KH IROORZLQJ H[DPSOH  GHPRQVWUDWHV WKH XVH RI ODEHO FRPSRQHQW ,Q WKLV H[DPSOH ZH FDQ VHHWKHILUVWODEHOLVFUHDWHGXVLQJWKHILUVWW\SHRIFRQVWUXFWRU7KHQRQO\WKHODEHOWH[WZLOOEH DVVLJQHG XVLQJ WKH VHW7H[W  PHWKRG 7KH VHFRQG ODEHO LV FUHDWHG XVLQJ WKH WKLUG W\SH FRQVWUXFWRU:HFDQDOVRFUHDWHDQ\FRPSRQHQWOLNHODEHOLQDVLQJOHOLQH Example 8.1 import java.awt.*; import java.applet.*; public class labeltest extends Applet { public void init() { Font f=new Font("Helvetica", Font.BOLD, 14); setFont(f); Label l1=new Label(); add(l1);

Comp-U-Learn

173

Java Programming I l1.setText("Hai! I am Label1"); Label l2= new Label("Hai! I am Label2", Label.CENTER); add(l2); add(new Label("Hai! I am Label3", Label.RIGHT)); } }

$IWHUFRPSLOLQJWKHODEHOWHVWMDYDILOHUXQWKHIROORZLQJODEHOWHVWKWPOILOHXVLQJWKHDSSOHWYLHZHU 7KHILJXUHVKRZVWKHRXWSXWRIWKHDERYHSURJUDP

Fig 8.2

Buttons $ EXWWRQ LV D 8, FRPSRQHQW WKDW ZKHQ SUHVVHG VHOHFWHG  ZLWK WKH PRXVH WULJJHUV VRPH DFWLRQ7RFUHDWHDEXWWRQXVHRQHRIWKHIROORZLQJFRQVWUXFWRUV Button() creates an empty button with no label. Button(String) creates a button with the given string as a label.

2QFH ZH KDYH D Button REMHFW ZH FDQ JHW WKH YDOXH RI WKH EXWWRQ V ODEHO E\ XVLQJ WKH getLabel()PHWKRGDQGVHWWKHODEHOXVLQJWKH setLabel(String)PHWKRG7KHIROORZLQJ H[DPSOHLOOXVWUDWHVWKHFUHDWLRQRIWKHEXWWRQVXVLQJGLIIHUHQWFRQVWUXFWRUV Example 8.2 import java.awt.*; public class buttontest extends java.applet.Applet { public void init() { Button b1=new Button(); add(b1);

174

Comp-U-Learn

Abstract Windowing Toolkit (AWT) b1.setLabel("Rewind"); Button b2= new Button("Play"); add(b2); add(new Button("Fast Forward")); add(new Button("Stop")); } }

$IWHU FRPSLOLQJ WKH DERYH EXWWRQWHVWMDYD ILOH UXQ WKH EHORZ EXWWRQWHVWKWPO ILOH XVLQJ WKH DSSOHWYLHZHU7KHRXWSXWLVDVVKRZQLQWKHILJXUH

Fig 8.3

Check Boxes &KHFN ER[HV DUH 8, FRPSRQHQWV WKDW FDQ EH VHOHFWHG RU GHVHOHFWHG FKHFNHG RU XQFKHFNHG  WR SURYLGHRSWLRQV&KHFNER[HVFDQEHXVHGLQWZRZD\V ♦ Nonexclusive: Given a series of check boxes, any of them can be selected at a time. ♦ Exclusive: Given a series, only one check box can be selected at a time. 7KHODWWHUNLQGRIFKHFNER[HVDUHFDOOHGUDGLREXWWRQVRUFKHFNER[JURXSV1RQH[FOXVLYHFKHFN ER[HVFDQEHFUHDWHGE\XVLQJWKH CheckboxFODVV:HFDQFUHDWHDFKHFNER[XVLQJRQHRIWKH IROORZLQJFRQVWUXFWRUV ♦ Checkbox() creates an empty check box, unselected. ♦ Checkbox(String) creates a check box with the given string as a label.

Comp-U-Learn

175

Java Programming I

♦ Checkbox(String, null, boolean) creates a check box that is either selected or deselected based on whether the boolean argument is true or false, respectively. (The null is used as a placeholder for a group argument. Only radio buttons have groups) Check box methods Method *HW/DEHO 6HW/DEHO 6WULQJ *HW6WDWH 6HW6WDWH ERROHDQ

Action Returns a string containing the check box's label. Changes the text of the check box's label. Returns true or false, based on whether the check box is selected or not. Changes the check box's state to selected (true) or unselected (false).

Radio Buttons 5DGLREXWWRQVKDYHWKHVDPHDSSHDUDQFHDVFKHFNER[HVEXWRQO\RQHLQDVHULHVFDQEHVHOHFWHG DWDWLPH7RFUHDWHDVHULHVRIUDGLREXWWRQVILUVWFUHDWHDQLQVWDQFHRICheckboxGroup CheckboxGroup cbg = new CheckboxGroup();

7KHQFUHDWHDQGDGGWKHLQGLYLGXDOFKHFNER[HVXVLQJWKHFRQVWUXFWRUZLWKWKUHHDUJXPHQWV WKH ILUVW LV WKH ODEHO WKH VHFRQG LV WKH JURXS DQG WKH WKLUG LV ZKHWKHU WKH FKHFN ER[ LV VHOHFWHG  1RWHWKDWEHFDXVHUDGLREXWWRQVE\GHILQLWLRQKDYHRQO\RQHLQWKHJURXSVHOHFWHGDWDWLPHWKH ODVWtrueWREHDGGHGZLOOEHWKHRQHVHOHFWHGE\GHIDXOW

add(new Checkbox("Yes", cbg, true); add(new Checkbox("No", cbg, false);

$OOWKHFKHFNER[PHWKRGVFDQEHXVHGZLWKWKHFKHFNER[HVLQWKHJURXS,QDGGLWLRQZHFDQ XVH WKH getCheckboxGroup() DQG setCheckboxGroup() PHWKRGV GHILQHG LQ WKH Checkbox() FODVV  WR DFFHVV DQG FKDQJH WKH JURXS RI DQ\ JLYHQ FKHFN ER[  )LQDOO\ WKH getCurrent() DQG setCurrent(Checkbox) PHWKRGV GHILQHG LQ CheckboxGroup FDQ EHXVHGWRJHWRUVHWWKHFXUUHQWO\VHOHFWHGFKHFNER[

176

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

7KHIROORZLQJFKHFNWHVWMDYDSURJUDPGHPRQVWUDWHVWKHFUHDWLRQRIERWKFKHFNER[HVDQGUDGLR EXWWRQV Example 8.3 import java.awt.*; import java.applet.*; public class checktest extends Applet { public void init() { Checkbox cb1=new Checkbox("Shoes"); add(cb1); add(new Checkbox("Socks")); add(new Checkbox("Pants")); add(new Checkbox("Underwear", null, true)); add(new Checkbox("Shirt")); CheckboxGroup cbg1=new CheckboxGroup(); add(new Checkbox("CoolDrinks",cbg1,false)); add(new Checkbox("FruitJuices",cbg1,false)); add(new Checkbox("IceCreams",cbg1,true)); } }

&RPSLOHWKLV-DYDILOHDQGUXQWKHIROORZLQJFKHFNWHVWKWPOILOH7KHRXWSXWLVDVVKRZQLQWKH ILJXUH

Fig 8.4

Comp-U-Learn

177

Java Programming I

Choices &KRLFHPHQXVDUHSRSXSPHQXVRILWHPVIURPZKLFKZHFDQFKRRVHRQHLWHP7RFUHDWHDFKRLFH PHQX FUHDWH DQ LQVWDQFH RI WKH Choice FODVV DQG WKHQ XVH WKH addItem() PHWKRG WR DGG LQGLYLGXDO LWHPV WR LW LQ WKH RUGHU LQ ZKLFK WKH\ VKRXOG DSSHDU )LQDOO\ DGG WKH HQWLUH FKRLFH PHQXWRWKHSDQHOLQWKHXVXDOZD\ &KRLFHV DUH XVHIXO ZKHQ ZH QHHG WR GLVSOD\ D QXPEHU RI DOWHUQDWLYHV LQ D OLPLWHG DPRXQW RI VSDFHDQGWKHXVHUGRHVQRWQHHGWRVHHDOOWKHDOWHUQDWLYHVDOOWKHWLPH$QRWKHUQDPHIRUWKLV 8,FRPSRQHQWLVSRSXSOLVWRUSXOOGRZQPHQX (YHQDIWHUWKHFKRLFHPHQXLVDGGHGWRDSDQHOZHFDQFRQWLQXHWRDGGLWHPVWRWKDWPHQXZLWK WKHaddItem()PHWKRG Choice methods Method JHW,WHP LQW FRXQW,WHPV JHW6HOHFWHG,QGH[ JHW6HOHFWHG,WHP VHOHFW LQW VHOHFW 6WULQJ

Action Returns the string item at the given position (items inside a choice begin at 0, just like arrays). Returns the number of items in the menu. Returns the index position of the item that's selected. Returns the currently selected item as a string. Selects the item at the given position. Selects the item with the given string.

7KHIROORZLQJH[DPSOHJLYHVDQLGHDRIFUHDWLQJDQSRSOLVWXVLQJWKHFKRLFHFODVV Example 8.4 import java.awt.*; import java.applet.*; public class choicetest extends Applet { public void init() { Choice c = new Choice(); c.addItem("Apples"); c.addItem("Oranges"); c.addItem("Strawberries"); c.addItem("Blueberries"); c.addItem("Bananas"); add(c); } }

178

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

$IWHUFRPSLOLQJWKHFKRLFHWHVWMDYDUXQWKHFKRLFHKWPOFRGHDQGVHHWKHRXWSXW We can get the output as shown in the following figure 8.5.

Fig 8.5

Text Fields 7H[W ILHOGV SURYLGH DQ DUHD ZKHUH ZH FDQ HQWHU DQG HGLW D VLQJOH OLQH RI WH[W 7R FUHDWH D WH[W ILHOGXVHRQHRIWKHIROORZLQJFRQVWUXFWRUV ♦ TextField() creates an empty TextField that is 0 characters wide (it will be resized by the current layout manager). ♦ TextField(int) creates an empty text field. The integer argument indicates the minimum number of characters to display. ♦ TextField(String) creates a text field initialized with the given string. The field will be automatically resized by the current layout manager. ♦ TextField(String, int) creates a text field some number of characters wide (the integer argument) containing the given string. If the string is longer than the width, we can select and drag portions of the text within the field, and the box will scroll left or right. )RUH[DPSOHWKHIROORZLQJOLQHFUHDWHVDWH[WILHOGFKDUDFWHUVZLGHZLWKWKHVWULQJ "Enter Your Name"DVLWVLQLWLDOFRQWHQWV

Comp-U-Learn

179

Java Programming I TextField tf = new TextField("Enter Your Name", 30); add(tf);

7H[WILHOGVLQFOXGHRQO\WKHHGLWDEOHILHOGLWVHOI:H XVXDOO\ QHHG WR LQFOXGH D ODEHO ZLWK D WH[W ILHOGWRLQGLFDWHZKDWEHORQJVLQWKDWWH[WILHOG :H FDQ DOVR FUHDWH D WH[W ILHOG WKDW REVFXUHV WKH FKDUDFWHUV W\SHG LQWR LWIRU H[DPSOH IRU SDVVZRUG ILHOGV 7R GR WKLV ILUVW FUHDWH WKH WH[W ILHOG LWVHOI DQG WKHQ XVH WKH setEchoCharacter()PHWKRGWRVHWWKHFKDUDFWHUWKDWLVHFKRHGRQWKHVFUHHQ+HUHLVDQ H[DPSOHWRLOOXVWUDWHWKH7H[W)LHOGFRPSRQHQW Example 8.5 import java.awt.*; import java.applet.*; public class texttest extends Applet { public void init() { add(new Label("Enter your name:")); add(new TextField("your name here",25)); add(new Label("Enter your phone number:")); add(new TextField(25)); add(new Label("Enter your password:")); TextField t = new TextField(15); t.setEchoCharacter('*'); add(t); } }

7KHIROORZLQJFRGHLVWKHFRUUHVSRQGLQJ+70/FRGHIRUWKHDERYHH[DPSOH:KHQZHUXQWKLV +70/ILOHWKHRXWSXWLVDVVKRZQLQWKHIROORZLQJILJXUH

Fig 8.6

180

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

Text field methods 7KHIROORZLQJWDEOHOLVWVWKHPHWKRGVZKLFKDUHDYDLODEOHLQWKLV7H[W)LHOGFRPSRQHQW Method *HW7H[W 6HW7H[W 6WULQJ *HW&ROXPQV 6HOHFW LQWLQW 6HOHFW$OO ,V(GLWDEOH 6HW(GLWDEOH ERROHDQ *HW(FKR&KDU (FKR&KDU,V6HW

Action Returns the text this text field contains (as a string). Puts the given text string into the field. Returns the width of this text field. Selects the text between the two integer positions (positions start from 0). Selects all the text in the field. Returns true or false based on whether the text is editable. true (the default) enables text to be edited; false freezes the text. Returns the character used for masking input. Returns true or false based on whether the field has a masking character.

Text Areas 7H[WDUHDLVDPXWLOLQHWH[WHGLWLQJFRPSRQHQW%XWLQWKH7H[W)LHOGFRPSRQHQWRQHFDQHQWHU WKH WH[W LQ D VLQJOH OLQH RQO\ /LNH WKH 7H[W)LHOG FODVV WKH 7H[W$UHD FODVV DOVR RIIHUV IRXU FRQVWUXFWRUV ♦ TextArea() creates an empty TextArea that is 0 characters wide (it will be resized by the current layout manager). ♦ TextArea(int, int) creates an empty textarea. The integer arguments indicates the number of: ♦ rows and columns in the text area respectively. ♦ TextArea(String) creates a text area initialized with the given string. The area will be automatically resized by the current layout manager. ♦ TextArea(String, int, int) creates a text area some number of characters wide (the integer argument) containing the given string. If the string is longer than the width specified, we can select and drag portions of the text within the field, and the box will scroll left or right. Comp-U-Learn

181

Java Programming I

/LNHWKH7H[W)LHOGWKH7H[W$UHDVXSSOLHVWKHVRPHPHWKRGV7KHVHDUHOLVWHGLQWKHIROORZLQJ WDEOH Method getText() setText(String) getRows() getColumns() selectAll() setEditable(boolean) insertText() replaceText()

Action Returns the text that text area contains (as a string). Puts the given text string into the area. Returns the number of rows in the area. Returns the number of columns in the area. Selects all the text in the area. true (the default) enables text to be edited; false freezes the text. Inserts the specified text at the specified position. Replaces text from the indicated start position to the end position.

+HUHLVDQH[DPSOHWRLOOXVWUDWHWKHXVDJHRIWH[WDUHDDORQJZLWKWKHSUHYLRXVH[DPSOH Example 8.6: import java.awt.*; import java.applet.*; public class areatest extends Applet { public void init() { add(new Label("Enter your name:")); add(new TextField("your name here",25)); add(new Label("Enter your phone number:")); add(new TextField(25)); add(new Label("Enter your password:")); TextField t = new TextField(15); t.setEchoCharacter('*'); add(t); TextArea ta = new TextArea(5,20); add(ta); ta.setEditable(true); } }

$IWHU FRPSLOLQJ WKLV DUHDWHVWMDYD ILOH UXQ WKH DUHDWHVWKWPO ILOH FRQWDLQLQJ WKH IROORZLQJ FRGH DQGZHFDQJHWWKHRXWSXWDVVKRZQLQILJXUH

182

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

Fig 8.7

Lists $ OLVW LV D FRPSRQHQW WKDW DOORZV XV WR FKRRVH RQH RU PXOWLSOH LWHPV 6WULQJV  IURP D OLVW RI LWHPV7KHOLVWPD\EHVFUROODEOH/LVWVFDQDOORZHLWKHUPXOWLSOHVHOHFWLRQVRUMXVWRQHVHOHFWLRQ DWDWLPH2WKHUFRPSRQHQWVWKDWDOORZXVHUVWRFKRRVHIURPPXOWLSOHRSWLRQVDUHFKHFNER[HV FKRLFHVDQGPHQXV7KHIROORZLQJDUHWKHW\SHVRIFRQVWUXFWRUVDYDLODEOHWRFUHDWHDOLVW ♦ List() creates a list. It acts as a default constructor. ♦ List(int, boolean.) creates a list with rows, visible rows, and given multiple selection behavior. The second parameter when given true, will allow multiple selection in the list. Lists methods 7KHIROORZLQJWDEOHOLVWVYDULRXVPHWKRGVDYDLODEOHLQWKHOLVWFODVV Method AddItem() GetItem() Clear() DelItem() DelItems() CountItems() GetSelectedIndex() GetSelectedItem() Select() Deselect()

Action Adds the specified item at the specified index. Returns the string in the specified index. Deletes all the items in the list. Deletes the item specified by the index. Deletes more than one items. Returns the number of items in the list. Returns the index of the selected item. Returns the selected string. Selects a item by an index . Deselects the items by an index value.

Comp-U-Learn

183

Java Programming I

Method IsSelected() GetRows() ReplaceItem()

GetVisibleIndex()

Action Return an boolean value if the specified item is selected. Returns the number of rows visible in the list. Replaces the item at the specified index AllowsMultipleSelections Returns boolean value whether the list allows multiple selection or not Gets the index of the item that was last made visible

7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKHOLVWFRPSRQHQWDQGLWVFRQVWUXFWRUV Example 8.7 import java.awt.*; import java.applet.*; public class listtest extends Applet { public void init() { // list allows one selection at a time List l1 = new List(); l1.addItem("Sony"); l1.addItem("Thomson"); l1.addItem("Panasonic"); l1.addItem("Samsung"); l1.addItem("Phillips"); //list allows multiple selection List l2 = new List(4,true); l2.addItem("Television"); l2.addItem("Video Player"); l2.addItem("Computer"); l2.addItem("Air Cooler"); l2.addItem("Washing Machine"); add(l1); add(l2); } }

$IWHUFRPSLOLQJWKLV-DYDILOHUXQWKHIROORZLQJ+70/FRGHXVLQJDSSOHWYLHZHUDQGWKHRXWSXW DSSHDUVDVVKRZQLQWKHILJXUH7KHILUVWOLVWDOORZVVHOHFWLQJRQO\RQHDWDWLPH%XWLQWKH QH[WRQHZHFDQVHOHFWDQ\QXPEHURILWHPVDWDWLPH

184

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

Fig 8.8

Scrollbars and Sliders 6FUROOEDUVDUHXVHGWRVHOHFWDYDOXHEHWZHHQDPD[LPXPDQGDPLQLPXPYDOXH7RFKDQJHWKH FXUUHQWYDOXHRIWKDWVFUROOEDUZHFDQXVHWKUHHGLIIHUHQWSDUWVRIWKHVFUROOEDU ♦ Arrows on either end, which increments or decrements the values by some small unit (1 by default). ♦ A range in the middle, which increments or decrements the value by a larger amount (10 by default). ♦ A box in the middle, often called an elevator or thumb, whose position shows where in the range of values the current value is located. Moving this box with the mouse causes an absolute change in the value, based on the position of the box within the scrollbar. 7RFUHDWHDVFUROOEDUZHXVHRQHRIWKUHHFRQVWUXFWRUV ♦ Scrollbar() creates a scrollbar with its initial maximum and minimum values both 0, in a vertical orientation. ♦ Scrollbar(int) creates a scrollbar with both its initial maximum and minimum values both 0. The argument represents an orientation, for which we can use the class variables Scrollbar.HORIZONTAL and Scrollbar.VERTICAL. ♦ Scrollbar(int, int, int, int, int) creates a scrollbar with the following arguments (each one is an integer, and they must be presented in this order): 7KH ILUVW DUJXPHQW LV WKH RULHQWDWLRQ RI WKH VFUROOEDU Scrollbar.HORIZONTAL DQG Vcrollbar. VERTICAL. 7KH VHFRQG DUJXPHQW LV WKH LQLWLDO YDOXH RI WKH VFUROOEDU ZKLFK VKRXOGEHDYDOXHEHWZHHQWKHVFUROOEDUVPD[LPXPDQGPLQLPXPYDOXHV7KHWKLUGDUJXPHQWLV WKHRYHUDOOZLGWK RUKHLJKWGHSHQGLQJRQWKHRULHQWDWLRQ RIWKHVFUROOEDUVER[7KHIRXUWKDQG ILIWKDUJXPHQWVDUHWKHPLQLPXPDQGPD[LPXPYDOXHVIRUWKHVFUROOEDU

Comp-U-Learn

185

Java Programming I

Scrollbar methods Method GetMaximum() getMinimum() getOrientation()

getValue() setValue(int) setLineIncrement(int )

getLineIncrement()

setPageIncrement(int inc) getPageIncrement()

Action Returns the maximum value. Returns the minimum value. Returns the orientation of this scrollbar:0 is 6FUROOEDU+25,=217$/  LV 6FUROOEDU9(57,&$/ Returns the scrollbars current value. Sets the current value of the scrollbar. Changes the increment to indicating a how far to scroll when the endpoints of the scrollbar are selected. The default is 1. Returns the increment for how far to scroll when the endpoints of the scrollbar are selected. Changes the increment by specifying how far to scroll when the inside range of the scrollbar is selected. The default is 10. Returns the increment by specifying how far to scroll when the inside range of the scrollbar is selected.

7KHIROORZLQJH[DPSOHH[SODLQVWKHXVDJHRIVFUROOEDUDVDVOLGHUEDU,QWKLVH[DPSOHZHFDQVHH WKHWZRQHZWRSLFV,QVHWVDQG(YHQWKDQGOLQJ7KHVHWZRWRSLFVDUHGLVFXVVHGLQGHWDLOLQWKH VXFFHHGLQJVHVVLRQV Example 8.7 import java.awt.*; import java.applet.*; public class slidertest extends Applet { Label l; public void init() { l = new Label("0", Label.CENTER); add(l); add(new Scrollbar(Scrollbar.HORIZONTAL,0,0,10,100)); } public Insets insets()

186

Comp-U-Learn

Abstract Windowing Toolkit (AWT) { return new Insets(15,15,15,15); } public boolean handleEvent(Event evt) { if (evt.target instanceof Scrollbar) { 1int v = ((Scrollbar)evt.target).getValue(); l.setText(String.valueOf(v)); repaint(); return true; } else return false; } }

:ULWH WKH DERYH FRGH VDYH LW DV VOLGHUWHVWMDYD $IWHU FRPSLOLQJ WKLV ILOH UXQ WKH IROORZLQJ VOLGHUKWPOILOHXVLQJDSSOHWYLHZHU

7KH RXWSXW RI WKH DERYH H[DPSOH LV VKRZQ LQ WKH IROORZLQJ ILJXUH ,Q WKLV DQ DSSOHW ZLQGRZ ZLWK RQH VPDOO VFUROO EDU ZLOO DSSHDU ,I ZH LQFUHDVH WKH EDU VL]H WKH ODEHO FRXQW LV LQFUHDVHG IURPWR

Fig 8.9

Canvases :H FDQ GUDZ RQ WKH  &DQYDVHV 7KH\ FDQ W FRQWDLQ RWKHU FRPSRQHQWV EXW WKH\ FDQ DFFHSW HYHQWV DQG ZH FUHDWH DQLPDWLRQ DQG GLVSOD\ LPDJHV RQ WKHP ,I ZH KDYH D SDQHO WKDW GRHVQ W

Comp-U-Learn

187

Java Programming I

QHHGWRGRDQ\WKLQJH[FHSWGLVSOD\LPDJHVRUDQLPDWLRQDFDQYDVZRXOGPDNHDOLJKWHUZHLJKW VXUIDFHWKDQDSDQHOGRHV7RFUHDWHDFDQYDVXVHWKH CanvasFODVVDQGDGGLWWRDSDQHODVZH ZRXOGWRDQ\RWKHUFRPSRQHQW Canvas can = new Canvas(); add(can);

&DQYDVHV DUH DOVR XVHIXO ZKHQ ZH ZDQW D FRQWURO 6LQFH ZH FDQQRW FKDQJH D VWDQGDUG FRQWURO DSSHDUDQFHE\VXEFODVVLQJLWVFRUUHVSRQGLQJFRPSRQHQWZHPXVWLQVWHDGLPSOHPHQWD&DQYDV VXEFODVVWRKDYHERWKWKHORRNZHZDQWDQGWKHVDPHEHKDYLRUDVWKHGHIDXOWLPSOHPHQWDWLRQRI FRQWUROV 7KH DFWXDO LPSOHPHQWDWLRQ RI D &DQYDV FRPHV XQGHU :LQGRZV DQG 3DQHOV 7KHVH DUH WKH LPSRUWDQWWRSLFVZKLFKDUHWREHGHDOWLQWKHVXFFHHGLQJVHVVLRQV

Summary In this session we were introduced to the Abstract Windowing Toolkit (AWT). Then we learnt AWT architecture, the component, container and User Interface Components. such as labels, buttons, text components, choices, lists, checkboxes and Scrollbars. Also we got a fundamental idea of a Canvas. So from now onwards we can create our applets with these components and make our applet as attractive as possible. Going Over It Again I. Fill in the Blanks  $:7VWDQGVIRUBBBBBBBBBBBBBBBBBBB  :HFDQDGGWKHFRPSRQHQWVWRWKHFRQWDLQHUZLWKWKHBBBBBBBBBPHWKRG  BBBBBBBBBBBBDUHSRSXSPHQXVRILWHPVIURPZKLFKRQHFDQFKRRVHDQLWHP  BBBBBBBBBBBBBPHWKRGGHOHWHVDOOWKHLWHPVLQWKHOLVW  7H[WDUHDLVDBBBBBBBBBBBBWH[WHGLWLQJFRPSRQHQW II. State True or False  /LVWVDOORZHLWKHUPXOWLSOHVHOHFWLRQVRUMXVWRQHVHOHFWLRQDWDWLPH  7H[W)LHOGFDQDOORZPXOWLSOHHQWULHV 188

Comp-U-Learn

Abstract Windowing Toolkit (AWT)

 6FUROOEDUVDUHXVHGWRVHOHFWDYDOXHEHWZHHQDPD[LPXPDQGDPLQLPXPYDOXH  )URP&KHFNER[FODVVZHFDQFUHDWHWKH5DGLREXWWRQV  %XWWRQFDQKDYHWKUHHW\SHRIFRQVWUXFWRUV III. One line Answers  :KDWLVD&RQWDLQHU"  :KDWDUHWKHYDULRXVW\SHVRI&KHFNER[HVDYDLODEOH"  :KDWLVWKHGLIIHUHQFHEHWZHHQ&KHFNER[HVDQGWKH5DGLREXWWRQV"  :KDWLVWKHGLIIHUHQFHEHWZHHQWKH7H[W)LHOGDQGWKH7H[W$UHD"  +RZPDQ\SDUDPHWHUVUHTXLUHGWRFUHDWHD6FUROOEDU" IV. Define the Following  DGG LQWKH3DQHO  FOHDU LQWKH/LVW  JHW2ULHQWDWLRQ LQ6FUROOEDU  VHOHFW LQ7H[W)LHOG  FRXQW,WHPV LQ&KRLFH

Comp-U-Learn

189

Session 9

Handling AWT Events

On Completion of this Session We will be able to understand...

) Introduction to Events ) Buttons Events ) Item Events ) Mouse Events ) Key Events

In This Session...



Introduction to Events



Applet Events



Button Events



Handling Multiple Events



Item Events



Mouse Event Handling



Double-clicks



Mouse Movements



Mouse-Drag & Mouse-Move Events



Mouse Enter and Mouse Exit Events



Keyboard Events



Default Keys

Handling AWT Events

Introduction to Events ,QWKLVVHVVLRQZHDUHJRLQJWROHDUQDERXWHYHQWGULYHQSURJUDPPLQJ7KHVHHYHQWVPD\EHRI GLIIHUHQW W\SH YL] PRXVH FOLFNV NH\ SUHVVHV QHWZRUN GDWD DUULYLQJ RQ WKH SRUW DQG PDQ\ %HIRUH GLYLQJ VWUDLJKW LQWR HYHQWV ZH ZLOO KDYH DQ LQWURGXFWLRQ WR HDFK HYHQWV DQG WKHLU IXQFWLRQV

Applet Events Initialization

,QLWLDOL]DWLRQRFFXUVZKHQRXUDSSOHWFRPHVLQWRH[LVWHQFH7KLVLVWKHILUVWHYHQWWKDWFDQRFFXU WRDQ\DSSOHW Destroy

7KLV LV RSSRVLWH WR LQLWLDOL]DWLRQ RFFXUV DV WKH ODVW HYHQW LQ DQ\ DSSOHW ,I ZH KDYH DQ\ ILQDO FOHDQXSWRGRGRLWKHUH Stop

$ VWRS HYHQW LQGLFDWHV WKDW WKH XVHU LV QR ORQJHU ORRNLQJ DW WKH SDJH WKDW FRQWDLQV WKH DSSOHW 7KLVRFFXUVZKHQWKHXVHUKDVOHIWWKHSDJHRUPLQLPL]HGWKHZLQGRZ Start

7KH VWDUW HYHQW RFFXUV ZKHQ D XVHU EULQJV DWWHQWLRQ EDFN WR WKH DSSOHW IRU LQVWDQFH DIWHU PD[LPL]LQJDZLQGRZRUUHWXUQLQJWRWKHDSSOHW·VSDJH,WDOZD\VRFFXUVDIWHUWKHLQLWLDOL]DWLRQ HYHQW Window Events Paint

7KLVHYHQWRFFXUVZKHQWKHSDUWLDOO\FRYHUHGDSSOHWZLQGRZLVXQFRYHUHG,WDOZD\VRFFXUVDIWHU WKHVWDUWHYHQWZKLFKZHKDYHDOUHDG\VHHQWKHSDLQWPHWKRG7KLVLVWKHPHWKRGLQZKLFKZH GRDOORXUGUDZLQJ:HFDQZULWHRQO\DWWKHDSSOHWVFUHHQXVLQJWKHSDLQWPHWKRG

Comp-U-Learn

193

Java Programming I Mouse Events mouseUp

7KLVHYHQWRFFXUVZKHQHYHUWKHPRXVHEXWWRQLVUHOHDVHGLQRXUDSSOHW,QPRVWFDVHVWKLVLVWKH HYHQWZHZLOOZDQWWRZDWFKRXWIRUQRWPRXVHGRZQ2QWKHVFUHHQDV\PERORIDEXWWRQLV W\SLFDOO\KLJKOLJKWHGZKHQWKHPRXVHEXWWRQLVSUHVVHGRQLWEXWLWLVQRWDFWLYDWHGWLOOWKHXVHU UHOHDVHVWKHPRXVHEXWWRQ7KLVJLYHV WKHXVHUDFKDQFH WRFKDQJH WKHLUPLQGE\PRYLQJWKH FXUVRURIIWKHEXWWRQZLWKRXW UHOHDVLQJLW0RXVHXS HYHQW DOVR RIIHUV WKH FRRUGLQDWHV RI WKH SRLQWZKHUHWKHPRXVHZDVUHOHDVHG mouseDown

7KHPRXVHGRZQHYHQWRFFXUVZKHQHYHUWKHPRXVHEXWWRQLVSUHVVHGLQWKHDSSOHW,QPRVW FDVHVZHZLOOZDQWWRZDLWIRUDPRXVHXSHYHQWWRRFFXUEHIRUHWDNLQJDQ\DFWLRQ7KHPRXVH GRZQHYHQWDOVRRIIHUVWKHFRRUGLQDWHVRIWKHSRLQWZKHUHWKHPRXVHZDVHQJDJHG mouseDrag

7KH PRXVH GUDJ HYHQW RFFXUV ZKHQ D XVHU PRYHV WKH PRXVH ZKLOH KROGLQJ GRZQ WKH PRXVH EXWWRQ0RXVHGUDJHYHQWRIIHUVWKHFRRUGLQDWHVRIWKHSRLQWZKHUHWKHPRXVHZDVZKHQWKH HYHQWRFFXUUHG*HQHUDOO\ZHJHWDVHTXHQFHRIPRXVHPRYHHYHQWVZKHQZHPRYHRXUKDQG mouseMove

7KHPRXVHPRYHHYHQWRFFXUVZKHQDXVHUPRYHVWKHPRXVHZLWKRXWKROGLQJGRZQWKHPRXVH EXWWRQ0RXVHPRYHHYHQWRIIHUVWKHFRRUGLQDWHVRIWKHSRLQWZKHUHWKHPRXVHZDVZKHQWKH HYHQWRFFXUUHG*HQHUDOO\ZHJHWDVHTXHQFHRIPRXVHPRYHHYHQWVZKHQZHPRYHRXUKDQG mouseEnter

2XUDSSOHWUHFHLYHVDPRXVHHQWHUHYHQWZKHQHYHUWKHFXUVRUHQWHUV RXUDSSOHWZLQGRZIURP VRPHZKHUHHOVH:HZLOODOVRUHFHLYHWKHFRRUGLQDWHVRIWKHSRLQWDWZKLFKWKHFXUVRUHQWHUHG RXU DSSOHW  7KLV LV W\SLFDOO\ IROORZHG E\ D VHTXHQFH RI PRXVH PRYHG HYHQWV DV WKH FXUVRU FRQWLQXHVWKURXJKWKHDSSOHW mouseExit

2XU DSSOHW UHFHLYHV D PRXVH H[LW HYHQW ZKHQHYHU WKH FXUVRU OHDYHV RXU DSSOHW  ,W ZLOO DOVR UHFHLYHWKHFRRUGLQDWHVRIWKHSRLQWDWZKLFKWKHFXUVRUH[LWHGRXUDSSOHW

194

Comp-U-Learn

Handling AWT Events Key Board Events keyDown

$NH\GRZQHYHQWLVJHQHUDWHGZKHQHYHUWKHXVHUSUHVVHVDNH\ZKLOHRXUDSSOHWLVDFWLYH$Q LQWHJHUNH\FRGHLVDYDLODEOHLQGLFDWLQJZKLFKNH\ZDVSUHVVHG$VDJHQHUDOUXOHZHZLOOFRQYHUW WKLVWRDFKDUWRJHWWKHDFWXDOFKDUDFWHU keyUp

$.H\XSHYHQWLVJHQHUDWHGZKHQHYHUWKHXVHUUHOHDVHVWKHSUHVVHGNH\$QLQWHJHUNH\FRGHLV UHWXUQHGLQGLFDWLQJZKLFKNH\ZDVSUHVVHG$VDJHQHUDOUXOHZHZLOOFRQYHUWWKLVWRDFKDUWR JHWWKHDFWXDOOHWWHU

Button Events :KHQ WKH XVHU FOLFNV D EXWWRQ W\SHV WH[W XVHV WKH PRXVH RU SHUIRUPV DQ\ RWKHU LQWHUIDFH UHODWHG DFWLRQ LQ RXU DSSOHW DQ LQWHUIDFH HYHQW RFFXUV  :KHQ WKH HYHQW RFFXUV LQ RXU DSSOHW PRXVH FOLFNV RXU DSSOHW LV QRWLILHG DQG ZH WDNH DSSURSULDWH DFWLRQ  7KDW·V WKH ZD\ WKH SURJUDPPLQJJRHVLQ*8, *UDSKLF8VHU,QWHUIDFH SURJUDPVOLNHWKRVHZULWWHQIRU:LQGRZV  ZH UHVSRQG WR XVHU HYHQW ZKHQ WKH\ KDSSHQ EHFDXVH WKH XVHU GLUHFWV WKH SURJUDP IORZ E\ PDQLSXODWLQJWKHFRQWUROVLQRXUDSSOHW,QRXUFDVHZHFDQILQGRXWZKDWHYHQWV²OLNHPRXVH PRYHPHQWVRUEXWWRQFOLFNV²RFFXUVDVRXUDSSOHWUXQVE\WKH$FWLRQ/LVWHQHULQWHUIDFH ,I ZH KDYH SURJUDPPHG LQ -DYD  ZH SUREDEO\ XVHG DQ DFWLRQ  PHWKRG WR KDQGOH EXWWRQ FOLFNVEXWWKHDFWLRQ PHWKRGLVQRZFRQVLGHUHGREVROHWH7KLVLVDIXQGDPHQWDOFKDQJH7KH QHZ-DYDWHFKQLTXHLVWKHXVHRIWKHGHOHJDWLRQEDVHGHYHQWPRGHO7RGRWKDWZHLQGLFDWHWKDW RXUDSSOHWFODVVZLOOLPSOHPHQWWKH$FWLRQ/LVWHQHULQWHUIDFH ,PSOHPHQWLQJ WKDW LQWHUIDFH ORRNV OLNH WKLV ZKHUH ZH DOVR LPSRUW WKH MDYDDZWHYHQW SDFNDJH WKDWKROGVWKH$FWLRQ/LVWHQHULQWHUIDFH import java.applet.Applet; import java.awt.*; import java.awt.event.*; // includes all the events referred to that program public class clicker extends Applet implements ActionListener { TextField t; Button b; public void init() { t=new TextField(20); add(t); b=new Button(“click me”); add(b); } }

Comp-U-Learn

195

Java Programming I

7KH ZD\ WKH GHOHJDWLRQ  EDVHG HYHQW PRGHO ZRUNV LV WKDW HYHQWV DUH SDVVHG IURP VRXUFH FRQWUROVWROLVWHQHUREMHFWV:HFRQQHFW/LVWHQHUWRRXU%XWWRQV:KHQDQHYHQWRFFXUVWKH OLVWHQHUREMHFWZLOO´KHDUµLW,QWKLVFDVHZHPDNHWKHOLVWHQHUREMHFWWKHDSSOHWREMHFWLWVHOIE\ FRQQHFWLQJ RXU DSSOHW WR EXWWRQ DV D OLVWHQHU DQG ZH ZLOO GR WKDW ZLWK WKH EXWWRQ·V DGG$FWLRQ/LVWHQHU PHWKRG%XWWRLQGLFDWHWKDWZHZDQWWKHDSSOHWLWVHOIWREHWKH%XWWRQ·V OLVWHQHUZHQHHGWRSDVVWKHDSSOHWLWVHOIDVDQDUJXPHQWWRDGG$FWLRQ/LVWHQHU  Using Button Events

:HFDWFKWKHHYHQWVVHQWWRXVE\ RYHUULGLQJ WKH$FWLRQ/LVWHQHULQWHUIDFH·VDFWLRQ3HUIRUPHG PHWKRGDQGDGGLQJWKHDERYHSURJUDPZKLFKORRNVOLNHWKLV Example 9.1 import java.applet.Applet; import java.awt.*; import java.awt.event.*; // includes all the events referred to that program public class clicker extends Applet implements ActionListener { TextField t; Button b; public void init() { t=new TextField(20); add(t); b=new Button(“click me”); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent e) {

} }

7KLVLVWKHPHWKRGWKDWZLOOEHFDOOHGZKHQWKHXVHUFOLFNVDEXWWRQ7KH$FWLRQ(YHQWREMHFW WKDWLVSDVVHGWRXVKHUHKROGVLQIRUPDWLRQDERXWWKHHYHQWWKDWRFFXUUHG)RUH[DPSOHLIZH·YH JRWPDQ\QXPEHURIEXWWRQVFOLFNHG²FOLFNLQJDQ\RQHEXWWRQZLOOFDOOWKLVPHWKRG+RZGR ZHPDNHVXUHWKDWRQO\RXUEXWWRQZDVFOLFNHG"

196

Comp-U-Learn

Handling AWT Events

:HFDQFKHFNZKLFKEXWWRQZDVFOLFNHGZLWKWKH$FWLRQ(YHQWFODVV·VJHW6RXUFH PHWKRG7KLV PHWKRGUHWXUQVWKHFRQWUROWKDWFDXVHGWKHHYHQWDQGZHFDQFKHFNWRVHHLIWKHFRQWUROLVRXU %XWWRQE Example 9.2 import java.applet.Applet; import java.awt.*; import java.awt.event.*; // all events to be handled public class clicker extends Applet implements ActionListener { TextField t; Button b; public void init() { t=new TextField(20); add(t); b=new Button(“click me”); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b){ } }

,IWKHFRQWUROWKDWFUHDWHGWKH-DYDHYHQWLVEXWWRQEWKHFRGHZHSODFHLQWKHFRGHEORFN³WKH FRGHVXUURXQGHGE\WKH^DQG`EUDFHVIROORZLQJ WKH LI VWDWHPHQW³ZLOO EH H[HFXWHG  7KDW LV EHFDXVH ZH XVH WKH -DYD HTXDOLW\ RSHUDWRU  WR FRPSDUH WKH FRQWURO UHWXUQHG E\ HYHQWJHW6RXUFH DQGEXWWRQE,I%XWWRQEZDVLQGHHGFOLFNHGZHZDQWWRGLVSOD\RXUPHVVDJH ´:HOFRPHWR86$´DQGZHGRWKDWE\ILUVWVHWWLQJXSD-DYDVWULQJREMHFWQDPHGPVJKROGLQJ WKDWWH[WDQG\WKHQGLVSOD\LQJWKDWVWULQJLQWKHWH[WILHOGXVLQJWKH7H[W)LHOG·VVHW7H[W PHWKRG 7KHFRPSOHWHSURJUDPLVJLYHQLQH[DPSOH Example 9.3 import java.applet.Applet; import java.awt.*; import java.awt.event.*; // includes all the events referred to that program public class clicker extends Applet implements ActionListener { TextField t; Button b; public void init() {

Comp-U-Learn

197

Java Programming I t=new TextField(20); add(t); b=new Button(“click me”); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { String msg=new String (“Welcome to USA “); if(e.getSource()==b) { t.setText(msg); } } }

$QGQRZRXUQHZDSSOHWLVFRPSOHWHG%XLOGLWQRZDQGUXQLW&OLFNWKHEXWWRQDQGZDWFKWKH ´:HOFRPHWR86$µPHVVDJHDSSHDULQWKHWH[WILHOGDVVKRZQEHORZ7KHRXWSXWIRUWKHDERYH SURJUDPLVJLYHQEHORZ

Fig 9.1

Handling Multiple Events 6XSSRVHZHKDYHWZREXWWRQVVD\EDQGEDQGD7H[W)LHOGVD\W,IZHSUHVVWKHILUVW%XWWRQ E LW VKRXOG GLVSOD\ D PHVVDJH ´ :HOFRPH WR 86$µ LQ WKH 7H[W)LHOG W DQG LW ZH SUHVV WKH VHFRQG%XWWRQELWVKRXOGGLVSOD\DPHVVDJHµ+L-DYD*X\VµLQWKHVDPH7H[W)LHOGW ,QRUGHUWRKDQGOHPXOWLSOHEXWWRQVWKHIROORZLQJH[DPSOHZLOOVKRZXVKRZPXOWLSOHHYHQWVDUH KDQGOHG 198

Comp-U-Learn

Handling AWT Events

Example 9.4 import java.applet.Applet; import java.awt.*; import java.awt.event.*; // includes all the events referred to that program public class clickers extends Applet implements ActionListener { TextField t; Button b1; Button b2; public void init() { t=new TextField(20); add(t); b1=new Button("Click This"); add(b1); b1.addActionListener(this); b2=new Button("Click This too"); add(b2); b2.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { t.setText("Welcome to USA"); } if(e.getSource()==b2) { t.setText("Hi Guys"); } } }

$QGQRZRXUQH[WDSSOHWLVFRPSOHWH%XLOGLWQRZDQGUXQLW&OLFNWKHEXWWRQEDQGZDWFK WKH´:HOFRPHWR86$µPHVVDJHDSSHDULQWKHWH[WILHOGWDQG&OLFNWKHEXWWRQEDQGZDWFKWKH ´+L*X\VµPHVVDJHDSSHDULQWKHWH[WILHOGLWDVVKRZQEHORZ7KHFRGHIRUWKLVDSSOHWDSSHDUV LQFOLFNHUVMDYD

Comp-U-Learn

199

Java Programming I

7KHRXWSXWIRUWKHDERYHSURJUDPLVJLYHQEHORZ

Fig 9.2

Item Events :KHQ WKH XVHU FOLFNV DQ LWHP LQ D FDQYDV FKRLFH OLVWV FKHFNER[ FKHFNER[ JURXS UDGLR EXWWRQV LQRXUDSSOHWDQLQWHUIDFHHYHQWRFFXUV:KHQWKHHYHQWVRFFXULQRXUDSSOHWVXFKDVD ZKHQWKHXVHUFOLFNVWKHLWHPRXUDSSOHWLVQRWLILHGDQGZHFDQWDNHDSSURSULDWHDFWLRQ7KLV LWHPFOLFNVFDQEHDFKLHYHGE\XVLQJWKHLWHP/LVWHQHULQWHUIDFHLQRXWDSSOHW

Fig. 9.3 ,PSOHPHQWLQJ WKDW LQWHUIDFH ORRNV OLNH WKLV ZKHUH ZH DOVR LPSRUW WKH MDYDDZWHYHQW SDFNDJH ZKLFKKROGVWKHLWHP/LVWHQHUDQG$FWLRQ/LVWHQHULQWHUIDFHLIDQ\RWKHUREMHFWVDUHLQFOXGHG 200

Comp-U-Learn

Handling AWT Events

Example 9.5 //program to show the items in a particular fashion by choice import java.applet.*; import java.awt.event.*; import java.awt.*; public class choice extends Applet implements itemListener { TextField t; Choice c; public void init() { add(t=new TextField(30)); c=new Choice(); c.add("Thomas"); c.add(“joseph”); c.add("Robin"); c.add("clinton"); c.add("John"); c.add("Jennifer"); c.add("Jannet"); add(c); } }

$W WKLV SRLQW RXU FKRLFH FRQWURO DQG 7H[W)LHOG ZLOO DSSHDU 7R GLVSOD\ WKH FKRLFH RI WKH XVHU PDNHVZHKDYHWRDGGDQLWHP/LVWHQHUWRWKH&KRLFHFRQWURO Example 9.6 import java.applet.*; import java.awt.event.*; import java.awt.*; public class choice extends Applet implements itemListener { TextField t; Choice c; public void init() { add(t=new TextField(30)); c=new Choice(); c.add("Thomas"); c.add(“joseph”); c.add("Robin"); c.add("clinton"); c.add("John"); c.add("Jennifer"); c.add("Jannet"); add(c); c.addItemListener(this); } }

Comp-U-Learn

201

Java Programming I

,QRUGHUWRUHDG&KRLFHFRQWUROHYHQWVZHDGGWKHLWHP6WDWH&KDQJH PHWKRGWRRXUDSSOHW +HUH E\ XVLQJ WKH WHUP F FKRLFH  LQ WKH DERYH FRGH ZH LQIRUP -DYD WKDW WKH FRQWURO ZH JHW IURPWKHHJHW,WHP6HOHFWDEOH FDOOZLOOEHDFKRLFHFRQWURO:HQHHGWRWHOOMDYDWKDWVRZHFDQ XVHWKH&KRLFHFRQWUROVJHW6HOHFWHG,WHP PHWKRGLQWKHVDPHVWDWHPHQW+HUHLVWKHFRPSOHWH SURJUDPWRXVHWKH,WHP(YHQWVFOHDUO\+HUHLVDSURJUDPWRVKRZWKHLWHPHYHQWVLQDFKRLFH XVLQJ,WHP/LVWHQHU Example 9.7 import import import public

java.applet.*; java.awt.event.*; java.awt.*; class choice extends Applet implements ItemListener

{ TextField t; Choice c; public void init() { add(t=new TextField(30)); c=new Choice(); c.add("Thomas"); c.add("Joseph"); c.add("Robin"); c.add("Clinton"); c.add("John"); c.add("Jennifer"); c.add("jannet"); c.addItemListener(this); add(c); } public void itemStateChanged(ItemEvent e) { if(e.getItemSelectable()==c) { if(c.getSelectedItem().equals("Thomas")) t.setText(“Hai Thomas"); // else if(c.getSelectedItem().equals("Joseph")) t.setText("Hai Joseph"); //else if(c.getSelectedItem().equals("Robin")) t.setText("Hai Robin"); //else

202

Comp-U-Learn

Handling AWT Events if(c.getSelectedItem().equals("Clinton")) t.setText("Monika"); //else if(c.getSelectedItem().equals("John")) t.setText("Hai John"); //else if(c.getSelectedItem().equals("Jennifer")) t.setText("Hai Jennifer"); //else if(c.getSelectedItem().equals("Jannet")) t.setText("Hai Jannet"); } } }

7KHRXWSXWRIWKHDERYHSURJUDPLVJLYHQEHORZ

Fig.9.4

Mouse Event Handling Mouse-Down and Mouse-Up Events

:KHQZHFOLFNWKHPRXVHRQFHWKH$:7JHQHUDWHVWZRHYHQWVDPRXVHGRZQHYHQWZKHQWKH PRXVHEXWWRQLVSUHVVHGDQGDPRXVHXSHYHQWZKHQWKHEXWWRQLVUHOHDVHG)RUH[DPSOHLIZH

Comp-U-Learn

203

Java Programming I

KDYHDSXOOGRZQPHQXWKHPRXVHGRZQH[WHQGVWKHPHQXDQGWKHPRXVHXSVHOHFWVDQLWHP +DQGOLQJ PRXVH HYHQWV LQ RXU DSSOHW LV HDV\DOO ZH KDYH WR GR LV RYHUULGH WKH ULJKWPHWKRG GHILQLWLRQLQRXUDSSOHW7KDWPHWKRGZLOOEHFDOOHGZKHQWKDWSDUWLFXODUHYHQWRFFXUV+HUH VDQ H[DPSOHIRUDPRXVHGRZQHYHQW public boolean mouseDown(Event e, int x, int y) { ... }

7KHPRXVH'RZQ PHWKRGDQGWKHPRXVH8S PHWKRGVWDNHVWKUHHSDUDPHWHUVWKHHYHQWLWVHOI DQG WKH [ DQG \ FRRUGLQDWHV ZKHUH WKH PRXVHGRZQ RU PRXVHXS HYHQW RFFXUUHG 7KH H DUJXPHQWLVDQLQVWDQFHRIWKHFODVV(YHQW$OOV\VWHPHYHQWVJHQHUDWHDQLQVWDQFHRIWKH(YHQW FODVVZKLFKFRQWDLQVLQIRUPDWLRQDERXWZKHUHDQGZKHQWKHHYHQWWRRNSODFHWKHNLQGRIHYHQW LW LV DQG RWKHU LQIRUPDWLRQ WKDW ZH PLJKW ZDQW WR NQRZ DERXW WKLV HYHQW 7KH [ DQG WKH \ FRRUGLQDWHV RI WKH HYHQW DV SDVVHG LQ WKURXJK WKH [ DQG \ DUJXPHQWV WR WKH PRXVH'RZQ PHWKRG  WR GHWHUPLQH SUHFLVHO\ ZKHUH WKH PRXVH FOLFN WRRN SODFH 6R IRU H[DPSOH LI WKH PRXVHGRZQHYHQWZDVRYHUDJUDSKLFDOEXWWRQZHFDQDFWLYDWHWKDWEXWWRQ +HUH VDVLPSOHPHWKRGWKDWSULQWVRXWLQIRUPDWLRQDERXWDPRXVHGRZQHYHQWZKHQLWRFFXUV public boolean mouseDown(Event evt, int x, int y) { System.out.println("Mouse down at " + x + "," + y); return true; }

%\LQFOXGLQJWKLVPHWKRGLQRXUDSSOHWHYHU\WLPHWKHXVHUFOLFNVWKHPRXVHLQVLGHWKHDSSOHW WKLV PHVVDJH ZLOO JHW SULQWHG 7KH $:7 V\VWHP FDOOV HDFK RI WKHVH PHWKRGV ZKHQ WKH DFWXDO HYHQW WDNHV SODFH 8QOLNH -DYD DSSOLFDWLRQV ZKHUH 6\VWHPRXWSULQWOQ  RXWSXWV WR WKH VFUHHQ ZKHUH WKH RXWSXW DSSHDUV LQ DSSOHWV YDULHV IURP V\VWHP WR V\VWHP DQG EURZVHU WR EURZVHU 1HWVFDSHKDVDVSHFLDOZLQGRZFDOOHG-DYDFRQVROHWKDWPXVWEHYLVLEOHIRUXVWRVHHWKHRXWSXW ,QWHUQHW([SORUHUORJV-DYDRXWSXWWRDVHSDUDWHILOH 7KHVHFRQGKDOIRIWKHPRXVHFOLFNLVWKHPRXVH8S PHWKRGZKLFKLVFDOOHGZKHQWKHPRXVH EXWWRQ LV UHOHDVHG 7R KDQGOH D PRXVHXS HYHQW DGG WKH PRXVH8S  PHWKRG WR RXU DSSOHW PRXVH8S ORRNVMXVWOLNHPRXVH'RZQ  public boolean mouseUp(Event evt, int x, int y) { .... }

204

Comp-U-Learn

Handling AWT Events

)RUH[DPSOHFRQVLGHUWKHIROORZLQJ6SRWVDSSOHWFUHDWLRQ7KH6SRWVDSSOHWVWDUWVZLWKDEODQN VFUHHQDQGWKHQVLWVDQGZDLWV:KHQZHFOLFNWKHPRXVHRQWKDWVFUHHQDEOXHGRWLVGUDZQ:H FDQSODFHXSWRGRWVRQWKHVFUHHQ /HW VVWDUWIURPWKHEHJLQQLQJDQGEXLOGWKLVDSSOHWVWDUWLQJIURPWKHLQLWLDOFODVVGHILQLWLRQ import java.awt.Graphics; import java.awt.Color; import java.awt.Event; public class Spots extends java.applet.Applet { final int MAXSPOTS = 10; int xspots[] = new int[MAXSPOTS]; int yspots[] = new int[MAXSPOTS]; int currspots = 0; }

7KLV FRGH XVHV WKUHH RWKHU $:7 FODVVHV *UDSKLFV &RORU DQG (YHQW 7KH ODVW FODVV (YHQW QHHGV WR EH LPSRUWHG LQ DQ\ DSSOHWV WKDW XVH HYHQWV 7KH FODVV KDV IRXU LQVWDQFH YDULDEOHV D FRQVWDQWWRGHWHUPLQHWKHPD[LPXPQXPEHURIVSRWVWKDWFDQEHGUDZQWZRDUUD\VWRVWRUHWKH [DQG\FRRUGLQDWHVRIWKHVSRWVWKDWKDYHDOUHDG\EHHQGUDZQDQGDQLQWHJHUWRNHHSWUDFNRI WKHQXPEHURIWKHFXUUHQWVSRW /HWXVDGGWKHLQLW PHWKRGZKLFKGRHVRQO\RQHWKLQJVHWWKHEDFNJURXQGFRORUWRZKLWH public void init() { setBackground(Color.white); }

:HKDYHVHWWKHEDFNJURXQGKHUHLQLQLW LQVWHDGRILQSDLQW DVZHKDYHGRQHLQSDVWH[DPSOHV EHFDXVH ZH QHHG WR VHW WKH EDFNJURXQG RQO\ RQFH $V SDLQW  LV FDOOHG UHSHDWHGO\ HDFK WLPH D QHZ VSRW LV DGGHG VHWWLQJ WKH EDFNJURXQG LQ WKH SDLQW  PHWKRG VORZV GRZQ WKDW PHWKRG XQQHFHVVDULO\ 7KHPDLQDFWLRQRIWKLVDSSOHWRFFXUVZLWKWKHPRXVH'RZQ PHWKRGVROHW VDGGWKDWRQHQRZ public boolean mouseDown(Event evt, int x, int y) { if (currspots < MAXSPOTS) { addspot(x,y); return true; } else { System.out.println("Too many spots."); return false; } }

Comp-U-Learn

205

Java Programming I

:KHQWKHPRXVHFOLFNRFFXUVWKHPRXVH'RZQ PHWKRGWHVWVWRVHHZKHWKHUWKHUH DUHIHZHU WKDQVSRWV,IVRLWFDOOVWKHDGGVSRW PHWKRGDQGUHWXUQVWUXH WKHPRXVHGRZQHYHQWZDV LQWHUFHSWHGDQGKDQGOHG ,IQRWLWMXVWSULQWVDQHUURUPHVVDJHDQGUHWXUQVIDOVH DGGVSRW DGGVWKHFRRUGLQDWHVRIWKHVSRWWRWKHDUUD\VWKDWVWRUHWKHFRRUGLQDWHVLQFUHPHQWV WKHFXUUVSRWVYDULDEOHDQGWKHQFDOOVUHSDLQW  void addspot(int x, int y) { xspots[currspots] = x; yspots[currspots] = y; currspots++; repaint(); }

:HPD\EHZRQGHULQJZK\ZHKDYHWRNHHSWUDFNRIDOOWKHSDVWVSRWVLQDGGLWLRQWRWKHFXUUHQW VSRW7KHUHDVRQLVUHSDLQW (DFKWLPHZHSDLQWWKHVFUHHQZHKDYHWRSDLQWDOOWKHROGVSRWVLQ DGGLWLRQWRWKHQHZHUVSRW2WKHUZLVHHDFKWLPHZHSDLQWHGDQHZVSRWWKHROGHUVSRWVZRXOG JHWHUDVHG1RZRQWRWKHSDLQW PHWKRG public void paint(Graphics g) { g.setColor(Color.blue); for (int i = 0; i < currspots; i++) { g.fillOval(xspots[i] -10, yspots[i] - 10, 20, 20); } }

,QVLGH SDLQW  ZH MXVW ORRS WKURXJK WKH VSRWV ZH YH VWRUHG LQ WKH [ VSRWV DQG \ VSRWV DUUD\V SDLQWLQJ HDFK RQH DFWXDOO\ SDLQWLQJ WKHP D OLWWOH WR WKH ULJKW DQG XSZDUG VR WKDW WKH VSRW LV SDLQWHGDURXQGWKHPRXVHSRLQWHUUDWKHUWKDQEHORZDQGWRWKHULJKW 7KHIROORZLQJSURJUDP FRYHULQJWKHHYHQWVZKLFKDUHGHVFULEHGDERYH Example 9.8 /* draw blue spots at each mouse click */ import java.awt.Graphics; import java.awt.Color; import java.awt.Event; public class ajay1 extends java.applet.Applet { final int MAXSPOTS = 10; int xspots[] = new int[MAXSPOTS]; int yspots[] = new int[MAXSPOTS]; int currspots = 0;

206

Comp-U-Learn

Handling AWT Events public void init() { setBackground(Color.white); } public boolean mouseDown(Event evt, int x, int y) { if (currspots < MAXSPOTS) { addspot(x,y); return true; } else { System.out.println("Too many spots."); return false; } } void addspot(int x,int y) { xspots[currspots] = x; yspots[currspots] = y; currspots++; repaint(); } public void paint(Graphics g) { g.setColor(Color.blue); for (int i = 0; i < currspots; i++) { g.fillOval(xspots[i] - 10, yspots[i] - 10, 20, 20); } } }

6DYHWKHDERYHILOHDVDMD\MDYD$IWHUFRPSLOLQJWKHDERYHILOHUXQWKHIROORZLQJ+70/ILOH

7KHRXWSXWIRUWKHDERYHSURJUDPLVJLYHQEHORZ

Fig 9.5 Comp-U-Learn

207

Java Programming I

Double-clicks The clickCount LV DQ LQWHJHU UHSUHVHQWLQJ WKH QXPEHU RI FRQVHFXWLYH PRXVH FOLFNV WKDW KDYH RFFXUUHG ZKHUH FRQVHFXWLYH LV XVXDOO\ GHWHUPLQHG E\ WKH RSHUDWLQJ V\VWHP RU WKH PRXVH KDUGZDUH ,IZH UHLQWHUHVWHGLQPXOWLSOHPRXVHFOLFNVLQRXUDSSOHWZHFDQWHVWWKLVYDOXHLQWKH ERG\RIRXUmouseDown()PHWKRGOLNHWKLV public boolean mouseDown(Event evt, int x, int y) { switch (evt.clickCount) { case 1: // single-click case 2: // double-click case 3: // triple-click .... } }

Mouse Movements (YHU\WLPHWKHPRXVHLVPRYHGDVLQJOHSL[HOLQDQ\GLUHFWLRQDPRXVHPRYHHYHQWLVJHQHUDWHG 7KHUH DUH WZR PRXVHPRYHPHQW HYHQWV PRXVH GUDJV ZKHUH WKH PRYHPHQW RFFXUV ZLWK WKH PRXVH EXWWRQ SUHVVHG GRZQ DQG SODLQ PRXVH PRYHPHQWV ZKHUH WKH PRXVH EXWWRQ LVQ W SUHVVHG 7RPDQDJHPRXVHPRYHPHQWHYHQWVXVHWKHPRXVH'UDJ DQGPRXVH0RYH PHWKRGV

Mouse-Drag and Mouse-Move Events 7KHPRXVH'UDJ DQGPRXVH0RYH PHWKRGVZKHQLQFOXGHGLQRXUDSSOHWFRGHLQWHUFHSWDQG KDQGOHPRXVHPRYHPHQWHYHQWV0RXVHPRYHDQGPRXVHGUDJHYHQWVDUHJHQHUDWHGIRUHYHU\ SL[HOFKDQJHVWKHPRXVHPRYHVVRDPRXVHPRYHPHQWIURPRQHVLGHRIWKHDSSOHWWRWKHRWKHU PD\ JHQHUDWH KXQGUHGV RI HYHQWV 7KH PRXVH0RYH  PHWKRG IRU SODLQ PRXVHSRLQWHU PRYHPHQWVZLWKRXWWKHPRXVHEXWWRQSUHVVHGORRNVYHU\PXFKOLNHWKHPRXVHFOLFNPHWKRGV public boolean mouseMove(Event evt, int x, int y) { ... }

7KH PRXVH'UDJ  PHWKRG KDQGOHV PRXVH PRYHPHQWV PDGH ZLWK WKH PRXVH EXWWRQ SUHVVHG GRZQ DFRPSOHWHGUDJJLQJPRYHPHQWFRQVLVWVRIDPRXVHGRZQHYHQWDVHULHVRIPRXVHGUDJ HYHQWVIRUHDFKSL[HOWKHPRXVHLVPRYHGDQGDPRXVHXS ZKHQWKH EXWWRQLVUHOHDVHG 7KH PRXVH'UDJ PHWKRGORRNVOLNHWKLV 208

Comp-U-Learn

Handling AWT Events public boolean mouseDrag(Event evt, int x, int y) { ... }

1RWHWKDWIRUERWKWKHPRXVH0RYH DQGPRXVH'UDJ PHWKRGVWKHDUJXPHQWVIRUWKH[DQG\ FRRUGLQDWHVDUHWKHQHZORFDWLRQRIWKHPRXVHQRWLWVVWDUWLQJORFDWLRQ

Mouse Enter and Mouse Exit Events )LQDOO\ WKHUH DUH WKH PRXVH(QWHU  DQG PRXVH([LW  PHWKRGV 7KHVH WZR PHWKRGV DUH FDOOHG ZKHQWKHPRXVHSRLQWHUHQWHUVRUH[LWVDQDSSOHWRUDSRUWLRQRIWKDWDSSOHW%RWKPRXVH(QWHU DQG PRXVH([LW  KDYH VLJQDWXUHV VLPLODU WR WKH PRXVHFOLFN PHWKRGV ²WKUHH DUJXPHQWV WKH HYHQWREMHFW DQG WKH [ DQG \ FRRUGLQDWHV RI WKH SRLQW ZKHUH WKH PRXVH HQWHUHG RU H[LWHG WKH DSSOHW7KHVHH[DPSOHVVKRZWKHVLJQDWXUHVIRUPRXVH(QWHU DQGPRXVH([LW  public boolean mouseEnter(Event evt, int x, int y) { ... } public boolean mouseExit(Event evt, int x, int y) { ... }

/HWXVFUHDWHDQDSSOHWWKDWHQDEOHVXVWRGUDZVWUDLJKWOLQHVRQWKHVFUHHQE\GUDJJLQJIURPWKH VWDUWSRLQWWRWKHHQGSRLQW+HUH VDVLPSOHFODVVGHILQLWLRQIRUWKH/LQHVDSSOHWZLWKDQXPEHU RILQLWLDOLQVWDQFHYDULDEOHVDQGDVLPSOHLQLW PHWKRG import java.awt.Graphics; import java.awt.Color; import java.awt.Event; import java.awt.Point; public class Lines extends java.applet.Applet { final int MAXLINES = 10; Point starts[] = new Point[MAXLINES]; // starting points Point ends[] = new Point[MAXLINES]; // ending points Point anchor; // start of current line Point currentpoint; // current end of line int currline = 0; // number of lines public void init() { setBackground(Color.white); } }

Comp-U-Learn

209

Java Programming I

7KH LQLW  PHWKRG NHHSV WUDFN RI 3RLQW REMHFWV 3RLQWV UHSUHVHQW D [ DQG \ FRRUGLQDWH HQFDSVXODWHG LQ D VLQJOH REMHFW 7R GHDO ZLWK SRLQWV ZH LPSRUW WKH 3RLQW FODVV DQG VHW XS D EXQFKRILQVWDQFHYDULDEOHVWKDWKROGSRLQWV ♦ ♦ ♦ ♦

The starts array holds points representing the starts of lines already drawn The ends array holds the endpoints of those same lines. anchor holds the starting point of the line currently being drawn. currentpoint holds the current endpoint of the line currently being drawn

)LQDOO\WKHLQLW PHWKRGVHWVWKHEDFNJURXQGRIWKHDSSOHWWRZKLWH7KHWKUHHPDLQHYHQWVWKLV DSSOHWGHDOVZLWKDUHPRXVH'RZQ WRVHWWKHDQFKRUSRLQWIRUWKHFXUUHQWOLQHPRXVH'UDJ  WRDQLPDWHWKHFXUUHQWOLQHDVLWLVEHLQJGUDZQDQGPRXVH8S WRVHWWKHHQGLQJSRLQWIRUWKH QHZOLQH*LYHQWKDWZHKDYHLQVWDQFHYDULDEOHVWRKROGHDFKRIWKHVHYDOXHVLW VPHUHO\DPDWWHU RISOXJJLQJWKHULJKWYDULDEOHVLQWRWKHULJKWPHWKRGV +HUH V PRXVH'RZQ  ZKLFK VHWV WKH DQFKRU SRLQW EXW RQO\ LI ZH KDYHQ W H[FHHGHG WKH PD[LPXPQXPEHURIOLQHV  public boolean mouseDown(Event evt, int x, int y) { if (currline < MAXLINES) { anchor = new Point(x,y); return true; } else { System.out.println("Too many lines."); return false; } }

:KLOHWKHPRXVHLVEHLQJGUDJJHGWRGUDZWKHOLQHWKHDSSOHWDQLPDWHVWKHOLQHEHLQJGUDZQ$V ZHGUDJWKHPRXVHDURXQGWKHQHZOLQHPRYHVZLWKLWIURPWKHDQFKRUSRLQWWRWKHWLSRIWKH PRXVH7KHPRXVH'UDJ HYHQWFRQWDLQVWKHFXUUHQWSRLQWHDFKWLPHWKHPRXVHPRYHV6RXVH WKDWPHWKRGWRNHHSWUDFNRIWKHFXUUHQWSRLQW DQGWRUHSDLQWIRUHDFKPRYHPHQWVRWKHOLQH DQLPDWHV 1RWHWKDWLIZH YHH[FHHGHGWKHPD[LPXPQXPEHURIOLQHVZHZRQ WZDQWWRGR DQ\RIWKLV+HUH VWKHPRXVH'UDJ PHWKRGWRGRDOOWKRVHWKLQJV public boolean mouseDrag(Event evt, int x, int y) { if (currline < MAXLINES) { currentpoint = new Point(x,y); repaint(); return true; } else return false; }

210

Comp-U-Learn

Handling AWT Events

7KH QHZ OLQH GRHVQ W JHW DGGHG WR WKH DUUD\V RI ROG OLQHV XQWLO WKH PRXVH EXWWRQ LV UHOHDVHG +HUH VPRXVH8S ZKLFKWHVWVWRPDNHVXUHZHKDYHQ WH[FHHGHGWKHPD[LPXPQXPEHURIOLQHV EHIRUHFDOOLQJWKHDGGOLQH PHWKRG GHVFULEHGQH[W  public boolean mouseUp(Event evt, int x, int y) { if (currline < MAXLINES) { addline(x,y); return true; } else return false; }

7KHDGGOLQH PHWKRGLVZKHUHWKHDUUD\VRIVWDUWLQJDQGHQGLQJSRLQWVJHWXSGDWHGDQGZKHUH WKHDSSOHWLVUHSDLQWHGWRWDNHWKHQHZOLQHLQWRHIIHFW void addline(int x,int y) { starts[currline] = anchor; ends[currline] = new Point(x,y); currline++; currentpoint = null; anchor = null; repaint(); }

1RWHWKDWLQWKLVPHWKRGZHDOVRVHWFXUUHQWSRLQWDQGDQFKRUWRQXOO%\VHWWLQJWKHVHYDULDEOHV WR QXOO ZH FDQ WHVW IRU WKDW YDOXH LQ WKH SDLQW  PHWKRG WR VHH ZKHWKHU ZH QHHG WR GUDZ D FXUUHQWOLQH 3DLQWLQJWKHDSSOHWPHDQVGUDZLQJDOOWKHROGOLQHVVWRUHGLQWKHVWDUWVDQGHQGVDUUD\VDVZHOODV GUDZLQJ WKH FXUUHQW OLQH LQ SURFHVV ZKRVH HQGSRLQWV DUH LQ DQFKRU DQG FXUUHQWSRLQW UHVSHFWLYHO\  7R VKRZ WKH DQLPDWLRQ RI WKH FXUUHQW OLQH GUDZ LW LQ EOXH +HUH V WKH SDLQW PHWKRGIRUWKH/LQHVDSSOHW public void paint(Graphics g) { // Draw existing lines for (int i = 0; i < currline; i++) { g.drawLine(starts[i].x, starts[i].y, ends[i].x, ends[i].y); } // Draw current line g.setColor(Color.blue); if (currentpoint != null) g.drawLine(anchor.x, anchor.y, currentpoint.x, currentpoint.y); }

Comp-U-Learn

211

Java Programming I

,QSDLQW ZKHQZHDUHGUDZLQJWKHFXUUHQWOLQHZHWHVWILUVWWRVHHZKHWKHUFXUUHQWSRLQWLVQXOO ,ILWLVWKHDSSOHWLVQ WLQWKHPLGGOHRIGUDZLQJDOLQHVRWKHUH VQRUHDVRQWRWU\GUDZLQJDOLQH WKDWGRHVQ WH[LVW%\WHVWLQJIRUFXUUHQWSRLQW DQGE\VHWWLQJFXUUHQWSRLQWWRQXOOLQWKHDGGOLQH PHWKRG ZHFDQSDLQWRQO\ZKDWZHQHHG 7KHIROORZLQJSURJUDPZLOOLQWHJUDWHWKHDERYHVWHSV Example 9.9 /* draw lines at each click and drag */ import java.awt.Graphics; import java.awt.Color; import java.awt.Event; import java.awt.Point; public class Lines extends java.applet.Applet { final int MAXLINES = 10; Point starts[] = new Point[MAXLINES]; // starting points Point ends[] = new Point[MAXLINES]; // endingpoints Point anchor; // start of current line Point currentpoint; // current end of line int currline = 0; // number of lines public void init() { setBackground(Color.white); } public boolean mouseDown(Event evt, int x, int y) { if (currline < MAXLINES) { anchor = new Point(x,y); return true; } else { System.out.println("Too many lines."); return false; } } public boolean mouseUp(Event evt, int x, int y) { if (currline < MAXLINES) { addline(x,y); return true; }

212

Comp-U-Learn

Handling AWT Events else return false; } public boolean mouseDrag(Event evt, int x, int y) { if (currline < MAXLINES) { currentpoint = new Point(x,y); repaint(); return true; } else return false; } void addline(int x,int y) { starts[currline] = anchor; ends[currline] = new Point(x,y); currline++; currentpoint = null; anchor = null; repaint(); } public void paint(Graphics g) { // Draw existing lines for (int i = 0; i < currline; i++) { g.drawLine(starts[i].x, starts[i].y, ends[i].x, ends[i].y); } // draw current line g.setColor(Color.blue); if (currentpoint != null) g.drawLine(anchor.x,anchor.y, currentpoint.x,currentpoint.y); } }

6DYHWKHDERYHSURJUDPDV/LQHVMDYDDQGFRPSLOHLW5XQWKHIROORZLQJ+70/FRGH

7KHRXWSXWIRUWKHDERYHSURJUDPLVVKRZQLQWKHIROORZLQJILJXUH

Comp-U-Learn

213

Java Programming I

Fig 9.6

Keyboard Events $ NH\ERDUG HYHQW LV JHQHUDWHG ZKHQHYHU WKH XVHU SUHVVHV D NH\ RQ WKH NH\ERDUG %\ XVLQJ NH\ERDUGHYHQWVZHFDQJHWKROGRIWKHYDOXHVRIWKHNH\VWKHXVHUSUHVVHGWRSHUIRUPDQDFWLRQ RUPHUHO\WRJHWFKDUDFWHULQSXWIURPWKHXVHUVRIRXUDSSOHW keyDown() & keyUp() Methods

7RFDSWXUHDNH\ERDUGHYHQWXVHWKHNH\'RZQ PHWKRG public boolean keyDown(Event evt, int key) { ... }

7KHNH\VJHQHUDWHGE\NH\GRZQHYHQWV DQGSDVVHGLQWRNH\'RZQ DVWKHNH\DUJXPHQW DUH LQWHJHUVUHSUHVHQWLQJ8QLFRGHFKDUDFWHUYDOXHVZKLFKLQFOXGHDOSKDQXPHULFFKDUDFWHUVIXQFWLRQ NH\VWDEVUHWXUQVDQGVRRQ7RXVHWKHPDVFKDUDFWHUV IRUH[DPSOHWRSULQWWKHP ZHQHHG WRFDVWWKHPWRFKDUDFWHUV currentchar = (char)key;

+HUH V D VLPSOH H[DPSOH RI D NH\'RZQ  PHWKRG WKDW GRHV QRWKLQJ EXW SULQW WKH NH\ ZH MXVW W\SHGLQERWKLWV8QLFRGHDQGFKDUDFWHUUHSUHVHQWDWLRQ public boolean keyDown(Event evt, int key) { System.out.println("ASCII value: " + key); System.out.println("Character: " + (char)key); return true; }

214

Comp-U-Learn

Handling AWT Events

$VZLWKPRXVHFOLFNVHDFKNH\GRZQHYHQWDOVRKDVDFRUUHVSRQGLQJNH\XSHYHQW7RLQWHUFHSW NH\XSHYHQWVXVHWKHNH\8S PHWKRG public boolean keyUp(Event evt, int key) { ... }

Default Keys 7KH(YHQWFODVVSURYLGHVDVHWRIFODVVYDULDEOHVWKDWUHIHUWRVHYHUDOVWDQGDUGQRQDOSKDQXPHULF NH\V VXFK DV WKH DUURZ DQG IXQFWLRQ NH\V ,I RXU DSSOHW V LQWHUIDFH XVHV WKHVH NH\V ZH FDQ SURYLGHPRUHUHDGDEOHFRGHE\WHVWLQJIRUWKHVHQDPHVLQRXUNH\7\SHG PHWKRGUDWKHUWKDQ WHVWLQJIRUWKHLUQXPHULFYDOXHV7KH7DEOHEHORZVKRZVWKHVWDQGDUGHYHQWFODVVYDULDEOHVIRU YDULRXVNH\VDQGWKHDFWXDONH\VWKH\UHSUHVHQW Class variables Event.HOME Event.END Event.PGUP Event.PGDN Event.UP Event.DOWN Event.LEFT Event.RIGHT Event.F1 Event.F2 Event.F3 Event.F4 Event.F5 Event.F6 Event.F7 Event.F8 Event.F9 Event.F10 Event.F11 Event.F12

Actual Keys The Home key The End key The Page Up key The Page Down key The up arrow The down arrow The left arrow The right arrow The F1 key The F2 key The F3 key The F4 key The F5 key The F6 key The F7 key The F8 key The F9 key The F10 key The F11 key The F12 key

/HW VORRNDWDQDSSOHWWKDWGHPRQVWUDWHVNH\ERDUGHYHQWV:LWKWKLVDSSOHWZHW\SHDFKDUDFWHU DQGLWGLVSOD\VWKDWFKDUDFWHULQWKHDSSOHWZLQGRZ:HWKHQW\SLQJDQRWKHUFKDUDFWHUDWDQ\ WLPH FKDQJH WKH FKDUDFWHU V FXUUHQW GLVSOD\ 7KH DSSOHW KDV RQO\ IRXU PHWKRGV LQLW 

Comp-U-Learn

215

Java Programming I

NH\3UHVVHG  NH\5HOHDVHG  DQG NH\7\SHG  DQG SDLQW   :H  DOVR QHHG LQVWDQFH YDULDEOHV WR NHHSWUDFNRIDUHWKH[DQG\SRVLWLRQVRIWKHFXUUHQWFKDUDFWHUDQGWKHYDOXHVRIWKDWFKDUDFWHU LWVHOI +HUH VWKHLQLWLDOFODVVGHILQLWLRQ import import import import public {

java.awt.Graphics; java.awt.Event; java.awt.Font; java.awt.Color; class Keys extends java.applet.Applet

}

/HWXVVWDUWE\DGGLQJDQLQLW PHWKRG public void init() { addKeyListener(this); requestFocus(); }

7KH SDLQW  PHWKRG KHUH LV DOPRVW WULYLDO MXVW GLVSOD\ WKH FXUUHQW FKDUDFWHU DW WKH FXUUHQW SRVLWLRQ public void paint(Graphics g) { g.drawString(s,30,10); g.drawString(s1,60,10); }

7KHIROORZLQJLVWKHSURJUDPIRUWKHHYHQWVZKLFKDUHGHFODUHGDERYH Example 9.10 /* press a key to see the display on the screen */ import java.awt.*; import java.awt.event.*; import java.applet.*; public class keys extends Applet implements KeyListener { int i; String s = ""; String s1 = ""; public void init() {

216

Comp-U-Learn

Handling AWT Events addKeyListener(this); requestFocus(); } public void keyPressed(KeyEvent e) { i = e.getKeyCode(); s = e.getKeyText(i); repaint(); } public void keyReleased(KeyEvent e) { i = e.getKeyCode(); s1 = e.getKeyText(i); repaint(); } public void keyTyped(KeyEvent e) { } public void paint(Graphics g) { g.drawString(s,30,10); g.drawString(s1,60,10); } }

6DYHWKHDERYHSURJUDPDVNH\VMDYD$IWHUFRPSLOLQJWKLVILOHUXQWKHIROORZLQJ +70/ILOH

2XWSXWIRUWKHDERYHSURJUDPLVJLYHQEHORZ7\SHDQ\FKDUDFWHULQWKH.H\ERDUGDQGVHHWKH FKDUDFWHULQWKHDSSOHWLIZHXVHDQ\RWKHUVSHFLDOFKDUDFWHUWKHPHVVDJH´8QNQRZQFKDUDFWHUVµ ZLOOEHGLVSOD\HG%\3UHVVLQJ)DQG3ULQW6FUHHQEXWWRQZHJHW

Fig. 9.7 Comp-U-Learn

217

Java Programming I

3UHVV(17(5.H\WRJHWWKHILUVW´(QWHUµIRUSUHVVLQJDQGVHFRQGIRUUHOHDVLQJ

Fig. 9.8

Summary In this section, we studied about various types of Events, their definitions, the overview of the Event Handlers, Button Events, Item Events, Mouse Motion Events and Key Events. In the next session we will study about the Layout Manager and various Layouts. Going Over It Again I. Fill in the Blanks

 ,Q$SSOHW(YHQWV´6WRSµVWDQGVIRUBBBBBBBBBBBBBBB  7KHYDULRXVHYHQWVRI$SSOHWVDUHBBBBBBBBBBBBBDQGBBBBBB  7KHYDULRXVNH\ERDUG(YHQWVDUHBBBBBBBBBBBBBBBBBBBBDQGBBBBBBBB  $FWLRQ/LVWHQHUVWDQGVIRUBBBBB  ,WHP/LVWHQHUVWDQGVIRUBBBBBBBBBBBBB II. State True or False

 7KH'HVWUR\(YHQW%HORQJVWR:LQGRZ(YHQWV  7KH.H\'RZQHYHQWVEHORQJWR.H\%RDUG(YHQWV

218

Comp-U-Learn

Handling AWT Events

 0RXVH'RZQDQG0RXVH8SHYHQWVDUHSUHVHQWLQ,WHP(YHQWV  %RROHDQUHWXUQVHLWKHURU  0RXVH0RYHPHQWLQYROYHVPRXVH'UDJDQG0RXVH0RYH III. One line Answers

 :KDWLVDQ(YHQW"  :KDWLVWKHXVHRI(YHQWLQSURJUDPPLQJ"  :KDWDUHWKHPDLQ(YHQWVLQ$SSOHWV"  :KDWDUHWKHGLIIHUHQFH0RXVH(YHQWDQGWKH,WHP(YHQWV"  /LVWWKHGLIIHUHQFHEHWZHHQNH\7\SHGDQG.H\SUHVVHGDQG5HOHDVH

Comp-U-Learn

219

Session 10

More About AWT

On Completion of this Session We will be able to understand...

) AWT Layout Managers ) Panels in AWT ) Frames in AWT ) Menus in AWT ) AWT Dialog boxes

In This Session...



Layout Managers



Flow Layout



Border Layout



Card Layout



Grid Layout



Grid Bag Layout



Insets



Panels



Frames



Menus



Menus Actions



Dialog Box

More About AWT

Layout Managers 7KH /D\RXW 0DQDJHU·V FODVVHV DUH VHW RI FODVVHV WKDW KHOS WR SRVLWLRQ WKH FRPSRQHQWV LQ D FRQWDLQHU8QOLNHRWKHUZLGRZLQJV\VWHPVZKHUHWKHXVHULQWHUIDFHFRPSRQHQWVFDQEHODLGRXW XVLQJ KDUG FRGHG SL[HO PHDVXUHPHQWV -DYD SURYLGHV /D\RXW 0DQDJHUV WR SRVLWLRQ WKH FRPSRQHQWV 7KLV LV EHFDXVH -DYD LV GHVLJQHG WR EH SODWIRUP LQGHSHQGHQW DQG DUUDQJLQJ XVHU LQWHUIDFH FRPSRQHQWV XVLQJ SL[HO PHDVXUHPHQWV PD\ QRW SURGXFH WKH GHVLUHG UHVXOW LQ DOO V\VWHPV 7KH /D\RXW 0DQDJHU GHWHUPLQHV KRZ $:7 FRPSRQHQWV DUH G\QDPLFDOO\ DUUDQJHG RQ WKH VFUHHQ (DFK SDQHO RQ WKH VFUHHQ FDQ KDYH LWV RZQ OD\RXW PDQDJHU %\ QHVWLQJ SDQHOV ZLWKLQ SDQHOVDQGXVLQJWKHDSSURSULDWHOD\RXWPDQDJHUIRUHDFKRQHZHFDQRIWHQDUUDQJHRXU8,WR JURXSDQGDUUDQJHFRPSRQHQWVLQDZD\WKDWLVERWKIXQFWLRQDOO\XVHIXODQGWKDWORRNVJRRGRQ DYDULHW\RISODWIRUPVDQGZLQGRZLQJV\VWHPV 7KH$:7SURYLGHVILYHEDVLFOD\RXWPDQDJHUV ♦ ♦ ♦ ♦ ♦

FlowLayout BorderLayout CardLayout GridLayout GridBagLayout.

7RFUHDWHDOD\RXWPDQDJHUIRUDJLYHQSDQHOFUHDWHDQLQVWDQFHRIWKDWOD\RXWPDQDJHUDQGWKHQ XVH WKH setLayout() PHWKRG IRU WKDW SDQHO 6HWWLQJ WKH GHIDXOW OD\RXW PDQDJHU LV EHVW GRQH GXULQJ WKH DSSOHW V LQLWLDOL]DWLRQ $IWHU WKH OD\RXW PDQDJHU LV VHW ZH FDQ VWDUW DGGLQJ FRPSRQHQWVWRWKHSDQHO2QFHWKHOD\RXWPDQDJHUIRUWKHFRQWDLQHULVVHWWKH8,FRPSRQHQWV DGGHGWRLWZRXOGEHDUUDQJHGGHSHQGLQJXSRQWKHOD\RXWVSHFLILHG %\GHIDXOWHYHU\&RQWDLQHUREMHFWKDVDOD\RXWPDQDJHUREMHFWWKDWFRQWUROVLWVOD\RXW)RUSDQHO REMHFWVWKH)ORZ/D\RXWLVWKHGHIDXOWOD\RXW)RUZLQGRZREMHFWVWKHGHIDXOWOD\RXWPDQDJHULV DQLQVWDQFHRIWKH%RUGHU/D\RXWFODVV

Note If we pass a value as null instead of the object of the layout manager in the setLayout() method, we can disable the active layout manager.

Flow Layout )ORZ /D\RXW LV WKH GHIDXOW OD\RXW PDQDJHU 7KLV LV WKH OD\RXW WKDW WKH H[DPSOHV LQ SUHFHGLQJ VHVVLRQVKDYHXVHG7KLV)ORZ/D\RXWFODVVLPSOHPHQWVDVLPSOHOD\RXWVW\OHZKLFKLVVLPLODUWR Comp-U-Learn

223

Java Programming I

KRZZRUGVIORZLQDWH[WHGLWRU)ORZOD\RXWDUUDQJHVFRPSRQHQWVIURPOHIWWRULJKWLQURZV 7KHURZVDUHDOLJQHGOHIWULJKWRUFHQWHUHG7KLVLVWKHPRVWEDVLFRIOD\RXWV7RFUHDWHDEDVLF IORZOD\RXWZLWKDFHQWHUHGDOLJQPHQWXVHWKHIROORZLQJOLQHRIFRGHLQRXUSDQHO VLQLWLDOL]DWLRQ EHFDXVH WKLV LV WKH GHIDXOW SDQHO OD\RXW ZH GRQ W QHHG WR LQFOXGH WKLV OLQH LI WKDW LV WKH LQWHQWLRQ  setLayout(new FlowLayout());

:LWKWKHOD\RXWVHWWKHRUGHULQZKLFKZHDGGHOHPHQWVWRWKHOD\RXWGHWHUPLQHVWKHLUSRVLWLRQ %\GHIDXOWWKH)ORZOD\RXWDOLJQPHQWZLOOEH&(17(5 7RFUHDWHDIORZOD\RXWZLWKDQDOLJQPHQWRWKHUWKDQFHQWHUHGDGGWKHFlowLayout.RIGHTRU )ORZ/D\RXW/()7DVDQDUJXPHQWDVIROORZV setLayout(new FlowLayout(FlowLayout.LEFT));

:HFDQDOVRVHWKRUL]RQWDODQGYHUWLFDOJDSYDOXHVE\XVLQJIORZOD\RXWV7KHJDSLVWKHQXPEHU RISL[HOVEHWZHHQFRPSRQHQWVLQDSDQHOE\GHIDXOWWKHKRUL]RQWDODQGYHUWLFDOJDSYDOXHVDUH WKUHHSL[HOVZKLFKFDQEHYHU\FORVHLQGHHG+RUL]RQWDOJDSVSUHDGVRXWFRPSRQHQWVWRWKHOHIW DQG WR WKH ULJKW YHUWLFDO JDS VSUHDGV WKHP WR WKH WRS DQG ERWWRP RI HDFK FRPSRQHQW $GG LQWHJHUDUJXPHQWVWRWKHIORZOD\RXWFRQVWUXFWRUWRLQFUHDVHWKHJDS)RUH[DPSOHWRDJDSRI SRLQWVLQWKHKRUL]RQWDODQGLQWKHYHUWLFDOGLUHFWLRQVZHKDYHWRFRQVWUXFWWKH)ORZOD\RXW XVLQJWKHIROORZLQJV\QWD[ setLayout(new FlowLayout(FlowLayout.LEFT, 30, 10));

7KHIROORZLQJH[DPSOHZLOOH[SODLQKRZWKHFRPSRQHQWVDUHDUUDQJHGLQWKH)ORZ/D\RXW Example 10.1 import java.awt.*; import java.applet.*; public class Flowtest extends Applet { public void init() { setLayout(new FlowLayout(FlowLayout.LEFT)); add(new Button("One")); add(new Button("Two")); add(new Button("Three")); add(new Button("Four")); add(new Button("Five")); } }

224

Comp-U-Learn

More About AWT

&RPSLOHWKLVILOH)ORZWHVWMDYDXVLQJMDYDFFRPSLOHUWKHQUXQWKHIROORZLQJ)ORZWHVWKWPO

Fig 10.1

Border Layout :KHQZHDGGDFRPSRQHQWWRDSDQHOWKDWXVHVDERUGHUOD\RXWZHLQGLFDWHLWVSODFHPHQWDVD JHRJUDSKLFGLUHFWLRQLQWKHVHQVHQRUWKVRXWKHDVWZHVWRUFHQWHU7KHFRPSRQHQWVDURXQGDOO WKHHGJHVDUHODLGRXWZLWKDVPXFKVL]HDVWKH\QHHGWKHFRPSRQHQWLQWKHFHQWHULIDQ\JHWV DQ\VSDFHOHIWRYHU7RXVHDERUGHUOD\RXWZHFUHDWHLWDVZHGRWKHRWKHUOD\RXWVWKHQZHDGG WKH LQGLYLGXDO FRPSRQHQWV ZLWK D VSHFLDO add() PHWKRG WKDW KDV WZR DUJXPHQWV 7KH ILUVW DUJXPHQWLVDVWULQJLQGLFDWLQJWKHSRVLWLRQRIWKHFRPSRQHQWZLWKLQWKHOD\RXWDQGWKHVHFRQG LVWKHFRPSRQHQWWRDGG)RUH[DPSOHLIZHZDQWWRLQFOXGHD7H[W)LHOGLQRXU%RUGHU/D\RXW XVHWKHIROORZLQJFRGHDIWHUFUHDWLQJWKHLQVWDQFHRIWKH%RUGHU/D\RXWFODVV add("North", new TextField("Title", 50));

:HFDQDOVRXVHWKLVIRUPRIadd()IRUWKHRWKHUOD\RXWPDQDJHUVWKHVWULQJDUJXPHQWZLOOMXVW EH LJQRUHG LI LW V QRW QHHGHG %RUGHU OD\RXWV FDQ DOVR KDYH KRUL]RQWDO DQG YHUWLFDO JDSV 1RWH WKDWWKHQRUWKDQGVRXWKFRPSRQHQWVH[WHQGDOOWKHZD\WRWKHHGJHRIWKHSDQHOVRWKHJDSZLOO UHVXOWLQOHVVYHUWLFDOVSDFHIRUWKHHDVWULJKWDQGFHQWHUFRPSRQHQWV7RDGGJDSVWRDERUGHU OD\RXWLQFOXGHWKRVHSL[HOYDOXHVLQWKHFRQVWUXFWRUDVZLWKWKHRWKHUOD\RXWPDQDJHUV setLayout(new BorderLayout(10, 10));

7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKHXVDJHRIWKH%RUGHUOD\RXW

Comp-U-Learn

225

Java Programming I

Example 10.2 import java.awt.*; import java.applet.*; public class Bordertest extends Applet { public void init() { setLayout(new BorderLayout()); add("North", new Button("One")); add("East", new Button("Two")); add("South", new Button("Three")); add("West", new Button("Four")); add("Center", new Button("Five")); add(new Button("Six")); } }

$IWHU FRPSLOLQJ WKH DERYH FRGH UXQ WKH IROORZLQJ +70/ FRGH :H FDQ JHW WKH RXWSXW DV VKRZQLQWKH)LJXUH&KHFNRXWKRZWKHEXWWRQVDUHDUUDQJHG

Fig 10.2 226

Comp-U-Learn

More About AWT

Card Layout &DUGOD\RXWVDUHXVHGWRSURGXFHVOLGHVKRZVRIFRPSRQHQWVRQHDWDWLPH:KHQZHFUHDWHD FDUGOD\RXWWKH FRPSRQHQWVZHDGGWRWKH RXWHU SDQHOZLOOEHRWKHUFRQWDLQHUFRPSRQHQWV² XVXDOO\RWKHUSDQHOV:HFDQWKHQXVHGLIIHUHQWOD\RXWVIRUWKRVHLQGLYLGXDOFDUGVVRWKDW HDFK VFUHHQ KDV LWV RZQ ORRN &DUGV LQ D FDUG OD\RXW DUH GLIIHUHQW SDQHOV DGGHG RQH DW D WLPH DQG GLVSOD\HGRQHDWDWLPHDVZHOO :KHQZHDGGHDFKFDUGWRWKHSDQHOZHFDQJLYHLWDQDPH7KHQWRIOLSEHWZHHQWKHFRQWDLQHU FDUGVZHXVHPHWKRGVGHILQHGLQWKHCardLayoutFODVVWRPRYHWRDQDPHGFDUGPRYHIRUZDUG RUEDFNRUPRYHWRWKHILUVWFDUGRUWRWKHODVWFDUG7\SLFDOO\ZHZLOOKDYHDVHWRIEXWWRQVWKDW FDOOWKHVHPHWKRGVWRPDNHQDYLJDWLQJWKHFDUGOD\RXWHDVLHU+HUHLVDVLPSOHFRGHWKDWFUHDWHVD FDUGOD\RXWFRQWDLQLQJWKUHHFDUGV setLayout(new CardLayout()); //add the cards Panel one = new Panel(); add("first", one); Panel two = new Panel(); add("second", two); Panel three = new Panel(); add("third", three); // move around show(this, "second"); //go to the card named "second" show(this, "third); //go to the card named "third" previous(this)/next(this); //go to the next or previous card first(this)/last(this); // got to the first or last card

+HUH WKH VKRZ  ILUVW  ODVW  QH[W  DQG SUHYLRXV  DUH WKH PHWKRGV ZKLFK DUH XVHG IRU WKH QDYLJDWLRQEHWZHHQWKH&DUGV,QWKHVXFFHHGLQJVHFWLRQZHDUHJRLQJWROHDUQDERXWSDQHOV

Grid Layouts 8VLQJDJULGOD\RXWZHSRUWLRQRIIWKHGLVSOD\DUHDRIWKHSDQHOLQWRURZVDQGFROXPQV(DFK FRPSRQHQWZHWKHQDGGWRWKHSDQHOLVSODFHGLQDFHOORIWKHJULGVWDUWLQJIURPWKHWRSURZDQG SURJUHVVLQJ WKURXJK HDFK URZ IURP OHIW WR ULJKW KHUH V ZKHUH WKH RUGHU RI FDOOV WR WKH DGG PHWKRGDUHYHU\UHOHYDQWWRKRZWKHVFUHHQLVODLGRXW  7R FUHDWH D JULG OD\RXW LQGLFDWH WKH QXPEHU RI URZV DQG FROXPQV ZH ZDQW WKH JULG WR KDYH ZKHQZHFUHDWHDQHZLQVWDQFHRIWKH*ULG/D\RXWFODVV7KHV\QWD[WRFUHDWHD*ULG/D\RXWZLWK WKUHHURZVDQGFROXPQVLV setLayout(new GridLayout(3, 3));

Comp-U-Learn

227

Java Programming I

*ULG OD\RXWV FDQ DOVR KDYH D KRUL]RQWDO DQG YHUWLFDO JDS EHWZHHQ FRPSRQHQWV WR FUHDWH JDSV DGGWKRVHSL[HOYDOXHV)RUH[DPSOHWKLVFRGHFUHDWHVDJULGOD\RXWZLWKURZVFROXPQVD SL[HOKRUL]RQWDOJDSDQGDSL[HOYHUWLFDOJDS setLayout(new GridLayout(3, 3, 10, 30));

7KHIROORZLQJH[DPSOHGHPRQVWUDWHVZHWKDWKRZWKH8,FRPSRQHQWVDUHDUUDQJHGLQWKH*ULG /D\RXW Example 10.3 import java.awt.*; import java.applet.*; public class Gridtest extends Applet { public void init() { setLayout(new GridLayout(3,2,10,10)); add(new Button("One")); add(new Button("Two")); add(new Button("Three")); add(new Button("Four")); add(new Button("Five")); add(new Button("Six")); } }

&RPSLOH WKH DERYH -DYD SURJUDP DQG UXQ WKH IROORZLQJ *ULGWHVWKWPO ILOH XVLQJ WKH DSSOHWYLHZHU7KHRXWSXWLVDVVKRZQLQILJXUH

Fig 10.3

228

Comp-U-Learn

More About AWT

Grid Bag Layout /LNH*ULG/D\RXWV*ULGEDJOD\RXWVDOORZXVWRDUUDQJHRXUFRPSRQHQWVLQDJULGOLNHOD\RXW +RZHYHUJULGEDJOD\RXWVDOVRDOORZXVWRFRQWUROWKHVSDQRILQGLYLGXDOFHOOVLQWKHJULGWKH SURSRUWLRQVEHWZHHQWKHURZVDQGFROXPQVDQGWKHDUUDQJHPHQWRIFRPSRQHQWVLQVLGHFHOOVLQ WKHJULG 7R FUHDWH D JULG EDJ OD\RXW ZH DFWXDOO\ XVH WZR FODVVHV GridBagLayout ZKLFK SURYLGHV WKH RYHUDOO OD\RXW PDQDJHU DQG GridBagConstraints ZKLFK GHILQHV WKH SURSHUWLHV RI HDFK FRPSRQHQWLQWKHJULGLWVSODFHPHQWGLPHQVLRQVDOLJQPHQWDQGVRRQ,WLVWKHUHODWLRQVKLS EHWZHHQWKHJULGEDJWKHFRQVWUDLQWVDQGHDFKFRPSRQHQWWKDWGHILQHVWKHRYHUDOOOD\RXW ,QLWVPRVWJHQHUDOIRUPFUHDWLQJDJULGEDJOD\RXWLQYROYHVWKHIROORZLQJVWHSV ♦ Creating a GridBagLayout object and defining it as the current layout manager, is the same as in other layout managers. ♦ Creating a new instance of GridBagConstraints. ♦ Setting up the constraints for a component ♦ Telling the layout manager about the component and its constraints. ♦ Adding the component to the panel. ,WLQYROYHVDVLPSOHIRXUVWHSSURFHVV Step 1: Design the Grid

7KH ILUVW SODFH WR VWDUW LQ WKH JULG EDJ OD\RXW LV RQ SDSHU 6NHWFKLQJ RXW RXU 8, GHVLJQ EHIRUHKDQG EHIRUH ZH ZULWH HYHQ D VLQJOH OLQH RI FRGH ZLOO KHOS HQRUPRXVO\ LQ WKH ORQJ UXQ ZLWKWU\LQJWRILJXUHRXWZKHUHHYHU\WKLQJJRHV /HW·VNHHSLQPLQGDVZHGUDZRXUJULGWKDWHDFKFRPSRQHQWPXVWKDYHLWVRZQFHOO:HFDQQRW SXW PRUH WKDQ RQH FRPSRQHQW LQWR WKH VDPH FHOO 7KH UHYHUVH LV QRW WUXH +RZHYHU RQH FRPSRQHQWFDQVSDQPXOWLSOHFHOOVLQWKH[RU\GLUHFWLRQV DV2.EXWWRQLQWKHERWWRPURZ ZKLFKVSDQVWZRFROXPQV $OVRODEHOWKHFHOOVZLWKWKHLU[DQG\FRRUGLQDWHV Step 2: Create a Grid in Java

/HW VJREDFNWR-DYDDQGVWDUWLPSOHPHQWLQJWKHOD\RXWZH YHMXVWGUDZQ,QLWLDOO\ZH UHJRLQJWR IRFXVH[FOXVLYHO\RQWKHOD\RXW²JHWWLQJWKHJULGDQGWKHSURSRUWLRQVULJKW/HWXVDOVRFUHDWHD KHOSHU PHWKRG WKDW WDNHV VHYHUDO YDOXHV DQG VHWV WKH FRQVWUDLQWV IRU WKRVH YDOXHV buildConstraints() WDNHV VHYHQ DUJXPHQWV D GridBagConstraints REMHFW DQG VL[ LQWHJHUV UHSUHVHQWLQJ WKH GridBagConstraints LQVWDQFH YDULDEOHV gridx gridy gridwidth gridheight weightxDQGweighty

Comp-U-Learn

229

Java Programming I void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) { gbc.gridx = gx; gbc.gridy = gy; gbc.gridwidth = gw; gbc.gridheight = gh; gbc.weightx = wx; gbc.weighty = wy; }

1RZOHW VPRYHRQWRWKHinit()PHWKRGZKHUHDOOWKHOD\RXWDFWXDOO\RFFXUV public void init() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(gridbag); constraints.fill = GridBagConstraints.BOTH; }

FRQVWUDLQWVILOOiVWKHUHVRWKDWWKHFRPSRQHQWVZLOOILOOWKHHQWLUHFHOOLQZKLFKWKH\ UHFRQWDLQHG ZKLFK PDNHV LW HDVLHU WR VHH ZKDW V JRLQJ RQ 1RZ ZH OO DGG WKH EXWWRQ SODFHKROGHUV WR WKH OD\RXW ZH OOXVHEXWWRQVDVSODFHKROGHUVIRUWKHDFWXDO8,HOHPHQWV 7KLVFRGHZLOOJRLQWRWKH init()PHWKRGMXVWDIWHUWKHsetLayoutOLQH // Name label buildConstraints(constraints, 0, 0, 1, 1, 100, 100); Button label1 = new Button("Name:"); gridbag.setConstraints(label1, constraints); add(label1);

7KHVH IRXU OLQHV VHW XS WKH FRQVWUDLQWV IRU DQ REMHFW FUHDWH D QHZ EXWWRQ DWWDFK WKRVH FRQVWUDLQWVWRWKDWEXWWRQDQGWKHQDGGLWWRWKHSDQHO1RWHWKDWFRQVWUDLQWVIRUDFRPSRQHQW DUHVWRUHGLQWKHGridBagConstraintsREMHFWVRWKHFRPSRQHQWGRHVQ WHYHQKDYHWRH[LVWWRVHW XS LWV FRQVWUDLQWV :KDW DUH WKH YDOXHV IRU WKH FRQVWUDLQWV WKDW ZH YH SOXJJHG LQWR WKH KHOSHU PHWKRGbuildConstraints" 7KHILUVWWZRLQWHJHUDUJXPHQWVDUHWKHgridxDQGgridyYDOXHVRIWKHFRQVWUDLQWV7KHVHDUHWKH FHOO FRRUGLQDWHV RI WKH FHOO WKDW FRQWDLQV WKLV FRPSRQHQW :LWK WKH FHOOV QHDUO\ QXPEHUHG RQ SDSHUDOOZHKDYHWRGRLVSOXJLQWKHULJKWYDOXHV1RWHWKDWLIZHKDYHDFRPSRQHQWWKDWVSDQV PXOWLSOHFHOOVWKHFHOOFRRUGLQDWHVDUHWKRVHRIWKHFHOOLQWKHWRSOHIWFRUQHU+HUHWKLVEXWWRQLV LQWKHWRSOHIWFRUQHUVRLWVgridxDQGgridy WKHILUVWWZRDUJXPHQWVWRbuildConstraints() DUH 0DQG0UHVSHFWLYHO\ 7KH VHFRQG WZR LQWHJHU DUJXPHQWV DUH WKH gridwidth DQG gridheight 7KHVH DUH QRW WKH SL[HO ZLGWKV DQG KHLJKWV RI WKH FHOOV UDWKHU WKH\ DUH WKH QXPEHU RI FHOOV WKLV FRPSRQHQW VSDQV 230

Comp-U-Learn

More About AWT

gridwidthIRUWKHFROXPQVDQGgridheightIRUWKHURZV+HUHWKLVFRPSRQHQWVSDQVRQO\RQH FHOOVRWKHYDOXHVIRUERWKDUH17KHODVWWZRLQWHJHUDUJXPHQWVDUHIRUweightxDQGweighty 7KHVHDUHXVHGWRVHWXSWKHSURSRUWLRQVRIWKHURZVDQGFROXPQV²LHKRZZLGHRUGHHSWKH\ ZLOOEH $IWHUWKHFRQVWUDLQWVKDYHEHHQEXLOWZHFDQDWWDFKWKHPWRDQREMHFWXVLQJWKHsetConstraints() PHWKRGVetConstraints()ZKLFKLVDPHWKRGGHILQHGLQGridBagLayoutWDNHVWZRDUJXPHQWV WKH FRPSRQHQW KHUH D EXWWRQ  DQG WKH FRQVWUDLQWV IRU WKDW EXWWRQ )LQDOO\ ZH FDQ DGG WKH EXWWRQ WR WKH SDQHO $IWHU ZH YH VHW DQG DVVLJQHG WKH FRQVWUDLQWV WR RQH FRPSRQHQW ZH FDQ UHXVH WKDW GridBagConstraints REMHFW WR VHW XS WKH FRQVWUDLQWV IRU WKH QH[W REMHFW 7KLV HIIHFWLYHO\ PHDQV GXSOLFDWLQJ WKRVH IRXU OLQHV IRU HDFK FRPSRQHQW LQ WKH JULG ZLWK GLIIHUHQW YDOXHVIRUWKHbuildConstraints()PHWKRG 7KH VHFRQG FHOO ZH OO DGG LV WKH RQH WKDW ZLOO KROG WKH WH[W ER[ IRU WKH QDPH 7KH FHOO FRRUGLQDWHVIRUWKLVRQHDUH1,0. buildConstraints(constraints, 1, 0, 1, 1, 100, 100);

7KHQH[WWZRFRPSRQHQWVDUHDODEHODQGDWH[WILHOG buildConstraints(constraints, 0, 1, 1, 1, 100, 100); buildConstraints(constraints, 1, 1, 1, 1, 100, 100);

2.EXWWRQVSDQVWZRFHOOV 7KHgridweightLV2 LWVSDQVFHOOV DQGWKHgridheightLV1 LQWKH ERWWRPURZRIWKHSDQHO+HUHWKHFHOOFRRUGLQDWHVDUHWKHOHIWDQGWRSPRVWFHOOZKHUHWKHVSDQ VWDUWV 0,2  buildConstraints(constraints, 0, 2, 2, 1, 100, 100);

Step 3: Determine the Proportions

7KHQH[WVWHSLVWRGHWHUPLQHWKHSURSRUWLRQVRIWKHURZVDQGFROXPQVLQUHODWLRQWRRWKHUURZV DQGFROXPQV)RUH[DPSOHLQWKLVFDVHZH OOZDQWWKHODEHOV QDPHDQGSDVVZRUG WRWDNHXSOHVV VSDFHWKDQWKHWH[WER[HV$QGZHPLJKWZDQWWKH2.EXWWRQDWWKHERWWRPWREHRQO\KDOIWKH KHLJKWRIWKHWZRWH[WER[HVDERYHLW:HDUUDQJHWKHSURSRUWLRQVRIWKHFHOOVZLWKLQRXUOD\RXW XVLQJWKHweightxDQGweightyFRQVWUDLQWV 7KHHDVLHVWZD\WRWKLQNRIweightxDQGweightyLVWKDWWKHLUYDOXHVDUHHLWKHUSHUFHQWDJHVRI WKH WRWDO ZLGWK DQG KHLJKW RI WKH SDQHO RU ]HUR LI WKH ZHLJKW RU KHLJKW KDV EHHQ VHW E\ VRPH RWKHUFHOO7KHYDOXHVRIweightxDQGweightyIRUDOORXUFRPSRQHQWVWKHUHIRUHVKRXOGVXPXS WR100&HOOVWKDWVSDQPXOWLSOHURZVRUFROXPQVVKRXOGDOZD\VEH0LQWKHGLUHFWLRQWKH\VSDQ %H\RQGWKDWLW VVLPSO\DTXHVWLRQRISLFNLQJDFHOOWRKDYHDYDOXHDQGWKHQDOOWKHRWKHUFHOOVLQ WKDWURZRUFROXPQVVKRXOGEH0 Comp-U-Learn

231

Java Programming I

Step 4: Add and Arrange the Components

:LWK WKH OD\RXW DQG SURSRUWLRQV LQ SODFH QRZ ZH FDQ UHSODFH WKH EXWWRQ SODFHKROGHUV ZLWK DFWXDOODEHOVDQGWH[WILHOGV:HDOVRQHHGWRDGGFRQVWUDLQWVWKDWDUUDQJHWKHFRPSRQHQWVLQVLGH WKHFHOO7KHUHDUHWZRRIWKHPfillDQGanchor 7KH fill FRQVWUDLQW GHWHUPLQHV IRU FRPSRQHQWV WKDW FDQ VWUHWFK LQ HLWKHU GLUHFWLRQ OLNH WH[W ER[HV DQGEXWWRQV LQZKLFKGLUHFWLRQWRVWUHWFKfillFDQKDYHRQH RIIRXUYDOXHV GHILQHG DV FODVVYDULDEOHVLQWKHGridBagConstraintsFODVV ♦ GridBagConstraints.BOTH, which stretches the component to fill the cell in both directions. ♦ GridBagConstraints.NONE, which causes the component to be displayed in its smallest size. ♦ GridBagConstraints.HORIZONTAL, which stretches the component in the horizontal direction. ♦ GridBagConstraints.VERTICAL, which stretches the component in the vertical direction. %\GHIDXOWWKHfillFRQVWUDLQWIRUDOOFRPSRQHQWVLVNONE7KHVHFRQGFRQVWUDLQWWKDWDIIHFWV KRZDFRPSRQHQWDSSHDUVLQWKHFHOOLVanchor7KLVFRQVWUDLQWDSSOLHVRQO\WRFRPSRQHQWVWKDW DUHQ WILOOLQJWKHZKROHFHOODQGLWWHOOVWKH$:7ZKHUHLQVLGHWKHFHOOWRSODFHWKHFRPSRQHQW 7KHSRVVLEOHYDOXHVIRUWKHanchorFRQVWUDLQWDUHGridBagConstraints.CENTERZKLFKDOLJQV WKHFRPSRQHQWERWKYHUWLFDOO\DQGKRUL]RQWDOO\LQVLGHWKHFHOORURQHRIHLJKWGLUHFWLRQYDOXHV GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagConstraints.EAST, GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHWEST, GridBagConstraints.WEST, or GridBagConstraints.NORTHWEST.

7KHGHIDXOWYDOXHRIanchorLVGridBagConstraints.CENTER:HVHWWKHVHFRQVWUDLQWVLQWKH VDPH ZD\ DV ZH GLG WR DOO WKH RWKHU RQHV E\ FKDQJLQJ LQVWDQFH YDULDEOHV LQ WKH GridBagConstraints REMHFW +HUH ZH FDQ FKDQJH WKH GHILQLWLRQ RI buildConstraints() WR WDNH WZRPRUHDUJXPHQWV WKH\ UHintV RUZHFRXOGMXVWVHWWKHPLQWKHERG\RIWKHinit()PHWKRG /HWXVPDNHWKUHHFKDQJHVWRWKHfillVDQGanchorVRIWKHFRPSRQHQWV ♦ The labels will have no fill and will be aligned to east (so they hug the right side of the cell). 232

Comp-U-Learn

More About AWT

♦ The text fields will be filled horizontally (so they start one line high, but stretch to the width of the cell). ♦ The button will have no fill and will be center aligned. 1RZ WKH IROORZLQJ H[DPSOH  LOOXVWUDWHV WKH WRWDO FRYHUDJH RI WKH DERYH VWHSV DQG JLYH DQ LGHDRIWKHJULGEDJOD\RXW Example 10.4 import import public { void

java.awt.*; java.applet.*; class Bagtest extends Applet buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy)

{ gbc.gridx = gx; gbc.gridy = gy; gbc.gridwidth = gw; gbc.gridheight = gh; gbc.weightx = wx; gbc.weighty = wy; } public void init() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(gridbag); // Name label buildConstraints(constraints, 0, 0, 1, 1, 10, 40); constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.EAST; Label label1 = new Label("Name:", Label.LEFT); gridbag.setConstraints(label1, constraints); add(label1); // Name text field buildConstraints(constraints, 1, 0, 1, 1, 90, 0); constraints.fill = GridBagConstraints.HORIZONTAL; TextField tfname = new TextField(); gridbag.setConstraints(tfname, constraints); add(tfname); // password label

Comp-U-Learn

233

Java Programming I buildConstraints(constraints, 0, 1, 1, 1, 0, 40); constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.EAST; Label label2 = new Label("Password:", Label.LEFT); gridbag.setConstraints(label2, constraints); add(label2); // password text field buildConstraints(constraints, 1, 1, 1, 1, 0, 0); constraints.fill = GridBagConstraints.HORIZONTAL; TextField tfpass = new TextField(); tfpass.setEchoCharacter('*'); gridbag.setConstraints(tfpass, constraints); add(tfpass); // OK Button buildConstraints(constraints, 0, 2, 2, 1, 0, 20); constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.CENTER; Button okb = new Button("OK"); gridbag.setConstraints(okb, constraints); add(okb); } }

$IWHUFRPSLOLQJWKLV%DJWHVWMDYDILOHUXQWKHIROORZLQJ+70/ILOHDQGVHHWKHRXWSXW:HJHW WKHRXWSXWDVVKRZQLQWKHILJXUH

Fig 10.4 234

Comp-U-Learn

More About AWT

ipadx and ipady

7KHVH WZR FRQVWUDLQWV FRQWURO WKH SDGGLQJ  WKDW LV WKH H[WUD VSDFH DURXQG DQ LQGLYLGXDO FRPSRQHQW %\ GHIDXOW QR FRPSRQHQWV KDYH H[WUD VSDFH DURXQG WKHP ipadx DGGV VSDFH WR HLWKHUVLGHRIWKHFRPSRQHQWDQGipadyDGGVLWDERYHDQGEHORZ

Insets ,QVHWVGHWHUPLQHWKHDPRXQWRIVSDFHEHWZHHQWKHHGJHVRIDSDQHODQGWKDWSDQHO VFRPSRQHQWV 7RLQFOXGHDQLQVHWRYHUULGHWKHinsets()PHWKRGLQRXUFODVV (LWKHUWKHAppletFODVVRURWKHU FODVVWKDWVHUYHVDVDSDQHO ,QVLGHWKHinsets()PHWKRGFUHDWHDQHZInsetsREMHFWZKHUHWKH FRQVWUXFWRUWRWKHInsetsFODVVWDNHVIRXULQWHJHUYDOXHVUHSUHVHQWLQJWKHLQVHWVRQWKHWRSOHIW ERWWRPDQGULJKWRIWKHSDQHO7KHinsets()PHWKRGVKRXOGWKHQUHWXUQWKDWInsetsREMHFW+HUH V VRPHFRGHWRDGGLQVHWVIRUDJULGOD\RXWWRWKHWRSDQGERWWRPDQGWRWKHOHIWDQGULJKW public Insets insets() { return new Insets(10, 30, 10, 30); }

7KHDUJXPHQWVWRWKHInsetsFRQVWUXFWRUSURYLGHSL[HOLQVHWVIRUWKHWRSERWWRPOHIWDQGULJKW HGJHV RI WKH SDQHO UHVSHFWLYHO\ 7KH IROORZLQJ H[DPSOH LOOXVWUDWHV WKH LQVHWV ZLWK  WKH ERUGHU OD\RXW 7KLVH[DPSOHLVVDPHDVWKH%RUGHUWHVWMDYDH[DPSOHH[FHSWZLWKWKH,QVHWV  Example 10.5 import java.awt.*; import java.applet.*; import java.util.*; public class Insettest extends Applet { public void init() { setLayout(new BorderLayout()); add("North", new Button("One")); add("East", new Button("Two")); add("South", new Button("Three")); add("West", new Button("Four")); add("Center", new Button("Five")); } public Insets insets() { return new Insets(10,10,10,10); } }

Comp-U-Learn

235

Java Programming I

$IWHUFRPSLOLQJWKLV,QVHWWHVWMDYDILOHUXQWKHIROORZLQJ,QVHWWHVWKWPOILOH

Fig.10.5 7KHIROORZLQJ ILJXUH  VKRZV WKH RXWSXW RI WKH DERYH SURJUDP &RPSDUH WKLV RXWSXW ZLWK WKHRXWSXWRIWKH%RUGHUWHVWMDYDSURJUDP ILJXUH ZHFDQHDVLO\XQGHUVWDQGWKHXVDJHRI WKH,QVHWV

Panels 7KH SDQHO FODVV LV D QRQDEVWUDFW UHFXUVLYHO\ QHVWDEOH FRQWDLQHU 7KH SDQHO FDQ FRQWDLQ 8, FRPSRQHQWVDQGRWKHUFRQWDLQHUV$SDQHOREMHFWFDQEHFRQVWUXFWHGXVLQJWKHIROORZLQJFRGH Panel p1= new Panel();

7KHDGG PHWKRGRIWKHFRQWDLQHUFODVVFDQEHXVHGWRDGGDQ\FRPSRQHQWWRWKHSDQHO/LNH WKHDOOFRQWDLQHUWKHOD\RXWRIWKH3DQHOFDQEHVHWXVLQJWKHVHW/D\RXW PHWKRG7KHGHIDXOW OD\RXWIRUWKH3DQHOLV)ORZ/D\RXW 7KHIROORZLQJH[DPSOHGHPRQVWUDWHVWKHSDQHOZLWK WKH&DUG/D\RXW Example 10.6 import java.awt.*; import java.applet.*; public class Paneltest extends Applet { Checkbox w1, w2, s1, m1;

236

Comp-U-Learn

More About AWT Panel p1; CardLayout cd; public void init() { Button b1= new Button b2= new add(b1); add(b2);

Button("Windows"); Button("Others");

cd = new CardLayout(); p1 = new Panel(); p1.setLayout(cd); w1 w2 s1 m1

= = = =

new new new new

Checkbox("Windows 95", null,true); Checkbox("Windows NT"); Checkbox("Solaris"); Checkbox("mac");

Panel p2 = new Panel(); p2.add(w1); p2.add(w2); Panel p3 = new Panel(); p3.add(s1); p3.add(m1); p1.add("Windows",p2); p1.add("Others",p3); add(p1); } public boolean mouseDown(Event e, int x, int y) { cd.next(p1); return true; } public boolean action(Event e, Object o) { if(e.target instanceof Button) { if(o.equals("Windows")) cd.show(p1,"Windows"); else if(o.equals("Others")) cd.show(p1,"Others"); return true; } return false; } }

Comp-U-Learn

237

Java Programming I

&RPSLOH WKH DERYH 3DQHOWHVWMDYD ILOH DQG UXQ WKH IROORZLQJ 3DQHOWHVWKWPO ILOH ZH FDQ JHW WKH RXWSXWDVVKRZQLQWKHILJXUH,IZHFOLFNWKH2WKHUV%XWWRQZHJHWWKHDSSOHWZLQGRZDV VKRZQLQWKHILJXUH+HUHHDFKZLOOEHFRQVLGHUHGDVDFDUG

Fig. 10.6

Fig 10.7

Frames )UDPHVDUHZLQGRZVWKDWDUHLQGHSHQGHQWRIDQDSSOHWDQGRIWKHEURZVHUWKDWFRQWDLQVLW7KH\ DUHVHSDUDWHZLQGRZVZLWKWKHLURZQWLWOHVUHVL]HKDQGOHVFORVHER[HVDQGPHQXEDUV:HFDQ FUHDWH IUDPHV IRU RXU RZQ DSSOHWV WR SURGXFH ZLQGRZV RU ZH FDQ XVH IUDPHV LQ -DYD DSSOLFDWLRQV WR KROG WKH FRQWHQWV RI  WKDW DSSOLFDWLRQ 7R FUHDWH D IUDPH XVH RQH RI WKH IROORZLQJFRQVWUXFWRUV ♦ new Frame() creates a basic frame without a title. ♦ new Frame(String) creates a basic frame with the given title.

238

Comp-U-Learn

More About AWT

%HFDXVH IUDPHV LQKHULW IURP :LQGRZ ZKLFK LQKHULWV IURP &RQWDLQHU ZKLFK LQ WXUQ LQKHULWV IURP &RPSRQHQW IUDPHV DUH FUHDWHG DQG XVHG PXFK LQ WKH VDPH ZD\ DV RWKHU $:7 FRPSRQHQWV DUH FUHDWHG DQG XVHG -XVW OLNH SDQHOV IUDPHV DUH FRQWDLQHUV ZH FDQ DGG RWKHU FRPSRQHQWV WR WKHP MXVW DV ZH ZRXOG WR UHJXODU SDQHOV XVLQJ WKH DGG  PHWKRG 7KH GHIDXOW OD\RXWIRUIUDPHVLV%RUGHU/D\RXW+HUH VDVLQJOHH[DPSOHWKDWFUHDWHVDIUDPHVHWVLWVOD\RXW DQGDGGVWZREXWWRQV win = new Frame("My Cool Window"); win.setLayout(new BorderLayout(10, 20)); win.add("North", new Button("Start")); win.add("Center", new Button("Move"));

7RVHWDVL]HIRUWKHQHZIUDPHXVHWKHresize()PHWKRGZLWKWKHZLGWKDQGKHLJKWRIWKHQHZ IUDPH)RUH[DPSOHWKLVOLQHRIFRGHUHVL]HVWKHZLQGRZWREHSL[HOVZLGHDQGSL[HOV KLJK win.resize(100, 200);

7KH pack() PHWKRG ZKLFK KDV QR DUJXPHQWV FUHDWHV D ZLQGRZ RI WKH VPDOOHVW SRVVLEOH VL]H JLYHQWKHFXUUHQWVL]HVRI DOOWKHFRPSRQHQWVLQVLGHWKDWZLQGRZDQG WKH OD\RXW PDQDJHU DQG LQVHWV LQ XVH +HUH V DQ H[DPSOH WKDW FUHDWHV WZR EXWWRQV DQG DGGV WKHP WR WKH ZLQGRZ 7KH ZLQGRZZLOOWKHQEHUHVL]HGWRWKHVPDOOHVWSRVVLEOHZLQGRZWKDWFDQVWLOOKROGWKRVHEXWWRQV win = new Frame("This is My Frame!"); win.setLayout(new FlowLayout())); win.add("North", new Button("OK")); win.add("Center", new Button("Cancel")); win.pack();

:KHQZHLQLWLDOO\FUHDWHDZLQGRZLW VLQYLVLEOH:HQHHGWRXVHWKHshow()PHWKRGWRPDNHWKH ZLQGRZDSSHDURQVFUHHQ ZHFDQXVHhide()WRKLGHLWDJDLQ  win.show();

1RWHWKDWZKHQZHSRSXSZLQGRZVIURPLQVLGHRIDSSOHWVWKHEURZVHUPD\LQGLFDWHLQVRPH ZD\WKDWWKHZLQGRZLVQRWDUHJXODUEURZVHUZLQGRZ²XVXDOO\ZLWKDZDUQLQJLQWKHZLQGRZ LWVHOI$SDUWIURPWKLVWKH)UDPH FODVV KDV VRPH PRUH PHWKRGV 7KH\ DUH VHW9LVLEOH ERROHDQ  VHW6L]H GLPHQVLRQV  VHW7LOWOH VWULQJ DV WLWOH  VHW/RFDWLRQ  DQG JHW/RFDWLRQ  ZKLFK DUH XVHG LQ VHWWLQJ DQG JHWWLQJ WKH ORFDWLRQ RI WKH SRSXS ZLQGRZ GLVSRVH   LV XVHG WR UHOHDVH DOO WKH UHVRXUFHVRIWKHSRSXSZLQGRZ7KHIROORZLQJH[DPSOHGHPRQVWUDWHVWKHFUHDWLRQRI)UDPHV :ULWHWKHIROORZLQJFRGHDQGVDYHLWDV)UDPHWHVWMDYD

Comp-U-Learn

239

Java Programming I

Example 10.7 import java.awt.*; import java.applet.*; class MyFrame extends Frame { MyFrame(String title) { super(title); } public void paint(Graphics g) { g.drawString("This is the Applet",10,20); } } public class Frametest extends Applet { MyFrame win; public void init() { win = new MyFrame("This is My Frame!"); win.setLayout(new FlowLayout()); win.add("North", new Button("OK")); win.add("Center", new Button("Cancel")); win.show(); win.resize(200,100); } public void stop() { win.hide(); } public void start() { win.show(); } }

$IWHUFRPSLOLQJWKHDERYHILOHUXQWKHIROORZLQJ)UDPHWHVWKWPOILOH:HJHWWKHRXWSXWZLQGRZ ZLWKDSRSXSZLQGRZDVVKRZQLQWKH)LJXUH

$VH[SHFWHGLIZHKDGVWDUWHGWKDWSRSXSZLQGRZDSSOHWWKHQHZZLQGRZ VFORVHER[GRHVQ W ZRUN 1RWKLQJ KDSSHQV ZKHQ ZH FOLFN WKH PRXVH RQ WKH ER[ 7R LPSOHPHQW EHKDYLRU IRU FORVLQJWKHZLQGRZRUSRSXSZLQGRZVWRKLGHWKHPRUWRH[LWWKHDSSOLFDWLRQDOWRJHWKHUIRU DSSOLFDWLRQV ² ZH·OO KDYH WR XVH D handleEvent() PHWKRG LQ RXU Frame FODVV WR WHVW IRU WKH WINDOW_DESTROYHYHQW,QWKHSRSXSZLQGRZH[DPSOHFKRRVLQJWKHFORVHER[VKRXOG KLGHWKHZLQGRZ FDOOWKHhide()PHWKRG :HFDQWKHQVKRZLWDJDLQXVLQJWKH2SHQ:LQGRZ 240

Comp-U-Learn

More About AWT

EXWWRQ LQ WKH DSSOHW 7KLV LV D YHU\ VLPSOH IL[ MXVW DGG WKH IROORZLQJ handleEvent() WR RXU MyFrameFODVV public boolean handleEvent(Event evt) { if (evt.id == Event.WINDOW_DESTROY) hide(); return super.handleEvent(evt); }

Fig 10.8

Menus (DFKQHZZLQGRZZHFUHDWHFDQKDYHLWVRZQPHQXEDUDORQJWKHWRSRIWKHVFUHHQ(DFKPHQX EDU FDQ KDYH D QXPEHU RI PHQXV DQG HDFK PHQX LQ WXUQ FDQ KDYH PHQX LWHPV 7KH $:7 SURYLGHVFODVVHVIRUDOOWKHVHDVMenuBarMenuDQGMenuItem Menus and Menu Bars

7RFUHDWHDPHQXEDUIRUDJLYHQZLQGRZFUHDWHDQHZLQVWDQFHRIWKHFODVVMenuBar MenuBar mbar = new MenuBar();

7R VHW WKLV PHQX EDU DV WKH GHIDXOW PHQX IRU WKH ZLQGRZ XVH WKH setMenuBar() PHWKRG GHILQHGLQWKHFrameFODVV  window.setMenuBar(mbar);

$GGLQGLYLGXDOPHQXV )LOH(GLWDQGVRRQ WRWKHPHQXEDUE\FUHDWLQJWKHPDQGWKHQDGGLQJ WKHPWRWKHPHQXEDUXVLQJadd()

Comp-U-Learn

241

Java Programming I Menu myMenu = new Menu("File"); mbar.add(myMenu);

6RPHV\VWHPVSURYLGHDVSHFLDOKHOSPHQXZKLFKLVGUDZQRQWKHULJKWVLGHRIWKHPHQXEDUDV RSSRVHGWRPDNLQJLWVRPHZKHUHLQWKHPLGGOH:HFDQLQGLFDWHWKDWDVSHFLILFPHQXLVWKHKHOS PHQXZLWKWKHVHW+HOS0HQX PHWKRG7KHJLYHQPHQXVKRXOGDOUHDG\KDYHEHHQDGGHGWRWKH PHQXLWVHOIEHIRUHEHLQJPDGHDKHOSPHQX Menu helpmenu = new Menu("Help"); mbar.add(helpmenu); mbar.setHelpMenu(helpmenu);

,IIRUDQ\UHDVRQZHZDQWWRSUHYHQWDXVHUIURPVHOHFWLQJDPHQXZHFDQXVHWKH disable() FRPPDQGRQWKDWPHQX DQGWKHenable()FRPPDQGWRPDNHLWDYDLODEOHDJDLQ  myMenu.disable();

Menu Items

7KHUHDUHIRXUNLQGVRILWHPVRQHFDQDGGWRLQGLYLGXDOPHQXV ♦ ♦ ♦ ♦

Instances of the class MenuItem, for regular menu items. Instances of the class CheckBoxMenuItem, for toggled menu items. Other menus, with their own menu items. Separators, for lines that separate groups of items on menus.

5HJXODU PHQX LWHPV DUH DGGHG E\ XVLQJ WKH 0HQX,WHP FODVV $GG WKHP WR D PHQX XVLQJ WKH DGG PHWKRG Menu myMenu = new Menu("Tools"); myMenu.add(new MenuItem("Info")); myMenu.add(new MenuItem("Colors"));

6XEPHQXVFDQEHDGGHGVLPSO\E\FUHDWLQJDQHZLQVWDQFHRI MenuDQGDGGLQJLWWRWKHILUVW PHQX:HFDQWKHQDGGLWHPVWRWKDWPHQX Menu submenu = new Menu("Sizes"); myMenu.add(submenu); submenu.add(new MenuItem("Small")); submenu.add(new MenuItem("Medium")); submenu.add(new MenuItem("Large"));

7KHCheckBoxMenuItemFODVVFUHDWHVDPHQXLWHPZLWKDFKHFNER[RQLWHQDEOLQJWKHPHQX VWDWHWREHWRJJOHGRQDQGRII&UHDWHDQGDGGD&KHFN%R[0HQX,WHPWKHVDPHZD\DVZHFUHDWH DQGDGGUHJXODUPHQXLWHPV)RUH[DPSOH 242

Comp-U-Learn

More About AWT CheckboxMenuItem coords = new CheckboxMenuItem("Show Coordinates"); myMenu.add(coords);

)LQDOO\ WR DGG D VHSDUDWRU  WR D PHQX D  OLQH  XVHG WR VHSDUDWH JURXSV RI LWHPV LQ D PHQX  FUHDWHDQGDGGDPHQXLWHPZLWKDK\SKHQ - DVWKHODEHO7KDWVSHFLDOPHQXLWHPZLOOEHGUDZQ ZLWKDVHSDUDWRUOLQH7KHVHQH[WWZROLQHVRI-DYDFRGHFUHDWHDVHSDUDWRUPHQXLWHPDQGDGGLW WRWKHPHQXmyMenu MenuItem msep = new MenuItem("-"); myMenu.add(msep);

$Q\PHQXLWHPFDQEHGLVDEOHGE\XVLQJWKHdisable()PHWKRGDQGHQDEOHGDJDLQXVLQJenable() method'LVDEOHGPHQXLWHPVFDQQRWEHVHOHFWHG MenuItem item = new MenuItem("Fill"); myMenu.addItem(item); item.disable();

:H OODGGDW\SLFDOPHQXDQGPHQXEDUWRWKHSRSXSZLQGRZDSSOHWLQDELWEXWILUVWOHW VOHDUQ DERXWKRZWRDFWLYDWHPHQXLWHPVZKHQWKH\ UHVHOHFWHG

Menu Actions 7KH DFW RI VHOHFWLQJ D PHQX LWHP FDXVHV DQ DFWLRQ HYHQW WR EH JHQHUDWHG :H FDQ KDQGOH WKDW DFWLRQ WKH VDPH ZD\ ZH KDQGOH RWKHU action PHWKRGV ² E\ RYHUULGLQJ action() %RWK UHJXODU PHQX LWHPV DQG FKHFN ER[ PHQX LWHPV KDYH DFWLRQV WKDW JHQHUDWH DQ H[WUD DUJXPHQW UHSUHVHQWLQJWKHODEHOIRUWKDWPHQX:HFDQXVHWKDWODEHOWRGHWHUPLQHZKLFKDFWLRQWRWDNH $OVRQRWHWKDWEHFDXVHCheckBoxMenuItemLVDVXEFODVVRIMenuItemZHGRQ WKDYHWRWUHDW WKDW PHQX LWHP DV D VSHFLDO FDVH ,Q WKLV H[DPSOH WKH 6KRZ &RRUGLQDWHV PHQX LWHP LV D CheckBoxMenuItemDQG)LOOLVDUHJXODUPHQXLWHP public boolean action(Event evt, Object arg) { if (evt.target instanceof MenuItem) { String label = (String)arg; if (label.equals("Show Coordinates")) toggleCoords(); else if (label.equals("Fill")) fillcurrentArea(); return true; } else return false; }

$OVRWKHUH DUHVRPHPHWKRGVLQHYHU\FODVVHV,Q0HQX FODVV DGG  DGG6HSHUDWRU  JHW,WHP DQGUHPRYH PHWKRGVDUHWKHUH,Q0HQX,WHPFODVVWKHUHDUHWKUHHPHWKRGVQDPHO\JHW/DEHO  VHW/DEHO VWULQJ  VHW(QDEOHG ERROHDQ  ,Q WKH &KHFNER[0HQX,WHP FODVV WKH JHW6WDWH  VHW6WDWH ERROHDQ DUHXVHGWRLQGLFDWHWKHVWDWHRIWKHFKHFNER[PHQXLWHP Comp-U-Learn

243

Java Programming I

7KH IROORZLQJ H[DPSOH   LOOXVWUDWHV WKH FUHDWLRQ RI PHQXV LQ D SRSXS ZLQGRZ  DQG WKH PHQX DFWLRQV ,Q WKLV H[DPSOH PHQX LQ WKH SRSXS ZLQGRZ KDV IRXU LWHPV RQH HDFK IRU WKH FRORUVUHGEOXHDQGJUHHQ ZKLFKZKHQVHOHFWHGFKDQJHWKHEDFNJURXQGRIWKHZLQGRZ DQG RQHFKHFNER[PHQXLWHPIRUUHYHUVLQJWKHFRORURIWKHWH[W WRZKLWH $OODUHDGGHGDVSDUWRI WKH FRQVWUXFWRU WR WKLV FODVV 7R KDQGOH WKHVH PHQX LWHPV ZKHQ WKH\ UH FKRVHQ ZH QHHG DQ action()PHWKRG,QVLGHaction() WHVWWRVHHLIWKHDFWLRQFDPHIURPDPHQXLWHP ZKLFKLQFOXGHV WKHRQHIRUFKHFNER[PHQXLWHP :KHQWKHDFWLRQLVRQWKHPHQXLWHPVWHVWIRUHDFKRIWKH PHQX ODEHOV LQ WXUQ )RU WKH UHG EOXH DQG JUHHQ PHQX LWHPV DOO ZH QHHG WR GR LV VHW WKH EDFNJURXQG)RUWKH5HYHUVH7H[WWRJJOHZHQHHGWRILUVWILQGRXWWKHFXUUHQWFRORURIWKHWH[W DQGWKHQUHYHUVHLW7RILQLVKXSFDOODrepaint()WRPDNHVXUHWKHEDFNJURXQGDQGWKHWH[WJHW XSGDWHGSURSHUO\DQGUHWXUQWKHDSSURSULDWHERROHDQ Example 10.8 import java.awt.*; import java.applet.*; class MyFrame extends Frame { String message = "This is a Window"; MyFrame(String title) { super(title); setFont(new Font("Helvetica", Font.BOLD, 12)); MenuBar mb = new MenuBar(); Menu m = new Menu("Colors"); m.add(new MenuItem("Red")); m.add(new MenuItem("Blue")); m.add(new MenuItem("Green")); m.add(new MenuItem("-")); m.add(new CheckboxMenuItem("Reverse Text")); mb.add(m); setMenuBar(mb); } public boolean action(Event evt, Object arg) { String label = (String)arg; if (evt.target instanceof MenuItem) { if (label.equals("Red")) setBackground(Color.red); else if (label.equals("Blue")) setBackground(Color.blue); else if (label.equals("Green")) setBackground(Color.green); else if (label.equals("Reverse Text")) { if (getForeground() == Color.black) { setForeground(Color.white); } else setForeground(Color.black); }

244

Comp-U-Learn

More About AWT repaint(); return true; } else return false; } public void paint(Graphics g) { g.drawString(message, 20, 20); }

public boolean handleEvent(Event evt) { if (evt.id == Event.WINDOW_DESTROY) hide(); return super.handleEvent(evt); } } public class Menutest extends Applet { Frame window; public void init() { add(new Button("Open Window")); add(new Button("Close Window")); window = new MyFrame("A Popup Window"); window.resize(150,150); window.show(); } public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) { String label = (String)arg; if (label.equals("Open Window")) { if (!window.isShowing()) window.show(); } else if (label.equals("Close Window")) { if (window.isShowing()) window.hide(); } } return true; } }

Comp-U-Learn

245

Java Programming I

$IWHUFRPSLOLQJWKHDERYH-DYDILOHUXQWKHIROORZLQJ+70/ILOHDQGWKHRXWSXWLVDVVKRZQLQ ILJXUH&OLFNWKH&RORULWHPVLQWKHVFUHHQDQGVHHWKHDFWLRQV

Fig 10.9

Dialog Box 'LDORJVDUHWUDQVLHQWZLQGRZVLQWHQGHGWRDOHUWWKHXVHUWRVRPHHYHQWRUWRJHWLQSXWIURPWKH XVHU 8QOLNH IUDPHV GLDORJV GR QRW JHQHUDOO\ KDYH D WLWOH EDU RU FORVH ER[HV $ PRGDO GLDORJ SUHYHQWV LQSXW WR DQ\ RI WKH RWKHU ZLQGRZV RQ WKH VFUHHQ XQWLO WKDW GLDORJ LV GLVPLVVHG 7KH $:7SURYLGHVWZRNLQGVRIGLDORJER[HVWKHDialogFODVVZKLFKSURYLGHVDJHQHULFGLDORJDQG FileDialogZKLFKSURGXFHVWKHSODWIRUPVSHFLILFILOHEURZVHUGLDORJ Dialog Objects

'LDORJVDUHFUHDWHGDQGXVHGPXFKLQWKHVDPHZD\DVZLQGRZV7RFUHDWHDJHQHULFGLDORJXVH RQHRIWKHVHFRQVWUXFWRUV ♦ Dialog(Frame, boolean) creates an initially invisible dialog, attached to the current frame, which is either modal (true) or not (false). ♦ Dialog(Frame, String, boolean) is the same as the previous constructor, with the addition of a title bar and a title indicated by the string argument. 246

Comp-U-Learn

More About AWT

File Dialog Objects

7KHFileDialogFODVVSURYLGHVDEDVLFILOHRSHQVDYHGLDORJER[WKDWHQDEOHVDFFHVVLQJWKHILOH V\VWHP 7KH FileDialog FODVV LV V\VWHPLQGHSHQGHQW EXW GHSHQGLQJ RQ WKH SODWIRUP WKH VWDQGDUG2SHQ)LOHRU6DYH)LOHGLDORJLVEURXJKWXS7RFUHDWHDILOHGLDORJXVHWKHIROORZLQJ FRQVWUXFWRUV ♦ FileDialog(Frame, String) creates an Open File dialog, attached to the given frame, with the given title. This form creates a dialog to load a file. ♦ FileDialog(Frame, String, int) also creates a file dialog, but that integer argument is used to determine whether the dialog is for loading a file or saving a file (the only difference is the labels on the buttons; the file dialog does not actually open or save anything). The possible options for the mode argument are FileDialog.LOAD and FileDialog.SAVE. ♦ The dialog window, like the frame window, is a panel on which one can layout and draw user interface components and perform graphic operations, just as we would on any other panel. Like other windows, the dialog is initially invisible, but we can show it with show() and hide it with hide(). ,QWKH'LDORJFODVVWKHUHDUHWKUHH PHWKRGV 7KHVHW5HVL]DEOH UHWXUQV DERROHDQYDOXHZKLFK GHWHUPLQHV WKH GLDORJ LV UHVL]DEOH RU QRW 7KH LV0RGDO  PHWKRG UHWXUQV WUXH LI WKH GLDORJ LV PRGDO7KHLV5HVL]DEOH PHWKRGUHWXUQVWUXHLIWKHGLDORJLVUHVL]DEOH,Q)LOHGLDORJFODVVZHFDQ DFFHVV WKH FKRVHQ ILOHQDPH E\ XVLQJ WKH getDirectory() DQG getFile() PHWKRGV ERWK UHWXUQ VWULQJVLQGLFDWLQJWKHYDOXHVWKHXVHUKDVFKRVHQ:HFDQWKHQRSHQWKDWILOHE\XVLQJWKHVWUHDP DQGILOHKDQGOLQJPHWKRGVDQGWKHQUHDGIURPRUZULWHWRWKDWILOH 7KHIROORZLQJH[DPSOHJLYHVDQLGHDRQFUHDWLRQRIGLDORJER[,QWKLVH[DPSOHWKHGLDORJ ER[LVFDOOHGE\PHDQVRIDQPHQXLWHPDORQJZLWKWKHSUHYLRXVH[DPSOH Example 10.9 import java.awt.*; import java.applet.*; public class Dialogtest extends Applet { Frame window; public void init() { add(new Button("Open Window")); add(new Button("Close Window")); window = new Dialtest("A Popup Window"); window.resize(150,150); window.show(); } public boolean action(Event evt, Object arg) {

Comp-U-Learn

247

Java Programming I if (evt.target instanceof Button) { String label = (String)arg; if (label.equals("Open Window")) { if (!window.isShowing()) window.show(); } else if (label.equals("Close Window")) { if (window.isShowing()) window.hide(); } } return true; } } class Dialtest extends Frame { String message = "This is a Window"; TextDialog dl; Dialtest(String title) { super(title); setLayout(new GridLayout(1,1)); setFont(new Font("Helvetica", Font.BOLD, 12)); MenuBar mb = new MenuBar(); Menu m = new Menu("Colors"); m.add(new MenuItem("Red"));

m.add(new MenuItem("Blue")); m.add(new MenuItem("Green")); m.add(new MenuItem("-")); m.add(new CheckboxMenuItem("Reverse Text")); m.add(new MenuItem("Set Text...")); mb.add(m); setMenuBar(mb); // make a dialog for this window dl = new TextDialog(this, "Enter Text", true); dl.resize(150,100); } public boolean action(Event evt, Object arg) { String label = (String)arg; if (evt.target instanceof MenuItem) { if (label.equals("Red")) setBackground(Color.red); else if (label.equals("Blue")) setBackground(Color.blue); else if (label.equals("Green")) setBackground(Color.green); else if (label.equals("Set Text...")) dl.show(); else if (label.equals("Reverse Text"))

248

Comp-U-Learn

More About AWT { if (getForeground() == Color.black) { setForeground(Color.white); } else setForeground(Color.black); } else return false; repaint(); return true; } public void paint(Graphics g) { g.drawString(message, 20, 20); } public boolean handleEvent(Event evt) { if (evt.id == Event.WINDOW_DESTROY) hide(); return super.handleEvent(evt); } } class TextDialog extends Dialog { TextField tf; Dialtest theFrame; TextDialog(Frame parent, String title, boolean modal) { super(parent, title, modal); theFrame = (Dialtest)parent; setLayout(new BorderLayout(10,10)); setBackground(Color.white); tf = new TextField(theFrame.message,20); add("Center", tf); add("South", new Button("OK")); resize(150,75); } public Insets insets() { return new Insets(30,10,10,10); } public boolean action(Event evt, Object arg) { String label = (String)arg; if (evt.target instanceof Button) {

Comp-U-Learn

249

Java Programming I if (label == "OK") { hide(); theFrame.message = tf.getText(); theFrame.repaint(); } } else return false; return true; } }

$IWHUFRPSLOLQJWKHDERYH-DYDILOHUXQWKHIROORZLQJ+70/ILOHWRJHWWKHRXWSXWDVVKRZQLQ WKHILJXUH&OLFNWKH&RORULWHPVLQWKHVFUHHQDQGVHHWKHDFWLRQV

Fig 10.10

Summary In this session we learn about the LayoutManagers and their need. The different type of layouts such as Flow layout, border layout, card layout , Grid layout and GridBag layout were dealt with in detail. In the middle of this session, we learnt about the panels along with the Card layout. After that the topics related to the window such as Frame, Menus and Dialog classes and their usage were covered with examples

250

Comp-U-Learn

More About AWT

Going Over It Again I. Fill in the Blanks

 BBBBBBBBBBBBPHWKRGLVXVHGWRVHWWKH/D\RXWRIDFRQWDLQHU  7KHGHIDXOWOD\RXWRI3DQHOLVBBBBBBBBBBBBB  $IUDPHFDQDFWDVDBBBBBBBBBBBBB  BBBBBBBBBBBPHWKRGLVXVHGWRHQDEOHGLVDEOHWKHPHQXLWHP  BBBBBBBBBBBBPHWKRGLVXVHGWRSRVLWLRQWKH'LDORJER[ II. State True or False

 ,QVHWVDUHXVHGWRSURYLGHWKHJDSEHWZHHQWKHFRPSRQHQWV  $QDSSOHWFDQEHPDGHWRFRQWDLQPHQXV  7KHGHIDXOWOD\RXWRIWKHFRQWDLQHULV)ORZOD\RXW  :HFDQKDYH&KHFNHG0HQXLWHPV  $'LDORJER[FDQEHPDGHUHVL]DEOHXVLQJWKHVHW6L]H PHWKRG III. One line Answers

 :KDWLV)UDPH"  :KDWDUHWKHW\SHVRI/D\RXWV"  +RZDUHWKHFRPSRQHQWVDUUDQJHGLQWKHFDUGOD\RXW"  &DQZHDGGDFRQWDLQHULQDSDQHO"  :KDWDUHWKHPHWKRGVLQ0HQXFODVV" IV. Define the Following

 VHW/D\RXW LQWKH3DQHO  LV5HVL]DEOH LQWKH'LDORJ  DGG6HSHUDWRU LQ0HQX  VHW6WDWH LQ&KHFNER[0HQX,WHP  VHW7LWOH LQIUDPH

Comp-U-Learn

251

Session 11

Java DataBase Connectivity

On Completion of this Session We will be able to understand...

) Introduction to JDBC ) JDBC vs ODBC ) JDBC Drivers ) Connection ) Prepared Statement ) Callable Statement ) Transaction processing ) Inserting, Updating and Deleting in a database

In This Session...



Introduction to JDBC



Microsoft’s ODBC



Tiering



JDBC Architecture



JDBC Drivers



DriverPropertyInfo Class



Connection Class



DatabaseMetaData Interface



Prepared Statement



Callable Statement



Executing SQL using JDBC



Transaction Processing

Java DataBase Connectivity

Introduction to JDBC -'%&VWDQGVIRU-DYD'DWDEDVH&RQQHFWLYLW\7KH-'%&LVDSRZHUIXOPHFKDQLVPWKDWDOORZV -DYDDSSOHWVWRSURYLGHGDWDEDVHDFFHVVRYHUWKH,QWHUQHWRU,QWUDQHW7KH-'%&LVDOVRYDOXDEOH ZKHQ XVLQJ -DYD WR FUHDWH ORFDO RU FOLHQWVHUYHU DSSOLFDWLRQV WKDW KDYH WR DFFHVV RQH RU PRUH GDWDEDVHV -'%& FDQ EH XVHG WR DFFHVV DQ\ GDWDEDVH WKDW LV UHVLGLQJ RQ WKH VDPH PDFKLQH RU DQ\ZKHUHLQWKH,QWHUQHW-'%&LVDULFKVHWRIFODVVHVWKDWJLYHVWUDQVSDUHQWDFFHVVWRDGDWDEDVH ZLWK VLQJOH DSSOLFDWLRQ SURJUDPPLQJ LQWHUIDFH $3,   7KLV DFFHVV LV KDQGOHG ZLWK SOXJLQ SODWIRUPVSHFLILFPRGXOHVDOVRFDOOHGGULYHUV ,Q RUGHU WR DFFHVV GDWDEDVHV UHPRWHO\ XVHUV QHHG D GDWDEDVH FOLHQW $ GDWDEDVH FOLHQW FRPPXQLFDWHVWRWKHGDWDEDVHVHUYHURQXVHU VEHKDOI,WSURYLGHVWKHXVHUZLWKWKHFDSDELOLW\WR XSGDWH WKH GDWDEDVH ZLWK QHZ LQIRUPDWLRQ RU WR UHWULHYH LQIRUPDWLRQ IURP WKH GDWDEDVH 7KH GDWDEDVH FOLHQWV WDON WR GDWDEDVH VHUYHUV XVLQJ 64/ VWDWHPHQWV 'DWDEDVH FOLHQWV XVH GDWDEDVH GULYHUV WR VHQG 64/ VWDWHPHQWV WR GDWDEDVH VHUYHUV DQG WR UHFHLYH UHVXOW VHWV DQG RWKHU UHVSRQVHV IURP WKH VHUYHUV -'%& GULYHUV DUH XVHG E\ -DYD DSSOLFDWLRQ DQG DSSOHWV WR FRPPXQLFDWHZLWKGDWDEDVHVHUYHUV

Microsoft's ODBC 0DQ\GDWDEDVHVHUYHUVXVHYHQGRUVSHFLILFSURWRFROV 7KLVPHDQVWKDWDGDWDEDVHFOLHQW KDVWR OHDUQDQHZODQJXDJHWRWDONWRDGLIIHUHQWGDWDEDVHVHUYHU0LFURVRIWKDVHVWDEOLVKHGDFRPPRQ VWDQGDUGIRUFRPPXQLFDWLQJZLWKGDWDEDVHVFDOOHG2SHQ'DWDEDVH&RQQHFWLYLW\%HIRUH2'%& PRVW GDWDEDVH FOLHQWV ZHUH VHUYHU VSHFLILF 2'%& GULYHUV DEVWUDFW DZD\ YHQGRU VSHFLILF SURWRFROVSURYLGLQJDFRPPRQDSSOLFDWLRQSURJUDPPLQJLQWHUIDFHWRGDWDEDVHFOLHQWV 2'%&RU2SHQGDWDEDVH&RQQHFWLYLW\LVDZD\RIFRQQHFWLQJDQ\IURQWHQGWRROWRDQ\EDFN HQG GDWDEDVH HQJLQH $ IURQWHQG WRRO LV RQH ZKLFK LV XVHG WR SURYLGH D XVHU LQWHUIDFH XVLQJ ZKLFK WKH XVHU ZLOO EH DEOH WR PDQLSXODWH WKH GDWD $ EDFNHQG UHDOO\ SHUIRUPV DOO WKH GDWD PDQLSXODWLRQDFWXDOO\ EDVHG RQ WKH UHTXHVWV RI WKH IURQWHQG $ EDFNHQG LV FDOOHG DV D VHUYHU DQGDIURQWHQGLVFDOOHGDVDFOLHQW7KHVHUYHUDQGFOLHQWDUHFRQQHFWHGE\PHDQVRIDGULYHU VRIWZDUH ,W LV WKH 2'%& GULYHU WKDW FRQYHUWV WKH UHTXHVWV IURP WKH 2'%& FRPSOLDQW FOLHQW LQWR WKH FRUUHVSRQGLQJ QDWLYH IRUPDW UHTXHVWV WR PDWFK WKH LPSOHPHQWDWLRQ VSHFLILHG DW WKH VHUYHU VLGH $QRWKHU LPSRUWDQW IHDWXUH RI 2'%& LV WKDW LW SURYLGHV FOLHQW DQ RSSRUWXQLW\ WR FRQQHFW WR PXOWLSOH GDWDEDVHV VLPXOWDQHRXVO\ ZKLFK FRXOG EH UHVLGLQJ LQ GLIIHUHQW SK\VLFDO ORFDWLRQV Advantages of ODBC drivers

♦ ODBC drivers are fast but not as fast as native drivers are. ♦ We can use the SQL to query the database.

Comp-U-Learn

255

Java Programming I Disadvantages

♦ Applications created using ODBC are usually not portable to other platforms without code modifications. ♦ Because the driver stub is linked into our application, change in the driver software API requires recompilation of the application. JDBC

-'%& LV D IURQWHQG WRRO IRU FRQQHFWLRQ WR D VHUYHU DQG LV VLPLODU WR 2'%& LQ WKDW UHVSHFW +RZHYHU-'%&FDQFRQQHFWRQO\WR-DYDFOLHQWVDQGLWXVHV2'%&IRUWKHFRQQHFWLYLW\-'%& LV HVVHQWLDOO\ D ORZOHYHO $SSOLFDWLRQ 3URJUDPPLQJ ,QWHUIDFH ,W LV FDOOHG D ORZ OHYHO $3, VLQFH DQ\GDWDPDQLSXODWLRQVWRUDJHDQGUHWULHYDOKDVWR EHGRQH E\ WKH SURJUDP LWVHOI 6RPH WRROV ZKLFKSURYLGHDKLJKHUOHYHOKDVWREHGRQHE\WKHSURJUDPLWVHOI Reasons for using JDBC

There are a number of reasons why JDBC is needed. These are stated hereunder. 2'%&LVD&ODQJXDJH$3,QRWD-DYD$3,-DYDLVREMHFWRULHQWHGDQG&LVQRW&XVHVSRLQWHUV DQGRWKHUSURJUDPPLQJFRQVWUXFWVWKDW-DYDGRHVQRWVXSSRUW$-DYDYHUVLRQRI2'%&ZRXOG UHTXLUH D VLJQLILFDQW UHZULWH RI WKH 2'%& $3, 2'%& GULYHUV PXVW EH LQVWDOOHG RQ FOLHQW PDFKLQHV7KLVPHDQVWKDWDSSOHWDFFHVVWRGDWDEDVHVZRXOGEHFRQVWUDLQHGE\WKHUHTXLUHPHQW WR GRZQORDG DQG LQVWDOO D -'%& GULYHU $ SXUH -'%& VROXWLRQ DOORZV -'%& GULYHUV WR EH DXWRPDWLFDOO\GRZQORDGHGDQGLQVWDOOHGDORQJZLWKWKH$SSOHW 7KLVJUHDWO\ VLPSOLILHV GDWDEDVH DFFHVVIRUDSSOHWXVHUV

Tiering %DVLFDOO\WKHDSSOLFDWLRQVKDYHWKUHHFRPSRQHQWV2QHLVWKHXVHULQWHUIDFH DSSOLFDWLRQFRGH  WKH EXVLQHVV ORJLF UXOHV  DQG WKH GDWD 7KH XVHU LQWHUIDFH GLVSOD\V WKH GDWD IURP WKH GDWDEDVH DQGWKHEXVLQHVVUXOHVPDQLSXODWHWKHGDWDIURPWKHGDWDEDVH7KHGDWDLVUHVLGHVLQWKHGDWDEDVH 7LHULQJLQYROYHVPRYLQJWKHORJLFDOORFDWLRQRIHDFKRIWKHVHWKUHHFRPSRQHQWV Single Tier Architecture

,QWKHVLQJOHWLHUDUFKLWHFWXUHWKHVHUYHUDQGWKHFOLHQWDUHRQWKHVDPHPDFKLQHRURWKHUZLVHSDUW RI WKH VDPH HQYLURQPHQW 7KLV LV KLJKO\ VXLWHG LQ VLPSOH DSSOLFDWLRQV $ FOLHQW WKDW QHHGV LQIRUPDWLRQ DQG WKH VRXUFH RI LQIRUPDWLRQ DUH D SDUW RI WKH VDPH HQYLURQPHQW 7KH PDLQ DGYDQWDJHRIVLQJOHWLHUDUFKLWHFWXUHLVWKHVLPSOLFLW\DQGSRUWDELOLW\RIWKHDSSOLFDWLRQGHYHORSHG 6WULFWO\ VSHDNLQJ WKH XVHU LQWHUIDFH EXVLQHVV ORJLF DQG WKH GDWD UHVLGH WRJHWKHU ORJLFDOO\ $Q H[DPSOHFRXOGEHDFDOFXODWRUDSSOLFDWLRQDQGDOVRG%DVH 256

Comp-U-Learn

Java DataBase Connectivity Two Tier Architecture

,Q D WZRWLHU DUFKLWHFWXUH WKH XVHU LQWHUIDFH DQG WKH EXVLQHVV UXOHV UHVLGH LQ GLIIHUHQW SODFHV ORJLFDOO\:HFDQWDNHXVHULQWHUIDFHWREHDVDFOLHQWDQGEXVLQHVVUXOHVWREHDVVHUYHU7KHQWKH VHUYHUZKLFKQRUPDOO\FRQWDLQVDOOWKHGDWDEDVHVUHVLGHVVHSDUDWHO\$Q\ QXPEHURIPDFKLQHV FDOOHG DV FOLHQWV FDQ DFFHVV WKH GDWD LQ WKH VHUYHU +HUH VHUYHU DQG WKH FOLHQW DUH QRW EXQGOHG WRJHWKHUDVDVLQJOHFRPSRQHQWORJLFDOO\+HUHDGDWDEDVHPDQDJHUWDNHVFRQWURORIWKHGDWDEDVH DQGSURYLGHVDFFHVVWRWKHFOLHQWVLQDQHWZRUN$OOGDWDEDVHDSSOLFDWLRQVFRPHXQGHUWKLVWZR WLHUDUFKLWHFWXUH7KH\DUHDOVRFDOOHGDVFOLHQWVHUYHUDSSOLFDWLRQV Three Tier Architecture

,Q D WKUHH WLHU DUFKLWHFWXUH WKH WKUHH FRPSRQHQWV XVHULQWHUIDFH GDWD DQG WKH EXVLQHVV UXOHV UHVLGHLQGLIIHUHQWORJLFDOORFDWLRQV+HUHWKHFOLHQWDFFHVVHVDUHPRWHVHUYLFHIRULQWHUDFWLQJZLWK WKHGDWDDQGUHVSRQGLQJEDFNWRWKHFOLHQW7KHFOLHQWKDVQRNQRZOHGJHDERXWWKHVHUYHURUWKH ORFDWLRQRIWKHGDWD,WFDQRQO\DFFHVVWKHUHPRWHVHUYLFH7KHUHPRWHVHUYLFHLQWXUQFRQQHFWV WRWKHVHUYHUDQGUHWULHYHVWKHGDWDIRUWKHFOLHQW+HUHDQ\QXPEHURIRWKHUVHUYHUVZKRLQWXUQ DUHFDWHULQJWRWKHLUFOLHQWUHTXHVWVFDQDFFHVVDGDWDEDVHVHUYHUZKLFKFRQWDLQVWKHGDWD7KXV DQLQWHUPHGLDWHVHUYHULVLQYROYHGLQWKLVW\SHRIDUFKLWHFWXUH7KHLQWHUPHGLDWHVHUYHUSHUIRUPV WZR ZD\ FRPPXQLFDWLRQV 7KDW LV LW SDVVHV WKH FOLHQW UHTXHVWV WR WKH GDWDEDVH VHUYHU DQG DOVR VHQGVWKHUHVXOWVIURPWKHVHUYHUEDFNWRWKHFOLHQW$WWKLVSRLQWWKLVWKUHHWLHUDUFKLWHFWXUHLV JDLQLQJZLGHSRSXODULW\DQGPRPHQWXP

JDBC Architecture

Application

JDBC Driver Manager

JDBCNative Driver

JDBC-ODBC Bridge Driver

JDBC Net Driver

Native Protocol JDBC Driver

Uses Net ODBC Uses native calls to access thedatabase

Uses native protocols to access the DB

Net protocols to access DB

Fig 11.1 Comp-U-Learn

257

Java Programming I

JDBC Drivers JDBC-ODBC Bridge Drivers

-DYD6RIWFUHDWHGWKH-DYD2'%&EULGJHGULYHUDVDWHPSRUDU\VROXWLRQWRGDWDEDVHFRQQHFWLYLW\ XQWLO VXLWDEOH -'%& GULYHUV ZHUH GHYHORSHG 7KH -'%&2'%& EULGJH GULYHU WUDQVODWHV WKH -'%& $3, LQWR WKH 2'%& $3, DQG LV XVHG ZLWK DQ 2'%& GULYHU $ EULGJH GULYHU SURYLGHG ZLWK -'%& FDQ FRQYHUW WKH -'%& FDOOV LQWR WKH HTXLYDOHQW 2'%& FDOOV XVLQJ WKH QDWLYH PHWKRGV 6LQFH 2'%& SURYLGHV IRU FRQQHFWLRQ WR DQ\ W\SH RI GDWDEDVH WKDW LV 2'%& FRPSOLDQW WR FRQQHFW WR D QXPEHU RI GDWDEDVHV VLPXOWDQHRXVO\ LV YHU\ VLPSOH ,W LV LPSOHPHQWHG LQ ERWK ELQDU\ FRGH DQG -DYD -DYD PXVW EH SUHLQVWDOOHG RQ D FOLHQW FRPSXWHU EHIRUHLWFDQEHXVHG All Java JDBC Net Drivers $ -'%& 1HW'ULYHU ZKLFK XVHV D FRPPRQ QHWZRUN SURWRFRO WR FRQQHFW WR DQ LQWHUPHGLDWH VHUYHUDQGLQWXUQHPSOR\VQDWLYHFDOOVWRFRQQHFWWRWKHGDWDEDVH7KLVDSSURDFKLVVXLWHGIRU DSSOHWV ZKHUH WKH UHTXHVWV PXVW JR WKURXJK WKH LQWHUPHGLDWH VHUYHU 7KLV GULYHU FDWHJRU\ FRQVLVWVRISXUH-DYDGULYHUVWKDWVSHDNDVWDQGDUGQHWZRUNSURWRFROWRGDWDEDVHDFFHVVVHUYHU 7KHGDWDEDVHDFFHVVVHYHUVWKHQWUDQVODWHWKHQHWZRUNSURWRFROLQWRDYHQGRUVSHFLILFGDWDEDVH SURWRFRO Native JDBC Driver

$-'%&'ULYHUZKLFKLVSDUWO\ZULWWHQLQ-DYDLVLPSOHPHQWHGXVLQJQDWLYHPHWKRGVWRDFFHVV WKH GDWDEDVH 7KLV LV XVHIXO LQ FDVH RI D -DYD $SSOLFDWLRQ WKDW FDQ UXQ RQO\ RQ VRPH VSHFLILF SODWIRUPV:ULWLQJWKLVW\SHRIGULYHUVLVHDVLHUFRPSDUHGWRZULWLQJRWKHUGULYHUV7KHVHGULYHUV FRPPXQLFDWHWRGDWDEDVHVHUYHUVLQWKHVHUYHU VQDWLYHSURWRFRO7KHVHGULYHUVDUHLPSOHPHQWHG LQDFRPELQDWLRQRIELQDU\FRGHDQG-DYDDQGWKH\PXVWEHLQVWDOOHGRQFOLHQWPDFKLQHV Native Protocol all – Java Driver

7KLVW\SHRI-'%&GULYHULVZULWWHQFRPSOHWHO\LQ-DYDDQGFDQDFFHVVWKHGDWDEDVHE\PDNLQJ XVH RI QDWLYH SURWRFROV RI WKH GDWDEDVH 7KLV PHWKRG RI GDWD DFFHVV LV VXLWDEOH LQ FDVH RI ,QWUDQHWV ZKHUH HYHU\WKLQJ FDQ UXQ DV DQ DSSOLFDWLRQ UDWKHU WKDQ DV DQ DSSOHW 7KLV GULYHU LV JHQHUDOO\SURYLGHGE\WKHGDWDEDVHYHQGRU DriverManager Class

7KH'ULYHU0DQDJHU&ODVVPDQDJHVWKHORDGLQJDQGXQORDGLQJRIGULYHUV 7KH'ULYHU0DQDJHU FODVVPDLQWDLQVD9HFWRUWKDWKROGVLQIRUPDWLRQDERXWDOOGULYHUVWKDWLWNQRZV7KHHOHPHQWVLQ WKH9HFWRUFRQWDLQLQIRUPDWLRQDERXWWKHGULYHUVXFKDVWKHFODVVQDPHRIWKH'ULYHUREMHFWD FRS\ RI WKH DFWXDO 'ULYHU DQG WKH 'ULYHU VHFXULW\ FRQWH[W 7KH GULYHUV PDQDJHG E\ WKH 258

Comp-U-Learn

Java DataBase Connectivity

'ULYHU&ODVV DUH UHSUHVHQWHG E\ WKH 'ULYHU FODVV $OWKRXJK WKH 'ULYHU0DQDJHU LV QRW D VWDWLF FODVV LW PDLQWDLQV DOO VWDWLF LQVWDQFH YDULDEOHV ZLWK VWDWLF DFFHVV PHWKRGV IRU UHJLVWHULQJ DQG XQUHJLVWHULQJ GULYHUV 0DLQWDLQLQJ WKHVH YDULDEOHV DQG PHWKRGV HUDGLFDWHV WKH QHHG IRU LQVWDQWLDWLRQRIWKH'ULYHU0DQDJHU,WVGDWDDOZD\VH[LVWVDVSDUWRIWKH-DYD5XQWLPH7KH-'%& GULYHUVPD\EHLQVWDOOHGE\VHWWLQJWKHMGEFGULYHUVV\VWHPSURSHUW\RUE\ORDGLQJWKHGULYHUFODVV XVLQJ WKH IRU1DPH  PHWKRG RI WKH 'ULYHU0DQDJHU FODVV 7KH 'ULYHU0DQDJHU FODVV GRHV QRW SURYLGHDFRQVWUXFWRU

Note The security context is an implementation dependant object that defines the environment in which the application is running. This information is usually enough for Java to perform security checks. When the DriverManager opens or queries a Driver, the security context of the driver is checked against the security context of the application. 7KHIROORZLQJDUHWKHYDULRXVPHWKRGVLQ'ULYHU0DQDJHUFODVV getDrivers() 5HWXUQVDQHQXPHUDWLRQRIDOOWKH-'%&GULYHUVWKDWDUHLQVWDOOHGRQWKHV\VWHP getConnection() 7KLVLVXVHGWRHVWDEOLVKDFRQQHFWLRQWRDGDWDEDVH getDriver() 5HWXUQVDGULYHUWKDWFDQVXSSRUWDFRQQHFWLRQYLDDVSHFLILHG85/ registerDriver() ,QYRNHGE\GULYHUVWRUHJLVWHUWKHPVHOYHVZLWK'ULYHU0DQDJHU deregisterDriver() ,QYRNHGE\GULYHUVWRGHUHJLVWHUWKHPVHOYHVZLWK'ULYHU0DQDJHU getLoginTimeout() 5HWXUQVWKHPD[LPXPWLPHIRUGULYHUVWRZDLWZKLOHWU\LQJWRORJLQWRDGDWDEDVH setLoginTimeout() 6HWVWKHPD[LPXPWLPHIRUGULYHUVWRZDLWZKLOHWU\LQJWRORJLQWRDGDWDEDVH

Comp-U-Learn

259

Java Programming I

getLogStream() 5HWXUQVWKHVWUHDPWKDWLVWREHXVHGIRUORJJLQJDQGWUDFHGDWDEDVHDFFHVVRYHUDQ,QWHUQHWRU ,QWUDQHW7KH-'%&LVDOVRYDOXDEOHZKHQXVLQJ-DYDWRFUHDWHORFDORUFOLHQWVHUYHUDQHDV\WR XVHSDFNDJH:KHQDGDWDEDVHFRQQHFWLRQLVHVWDEOLVKHGXVLQJWKHJHW&RQQHFWLRQ PHWKRGRI 'ULYHU0DQDJHUWKHJHW&RXQWWRKDYHSUHORDGHG6RPHRIWKHPHWKRGVLQWKH'ULYHU,QWHUIDFH DUHDVIROORZV connect()

$Q DEVWUDFW PHWKRG WKDW LV RYHUULGGHQ E\ D GULYHU WR HVWDEOLVK D GDWDEDVH FRQQHFWLRQ 7KH 'ULYHU0DQDJHULQYRNHVWKLVPHWKRGIRUWKHGULYHU acceptsURL()

5HWXUQV D ERROHDQ YDOXH LQGLFDWLQJ ZKHWKHU D GULYHU LV FDSDEOH RI RSHQLQJ  D GDWDEDVH FRQQHFWLRQYLDDVSHFLILHG85/ getPropertyInfo()

5HWXUQV D 'ULYHU3URSHUW\,QIR DUUD\ WKDW SURYLGHV LQIRUPDWLRQ DERXW KRZ WR XVH D GULYHU WR FRQQHFWWRDGDWDEDVH getMajorVersion()

5HWXUQVWKHGULYHU VPDMRUYHUVLRQQXPEHU getMinorVersion()

5HWXUQVWKHGULYHU VPLQRUYHUVLRQQXPEHU jdbcCompliant()

5HWXUQVDERROHDQYDOXHLQGLFDWLQJZKHWKHUDGULYHULVIXOO\-'%&FRPSOLDQW,WPXVWSDVVWKH -'%&FRPSOLDQFHWHVWVWRUHWXUQWUXH

DriverPropertyInfo Class $Q DUUD\ RI REMHFWV RI WKH 'ULYHU3URSHUW\,QIR FODVV LV UHWXUQHG E\ WKH JHW3URSHUW\,QIR PHWKRGRIWKH'ULYHUFODVVWRSURYLGHLQIRUPDWLRQDERXWDGULYHUWKDWFDQEHXVHGWRHVWDEOLVKD GDWDEDVHFRQQHFWLRQ7KH'ULYHU3URSHUW\,QIRFODVVSURYLGHVWKHIROORZLQJILYHILHOGYDULDEOHVWR GHVFULEHDSURSHUW\RIDGULYHU 260

Comp-U-Learn

Java DataBase Connectivity

Name Description Value Choices Required

The property's name A description of the property The current value of the property A list of possible values A variable that indicates whether the property is required

7KHIROORZLQJSURJUDPZLOOLOOXVWUDWHWKHXVDJHRI'ULYHUFODVVDQGLWVPHWKRGV Example 11.1 import java.util.*; import java.sql.*; class jd1 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Enumeration drivers=DriverManager.getDrivers(); System.out.println("available drivers"); while(drivers.hasMoreElements()) { Driver driver=(Driver)drivers.nextElement(); System.out.println("Driver :"+driver.getClass().getName()); System.out.println("Major Version :"+driver.getMajorVersion()); System.out.println("Minor Version: "+driver.getMinorVersion()); System.out.println("JDBC compliant :"+driver.jdbcCompliant()); } } catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

7KHRXWSXWRIWKHSURJUDPLVDVIROORZV C:\jdk1.2\bin>java.jd1 Available drivers Driver sun jdbc odbc.JdbcOdbcDriver Major Version 1 Minor Version 2001 JDBC compliant true C:\jdk1.2\bin>

Comp-U-Learn

261

Java Programming I

Connection Class ,WLVWKHGULYHU VUHVSRQVLELOLW\WRUHJLVWHUZLWKWKH'ULYHU0DQDJHUDQGFRQQHFWZLWKWKHGDWDEDVH 7KHFRQQHFWLRQFODVVUHSUHVHQWVWKRVHGDWDEDVHFRQQHFWLRQV7KH&RQQHFWLRQFODVVHQFDSVXODWHV WKHGDWDEDVHFRQQHFWLRQLQWRDQHDV\WRXVHSDFNDJH:KHQDGDWDEDVHFRQQHFWLRQLVHVWDEOLVKHG XVLQJ WKH JHW&RQQHFWLRQ  PHWKRG RI 'ULYHU0DQDJHU WKH JHW&RQQHFWLRQ PHWKRG UHWXUQV DQ REMHFW WKDW LPSOHPHQWV WKH &RQQHFWLRQ LQWHUIDFH 7KLV LQWHIDFH GHILQHV WKH PHWKRGV IRU LQWHUDFWLQJZLWKWKHGDWDEDVHYLDWKHHVWDEOLVKHGFRQQHFWLRQ getConnection()

7KLVLVWRHVWDEOLVKDFRQQHFWLRQWRDGDWDEDVH GetConnection(String url) GetConnection(String url,String userId, String password)

7KHILUVWIRUPWDNHVD6WULQJDUJXPHQWWKDWVSHFLILHVWKH85/RIWKHGDWDEDVH7RFRQQHFWZLWKD -'%&GDWDVRXUFHWKH85/LVXVHG7KH\DUHRIWKHIROORZLQJIRUP Jdbc:subprotocol:subname

,Q WKLV V\QWD[ VXE SURWRFRO LV WKH QDPH RI WKH GULYHU VHW WKDW GHILQHV D SDUWLFXODU GDWDEDVH FRQQHFWLYLW\ PHWKRG 6HYHUDO GULYHUV FDQ UHSUHVHQW WKLV PHWKRG 7KH VXE QDPH SDUW LV WKH DGGLWLRQDOLQIRUPDWLRQQHFHVVDU\WRFRPSOHWHWKH85/7KLVLQIRUPDWLRQGLIIHUVGHSHQGLQJRQ WKHVXESURWRFRO6XSSRVHZHZDQWWRFRQQHFWZLWKDQ0664/6HUYHUGDWDVRXUFHRQWKHKRVW WKXQGHUIR[FRPRQSRUWDQGGDWDVRXUFHLVIUHVKWKHFRQQHFWLRQ85/ZRXOGEHDVIROORZV Jdbc:msql://thunder.fox.com:80/fresh.

+HUH PVTO LV WKH VXESURWRFRO DQG WKXQGHUIR[FRP LV WKH KRVW QDPH RQ SURWRFRO SRUW  DQG GDWDVRXUFH LV IUHVK )RU WKH -'%&2'%& %ULGJH WKH VXEQDPH LV WKH 2'%& GDWDVRXUFH QDPH UHSUHVHQWLQJ  WKH GDWDVRXUFH 7KH -'%&2'%& %ULGJH LV ORFDO RQO\ :H FDQQRW FUHDWH UHPRWHO\ ORDGHG DSSOHWV WKDW XVH WKLV EULGJH EHFDXVH LW LV LPSOHPHQWHG LQ D SODWIRUP VSHFLILF PDQQHULWEUHDNVWKHDSSOHWVHFXULW\PRGHO7KHUHLVKRZHYHUDQRWKHUPHWKRGRILPSOHPHQWLQJ WKH -'%&2'%& %ULGJH 6HYHUDO FRPSDQLHV KDYH UHPRWH -'%&B2'%& EULGJH VRIWZDUH WKDW DOORZV DSSOHWV WR UXQ DJDLQVW 2'%& GDWD VRXUFH ZKHQ ORDGHG UHPRWHO\ 7ZR RI WKHVH FRPSDQLHVDUH,'6VRIWZDUHDQG:HE/RJLF 7KHIROORZLQJDUHVRPHRIWKHPHWKRGVLQWKH&RQQHFWLRQFODVV close()

&ORVHVDGDWDEDVHFRQQHFWLRQ 262

Comp-U-Learn

Java DataBase Connectivity getMetaData()

5HWXUQV DQ REMHFW RI WKH 'DWDEDVH0HWD'DWD LQWHUIDFH WKDW FDQ EH XVHG WR REWDLQ GHWDLOHG LQIRUPDWLRQDERXWWKHVWUXFWXUHDQGFDSDELOLWLHVRIDGDWDEDVH createStatement()

&UHDWHVD64/6WDWHPHQWREMHFW prepareStatement()

&UHDWHV D 64/ 3UHSDUHG6WDWHPHQW REMHFW XVLQJ DQ 64/ VWULQJ 3UHSDUHG6WDWHPHQW REMHFWV DUH SUHFRPSLOHG64/VWDWHPHQWVWKDWDUHPRUHHIILFLHQWO\H[HFXWHG prepareCall()

&UHDWHVD64/&DOODEOH6WDWHPHQWREMHFWXVLQJDQ64/VWULQJ&DOODEOH6WDWHPHQWREMHFWVDUH64/ VWRUHGSURFHGXUHFDOOVWDWHPHQWV setReadOnly()

7KLVPHWKRGDFFHSWVDERROHDQYDOXH$YDOXH758(PDNHVWKHGDWDEDVHRSHQLQD5HDGRQO\ PRGH7KLVPHWKRGFDQQRWEHFDOOHGLQWKHPLGGOHRIWKHWUDQVDFWLRQ isReadOnly()

7KLVLVXVHGWRVHHZKHWKHUWKHFRQQHFWLRQLVLQUHDGRQO\PRGH7KHUHWXUQYDOXHLVERROHDQ

DatabaseMetaData Interface 'DWDEDVH0HWD'DWD ,QWHUIDFH LV LPSOHPHQWHG E\ WKH -'%& GULYHU WR SURYLGH WKH QHFHVVDU\ LQIRUPDWLRQ RQ GDWDEDVH DQG GDWD GLFWLRQDU\ 7KH JHW0HWD'DWD PHWKRG UHWXUQV D 'DWDEDVH 0HWD'DWDREMHFWDIWHUFRQQHFWLRQLVHVWDEOLVKHG 7KH IROORZLQJ H[DPSOH PDNHV XVH RI WKH 'DWDEDVH0HWD'DWD FODVV DQG LWV PHWKRGV WR UHWULHYH LQIRUPDWLRQDERXWWKHGDWDEDVHDQGWKHWDEOHDIWHUHVWDEOLVKLQJDVXFFHVVIXOFRQQHFWLRQ )ROORZWKHVWHSVJLYHQEHORZWRFUHDWHDQ2'%&GULYHU ♦ Click Programs Æ Settings Æ Control Panel and select 32bit ODBC ♦ Click System DSN Tab and then click Add button ♦ Select ODBC Oracle Driver from the list and then press Finish Button Comp-U-Learn

263

Java Programming I

♦ Type a name for the DataSource Name. Remember this name has to be used in the getConnection method. For example in our case it is (“jdbc:odbc:you”, “scott”,”tiger”) ♦ We may give some comments in the Description box. ♦ In UserID we can specify the username as SCOTT . ♦ Click OK to close the dialog box. ♦ Click Ok once again to close the ODBC Driver Manager Dialog Box.

Note The above mentioned steps are applicable to all the programs which involves database connectivity through ODBC. 1RZW\SHWKLVSURJUDPLQ1RWHSDGDQGVDYHLWDVMGMDYD Example 11.2 import java.util.*; import java.sql.*; class jd1 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); DatabaseMetaData dm=c.getMetaData(); System.out.println("Database Name :"+dm.getDatabaseProductName()); System.out.println("Database Version:"+dm.getDatabaseProductVersion()); System.out.println("Database URL:"+dm.getURL()); System.out.println("User Name :"+dm.getUserName()); System.out.println(); System.out.println("Database Driver :"+dm.getDriverName()); System.out.println("Database Driver Version:"+dm.getDriverVersion()); System.out.println("Major Version :"+dm.getDriverMajorVersion()); System.out.println("Minor Version: "+dm.getDriverMinorVersion()); ResultSet rs=dm.getTables(null,null,null,null); while(rs.next()) { System.out.println(rs.getString(3));

264

Comp-U-Learn

Java DataBase Connectivity } c.close(); }catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

Creating a statement

$IWHUHVWDEOLVKLQJWKHFRQQHFWLRQWKHQH[WVWHSLVWRFUHDWHD64/VWDWHPHQWVRWKDWLWFDQEH H[HFXWHG7KHFUHDWH6WDWHPHQWLVDPHWKRGLQWKH&RQQHFWLRQFODVV7KLVPHWKRGGRHVQRWWDNH DQ\DUJXPHQWV$FWXDO64/WREHH[HFXWHGLVSDVVHGZKHQH[HFXWHLVFDOOHG

Prepared Statement $3UHSDUHG6WDWHPHQWLVXVHIXOZKHQWKHVDPH VWDWHPHQW LV WR EH UHSHDWHG VHYHUDO WLPHV ,W LV DOVRSRVVLEOHWRFKDQJHWKHSDUDPHWHUVLQ3UHSDUHGVWDWHPHQWV3UHSDUHGVWDWHPHQWVDUHEDVLFDOO\ XVHIXOWR LQFUHDVH WKH HIILFLHQF\ RI WKH SURJUDPV ,W H[WHQGV WKH 6WDWHPHQW ,QWHUIDFH WR GHILQH PHWKRGV WKDW DUH XVHG WR ZRUN ZLWK SUHFRPSLOHG 64/ VWDWHPHQWV 3UHSDUHG6WDWHPHQW REMHFWV PD\EHXVHGZLWKSDUDPHWHUL]HG64/VWDWHPHQWV7KHVHSDUDPHWHUL]HG64/VWDWHPHQWVUHSODFH DFRQVWDQW64/H[SUHVVLRQZLWKDTXHVWLRQPDUN For example Select ? from emp

" PDUN ZLOO WKHQ EH UHSODFHG E\ WKH SDUDPHWHU SDVVHG 7KH PHWKRGV VHW,QW VHW6WULQJ VHW2EMHFW  VHW'DWH VHW7LPH VHW'RXEOH DUH XVHG WR VHW WKH YDOXHV WR WKH DSSURSULDWH SDUDPHWHUV For example PreparedStatement st=con.prepareStatement("select * from item where pcode=?); St.setInt(1,100);

+HUHWKHILUVWSDUDPHWHUWRVHW,QWLVWKHQXPEHURIWKHDUJXPHQWLHRQO\RQHSDUDPHWHUWREH SDVVHG 7KH VHFRQG DUJXPHQW UHIHUV WR WKH YDOXH +HUH WKH GHWDLOV RI WKH LWHP ZKRVH SURGXFW FRGHLVZLOOEHFRQWDLQHGLQWKHUHVXOWVHW

Comp-U-Learn

265

Java Programming I

Callable Statement &DOODEOH 6WDWHPHQW LV XVHIXO WR FDOO WKH VWRUHG SURFHGXUHV LQ WKH 'DWDEDVH HQJLQH $ VWRUHG SURFHGXUH LV XVHG  ZKHQ GLIIHUHQW W\SHV RI FOLHQWV QHHG WKH VDPH IXQFWLRQDOLW\ $QRWKHU DGYDQWDJHRIWKLVLVWKDWLWFDQEHXVHGWRFKHFNIRUDOOW\SHVRIFRQVWUDLQWVVLQFHWKHZKROHGDWD LV DYDLODEOH WR VWRUHG SURFHGXUHV ,W LV D PHFKDQLVP WR H[HFXWH VWRUHG SURFHGXUHV QRW DQ HQFDSVXODWLRQ RI VWRUHG SURFHGXUHV 7KH  SDUDPHWHUV FDQ DOVR EH SDVVHG WR WKH VWRUHG SURFHGXUHV,WKDVWKHVDPHIXQFWLRQVDVWKHSUHSDUHG6WDWHPHQWLQWHUIDFH

Executing SQL using JDBC 7KH64/VWDWHPHQWVDUHH[HFXWHGXVLQJWKHH[HFXWHPHWKRG7KLVFDQEHXVHGWR H[HFXWHDQ\ W\SHRI64/VWDWHPHQWV7KHUHVXOWRI64/VWDWHPHQWVYDULHV)RUH[DPSOHWKHUHVXOWRIDVHOHFW LQVHUWXSGDWHDQGGHOHWHDUHQRWLGHQWLFDO 7R VROYH WKHVH GLIIHUHQFHV LQ WKH UHVXOWVHW -'%& RIIHUV WKUHH PHWKRGV 7KH ILUVW RQH LV H[HFXWH4XHU\ PHWKRGZKLFKFDQEHXVHGLQFDVHWKHUHWXUQUHVXOWRIWKH64/VWDWHPHQWLVD SRUWLRQRIDGDWDEDVH7KHUHWXUQYDOXHRIWKLVIXQFWLRQLVD5HVXOW6HWZKLFKLVQRWKLQJEXWWKH SRUWLRQRIGDWDEDVHKDYLQJVRPHURZVRIWKHWDEOH7KHQH[WPHWKRGLVH[HFXWH8SGDWH ZKLFK FDQEHXVHGIRULQVHUWGHOHWHDQGXSGDWHFRPPDQGVWKDWZRUNRQWKHGDWDLQVLGHWKHWDEOHV7KH UHWXUQYDOXHRIWKLVPHWKRGLVDQLQWHJHUZKLFKVD\VWKHQXPEHURIURZVWKDWKDYHEHHQDIIHFWHG E\WKHVH64/FRPPDQGV7KHQH[WPHWKRGLVH[HFXWH ZKLFKLVXQLYHUVDODQGFDQEHXVHGIRU DQ\ W\SH RI 4XHULHV :KHQ ZH XVH WKH H[HFXWH  PHWKRG LW LV HVVHQWLDO WKDW ZH JHW HDFK DQG HYHU\ UHVXOW VHSDUDWHO\ 7KH UHWXUQ YDOXH RI HDFK DQG HYHU\ UHVXOW LV JLYHQ H[SOLFLWO\ 7KH JHW0RUH5HVXOWV LVXVHGWRJHWWKHQH[WUHWXUQYDOXHLQWRWKHEXIIHU7KHUHWXUQYDOXHIRUWKLV PHWKRG FDQ EH HLWKHU D UHVXOWVHW RU DQ LQWHJHU 7KH PHWKRG JHW5HVXOW6HW  LV XVHG WR JHW WKH 5HVXOW6HWREMHFWIURPWKHFXUUHQW64/VWDWHPHQWH[HFXWHG,QFDVHJHW0RUH5HVXOWV UHWXUQVDQ LQWHJHUWKHQWKHPHWKRGJHW8SGDWH&RXQWKDVWREHXVHG,WUHWXUQVDQLQWHJHUYDOXHLQGLFDWLQJ WKHQXPEHURIURZVDIIHFWHGE\WKHJLYHQ64/FRPPDQG

Note There is no direct way of checking the return value of the method getMoreResults. It has to be done only by using the two methods getResultSet() and getUpdateCount(). All JDBC methods throw SQLException, which must be caught.

Transaction Processing $WUDQVDFWLRQFRQVLVWVRIDJURXSRIUHODWHGGDWDEDVHRSHUDWLRQV7KH64/VWDWHPHQWVWKDWPDNH XSDWUDQVDFWLRQXSGDWHWKHGDWDEDVHDWWKHVDPHWLPH(YHQWKRXJKWKHVWDWHPHQWVDUHH[HFXWHG 266

Comp-U-Learn

Java DataBase Connectivity

LQVHTXHQFHWKH\GRQRWSHUPDQHQWO\XSGDWHWKHGDWDEDVHXQWLOWKH\DUHFRPPLWWHG,IDQHUURU RFFXUVGXULQJWKHSURFHVVLQJRIDWUDQVDFWLRQWKH64/VWDWHPHQWVWKDWPDNHXSWKHWUDQVDFWLRQ FDQEHUROOHGEDFN 7KHVHW$XWR&RPPLW FRPPLW DQGUROOEDFN PHWKRGVRIWKHFRQQHFWLRQLQWHUIDFHDUHXVHGWR LPSOHPHQW WUDQVDFWLRQ SURFHVVLQJ 7KH VHW$XWR&RPPLW  PHWKRG WXUQV RII DXWRPDWLF FRPPLWWLQJ RI 64/ VWDWHPHQWV 7KH VHW$XWR&RPPLW 758(  HQDEOHV DXWR FRPPLWV ZKLOH VHW$XWR&RPPLW )$/6( GLVDEOHVDXWRFRPPLW,IDXWRFRPPLWLVWXUQHGRQWKHQDOOWKH64/ VWDWHPHQWV DUH H[HFXWHG DQG FRPPLWWHG DV LQGLYLGXDO WUDQVDFWLRQV :KHQ VHW$XWR&RPPLW  LV WXUQHGRII64/VWDWHPHQWVDUHRUJDQL]HGLQWRDVLQJOHWUDQVDFWLRQXQWLODFRPPLW RUUROOEDFN PHWKRGLVLQYRNHG7KHJHW$XWR&RPPLW LVXVHGWRNQRZWKHFXUUHQWDXWRFRPPLWVWDWH7KH FRPPLW PHWKRGFRPSOHWHVDWUDQVDFWLRQE\FRPPLWWLQJDOO64/VWDWHPHQWVWKDWDUHH[HFXWHG VLQFH WKH ODVW FRPPLW RU UROOEDFN 7KH UROOEDFN  PHWKRG UHYHUVHV D WUDQVDFWLRQ WKDW LV LQ SURJUHVVE\HUDVLQJWKHHIIHFWVRIDOO64/VWDWHPHQWVWKDWDUHH[HFXWHGVLQFHWKHODVWFRPPLWRU UROOEDFN $QH[DPSOHWRVKRZDVLPSOHGDWDEDVHRSHUDWLRQ Example 11.3 import java.sql.*; import java.util.*; class jd2 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:uma","scott","tiger"); Statement st=c.createStatement(); System.out.println("Executing SQl"); ResultSet rs=st.executeQuery("Select * from item"); try { while(rs.next()) { System.out.print(rs.getInt("pcode")+ ":"); System.out.println(rs.getString("pname")); System.out.println(rs.getString("price")); } } catch(Exception e) { System.out.println("Inside :" +e);

Comp-U-Learn

267

Java Programming I } } catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

2XWSXWRIMGMDYD C:\jdk1.1.7\bin>javac jd2.java C:\jdk1.1.7\bin>java jd2 Executing SQl 1:lux 20 2:hamam 15 3:cinthol 13 4:doy 14 5:rexona 18

7KLVSURJUDPJLYHV WKH GDWD DYDLODEOH LQ WKH LWHP WDEOH ,Q RUGHU WR H[HFXWH WKLV SURJUDP ILUVW OHW·VFUHDWHDWDEOHFDOOHGLWHPXVLQJWKHIROORZLQJFRPPDQGLQ2UDFOH create table item ( pcode Number(3), pname varchar2(20), price Number(3) );

,QVHUWWKHIROORZLQJYDOXHVLQWRWKHWDEOHXVLQJWKHLQVHUWVWDWHPHQW7KHQH[HFXWHWKHSURJUDP 7KLVVKRZVWKHXVDJHRIVHOHFWFRPPDQGLQ-'%&7KHSDUDPHWHUVWRJHW&RQQHFWLRQVKRXOGEH WKH '61 WKDW ZH FUHDWHG WKURXJK 2'%& $QG WKH XVHUQDPH DQG SDVVZRUG VKRXOG EH RXU 2UDFOHXVHUQDPHDQGSDVVZRUG 7KHQH[WH[DPSOHZLOOVKRZZHKRZWRLQVHUWQHZYDOXHVLQWRWKHWDEOHXVLQJ2'%& Example 11.4 import java.sql.*; import java.util.*; import java.io.*;

268

Comp-U-Learn

Java DataBase Connectivity class jd9 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); Statement st=c.createStatement();

DataInputStream sin=new DataInputStream(System.in); System.out.println("Enter the code for the product : "); System.out.flush(); String st2=sin.readLine(); int y=Integer.parseInt(st2);

DataInputStream tin=new DataInputStream(System.in); System.out.println("Enter the name of the product : "); System.out.flush(); String st1=tin.readLine();

DataInputStream rin=new DataInputStream(System.in); System.out.println("Enter the price of the product : "); System.out.flush(); String st3=rin.readLine(); int z=Integer.parseInt(st3);

try {

int x=st.executeUpdate("insert into item values("+y+",'"+st1+"',"+z+")"); System.out.println("Number of rows affected="+x); } catch(Exception e) { System.out.println("Inside :" +e); } } catch(Exception e) { System.out.println(e); } } }

Comp-U-Learn

269

Java Programming I

7KHRXWSXWRIWKHSURJUDP C:\jdk1.1.7\bin>java jd9 Enter the code for the product : 1 Enter the name of the product : Dettol Enter the price of the product : 18 Number of rows affected=1

+HUHWKHXVHUJLYHVWKHYDOXHVIRULQVHUWLRQWRWKHSURJUDPDWUXQWLPHDQGWKHYDOXHVDUHWKHQ LQVHUWHG7KHSURJUDPGRHVQRWPDNHXVHRISUHSDUH6WDWHPHQWV 1RZZHZLOOVHHKRZWRXSGDWHDUHFRUGLQDWDEOH)LUVWOHW·VJLYHWKHYDOXHVIRUXSGDWLQJLQWKH SURJUDPLWVHOI Example 11.5 import java.sql.*; import java.util.*; class jd3 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); Statement st=c.createStatement(); try { int z=st.executeUpdate("update item set pname='Margo' where pname='lux'"); System.out.println("number of rows affected="+z); } catch(Exception e) { System.out.println("Inside :" +e); } } catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

270

Comp-U-Learn

Java DataBase Connectivity

2XWSXWRIWKHSURJUDPMG C:\jdk1.1.7\bin>javac jd3.java C:\jdk1.1.7\bin>java jd3 number of rows affected=1 C:\jdk1.1.7\bin>

)LQDOO\ZHVKDOOVHHKRZWRGHOHWHDUHFRUGDOVR7KHUHFRUGIRUGHOHWLRQLVJLYHQLQWKHSURJUDP LWVHOI Example 11.6 import java.sql.*; import java.util.*; class jd4 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); Statement st=c.createStatement(); try { int z=st.executeUpdate("delete from item where pname='hamam' "); System.out.println("number of rows affected="+z); } catch(Exception e) { System.out.println("Inside :" +e); } } catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

2XWSXWRIMG C:\jdk1.1.7\bin>javac jd4.java C:\jdk1.1.7\bin>java jd4 number of rows affected=1 C:\jdk1.1.7\bin>

Comp-U-Learn

271

Java Programming I

Note We can execute jd2.java program after insert, update and delete to view the changes in the backend. 7KHIROORZLQJSURJUDPZLOOQRZLOOXVWUDWHSUHSDUHG6WDWHPHQWDQGLWVXVDJH Example 11.7 import java.sql.*; import java.util.*; import java.io.*; class jd10 { public static void main(String argv[]) throws Exception { if(argv.length<3) { System.out.println("Pass pcode,pname,price as arguments "); } try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); PreparedStatement st=c.prepareStatement("insert into item values(?,?,?"+")"); st.setInt(1,Integer.parseInt(argv[0])); st.setString(2,argv[1]); st.setInt(3,Integer.parseInt(argv[2])); try { int z=st.executeUpdate(); System.out.println("Number of rows affected="+z); } catch(Exception e) { System.out.println("Inside :" +e); } st.close(); c.close(); } catch(Exception e) { System.out.println(e); } } }

272

Comp-U-Learn

Java DataBase Connectivity

7KHRXWSXWLVDVIROORZV C:\jdk1.1.7\bin>java jd10 Pass pcode,pname,price as arguments java.lang.ArrayIndexOutOfBoundsException: 0 C:\jdk1.1.7\bin>java jd10 6 Breeze 21 Number of rows affected=1 C:\jdk1.1.7\bin>java jd2 Executing SQl 1:Dettol 18 2:Margo 12 3:Hamam 13 4:dove 14 5:rexona 18 6:Breeze 21 12:Neem 17

1RWH WKH LQVHUW VWDWHPHQW JLYHQ LQ SUHSDUH6WDWHPHQW 7KH YDOXHV IRU LQVHUWLRQ DUH JLYHQ DV FRPPDQGOLQHDUJXPHQWVDQGWKHSURJUDPLQVHUWVWKHYDOXHVLQWKHWDEOH,WFDQEHYHULILHGXVLQJ MGMDYDSURJUDPZKLFKGLVSOD\VWKHFRQWHQWVRIWKHWDEOHLWHP /HWXVWDNHDQRWKHUSURJUDPWKDWXVHVSUHSDUH6WDWHPHQWIRUXSGDWLRQ Example 11.8 import java.sql.*; import java.util.*; import java.io.*; class jd8 { public static void main(String argv[]) throws Exception { if(argv.length<2) { System.out.println("Pass pcode and pname as arguments "); } try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Comp-U-Learn

273

Java Programming I Connection c=DriverManager.getConnection("jdbc:odbc:you","scott","tiger"); PreparedStatement st=c.prepareStatement("update item set pname= ? where code = ?"); st.setString(1,argv[1]); st.setInt(2,Integer.parseInt(argv[0])); try { int z=st.executeUpdate(); System.out.println("Number of rows affected="+z); } catch(Exception e) { System.out.println("Inside :" +e); } st.close(); c.close(); } catch(Exception e) { System.out.println(e); } } }

2XWSXWRIMGLVDVIROORZV Before update PCODE PNAME PRICE --------- ---------- --------3 cinthol 13 4 doy 14 5 rexona 18 After Execution C:\jdk1.1.7\bin>java jd8 Pass pcode and pname as arguments java.lang.ArrayIndexOutOfBoundsException: 1 C:\jdk1.1.7\bin>java jd8 3 Hamam Number of rows affected=1 C:\jdk1.1.7\bin>java jd2 Executing SQl 3:Hamam 13 4:dove 14 5:rexona 18

274

Comp-U-Learn

Java DataBase Connectivity

7KHH[DPSOHEHORZLVWRVKRZDVLPSOHGDWDUHWULHYDORSHUDWLRQLQD0LFURVRIW$FFHVVGDWDEDVH 7KH 7DEOH QDPH LV ERRN DQG WKH ILHOGV DUH ERRNFRGH ERRNQDPH DQG SULFH 'DWDVRXUFH LQ 2'%&LV/,%)LUVWFUHDWHDWDEOHLQ$FFHVVFDOOHGERRNLQVHUWVRPHYDOXHVLQWRWKHWDEOHDQG WKHQH[HFXWHWKHSURJUDP Example 11.9 import java.sql.*; import java.util.*; class jd2 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection("jdbc:odbc:LIB"); Statement st=c.createStatement(); System.out.println("Executing SQl"); ResultSet rs=st.executeQuery("Select * from BOOK"); try { while(rs.next()) { System.out.print(rs.getInt("PRICE")+ ":"); System.out.println(rs.getString("BOOK_CODE")); System.out.println(rs.getString("BOOK_NAME")); } } catch(Exception e) { System.out.println("Inside :" +e); } } catch(Exception e) { System.out.println(e); System.out.println("Cannot find the class"); } } }

7KHRXWSXWRIWKHSURJUDPLV C:\jdk1.1.5\bin>java jd2 Executing SQl 200:B004 ORACLE & DEV 2K 150:B005 OBJECT ORIENTED C++ 700:B006

Comp-U-Learn

275

Java Programming I SOFTWARE ENGINEERING 300:B007 POWER BUILDER 450:B008 WIN 32 API BIBLE 500:B009 JAVA REFERENCE

Summary

This session explains the basics of JDBC, various kinds of drivers being used and also the usage of JDBC – ODBC Bridge driver. We also saw the basic operations of performing insertion, updation and deletion through JDBCODBC and how to retrieve data using the select statement. Some examples were also shown on prepareStatement. Basically the aim is to do a client-server programming in Java using JDBC-ODBC Bridge driver.

Going Over It Again I. Fill in the Blanks

 7KHPHWKRGJHW&RQQHFWLRQKDVWKHBBBBBBBBBBBBBBBBBBBBBBBBBBBSDUDPHWHUV  7KH'DWDEDVH0HWD'DWDREMHFWLVUHWULHYHGXVLQJBBBBBBBBBBBPHWKRG  BBBBBBBBBBBBBBBBBBBBPHWKRGLVXVHGWRNQRZWKHFXUUHQWFRPPLWVWDWH  7KHBBBBBBBBBBBBBBPHWKRGFORVHVWKHGDWDEDVHFRQQHFWLYLW\  7KHBBBBBBBBBBBBBBBBBBPHWKRGLVXVHGWRFRPPLWWKHWUDQVDFWLRQV II. One line Answers

 /LVWWKHYDULRXV-'%&GULYHUV  ([SODLQVLQJOHWLHUDUFKLWHFWXUH  ([SODLQWKUHHWLHUDUFKLWHFWXUH  6WDWHWKHXVDJHRIFDOODEOHVWDWHPHQW  :KDWGRHVWUDQVDFWLRQSURFHVVLQJPHDQ"

276

Comp-U-Learn

Session 12

Networking in Java

On Completion of this Session We will be able to understand...

) Datagram Sockets ) Datagram Packets ) Creating links Inside an Applet ) Connection class

In This Session...



Networking in Java



Datagrams



What is a Datagram?



DatagramPacket



DatagramSocket



Duplication of Socket



Creating Links Inside Applets



Opening Web Connections



The URL Connection Class



Sockets



Other Applet Hints



Communicating Between Applets

Networking in Java

Networking in Java 1HWZRUNLQJ LV RQH RI -DYD·V XQLTXH IHDWXUHV $V EHIRUH LW SURYLGHV YDULRXV VHW RI FODVVHV IRU DFFHVVLQJ ERWK ORFDO DQG LQWHUQHWZRUNLQJ LQ DQ DEVWUDFW IDVKLRQ WKDW LV W\SLFDO RI -DYD 7KH SDFNDJH MDYDQHW RIIHUV SOHQW\ RI FODVVHV DQG LQWHUIDFHV IRU SHUIRUPLQJ LQWHUQHWZRUNLQJ LQ D VPRRWK DQG VRSKLVWLFDWHG IDVKLRQ %XW EHIRUH GLYLQJ LQWR WKH QXDQFHV RI LW ZH QHHG WR XQGHUVWDQGFHUWDLQFRQFHSWV 1HWZRUNLQJLVWKHFRPPXQLFDWLRQEHWZHHQWZRPDFKLQHVORFDORUUHPRWH$QGWKHUHDUHWZR IRUPV RI QHWZRUNLQJ FRQQHFWLRQRULHQWHG DQG FRQQHFWLRQOHVV ,Q D &RQQHFWLRQRULHQWHG QHWZRUNIURPRXUPDFKLQHZHNQRZWKHRWKHUHQGDQGWDONWRWKHPDFKLQHE\HVWDEOLVKLQJD ILUPFRQQHFWLRQ6RZKHQZHVHQGWKHGDWDWRWKHRWKHUHQGZHDUHSUHWW\VXUHWKDWLWZLOOUHDFK WKHUH (YHQ LI LW GRHVQ·W ZH·OO JHW WR NQRZ WKDW LW GLGQ·W ,Q D FRQQHFWLRQOHVV VHWXS ZH GRQ·W PDNHDFRQQHFWLRQWRWKHRWKHUHQGEHIRUHVHQGLQJWKHGDWD:HMXVWSXWWKHGDWDLQDSDFNHW ODEHOWKHDGGUHVVRIWKHRWKHUHQGRQWKHSDFNHWDQGMXVWVHQGLW:HDFWXDOO\DUHQRWERWKHUHG ZKHWKHULWUHDFKHVRUQRW$QGZHZRQ·WNQRZKRZVXFFHVVIXOWKHRSHUDWLRQRIVHQGLQJWKHGDWD ZDV 7ZR SURWRFROV DUH XVHG IRU WKHVH RSHUDWLRQV 7&3 DQG 8'3 7&3 VWDQGV IRU 7UDQVPLVVLRQ &RQWURO3URWRFROLVDFRQQHFWLRQRULHQWHGRQH,WDLPVDWHVWDEOLVKLQJDFRQQHFWLRQWRWKHRWKHU HQG EHIRUH DWWHPSWLQJ DQ\ FRPPXQLFDWLRQ 8'3 VWDQGV IRU 8VHU 'DWDJUDP 3URWRFRO RQ WKH RWKHU KDQG EHOLHYHV LQ MXVW VHQGLQJ WKH GDWD ZLWKRXW DQ\ IXUWKHU ERWKHUDWLRQ %RWK WKHVH SURWRFROV FRPH ZLWK WKHLU RZQ VKDUH RI PHULWV DQG GHPHULWV 7&3 LV D UHOLDEOH SURWRFRO EXW FRPHVZLWKDKLJKHUPHPRU\RYHUKHDGXQGHUVWDQGDEO\RIFRXUVH8'3LVXQUHOLDEOHEXWDOLJKW ZHLJKWSURWRFRO -DYDVXSSRUWVERWKWKHVHSURWRFROV &RQQHFWLRQEHWZHHQWZRFRPSXWHUVLVHVWDEOLVKHGE\PHDQVRIDFRQFHSWFDOOHG6RFNHWV:KDW DUHVRFNHWVDQGZK\DUHWKH\UHTXLUHG",PDJLQHKDYLQJWRFRPPXQLFDWHZLWKWZRPDFKLQHV":H QHHGWRXQGHUVWDQGORWRIWHFKQLFDOKDUGZDUHDQGSODWIRUPUHODWHGGHWDLOVEHIRUHZHDWWHPSWDQ\ FRPPXQLFDWLRQ 1HWZRUNLQJ LV D FRPSOH[ SURFHVV $ 6RFNHW KLGHV WKHVH LQWULFDFLHV IURP WKH SURJUDPPHUDQGKHOSVKLPKDQGOHQHWZRUNVDVVLPSOHDVKRZKHKDQGOHVGLVNILOHV$6RFNHWLV DQDEVWUDFWFRPPXQLFDWLRQSRLQWVDFURVVWZRFRPSXWHUV 7KRXJK VRFNHWV KHOS FRQQHFW WKH\ FRPH LQ WZR IODYRUV )RU FRQQHFWLRQ DQG FRQQHFWLRQOHVV RSHUDWLRQV:KHQ\RXKDYHDILUPFRQQHFWLRQEHWZHHQWZRPDFKLQHV\RXFDQFRPIRUWDEO\VHQG GDWDFRQWLQXRXVO\$QGYLFHYHUVD$QGLI\RXGRQ·WKDYHDFRQQHFWLRQDQGXVH8'3\RXFDQ·W VHQGWKHGDWDFRQWLQXRXVO\
Comp-U-Learn

279

Java Programming I

$QG WKH WZR PDFKLQHV ZKLFK FRPPXQLFDWH QHHG QRW EH RQ WKH VDPH OHYHO VR WR VSHDN 2QH PDFKLQH FDQ EH D VHUYHU DQG RWKHU D FOLHQW $ 6HUYHU VHUYHV $QG &OLHQW UHFHLYHV +HQFH D 6HUYHUDOZD\VUHFHLYHVUHTXHVWVIURPFOLHQWVDQGVHUYLFHWKHLUUHTXHVWV,WFRXOGEHDGDWDEDVHD SULQWRUD:HERUDPDLOVHUYHU%DVHGRQLWVW\SHLWSURFHVVHVWKHLUUHTXHVWVDQGVHQGVWKHP ZKDW WKH\ KDYH DVNHG IRU 2I FRXUVH WKH UHTXHVWV DUH SURFHVVHG RQO\ EDVHG RQ WKH VHFXULW\ UHVWULFWLRQV :LWKWKLVXQGHUVWDQGLQJZHSURFHHGIXUWKHUWROHDUQKRZ-DYDKDQGOHVWKHVHLQWULFDFLHV

Datagrams &OLHQWVDQGVHUYHUVWKDWFRPPXQLFDWHWKURXJKDFKDQQHOVKRXOGKDYHDGHGLFDWHGSRLQWWRSRLQW FRPPXQLFDWLRQEHWZHHQWKHPVHOYHV%\FKDQQHOWKH\KDYHWRFRQQHFWWUDQVPLWWKHGDWDDQG FORVH WKH FRQQHFWLRQ 7KH GDWD ZKLFK LV UHFHLYHG ZLOO EH DUUDQJHG LQ DQ RUGHU LQ ZKLFK WKH\ ZHUHVHQW ,QWKHRWKHUZRUGVDSSOLFDWLRQWKDWFRPPXQLFDWHVYLDGDWDJUDPVVHQGDQGUHFHLYHFRPSOHWHO\ LQGHSHQGHQWSDFNHWVRILQIRUPDWLRQ$QGWKHVHFKDQQHOVGRQRWQHHGWRKDYHDGHGLFDWHGSRLQW WRSRLQWFKDQQHOIDFLOLW\ :HFDQGHILQHDGDWDJUDPDVDQLQGHSHQGHQWVHOIFRQWDLQHGPHVVDJHSDFNHWZKLFKFDQEHVHQW RYHUWKHQHWZRUNZKRVHDUULYDODUULYDOWLPHDQGFRQWHQWDUHQRWJXDUDQWHHG 7KH MDYDQHW SDFNDJH FRQWDLQV WZR PDMRU FODVVHV WR KHOS XV WR ZULWH -DYD SURJUDPV WKDW XVH GDWDJUDPVWRVHQGDQGUHFHLYHSDFNHWVRYHUWKHQHWZRUN7KH\DUH ♦ DatagramPacket ♦ Datagram Socket 2XUDSSOLFDWLRQVHQGVDQGUHFHLYHV'DWDJUDP3DFNHWVWKURXJKD'DWDJUDP6RFNHW

What is a Datagram? Writing A Datagram Client/Server

7KH H[DPSOH IHDWXUHG LQ WKLV VHFWLRQ FRPSULVHV WZR DSSOLFDWLRQV D FOLHQW DQG D VHUYHU  7KH VHUYHUZLOOUHFHLYHGDWDJUDPSDFNHWVRYHUDGDWDJUDPVRFNHW(DFKGDWDJUDPSDFNHWUHFHLYHGE\ WKH VHUYHU LQGLFDWHV D FOLHQW UHTXHVW IRU DQ DFNQRZOHGJHPHQW RU VRPHWKLQJ WR SULQW RQ WKH VFUHHQ 7KHIROORZLQJH[DPSOHLOOXVWUDWHVWKHFOLHQWDQGVHUYHUSURJUDPVVHSDUDWHO\ 280

Comp-U-Learn

Networking in Java The Client Side

'DWDJUDP6RFNHWLVDNLQGRISURWRFROIRUWUDQVPLWWLQJGDWDIURPWKHFOLHQWVLGH VHQGHU WRWKH VHUYHUVLGH UHFHLYHU 7KHH[DPSOHEHORZVKRZVKRZWKHIORZJRHVIRUWKHFOLHQWVLGH Example 12.1 //Transmission of single file import java.net.*; import java.io.*; class Transfer { public static void main(String args[])throws Exception { int i=0; byte b[]=new byte[1200]; // creating temporary memory for object b. FileInputStream f=new FileInputStream("clicker.java"); DatagramSocket d=new DatagramSocket(666); while(f.available()!=0) { b[i]=(byte)f.read(); i++; } f.close(); d.send(new DatagramPacket(b,i,InetAddress.getByName("srini"),999)); } // here we have to have our own machine number like “srini” for us. }

:HZLOOVWXG\LQGHWDLODERXWWKHHDFKDQGHYHU\OLQHRIWKHDERYHWUDQVPLWWLQJSURJUDPDQGWKHQ FRQFHQWUDWHRQKRZWKHPHVVDJHKDVEHHQUHFHLYHGLQWKHVHUYHU UHFHLYLQJVLGH  Explanation for Transfer.java import java.net.*; import java.io.*;

$OO SDFNDJHV ZKLFK LQYROYH WKH LQSXWRXWSXW IXQFWLRQV DUH SUHVHQW RQO\ LQ  LRMDYD   6R LQ RUGHU WR XWLOL]H WKHVH SDFNDJHV ZH KDYH WR LPSRUW WKHVH SDFNDJHV WR DFWLYDWH WKH WUDQVPLWWLQJ DQGUHFHLYLQJSURJUDPV Comp-U-Learn

281

Java Programming I

7KH QHWMDYD SDFNDJH LV LQYROYHG  LQ RUGHU WR LPSRUW WKH IXQFWLRQV IRU 'DWDJUDP6RFNHW DQG 'DWDJUDP3DFNHWSURJUDPPLQJ ,QRUGHUWRJHWWKHUHTXLUHGILOHRUWH[WWKHILOHLQSXWVWUHDPLVDGGHGDERYH FileInputStream f=new FileInputStream("clicker.java");

,QRUGHUWRWUDQVIHUWKHUHTXLUHGILOHRUWH[WWKURXJKSDFNHWVWKH'DWDJUDP3DFNHWLVLQWURGXFHG KHUH7KHUHDUHWZRW\SHVRI'DWDJUDPV7KH\DUHDVIROORZV ♦ DatagramPacket ♦ DatagramSocket

DatagramPacket +HUHWKHDFWXDOPHVVDJHLVVSOLWLQWRGLIIHUHQWSDFNHWVZLWKDVHQGLQJDGGUHVVDQGDUHFHLYLQJ DGGUHVV   :KHQ WKH SDFNHWV DUH UHDFKHG 7KH\ ZLOO DXWRPDWLFDOO\ JHW UHDUUDQJHG LQ  WKH RUGHU WKH\ZHUHVHQW7KHFRQWDLQHUXVHGWRFDUU\WKRVHPHVVDJHVDUHWKH'DWDJUDP3DFNHWV +HUH WKH 'DWDJUDP3DFNHWV DUH GLYLGHG LQWR  GLYLVLRQV LQFOXGLQJ WKH VHQGHU·V DGGUHVV DQG WKH UHFHLYHU·VDGGUHVV 7KHIROORZLQJFRGHLVWRGHILQHZKHWKHUWKHLQFRPLQJPHVVDJHFRQWDLQVDQ\GDWDRUQRW while(f.available()!=0) { b[i]=(byte)f.read(); i++; } f.close();

2QFHWKHPHVVDJHLVWUDSSHGLWZLOOFKHFNIRUWKHGDWD,IIRXQGLWZLOOFDVWLWLQWRE\WH2QFH DOOWKHGDWDDUHUHDGIURPWKHILOHZHKDYHWRFORVHWKHILOH1RZGDWDLVUHDG\IRUVHQGLQJ

DatagramSocket $V GHILQHG SUHYLRXVO\ LW LV OLNH D FKDQQHO WR VHQG DQG UHFHLYH PHVVDJHV WKURXJK D 'DWDJUDP3DFNHW7KHVH'DWDJUDP6RFNHWDUHRIWZRW\SHV7KH\DUH 'DWDJUDP6RFNHWZLWKSRUW12 LQFRPLQJ 282

Comp-U-Learn

Networking in Java

'DWDJUDP6RFNHWZLWKSRUW12 RXWJRLQJ ,QWKHDERYHSURJUDPZHKDYHXVHG DatagramSocket d=new DatagramSocket(666);

$VWKHDERYHSURJUDPLVWRVHQGWKHSDFNHWVWKH'DWDJUDP6RFNHWDGGUHVVLVXVHG 7KHPDLQFRQFHSWRIVHQGLQJWKHPHVVDJHLVWRGHILQHWKH'DWDJUDP6RFNHWZLWKWKH,QHWDGGUHVV RIWKHFOLHQWPDFKLQHZKHUHWKHPHVVDJHKDVWRUHDFK d.send (new DatagramPacket (b,i,InetAddress.getByName ("srini"),999)); 7KH'DWDJUDP3DFNHWVKRXOGEHLQLWLDOL]HGZLWKWKHE\WHVWREHVHQW´EµWKHQXPEHURIURZV LH WKH URZ FRXQW RI E\WH DUUD\  WR EH VHQW ,QHW$GGUHVVJHW%\1DPH ´ WKH QDPH RI WKH PDFKLQH ZKHUH ZH KDYH WR VHQG WKH PHVVDJHµ IROORZHG E\ WKH SRUW QR µµ ZKHUH WKH VHUYHU LV OLVWHQLQJ 7KH SURFHVV RI VHQGLQJ LV KRZ RYHU :H ZLOO QRZ VHH KRZ WKH PHVVDJHV DUH UHFHLYHG DW WKH VHUYHU UHFHLYLQJVLGH  The Server Side

,WLVDNLQGRISURWRFROIRUUHFHLYLQJWKH  GDWD IURP WKH FOLHQW VLGH VHQGHU  WR WKH VHUYHU VLGH UHFHLYHU 7KHH[DPSOHEHORZVKRZVKRZWKHIORZJRHVDWWKHVHUYHUVLGH Example 12.2 import java.io.*; import java.lang.*; import java.net.*; class received { public static void main(String args[]) throws Exception { int c,j=0; byte b[]=new byte[1024]; DatagramSocket d=new DatagramSocket(999); while(true) {

Comp-U-Learn

283

Java Programming I DatagramPacket p= new DatagramPacket(b,1024); d.receive(p); System.out.println (new String(p.getData(),0,0,p.getLength())); } } }

+HUHLQWKHDERYHSURJUDPLPSRUWLQJWKH-DYDSDFNDJHVZLOOEHVDPHDVWKHWUDQVIHUSURJUDPRI WKHFOLHQWVLGH7KHGLIIHUHQFHLVPDLQO\RQDFFHSWLQJWKHPHVVDJHDQGGLVSOD\LQJWKHPHVVDJH RQWKHVFUHHQWKURXJKWKH'DWDJUDP6RFNHWSRUWDGGUHVV´µ $WWKLVPRPHQWEHIRUHZHJHWEDIIOHGE\WKHWHUPSRUWOHW·VGHILQHLW $SRUWLVDFRQQHFWLRQSRLQWIRUDGHYLFH,WFRXOGEH DSK\VLFDO KDUGZDUHFDUGRU DQDEVWUDFW VRIWZDUH SRLQW (DFK VHUYLFH KDV D VHSDUDWH SRUW QXPEHU IRU PDNLQJ XQLTXH FRQQHFWLRQV )RU LQVWDQFH+773SURWRFRODOZD\VKDVDVWDQGDUGSRUWQXPEHU6RPHRIWKHFRPPRQO\XVHG SRUWQXPEHUVDUHGHILQHGKHUH Port 21 23 25 80

Protocol File Transfer Protocol Telnet SMTP HTTP

7KHSRUWVHOHFWLRQLVVKRZQEHORZ DatagramSocket d=new

DatagramSocket(999);

+HUH IRU UHFHLYLQJ WKH GDWD WKH SRUW DGGUHVV ´µ LV XVHG 8VLQJ WKH VRFNHW FODVV· VHQG PHWKRGZHWUDQVPLWWHGWKHGDWD1RZWRUHFHLYHWKHGDWDZHKDYHWRUHFHLYHWKH6RFNHWFODVV· UHFHLYHPHWKRG6LQFHWKHUHFHLYLQJHQGGRHVQRWKDYHDSDFNHWWRKROGWKHRQFRPLQJSDFNHW ILUVW ZH KDYH WR FUHDWH D SDFNHW LQ WKH UHFHLYLQJ HQG 7KH UHFHLYH PHWKRG ZLOO SXW WKH SDFNHW LQIRUPDWLRQLWKDVUHFHLYHGWKURXJKWKHSRUWLQWKHQHZO\FUHDWHGSDFNHW 1RZWKHGDWDWKDWLVVHQWWR\RXUPDFKLQHLVDYDLODEOHLQSDFNHWS7KHJHW'DWD PHWKRGLVXVHG WRH[WUDFWWKHVWULQJIURPWKHSDFNHWLQRUGHUWRGLVSOD\LWRQWKHVFUHHQ while(true) { DatagramPacket p= new DatagramPacket(b,1024); d.receive(p);

284

Comp-U-Learn

Networking in Java System.out.println(new String(p.getData(),0,0,p.getLength())); }

&DUHVKRXOGEHWDNHQWKDWWKHVL]HRIWKHE\WHDUUD\LVVXIILFLHQWHQRXJKWRKROGWKHGDWDLQWKH ILOHWREHVHQW 1RZZHZLOOORRNRXWIRUDSURJUDPZKHUHZHFDQVHQGPDQ\PHVVDJHVWRPDQ\PDFKLQHVWKDW LVWRGLIIHUHQWVHUYHU UHFHLYLQJVLGH PDFKLQHV

Duplication of Socket )URP WKH DERYH SURJUDP ZH NQRZ KRZ WR VHQG DQG UHFHLYH ILOHV DQG PHVVDJHV IURP RQH V\VWHPWRDQRWKHU7KHVHFDQEHDFKLHYHGE\XVLQJWKH'DWDJUDP6RFNHWDGGUHVVRI´µIRU VHQGLQJDQG'DWDJUDP6RFNHWDGGUHVVRI´µIRUUHFHLYLQJWKHPHVVDJHVRUILOHOLNHWKDW %XWWKHUHDUHVRPHFDVHZKHUHZHKDYHWRVHQGPHVVDJHIURPRQHPDFKLQHWRRWKHUGLIIHUHQW RWKHU FOLHQW RU VHUYHU PDFKLQHV 7KH\ FDQ EH DFKLHYHG E\ GXSOLFDWLRQ RI WKH 'DWDJUDP6RFNHW SRUWDGGUHVV )RUGXSOLFDWLRQZHKDYHWRDSSO\WKHUXOHVEHORZ )RUVHQGLQJPHVVDJHVRUILOHVWRDVLQJOHPDFKLQHWKHSRUWDGGUHVVIRU'DWDJUDP6RFNHWZLOOEH ´µDQGIRUUHFHLYLQJWKHSRUWDGGUHVVZLOOEH´µ )RUVHQGLQJPHVVDJHVRUILOHVWRPDQ\PDFKLQHVWKHSRUWDGGUHVVIRU'DWDJUDP6RFNHWVKRXOGEH RWKHUWKDQ´µ·DQGIRUUHFHLYLQJWKHSRUWDGGUHVVVKRXOGEHRWKHUWKDQ´µ 7KHYDOXHIRUWKHVHQGLQJSRUWZLOOEHDQ\WKLQJUDQJLQJIURP´WRµ$QGWKHUHFHLYLQJ SRUWZLOOKDYHWKHDGGUHVVUDQJLQJIURP´WRµ +HUHIRUPXOWLVHQGLQJPHVVDJHVRUILOHVWKHSRUWDGGUHVVVKRXOGEHPHQWLRQHGLQWKHVHQGHUV SURJUDPWRLGHQWLI\ZKLFKSRUWDGGUHVVWKHPHVVDJHKDVWRUHDFK 7KHIROORZLQJSURJUDPLVGRQHXVLQJ$SSOHWWRHVWDEOLVKDFRQQHFWLRQEHWZHHQRQHPDFKLQHWR DQRWKHU7KLVSURJUDPZLOOGLVSOD\DWH[WDUHDDQGDWH[WILHOG7KHPHVVDJHJLYHQLQWKHWH[WILHOG ZLOOEHVHQWWRPDFKLQH´6ULQLµLQRXUFDVH7RPDNHLWFOHDUWKHVHQGPHWKRGVKRXOGFRQWDLQ WKHQDPHRIWKHPDFKLQHWRZKRP\RXZDQWWRFRPPXQLFDWH 7KHVDPHSURJUDPFDQEHXVHGIRUUHFHLYLQJWRR
Comp-U-Learn

285

Java Programming I

Example 12.3: // Example for sending and receiving a message at the same time. import java.io.*; import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; public class ajay extends Applet implements ActionListener { TextField t1; TextArea ta1; Button b1; DatagramSocket d; private String s1; public void init() { neethi l =new neethi(); l.start(); try{d=new DatagramSocket(666);} catch(Exception e) {} setLayout(new FlowLayout()); ta1=new TextArea(" ",10,10); add(ta1); t1=new TextField(20); add(t1); t1.addActionListener(this); } public void actionPerformed(ActionEvent event) { int i; if(event.getSource()==t1) { try { byte b[]=new byte[1024]; s1=t1.getText(); t1.setText(""); for(i=0;i<s1.length();i++) b[i]=(byte)s1.charAt(i); d.send(new DatagramPacket(b,i,InetAddress.getByName("srini"),999)); } catch(Exception e){} }

286

Comp-U-Learn

Networking in Java } class neethi extends Thread { public void run() { int c,j=0; try { byte b[]=new byte[1024]; DatagramSocket d=new DatagramSocket(999); while(true) { DatagramPacket p= new DatagramPacket(b,1024); d.receive(p); ta1.append(new String(p.getData(),0,0,p.getLength())); ta1.append('\n'+" "); } } catch(Exception y){} } } }

Note The identification for the individual machine can be taken by clicking mycomputer icon on the desktop, then enter into the display icon and then enter the network and then click identification to see the inet address of the particular machine. 7KHRXWSXWZLOOORRNOLNHWKLV

Fig. 12.1 Comp-U-Learn

287

Java Programming I

Creating Links Inside Applets 7KHUHDUHWKUHHZD\VRIFRPPXQLFDWLQJZLWKV\VWHPVRQWKH1HW ♦ showDocument(), which enables an applet to tell the browser to load and link to another page on the Web. ♦ openStream(), a method that opens a connection to a URL and enables us to extract data from the connection. ♦ The socket classes, Socket and ServerSocket, which enable us to open standard socket connection to hosts and read and write from those connections. 7ROLQNWRDQHZSDJHZHFUHDWHDQHZLQVWDQFHRIWKHFODVV85/7KH URLFODVVUHSUHVHQWVD XQLIRUPUHVRXUFHORFDWRU7RFUHDWHDQHZ85/ZHFDQXVHRQHRIIRXUIRUPV ♦ 85/ 6WULQJ6WULQJLQW6WULQJ FUHDWHVDQHZ85/REMHFWJLYHQDSURWRFRO KWWSIWS JRSKHU ILOH  D KRVWQDPH ZZZOQHFRP IWSQHWFRPFRP  D SRUW QXPEHU  IRU KWWS DQGDILOHQDPHRUSDWKQDPH ♦ 85/ 6WULQJ 6WULQJ6WULQJ GRHVWKHVDPHWKLQJDVWKHSUHYLRXVIRUPPLQXVWKHSRUW QXPEHU ♦ 85/ 85/6WULQJ FUHDWHVD85/JLYHQDEDVHSDWKDQGDUHODWLYHSDWK)RUWKHEDVH ZH FDQ XVH JHW'RFXPHQW%DVH  IRU WKH 85/ RI WKH FXUUHQW +70/ ILOH RU JHW&RGH%DVH  IRU WKH 85/ RI WKH -DYD DSSOHW FODVV ILOH 7KH UHODWLYH SDWK ZLOO EH WUDFHGRQWRWKHODVWGLUHFWRU\LQWKRVHEDVH85/V MXVWDVZLWKLPDJHVDQGVRXQGV  ♦ 85/ 6WULQJ  FUHDWHV D 85/ REMHFW IURP D 85/ VWULQJ ZKLFK VKRXOG LQFOXGH WKH SURWRFROKRVWQDPHRSWLRQDOSRUWQDPHDQGILOHQDPH  )RUWKHODVWRQH FUHDWLQJD85/IURPDVWULQJ ZHKDYHWRFDWFKDPDOIRUPHG85/H[FHSWLRQ 6RHQFORVHWKH85/FRQVWUXFWRULQDtry block and catch the exception. String url=”http://www.yahoo.com/; try { the URL=new URL(url); } } catch(Malformed URL Exception e) { System out printIn(“Bad URL: “+URL); }

*HWWLQJD85/REMHFWLV WKH KDUG SDUW 2QFH ZH KDYH RQH DOO ZH KDYH WR GR LV SDVV LW WR WKH EURZVHU'RWKLVE\XVLQJWKLVVLQJOHOLQHRIFRGHZKHUHWKH85/LVWKH85/REMHFWWROLQNWR getAppletContext().showDocument(theURL);

288

Comp-U-Learn

Networking in Java

7KHEURZVHUWKDWFRQWDLQVRXU85/ZLOOWKHQORDGDQGGLVSOD\WKHGRFXPHQWDWWKDW85/ Example 12.4 import java.net.URL; import java.net.MalformedURLException; class first { String name; URL url; Bookmark(String name, String theURL) { this.name = name; try { this.url = new URL(theURL); } catch ( MalformedURLException e) { System.out.println("Bad URL: " + theURL); } } }

Example 12.5 import java.awt.*; import java.net.URL; import java.net.MalformedURLException; public class second extends java.applet.Applet { Bookmark bmlist[] = new Bookmark[3]; public void init() { bmlist[0] = new Bookmark("Compulearn Home Page",” http://www.compulearn.com"); bmlist[1] = new Bookmark("Gamelan", "http://www.gamelan.com"); bmlist[2]= new Bookmark("Java Home Page", "http://java.sun.com"); setLayout(new GridLayout(bmlist.length,1, 10, 10)); for (int i = 0; i < bmlist.length; i++)

Comp-U-Learn

289

Java Programming I

{ add(new Button(bmlist[i].name)); } } public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) { LinkTo((String)arg); return true; } else return false; } void LinkTo(String name) { URL theURL = null; for (int i = 0; i < bmlist.length; i++) { if (name.equals(bmlist[i].name)) theURL = bmlist[i].url; } if (theURL != null) getAppletContext().showDocument(theURL); } }

second.htm

<TITLE>Button links in Java

Button links in Java

<APPLET CODE="second.class" WIDTH=200 HEIGHT=100>

The Source for Button Link
The Source for Bookmark

7ZRFODVVHVPDNHXSWKLVDSSOHW7KH secondFODVVLPSOHPHQWVWKHDFWXDODSSOHWLWVHOIWKHFODVV firstUHSUHVHQWVDERRNPDUN%RRNPDUNVKDYHWZRSDUWVDQDPHDQGD85/7KLVSDUWLFXODU DSSOHW FUHDWHV WKUHH ERRNPDUN LQVWDQFHV DQG VWRUHV WKHP LQ DQ DUUD\ RI ERRNPDUNV )RU HDFK ERRNPDUNDEXWWRQLVFUHDWHGZKRVHODEHOLVWKHYDOXHRIWKHERRNPDUN VQDPH 290

Comp-U-Learn

Networking in Java

:KHQWKHEXWWRQVDUHSUHVVHGWKH linkTo()PHWKRGLVFDOOHG linkTo() H[WUDFWVWKHQDPHRIWKH EXWWRQIURPWKHHYHQWXVHVLWWRORRNXSWKHDFWXDO85/IURPWKHERRNPDUNREMHFWDQGWKHQ WHOOVWKHEURZVHUWRORDGWKH85/UHIHUHQFHGE\WKDWERRNPDUN

Opening Web Connections 6RPHWLPHVLQVWHDGRIDVNLQJWKHEURZVHUWRMXVWORDGWKHFRQWHQWVRIDILOHZHPLJKWZDQWWR JHWKROGRIWKDW ILOH V FRQWHQWV VR WKDW RXU DSSOHW FDQ XVH WKHP ,I WKH ILOH ZH ZDQW WR JUDE LV VWRUHGRQWKH:HEDQGFDQEHDFFHVVHGXVLQJWKHPRUHFRPPRQ85/IRUPV http ftpDQGVR RQ RXUDSSOHWFDQXVHWKH85/FODVVWRJHWLW 1RWHWKDWIRUVHFXULW\UHDVRQVDSSOHWVE\GHIDXOWFDQFRQQHFWEDFNWRRQO\WKHVDPHKRVWIURP ZKLFKWKH\DUHRULJLQDOO\ORDGHG,IWKHILOHWKHDSSOHWZDQWVWRUHWULHYHLVRQWKHVDPHV\VWHP ORFDOO\85/FRQQHFWLRQVLVWKHHDVLHVWZD\WRJHWWKHILOH openStream()

7KH85/FODVVGHILQHVDPHWKRGFDOOHG openStream()ZKLFKRSHQVDQHWZRUNFRQQHFWLRQXVLQJ WKHJLYHQ85/ DQKWWSFRQQHFWLRQIRU:HE85/VDQ)73FRQQHFWLRQIRU)7385/VDQGVR RQ DQGUHWXUQVDQLQVWDQFHRIWKHFODVVInputStream SDUWRIWKHjava.ioSDFNDJH  ,IZHFRQYHUWWKDWVWUHDPWRD DataInputStream ZLWKD BufferedInputStreamLQWKHPLGGOHIRU EHWWHU SHUIRUPDQFH  ZH FDQ WKHQ UHDG FKDUDFWHUV DQG OLQHV IURP WKDW VWUHDP  )RU H[DPSOH WKHVH OLQHV RSHQ D FRQQHFWLRQ WR WKH 85/ VWRUHG LQ WKH YDULDEOH WKH URL DQG WKHQ UHDG DQG HFKRHDFKOLQHRIWKHILOHWRWKHVWDQGDUGRXWSXW try { InputStream in = theURL.openStream(); DataInputStream data = new DataInputStream(new BufferedInputStream(in); String line; while ((line = data.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); }

7KLVDSSOHWXVHVWKHopenStream()PHWKRGWRRSHQDFRQQHFWLRQWRD:HEVLWHUHDGVDILOHIURP WKDWFRQQHFWLRQDQGGLVSOD\VWKHUHVXOWLQDWH[WDUHD Comp-U-Learn

291

Java Programming I

7KHILOHFUHDWHGVKRXOGEHVWRUHGLQWKHGLUHFWRU\ZKHUHWKHDSSOHWFODVVILOHVDUHVWRUHG Example 12.6: /* get a text file and read it into a text area */ import import import import import import import

java.awt.*; java.io.DataInputStream; java.io.BufferedInputStream; java.io.IOException; java.net.URL; java.net.URLConnection; java.net.MalformedURLException;

public class Gettext extends java.applet.Applet implements Runnable { URL theURL; Thread runner; TextArea ta = new TextArea("Getting text..."); public void init() { setLayout(new GridLayout(1,1)); String url = "ajay.txt"; try { this.theURL = new URL(url); } catch ( MalformedURLException e) { System.out.println("Bad URL: " + theURL); } add(ta); } public Insets insets() { return new Insets(10,10,10,10); } public void start() { if (runner == null) { runner = new Thread(this); runner.start();

292

Comp-U-Learn

Networking in Java } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void run() { URLConnection conn = null; DataInputStream data = null; String line; StringBuffer buf = new StringBuffer(); try { conn = this.theURL.openConnection(); conn.connect(); ta.setText("Connection opened..."); data = new DataInputStream(new BufferedInputStream( conn.getInputStream())); ta.setText("Reading data..."); while ((line = data.readLine()) != null) { buf.append(line + "\n"); } ta.setText(buf.toString()); } catch (IOException e) { System.out.println("IO Error:" + e.getMessage()); } } }

GetAjay1.htm <TITLE>Get the text

Get the text

<APPLET CODE="Gettext.class" WIDTH=450 HEIGHT=400>

The Source

7KH init()PHWKRGVHWVXSWKH85/DQGWKHWH[WDUHDLQZKLFKWKHILOHZLOOEHGLVSOD\HG6LQFHLW PLJKWWDNHVRPHWLPHWRORDGWKHILOHRYHUWKHQHWZRUNZHSXWWKDWURXWLQHLQWRDWKUHDGDQGXVH

Comp-U-Learn

293

Java Programming I

WKHIDPLOLDU start() stop()DQG run()PHWKRGVWRFRQWUROWKDWWKUHDG,QVLGH run()ZHLQLWLDOL]HD EXQFKRIYDULDEOHVDQGWKHQRSHQWKHFRQQHFWLRQWRWKH85/ XVLQJWKHopenStream()PHWKRG  2QFHWKHFRQQHFWLRQLVRSHQZHVHWXSDQLQSXWVWUHDPDQGUHDGIURPLWOLQHE\OLQHSXWWLQJ WKH UHVXOW LQWR DQ LQVWDQFH RI StringBuffer. 2QFH DOO WKH GDWD LV UHDG WKH StringBuffer REMHFW LV FRQYHUWHGLQWRDUHDOVWULQJDQGWKHQSXWWKDWUHVXOWLQWKH7H[W$UHDRIWKHDSSOHW 2QHWKLQJWRQRWHLQWKLVH[DPSOHLVWKDWWKHFRGHIRURSHQLQJDQHWZRUNFRQQHFWLRQUHDGLQJ WKHILOHDQGVWRULQJWKHFRQWHQWVLQDVWULQJLVHQFORVHGLQDWU\EORFN7KLVLVDQHIILFLHQWPHWKRG LQQHWZRUNLQJSURJUDPVVLQFHWKHH[FHSWLRQVDQGHUURUVDUHKDQGOHGVXLWDEO\

The URL Connection Class URL V openStream() PHWKRG LV DFWXDOO\ D VLPSOLILHG XVH RI WKH URLConnection FODVV URLConnection SURYLGHV D ZD\ WR UHWULHYH ILOHV E\ XVLQJ 85/VRQ :HE RU )73 VLWHV VR WR VSHDNURLConnectionDOVRHQDEOHVXVWRFUHDWHRXWSXWVWUHDPVLIWKHSURWRFRODOORZVLW

7R XVH D 85/ FRQQHFWLRQ \RX ILUVW FUHDWH D QHZ LQVWDQFH RI WKH FODVV URLConnection VHW LWV SDUDPHWHUV ZKHWKHULWHQDEOHVZULWLQJIRUH[DPSOH DQGWKHQXVHWKHconnect()PHWKRGWRRSHQ WKHFRQQHFWLRQ

Sockets )RUQHWZRUNLQJDSSOLFDWLRQV-DYDSURYLGHVWKHSocketDQGServerSocketFODVVHVDVDQDEVWUDFWLRQ RIVWDQGDUGVRFNHWSURJUDPPLQJWHFKQLTXHV 7KH Socket FODVV SURYLGHV D FOLHQWVLGH VRFNHW LQWHUIDFH VLPLODU WR VWDQGDUG 81,; VRFNHWV 7R RSHQDFRQQHFWLRQFUHDWHDQHZLQVWDQFHRI Socket ZKHUH hostnameLVWKHKRVWWRFRQQHFWWR DQGportnumLVWKHSRUWQXPEHU  Socket connection=new Socket(hostname, portnum); 2QFH WKH VRFNHW LV RSHQ ZH FDQ XVH LQSXW DQG RXWSXW VWUHDPV WR UHDG DQG ZULWH IURP WKDW VRFNHW DataInputStream in = new DataInputStream( new BufferedInputStream(connection.getInputStream())); DataOutputStream out= new DataOutputStream( new BufferedOutputStream(connection.getOutputStream()));

294

Comp-U-Learn

Networking in Java

2QFHZHDUHGRQHZLWKWKHVRFNHWGRQRWIRUJHWWRFORVHLWXVLQJWKHIROORZLQJFRGH connection.close()

6HUYHUVLGHVRFNHWVZRUNVLPLODUO\ZLWKWKHH[FHSWLRQRI WKH accept()PHWKRG$VHUYHUVRFNHW OLVWHQVRQD7&3SRUWIRUDFRQQHFWLRQIURPDFOLHQWZKHQDFOLHQWFRQQHFWVWRWKDWSRUWWKH accept()PHWKRGDFFHSWVDFRQQHFWLRQIURPWKDWFOLHQW %\XVLQJERWKFOLHQWDQGVHUYHUVRFNHWVZHFDQFUHDWHDSSOLFDWLRQVWKDWFRPPXQLFDWHZLWKHDFK RWKHURYHUWKHQHWZRUN 7RFUHDWHDVHUYHUVRFNHWDQGELQGLWWRDSRUWFUHDWHDQHZLQVWDQFHRI ServerSocketZLWKWKH SRUWQXPEHU ServerSocket sconnection

= new ServerSocket(8888);

7R OLVWHQ RQ WKDW SRUW DQG WR DFFHSW D FRQQHFWLRQ IURP DQ\ FOLHQWV LI RQH LV PDGH  XVH WKH

accept()PHWKRG

sconnection.accept();

2QFH WKH VRFNHW FRQQHFWLRQ LV PDGH ZH FDQ XVH LQSXW DQG RXWSXW VWUHDPV WR UHDG IURP DQG ZULWHWRWKHFOLHQW

Other Applet Hints showStatus() Method

7KHshowStatus()PHWKRGDYDLODEOHLQWKHAppletFODVVHQDEOHVXVWRGLVSOD\DVWULQJLQWKHVWDWXV EDURIWKHEURZVHUZKLFKFRQWDLQVWKHDSSOHW:HFDQXVHWKLVIRUSULQWLQJHUURUOLQNKHOSRU RWKHUVWDWXVPHVVDJHV GetAppletContext( )showsStatus(“Change the color”);

7KH getAppletContext() PHWKRG HQDEOHV \RXU DSSOHW WR DFFHVV IHDWXUHV RI WKH EURZVHU WKDW FRQWDLQVLW Applet Information

7KH$:7JLYHVXVDPHFKDQLVPIRUDVVRFLDWLQJLQIRUPDWLRQZLWK\RXUDSSOHW8VXDOO\WKHUHLVD PHFKDQLVP LQ WKH EURZVHU YLHZLQJ WKH DSSOHW WR YLHZ GLVSOD\ LQIRUPDWLRQ :H  FDQ XVH WKLV PHFKDQLVP WR VLJQ RXU QDPH RU RXU RUJDQL]DWLRQ WR RXU DSSOHW RU WR SURYLGH FRQWDFW LQIRUPDWLRQVRWKDWXVHUVFDQJHWKROGRI\RXLIWKH\ZDQW Comp-U-Learn

295

Java Programming I

7RSURYLGHLQIRUPDWLRQDERXW\RXUDSSOHWRYHUULGHWKHgetAppletInfo()PHWKRG Public String getAppletInfo(){ Return “GetAjya copyright1998 Compulearn”; }

Communicating Between Applets 6RPHWLPHVZHZDQWWRKDYHDQ+70/SDJHWKDWKDVVHYHUDOGLIIHUHQWDSSOHWVRQLW7RGRWKLV DOO ZH KDYH WR GR LV WR LQFOXGH VHYHUDO GLIIHUHQW LWHUDWLRQV RI WKH DSSOHW WDJWKH EURZVHU ZLOO FUHDWHGLIIHUHQWLQVWDQFHVRIRXUDSSOHWIRUHDFKRQHWKDWDSSHDUVRQWKH+70/SDJH :KDWLIZHZDQWWRFRPPXQLFDWHEHWZHHQWZRDSSOHWV":KDWLIZHZDQWDFKDQJHLQRQHDSSOHW WRDIIHFWWKHRWKHUDSSOHWVLQVRPHZD\"7KHEHVWZD\WRGRWKLVLVWRXVHWKHDSSOHWFRQWH[WWR JHWWRGLIIHUHQWDSSOHWVRQWKHVDPHSDJH :HKDYHDOUHDG\VHHQWKHXVHRIWKH getAppletContext()PHWKRGIRUVHYHUDORWKHUSXUSRVHVZH FDQDOVRXVHLWWRJHWKROGRIWKHRWKHUDSSOHWVRQWKHSDJH)RUH[DPSOHWRFDOODPHWKRGFDOOHG sendMessage() RQ DOO WKH DSSOHWV RQ D SDJH LQFOXGLQJ WKH FXUUHQW DSSOHW  XVH getApplets() PHWKRGDQGDforORRSWKDWORRNVVRPHWKLQJOLNHWKLV For (Enumeration e=getAppletContext()getApplets(); e.hasMoreElements(){ Applet current=(Applet)(e.nextElement()); current sendMessage(); }

7KH getApplets() PHWKRG UHWXUQV DQ Enumeration REMHFW ZLWK D OLVW RI WKH DSSOHWV RQ WKH SDJH ,WHUDWLQJ RYHU WKH Enumeration REMHFW LQ WKLV ZD\ HQDEOHV XV WR DFFHVV HDFK HOHPHQW LQ WKH (QXPHUDWLRQ LQ WXUQ ,I ZH ZDQW WR FDOO D PHWKRG LQ D VSHFLILF DSSOHW LW LV VOLJKWO\ PRUH FRPSOLFDWHG7RGRWKLVZHJLYHRXUDSSOHWVQDPHVDQGWKHQUHIHUWRWKHPE\QDPHLQVLGHWKH ERG\RIFRGHIRUWKDWDSSOHW 7RJLYHDQDSSOHWDQDPHXVHWKHNAMESDUDPHWHULQRXU+70/ILOH

This applet sends information: <APPLET CODE=”MyApplet class”WIDTH=100 HEIGHT=150 NAME=”sender”>

This applet receives information from the sende: <APPLET CODE=”MyApplet.class “WIDTH=100 HEIGHT=150 NAME=”receiver”>

7R JHW D UHIHUHQFH WR DQRWKHU DSSOHW RQ WKH VDPH SDJH XVH WKH getApplet() PHWKRG IURP WKH DSSOHWFRQWH[WZLWKWKHQDPHRIWKDWDSSOHW7KLVJLYHVXVDUHIHUHQFHWRWKHDSSOHWRIWKDWQDPH :HFDQWKHQUHIHUWRWKDWDSSOHWDVLILWZHUHMXVWDQRWKHUREMHFWFDOOPHWKRGVVHWLWVLQVWDQFH YDULDEOHVDQGVRRQ+HUH VVRPHFRGHWRGRMXVWWKDW 296

Comp-U-Learn

Networking in Java // get ahold of the receiver applet Applet receiver = getAppletContext().getApplet("receiver"); // tell it to update itself. reciever.update(text, value);

,QWKLVH[DPSOHZHXVHWKH getApplet()PHWKRGWRJHWDUHIHUHQFHWRWKHDSSOHWZLWKWKHQDPH receiver*LYHQWKDWUHIHUHQFHZHFDQWKHQFDOOPHWKRGVLQWKDWDSSOHWDVLILWZHUHMXVWDQRWKHU REMHFWLQ\RXURZQHQYLURQPHQW)RUH[DPSOHLIERWKDSSOHWVKDYHDQupdate()PHWKRGZHFDQ WHOOWKHreceiverWRXSGDWHLWVHOIE\XVLQJWKHLQIRUPDWLRQWKHFXUUHQWDSSOHWKDV

Summary In this session, various URL and their connection class, how they are linked with the website and other inet address methods were are discussed. We also studied about the DatagramPacket, DatagramSocket, duplication of DatagramSocket and how the files have been sent through the Socket.

Going Over It Again I. Fill in the Blanks

 7KHPHWKRGWKDWRSHQVDFRQQHFWLRQWRD85/LVJLYHQE\BBBBBBBBBBBB  7KHWU\DQGFDWFKPHWKRGLVXVHGWRBBBBBBBBBBBBBBBBBBBB  ,QD85/FRQQHFWLRQFODVVBBBBBBBBBBBBBBBBBLVXVHGWRFORVHWKHFRQQHFWLRQ  7KHSRUWDGGUHVVIRUWKH'DWDJUDP6RFNHWWRVHQGQRUPDOO\LVJLYHQE\BBBBBBBBBBBB  7KHSRUWDGGUHVVIRUWKH'DWDJUDP6RFNHWWRUHFHLYHQRUPDOO\LVJLYHQE\BBBBBBBBBBBB II. State True or False

 7KHSRUWDGGUHVVIRUWKH'DWDJUDP6RFNHWWRVHQGLV´µ  7KH JHW$SSOHW&RQWH[W  PHWKRG HQDEOHV RXU DSSOHW WR DFFHVV IHDWXUHV RI WKH EURZVHU WKDW FRQWDLQVLW  $OOWKHPHVVDJHVDUHVHQWDVE\WHVRQO\

Comp-U-Learn

297

Java Programming I

 )RUGXSOLFDWLRQRI'DWDJUDP6RFNHWWKHSRUWDGGUHVVZLOOEH´µ  )RUGXSOLFDWLRQRI'DWDJUDP6RFNHWWKHSRUWDGGUHVVZLOOEHRWKHUWKDQ´µ III. One line Answers

 :KDWLVD1HWZRUN"  :KDWDUHWKHWKUHHZD\VLQZKLFKZHFDQFRPPXQLFDWHZLWKV\VWHPVRQWKH1HW"  :KDWLVD6RFNHW"  :KDWLVDGDWDJUDP"  :KDWLVWKHGLIIHUHQFHEHWZHHQ'DWDJUDP6RFNHWDQGWKH'DWDJUDP3DFNHWV"

298

Comp-U-Learn

Glossary

Glossary API (Application Programming Interface) $FROOHFWLRQRIFODVVHVPHWKRGVDQGGDWDPHPEHUVWKDW\RXFDQLPSRUWLQWR-DYD Applet $ FRPSLOHG -DYD SURJUDP WKDW FDQ EH HPEHGGHG LQ D :HE SDJH DQG GRZQORDGHG WR UXQ LQ D :HEEURZVHU AWT(Abstract Windowing Toolkit) 7KH-DYDSDFNDJHRIXVHULQWHUIDFHPHWKRGVZKLFKKDQGOHVJUDSKLFVDQGZLQGRZV Base class FODVVIURPZKLFKDQRWKHUFODVVLVGHULYHG Boolean $YDULDEOHW\SH%RROHDQYDULDEOHPD\EHVHWWRRQO\WUXHRUIDOVH Bytecode -DYD H[HFXWDEOH ELQDU\ FRGHV ZKLFK PDNH XS DSSOHWV  %\WH FRGHV DUH ZKDW WKH FRPSLOHU SURGXFHV7KH\PDNHXSFODVVILOHV Cast $PHDQVRIRYHUULGLQJDYDULDEOH·VW\SHWHPSRUDOO\FKDQJLQJWKDWW\SHWRDQRWKHUW\SH Check box group $FROOHFWLRQRIUDGLREXWWRQV:KHQFKHFNER[HVDUHDGGHGWRDMDYD&KHFN%R[*URXSREMHFW WKH\EHFRPHUDGLREXWWRQV Class “ template” 8VHGWRFUHDWHREMHFWVPXFKOLNHDYDULDEOH·VW\SH$FODVVLVWRDQREMHFWZKDWDFRRNLHFXWWHULV WRDFRRNLH Comp-U-Learn

299

Java Programming I

Class library OLEUDULHVWKDWFRQWDLQYDULRXV-DYDFODVVHV7KHVHOLEUDULHVDUHFDOOHGSDFNDJHVLQ-DYD Client RQHKDOIRIDFOLHQWVHUYHUSDLU&OLHQWVUHO\RQDVHUYHUWRSHUIRUPVRPHWDVNIRUWKHP Client/server 0RGHOVSOLWWLQJDQDSSOLFDWLRQLQWRWZRSDUWVRQHSDUWLQWKHFOLHQWDQGRQHSDUWLQWKHVHUYHU FUHDWHVDFOLHQWVHUYHUSDLU$SSOLFDWLRQVWKDWZRUNWKLVZD\XVHWKHFOLHQWVHUYHUPRGH Clipping rectangle $JUDSKLFVUHFWDQJOHERXQGLQJDSDUWRIWKHGLVSOD\DUHDWRZKLFKZHZDQWWRUHVWULFWJUDSKLFV RSHUDWLRQV Compiler $ SURJUDP WKDW WUDQVODWHV -DYD VRXUFH FRGH LQWR UXQQDEOH E\WH FRGHV  ,Q RWKHU ZRUGV D FRPSLOHUWUDQVODWHV-DYDILOHVLQWRFODVVILOHV Constructor $QDXWRPDWLFDOO\UXQPHWKRGRIDFODVVXVHGIRULQLWLDOL]DWLRQRIDQREMHFW$FRQVWUXFWRULVUXQ ZKHQHYHUDQREMHFWRIWKHFODVVFRQWDLQLQJWKHFRQVWUXFWRULVFUHDWHG Container $QREMHFWRIWKH-DYDFRQWDLQHUFODVV$FRQWDLQHUFDQFRQWDLQFRQWUROREMHFWV Control $Q\RIWKHYDULRXVXVHULQWHUIDFHREMHFWVVXFKDVWH[WILHOGVWH[WDUHDVVFUROOEDUVDQGEXWWRQV Critical section $ VHFWLRQ RI FRGH ZKHUH WKUHDGV VKRXOG EH DOORZHG WR XQGHUWDNH WKHLU WDVNV ZLWKRXW LQWHUIHUHQFH,Q-DYDDFULWLFDOVHFWLRQLVHQFORVHGLQDV\QFKURQL]HG EORFN

300

Comp-U-Learn

Glossary

Debugger $Q DSSOLFDWLRQ WKDW OHWV \RX H[HFXWH D -DYD SURJUDP ZKLOH ZDWFKLQJ WKH SURJUDP·V VWDWH  7KH H[HFXWLRQRIDGHEXJJHULVRIWHQOLQHE\OLQH Double buffering $JUDSKLFVPHWKRGRISUHSDULQJLPDJHVRIIVFUHHQLQDPHPRU\EXIIHUDQGWKHQGLVSOD\LQJWKH UHVXOWRQVFUHHQ Encapsulation 7KHSURFHVVRIZUDSSLQJERWKGDWDDQGIXQFWLRQVLQWRFODVVHV Event $XVHULQWHUIDFHWULJJHUHGRFFXUUHQFHVXFKDVDPRXVHFOLFNDEXWWRQSXVKRUDNH\VWULNH Exeception $QHUURUPHVVDJHWKDWXVXDOO\LQGLFDWHVDSUREOHPLQSURJUDPIORZIRUH[DPSOHZKHQ\RXWU\ WRDFFHVVDQDUUD\EH\RQGLWVERXQGDULHVDQDUUD\ERXQGDU\H[FHSWLRQRFFXUV Frame 7KHRXWOLQHRUERUGHURIDZLQGRZRURIDQLQGLYLGXDOLPDJHLQDQLPDWLRQ Inheritance 7KHSURFHVVWKURXJKZKLFKGHULYHGFODVVHVJHWIXQFWLRQDOW\IURPWKHLUEDVHFODVVHV ISP (Internet Service Provicer) 8VXDOO\DQH[WHUQDOFRPSDQ\WKDWSURYLGHVDPDFKLQHFRQQHFWHGWRWKHLQWHUQHWDFWLQJDVDKRVW PDFKLQHIRULQGLYLGXDOXVHUV Java Virtual Machine 7KHV\VWHPWKDWORDGVDQGH[HFXWHVE\WHFRGHILOHV JDK(Java Development Kit) 6XQ·VVHWRIWRROVIRU-DYDGHYHORSHUV Comp-U-Learn

301

Java Programming I

Layout 7KH DUUDQJHPHQW RI FRQWUROV LQ D -DYD DSSOLFDWLRQ RU DSSOHW XVXDOO\ KDQGOHG E\ RQH RU PRUH -DYDOD\RXWPDQDJHUV Member $VKRUWQDPHIRUDPHPEHURIDFODVVPHDQLQJDPHWKRGHPEHGGHGGDWDRUDFODVVFRQVWDQW Method 0HPEHUIXQFWLRQRIDFODVV Multi-Threading 7KH EDVLV RI PXOWLWDVNLQJ LQ D SURJUDP ,Q PXOWLWKUHDGLQJ HDFK WKUHDG UHSUHVHQWV DQ LQGHSHQGHQWH[HFXWLRQVWUHDP Null $YDOXHXVXDOO\VHWWRLQ-DYD Object 7KHLQVWDQFHRIDFODVV$FODVVDFWVDVD´WHPSODWHµIRUREMHFWV$ FODVVLVWR DQ REMHFW DVD FRRNLHFXWWHULVWRDFRRNLH Overloading in object-oriented language 7KHSURFHVVRIGHILQLQJPXOWLSOHPHWKRGVZLWKWKHVDPHQDPHEXWGLIIHUHQWSDUDPHWHUOLVWVVR WKDWWKHPHWKRGPD\EHFDOOHGZLWKGLIIHUHQWVHWVRISDUDPHWHUV Overriding ,QREMHFWRULHQWHGSURJUDPPLQJWKHSURFHVVRIUHGHILQLQJDPHWKRGRULJLQDOO\LQKHULWHGIURPD EDVHFODVV Panel $OD\RXWFRQVWUXFWZKLFKKROGVFRQWUROVLQDVSHFLILHGDUUDQJHPHQWIRUGLVSOD\LQJRQWKHVFUHHQ

302

Comp-U-Learn

Glossary

Source file $WH[WILOHWKDWKROGVWKH-DYDVWDWHPHQWVWREHFRPSLOHGLQWRDQDSSOHWRUDSSOLFDWLRQ subclass $FODVVWKDWGHVFHQGVIURPDJLYHQFODVV superclass 7KHFODVVIURPZKLFKDJLYHQFODVVLVGHULYHG this keyword $-DYDNH\ZRUGXVHGWRUHIHUWRDFXUUHQWREMHFW7KLVNH\ZRUGLVXVXDOO\SDVVHGDVDSDUDPHWHU WRPHWKRGV Thread $Q H[HFXWLRQ VWUHDP LQ D SURJUDP  $ SURJUDP PD\ KDYH PDQ\ WKUHDGV DQG WKHUHIRUH EH PXOWLWDVNLQJ Throwable 2EMHFW DQ REMHFW GHULYHG IURP WKH -DYD H[FHSWLRQ FODVV WKDW PD\ EH WKURZQ WR FDXVH DQ H[FHSWLRQ Unicode 8QLFRGH LV DQ DOWHUQDWH FKDUDFWHU VHW IRU $6&,, ,W SURYLGHV IHDWXUHV WKDW VXSSRUW PXOWLSOH ODQJXDJHVOLNH*HUPDQ)UHQFKHWF-DYDXVHV8QLFRGHFKDUDFWHUVHWLQVWHDGRI$6&,,DV-DYDLV DLPHGDWEHLQJDPXOWLSODWIRUPDQGPXOWLOLQJXDOODQJXDJH

Comp-U-Learn

303

Appendix 1

Appendix 1 Inside JDK 1.2 The Java Foundation Classes -DYD)RXQGDWLRQ&ODVVHVDUHDVHWRI$3,VIRUEXLOGLQJ*8,UHODWHGFRPSRQHQWVRI-DYDDSSOHWV DQG DSSOLFDWLRQV -)&  ZDV UHOHDVHG VHSDUDWHO\ IURP -'. LQ )HEUXDU\ RI  VR WKDW WKH\ FRXOGEHXVHGZLWKWKHWKHQFXUUHQW-'.-'.LQWHJUDWHV-)&DVD&RUH$3,DQGDGGV -DYD'DQG'UDJDQG'URS$3,V7KH$3,VLQFOXGHGZLWK-)&LVDVIROORZV ♦ ♦ ♦ ♦ ♦

The Abstract Window Toolkit Swing Java 2D Drag and Drop Accessibility

Abstract Window Toolkit $EVWUDFW:LQGRZLQJ7RRONLWSURYLGHVWKHFDSDELOLW\WRFUHDWHSODWIRUPLQGHSHQGHQW*8,EDVHG SURJUDPV DQG LV D YHU\ LPSRUWDQW FRQWULEXWRU WR -DYD·V SRSXODULW\ 7KH $:7 RI -'.  KDV EHHQ DXJPHQWHG ZLWK PDQ\ QHZ FODVVHV DQG LQWHUIDFHV WKDW DGG GUDZLQJ SDLQWLQJ DQG LPDJH SURFHVVLQJFDSDELOLWLHVDQGVXSSRUWWKH$FFHVVLELOLW\'UDJDQG'URSDQG-DYD'$3,V $FFHVVLELOLW\$3,LVD-)&$3,WKDWKDVEHHQDGGHGWR-'.,WSURYLGHVVXSSRUWIRUWKHXVH RI $VVLVWLYH WHFKQRORJLHV ZLWK RWKHU -)& FRPSRQHQWV $VVLVWLYH WHFKQRORJLHV VXFK DV VFUHHQ PDJQLILHUV DQG VSHHFK UHFRJQLWLRQ V\VWHPV DUH LQWHQGHG IRU XVH E\ GLVDEOHG XVHUV EXW DOVR YDOXDEOH WRROV IRU WKH DYHUDJH QRQ ²GLVDEOHG XVHU 7KHVH WHFKQRORJLHV SURYLGH QRQVWDQGDUG ZD\V RI LQWHUDFWLQJ ZLWK VRIWZDUH DSSOLFDWLRQV 7KH $FFHVVLELOLW\ $3, FRQVLVWV RI FODVVHV DQG LQWHUIDFHVIRULQFRUSRUDWLQJDFFHVVLELOLW\IHDWXUHVLQWRDSSOHWVDQGDSSOLFDWLRQV Java 2D

7KLV $3, SURYLGHV FRPSUHKHQVLYH VXSSRUW IRU WZRGLPHQVLRQDO GUDZLQJ LPDJH SURFHVVLQJ JUDSKLFV UHQGHULQJ FRORU PDQDJHPHQW DQG SULQWLQJ ,W FRQVLVWV RI DQ LPDJLQJ PRGHO WKDW VXSSRUWV OLQH DUW WH[W LPDJHV VSDWLDO DQG FRORU WUDQVIRUPDWLRQV DQG LPDJH FRPSRVLQJ 7KH PRGHO LV GHYLFH LQGHSHQGHQW DOORZLQJ GLVSOD\HG DQG SULQWHG JUDSKLFV WR EH UHQGHUHG LQ D

Comp-U-Learn

305

Java Programming I

FRQVLVWHQW PDQQHU 7KH -DYD ' $3, LV LQFRUSRUDWHG LQWR WKH MDYDDZW DQG MDYDDZWLPDJH SDFNDJHV Drag and Drop

'UDJ DQG 'URS LV W\SLFDOO\ XVHG WR RUJDQL]H GHVNWRSV PDQDJH ILOHV RSHQ GRFXPHQWV DQG H[HFXWH DSSOLFDWLRQV 7KH 'UDJ DQG 'URS $3, DOORZV WKH -'.  WR SURYLGH SODWIRUP LQGHSHQGHQW VXSSRUW RI GUDJ DQG GURS ,W VXSSRUWV GUDJ DQG GURS ZLWKLQ -DYD DSSOLFDWLRQV EHWZHHQ -DYD DSSOLFDWLRQV DQG EHWZHHQ -DYD DQG QDWLYH SODWIRUP DSSOLFDWLRQV 7KH 'UDJ DQG 'URS$3,LVLPSOHPHQWHGLQWKHMDYDDZWGQGSDFNDJHDQGLVVXSSRUWHGE\FODVVHVDQGLQWHUIDFHV LQRWKHU-)&SDFNDJHV Java IDL

7KH &RPPRQ 2EMHFW 5HTXHVW %URNHU DUFKLWHFWXUH &25%$  LV D VWDQGDUG DSSURDFK WR GHYHORSLQJ GLVWULEXWHG REMHFWV IRU XVH LQ GLVWULEXWHG REMHFWRULHQWHG V\VWHPV &25%$ ZDV GHYHORSHGE\WKH2EMHFW0DQDJHPHQW*URXS 20* DFRQVRUWLXPRIVRIWZDUHFRPSDQLHVDQG RWKHURUJDQL]DWLRQV7KHFDSDELOLW\WRXVH-DYDREMHFWVZLWKLQ&25%$LVUHIHUUHGWRDV-DYD,'/ DQG KDV EHHQ LQFRUSRUDWHG LQWR -'.  -DYD ,'/ SURYLGHV DQ $3, DQG D VHW RI WRROV IRU LQWHUIDFLQJ-DYDREMHFWVZLWK&25%$REMHFWVDQGIRUGHYHORSLQJ&25%$REMHFWVLQ-DYD-DYD ,'/DOVRLQFOXGHVD-DYD2EMHFW5HTXHVW%URNHU 25% DQGDQ25%QDPHVHUYHU The Collections API

7KH &ROOHFWLRQV $3, LV D VHW RI FODVVHV DQG LQWHUIDFHV WKDW SURYLGH DQ LPSOHPHQWDWLRQ LQGHSHQGHQW IUDPHZRUN IRU ZRUNLQJ ZLWK FROOHFWLRQV RI REMHFWV 7KLV $3, FRQVLVWV RI HOHYHQ FODVVHV DQG HLJKW LQWHUIDFHV WKDW KDYH EHHQ DGGHG WR WKH MDYDXWLO SDFNDJH 7KHVH FODVVHV DQG LQWHUIDFHVSURYLGHVXSSRUWIRUJHQHULFFROOHFWLRQVVHWVEDJVPDSVOLVWVDQGOLQNHGOLVWV7KHVH FODVVHVDQGLQWHUIDFHVFDQEHHDVLO\H[WHQGHGWRSURYLGHVXSSRUWIRUFXVWRPREMHFWFROOHFWLRQV Reference Objects

5HIHUHQFHREMHFWVLQWURGXFHGZLWK-'.VWRUHUHIHUHQFHVWRRWKHUREMHFWV7KH\DUHVLPLODULQ IXQFWLRQWR&DQG&SRLQWHUVEXWGRQRWSURYLGHDFFHVVWRVSHFLILFPHPRU\DGGUHVVHV7KH MDYDODQJUHI 3DFNDJH SURYLGHV VL[ FODVVHV WKDW LPSOHPHQW UHIHUHQFH REMHFWV 7KHVH FODVVHV DOVR SURYLGH WKH FDSDELOLW\ WR QRWLI\ D SURJUDP ZKHQ D UHIHUHQFHG REMHFW LV VXEMHFW WR JDUEDJH FROOHFWLRQ 7KLV FDSDELOLW\ HQDEOHV UHIHUHQFH REMHFWV WR EH XVHG WR LPSOHPHQW REMHFWFDWFKLQJ PHFKDQLVPV Package Version Identification

3DFNDJH YHUVLRQ LGHQWLILFDWLRQ LV DOVR D QHZ FDSDELOLW\ WKDW ZDV LQWURGXFHG ZLWK -'.  LW DOORZV DSSOHWV DQG DSSOLFDWLRQV WR REWDLQ YHUVLRQ LQIRUPDWLRQ DERXW D SDUWLFXODU -DYD SDFNDJH

306

Comp-U-Learn

Appendix 1

7KLV YHUVLRQ LQIRUPDWLRQ HQDEOHV ODUJH FRPSOH[ DSSOLFDWLRQV WR HYROYH RYHU WLPH ZLWK VRPH DSSOLFDWLRQSDFNDJHVEHLQJXSJUDGHGLQGHSHQGHQWO\RIRWKHUV7KHQHZ3DFNDJHFODVVSURYLGHV PHWKRGVIRUREWDLQLQJSDFNDJHYHUVLRQLQIRUPDWLRQ Input Method API

7KH ,QSXW 0HWKRG $3, LV DQ DGGLWLRQ WR WKH -'.·V LQWHUQDWLRQDOL]DWLRQ VXSSRUW WKDW HQDEOHV WH[WHGLWLQJ FRPSRQHQWV WR UHFHLYH IRUHLJQ ODQJXDJH WH[W LQSXW WKURXJK LQSXW PHWKRGV ,W LV GHVLJQHG WR VXSSRUW ODUJH FKDUDFWHU VHWV VXFK DV &KLQHVH -DSDQHVH DQG .RUHDQ $Q LQSXW PHWKRG OHWV XVHUV HQWHU WKRXVDQGV RI GLIIHUHQW FKDUDFWHUV W\SHG DQG WKHQ FRQYHUWHG WR FUHDWH RQHRUPRUHFKDUDFWHUV Reflection

5HIOHFWLRQVXSSRUWZDVLQWURGXFHGLQ-'.5HIOHFWLRQHQDEOHVFODVVHVLQWHUIDFHVDQGREMHFWV WREHH[DPLQHGDQGWKHLUSXEOLFILHOGVFRQVWUXFWRUVDQGPHWKRGVWREHGLVFRYHUHGDQGXVHGDW UXQWLPH7KHVHFDSDELOLWLHVDUHXVHGE\-DYD%HDQV2EMHFW,QVSHFWLRQ7RROV-DYDUXQWLPHWRROV VXFKDVWKHGHEXJJHUDQGRWKHU-DYDDSSOLFDWLRQVDQGDSSOHWV-'.SURYLGHVWKHFDSDELOLW\WR LGHQWLI\ D ILHOG PHWKRG RU FRQVWUXFWRUV DV VXSSUHVVLQJ GHIDXOW -DYD ODQJXDJH DFFHVV FRQWUROV 7KLVSHUPLWVUHIOHFWLRQWREHEHWWHUXVHGZLWKWKHPRUHIOH[LEOH-'.VHFXULW\PRGHO Sound Files and Audio Files

-'.SURYLGHGWKHFDSDELOLW\IRUDSSOHWVWRSOD\DXGLRILOHVWKDWZHUHLQWKH6XQ$XGLR $8 IRUPDW -'.  SURYLGHV D QHZ VRXQG HQJLQH WKDW DOORZV DXGLR ILOHV WR EH SOD\HG E\ ERWK DSSOHWV DQG DSSOLFDWLRQV 7KH VRXQG HQJLQH DOVR SURYLGHV VXSSRUW IRU WKH 0XVLFDO ,QVWUXPHQW GLJLWDO ,QWHUIDFH 0,',  WKH 0LFURVRIW :LQGRZV $XGLR )LOH IRUPDW :$9(  WKH 5LFK 0XVLF )RUPDW 50) DQGWKH$XGLR,QWHUFKDQJH)LOH)RUPDW $,))  Native Interface

7KH -DYD 1DWLYH ,QWHUIDFH -1,  SURYLGHV WKH FDSDELOLW\ IRU -DYD REMHFWV WR DFFHVV PHWKRGV ZULWWHQ LQ ODQJXDJHV RWKHU WKDQ -DYD ,Q -'.  WKH -1, LQFOXGHV QHZ FDSDELOLWLHV IRU FRQWUROOLQJWKHPDQQHULQZKLFKQDWLYHPHWKRGVLQWHUDFWZLWKWKH-DYD9LUWXDO0DFKLQH Performance

7KHRYHUDOOSHUIRUPDQFHRIWKH-'.WRROVKDVEHHQJUHDWO\LPSURYHG)LUVWDQGIRUHPRVWLVWKH LQFOXVLRQ RI D MXVWLQWLPH FRPSLOHU ZLWK WKH -'. 2WKHU SHUIRUPDQFH HQKDQFHPHQWV LQFOXGH

Comp-U-Learn

307

Java Programming I

WKH XVH RI QDWLYH OLEUDULHV IRU VRPH SHUIRUPDQFH FULWLFDO &RUH $3, FODVVHV LPSURYHPHQWV WR PXOWLWKUHDGLQJSHUIRUPDQFHDQGUHGXFWLRQLQPHPRU\XVDJHIRUVWULQJFRQVWDQWV Important language Changes

,Q -'.  WKH VWRS  VXVSHQG  DQG UHVXPH  PHWKRGV RI WKH 7KUHDG FODVV KDYH EHHQ GHSUHFDWHG EHFDXVH RI HUURUV DQG LQFRQVLVWHQFLHV WKDW PD\ RFFXU DV WKH UHVXOW RI WKHLU XVH ,QVWHDGRIXVLQJWKHVWRS LWLVUHFRPPHQGHGWKDWWKUHDGVPRQLWRUWKHLUH[HFXWLRQDQGVWRSE\ UHWXUQLQJ IURP WKHLU UXQ  PHWKRG $ WKUHDG PD\ GHWHUPLQH WKDW LWHP H[HFXWLRQ VKRXOG EH VWRSSHGDVWKHUHVXOWRIPRQLWRULQJWKHVWDWHRIDVKDUHGYDULDEOH,QDGGLWLRQLWLVUHFRPPHQGHG WKDW WKUHDGV VXVSHQG DQG UHVXPH WKHLU RZQ H[HFXWLRQ DV WKH UHVXOW RI PRQLWRULQJ LQWHUIDFH HYHQWVVXFKDVWKHYDOXHRIVKDUHGYDULDEOHV 7KHZDLW DQGQRWLI\ PHWKRGVRIWKH2EMHFWFODVVVKRXOGEHXVHGWRFDXVHDWKUHDGWRZDLWRQ FKDQJHVWRWKHYDOXHRIDVKDUHGYDULDEOH

Note In addition to changes to the Thread class, other classes, interfaces and methods have been deprecated in JDK 1.2. a complete description of these changes is included with the JDK 1.2 documentation. A deprecated API element is one that is still supported for backward compatibility but is being phased out of future JDK versions. Java 3D

7KH -DYD ' $3, SURYLGHV WKH FDSDELOLW\ RI FUHDWLQJ WKUHHGLPHQVLRQDO JUDSKLFV DSSOHWV DQG DSSOLFDWLRQV,WFRQVLVWVRIFODVVHVDQGLQWHUIDFHVWKDWVXSSRUW'REMHFWVDQGWUDQVIRUPDWLRQV The Java Media Framework

7KLV SURYLGHV VXSSRUW IRU SOD\LQJ DXGLR YLGHR DQG RWKHU PXOWLPHGLD ZLWKLQ -DYD DSSOHWV DQG DSSOLFDWLRQV ,W VXSSRUWV D ZLGH UDQJH RI DXGLR DQG YLGHR IRUPDWV DQG SURYLGHV DQLPDWLRQ FDSDELOLWLHV

The Speech API The Speech API adds speech recognition and synthesis capabilities to Java. JavaMail

-DYD0DLOSURYLGHVDVHWRIFODVVHVDQGLQWHUIDFHVIRUGHYHORSLQJFOLHQWDQGVHUYHUFRPSRQHQWVRI HPDLOV\VWHPV 308

Comp-U-Learn

Appendix 1

Java Naming and Directory Services

7KH-DYD1DPLQJDQG'LUHFWRU\,QWHUIDFH -1', DOORZV-DYDDSSOHWVDQGDSSOLFDWLRQVWRDFFHVV QDPLQJ DQG GLUHFWRU\ VHUYLFHV XVLQJ SURWRFROV VXFK DV WKH /LJKWZHLJKW 'LUHFWRU\ $FFHVV SURWRFRO The Java Management API

7KH-DYD0DQDJHPHQW$3,SURYLGHVD-DYDEDVHGIUDPHZRUNIRUPDQDJLQJHQWHUSULVHQHWZRUNV DQGQHWZRUNUHVRXUFHV JavaSpaces

-DYD6SDFH VXSSRUWV WKH GHYHORSPHQW RI GLVWULEXWHG DSSOLFDWLRQV E\ SURYLGLQJ SHUVLVWHQW GLVWULEXWHGREMHFWFDSDELOLWLHV JavaCommerce

7KH-DYD&RPPHUFHSURYLGHVWKHFDSDELOLW\WREXLOGHOHFWURQLFFRPPHUFHDSSOLFDWLRQVLQ-DYD ActiveX Vs Java Classes

:KHQ 0LFURVRIW LQWURGXFHG WKH 9%; IRU XVH ZLWKLQ WKH 9LVXDO %DVLF SURJUDPPLQJ HQYLURQPHQWLWFUHDWHGDQHQWLUHLQGXVWU\RIFRPSRQHQWPDQXIDFWXUHUV7KH9%;VWDQGDUGZDV TXLWH VWUDLJKWIRUZDUG DQG DOORZHG GHYHORSHUV WR LPSOHPHQW HQFDSVXODWLRQ RI GLVWULEXWDEOH SURJUDPPLQJWRROV(DFK9%;2&;LPSOHPHQWVLWVRZQSURSHUWLHVDQGPHWKRGVDQGDOORZV WKHSURJUDPPHUWRWUDSHYHQWV$OWKRXJK2&;QRZFDOOHG$FWLYH;FRQWUROVDUHLPSOHPHQWHG XVLQJ0LFURVRIW2/(WKHVHFRQWUROVVWLOODSSHDUWRWKHGHYHORSHUDVDVHWRISURSHUWLHVPHWKRGV DQGHYHQWVHQFDSVXODWHGLQRQHVLQJOHSURJUDPPLQJREMHFW $ -DYD FODVV DOORZV GHYHORSHUV VRPH DGYDQWDJHV RYHU DQ $FWLYH; FRQWURO ,JQRULQJ IRU WKH PRPHQWYDULRXVIHDWXUHVEXLOWLQWRWKHODQJXDJHVXFKDVWKUHDGLQJDQGH[FHSWLRQKDQGOLQJ-DYD FODVVHV IXOO\ VXSSRUW LQKHULWDQFH DQG SRO\PRUSKLVP &XUUHQWO\ KXQGUHGV RI -DYD FODVV VRXUFH ILOHVDUHIUHHO\DYDLODEOHRQWKH:RUOG:LGH:HE7KLVOLVWJURZVGDLO\DQGLWLVJURZLQJTXLFNO\ -DYD GHYHORSHUV HQYLVLRQ D ZRUOG ZKHUH -DYD FODVV FOHDULQJKRXVHV DUH DYDLODEOH WR TXLFNO\ GRZQORDG FODVVHV WKDW FDQ EH H[WHQGHG E\ LQGLYLGXDO GHYHORSHUV ,Q DGGLWLRQ WR WKLV YDULRXV WKLUGSDUW\-DYDFODVVOLEUDULHVDUHDOUHDG\DSSHDULQJIRUWKHVXSSRUWRIYDULRXVRSHUDWLRQVVXFKDV PXOWLPHGLD QHWZRUNLQJ DQG GDWDEDVH DFFHVV $OO RI WKLV FRGH LV FRPSOHWHO\ UHXVDEOH DQG H[WHQVLEOH QRWWRPHQWLRQSODWIRUPLQGHSHQGHQW  :KHQD-DYDFODVVLVGRZQORDGHGIURPD:HE6HUYHULWLVDEOHWRFRPPXQLFDWHIUHHO\ZLWKWKH VHUYHUWKDWLWZDVGRZQORDGHGIURP7KLVLVH[WUHPHO\XVHIXOIRUGDWDEDVHVDFFHVVUXQQLQJ&*, VFULSWV RU UHWULHYLQJ DGGLWLRQDO FODVVHV $FWLYH ; FRQWUROV PHDQZKLOH DUH DOORZHG WR FRPPXQLFDWH ZLWK DQ\ PDFKLQH FRQWDLQLQJ 'LVWULEXWHG &RPSRQHQW 2EMHFW 0RGHO REMHFWV Comp-U-Learn

309

Java Programming I

$FWLYH;FRQWUROVDUHDOVREDVLFDOO\DOORZHGIXOODFFHVVWRWKHXVHU·VV\VWHPXQOLNH-DYDDSSOHWV ZKLFKDUHUHVWULFWHG$FWLYH;FRQWUROVGRKDYHVRPHGLVWLQFWDGYDQWDJHVKRZHYHU$Q\$FWLYH; FRQWDLQHUDSSOLFDWLRQFDQFRPPXQLFDWHZLWKDQGGLVSOD\DQ$FWLYH;FRQWUROZLWKLQLWVZLQGRZ 7KLVPHDQVWKDW:HEEURZVHUVWKDWDUH$FWLYH;HQDEOHG VXFKDV0LFURVRIW,QWHUQHW([SORUHU   ZLOO EH DEOH WR GLVSOD\ ([FHO VSUHDGVKHHWV GLUHFWO\ RQ DQ +70/ SDJH $FWLYH; FRQWUROV XSORDGHG WR D XVHU·V :HG EURZVHU FDQ DOVR FRPPXQLFDWH ZLWK DQ\ DSSOLFDWLRQ WKDW VXSSRUWV &20 &RPSRQHQW2EMHFW0RGHO LQWHUIDFHV &XUUHQWO\0LFURVRIWLQWHQGVWRZUDS-DYDFODVVHVZLWKDQ$FWLYH;OD\HUWRDOORZ-DYDGHYHORSHUV WRWDNHDGYDQWDJHRIWKHIHDWXUHVPHQWLRQHGKHUH7KLVZLOOEHGRQHWKURXJKWKHPDJLFRIWKH 0LFURVRIWZLQGRZV9LUWXDO0DFKLQHIRU-DYDDQGWKHXQGHUO\LQJ&RPSRQHQW2EMHFW0RGHO

310

Comp-U-Learn

Appendix 2

Appendix 2 Java Tools Javadoc -DYDGRFH[DPLQHVWKHVRXUFHFRGHDQGJHQHUDWHV+70/ILOHVWKDWSURYLGHDIXOO\LQWHJUDWHGVHW RI GRFXPHQWDWLRQ IRU -DYD VRIWZDUH +70/ ILOHV JHQHUDWHG E\ MDYDGRF GRFXPHQW WKH FODVVHV LQWHUIDFHV DQG YDULDEOHV PHWKRGV DQG H[FHSWLRQV WKDW DUH GHFODUHG DQG XVHG LQ WKH SURJUDPV 7KHVH ILOHV GHVFULEH WKH VRIWZDUH DW WKH SDFNDJH DQG FODVV OHYHO 7KH OLQNLQJ FDSDELOLWLHV RI +70/DUHXVHGWRSURYLGHH[WHQVLYHFURVVUHIHUHQFLQJ EHWZHHQ UHODWHG VRIWZDUH FRPSRQHQWV 7KHVHOLQNVDOORZ\RXWRTXLFNO\DFFHVVDOORIWKHGRFXPHQWDWLRQWKDWLVUHOHYDQWWRDSDUWLFXODU WRSLF -DYDGRF GLIIHUV IURP RWKHU GRFXPHQWDWLRQ JHQHUDWRUV LQ WKDW LW JRHV EH\RQG VLPSOH FRPPHQWVFDQQLQJDFWXDOO\SDUVLQJ\RXUVRXUFHFRGHWRJHQHUDWHGRFXPHQWDWLRQWKDWGHVFULEHV WKHVWUXFWXUHDQGEHKDYLRURI\RXUSURJUDPV,WPDNHVMXGLFLRXVXVHRI+70/OLQNVWRJHQHUDWH GRFXPHQWDWLRQWKDWDOORZV\RXWRHDVLO\WUDYHUVHWKHVWUXFWXUHRI\RXUVRIWZDUH 7KHMDYDGRFSURJUDPUHFRJQL]HVVSHFLDOW\SHVRIFRPPHQWVWKDWDUHLQVHUWHGLQWKHVRXUFHFRGH :KHQ LW SDUVHV WKH VRXUFH FRGH LW FRPELQHV WKH FRPPHQWV ZLWK WKH VWUXFWXUDO LQIRUPDWLRQ LW JHQHUDWHV7KHFRPPHQWVDUHWKHQLQWHJUDWHGLQWRWKHVRIWZDUH·V+70/GHVFULSWLRQ7KHVSHFLDO FRPPHQWVUHFRJQL]HGE\MDYDGRFFRQVLVWRIGRFFRPPHQWVMDYDGRFWDJVDQG+70/WDJV 7KH MDYDGRF WDJV DUH VSHFLDO WDJV WKDW DUH HPEHGGHG LQ GRF FRPPHQWV 7KHVH WDJV DOORZ LQFOXGLQJ LQIRUPDWLRQ LQ VRIWZDUH ,W DOVR DOORZV WR LQVHUW +70/ WDJV GLUHFWO\ LQWR WKH VRXUFH FRGH

Java Plug in 2QH RI WKH ELJJHVW SUREOHPV IDFLQJ DSSOHW GHYHORSHUV LV PDLQWDLQLQJ EDFNZDUG FRPSDWLELOLW\ ZLWK ROGHU EURZVHUV VXFK DV 1DYLJDWRU  DQG ,QWHUQHW ([SORUHU  WKDW GRQ·W VXSSRUW -'. OHW DORQH -'.  ,Q RUGHU WR SURYLGH DSSOHWV WKDW ZRUN ZLWK PRVW RI WKH LQVWDOOHG EURZVHU EDVH DSSOHW GHYHORSHUV ZHUH IRUFHG LQWR D ´OHDVW FRPPRQ GHQRPLQDWRUµ DSSURDFK 7KLV DSSURDFK JHQHUDOO\ UHVXOWV LQ DSSOHWV WKDW GR QRW H[FHHG WKH FDSDELOLWLHV RI -'.  -DYD6RIWGHYHORSHG-DYD3OXJ,QDVDVROXWLRQWRWKLVSUREOHP-DYD3OXJ,QIRUPHUO\NQRZQDV $FWLYDWRUDOORZVXVHUV WRXVHYDULRXVYHUVLRQVRI6XQ·V -DYD 5XQWLPH (QYLURQPHQW ZLWK WKHLU EURZVHU LQVWHDG RI WKH -DYD 9LUWXDO 0DFKLQH SURYLGHG E\ WKH EURZVHU YHQGRU -DYD 3OXJ,Q ZRUNV ZLWK 1DYLJDWRU  RU ODWHU DQG ,QWHUQHW ([SORUHU DQG DV D EURZVHU SOXJ LQ ZKHQ XVHG ZLWK1DYLJDWRU

Comp-U-Learn

311

Appendix 3

Appendix 3 Java Development Environments Visual Development Tools 9LVXDO 'HYHORSPHQW 7RROV VLPSOLI\ WKH VRIWZDUH GHYHORSPHQW SURFHVV OHWWLQJ \RX FUHDWH WKH JUDSKLFDO XVHU LQWHUIDFH *8,  RI DSSOHWV DQG DSSOLFDWLRQV E\ GUDJJLQJ DQG GURSSLQJ XVHU LQWHUIDFHFRPSRQHQWVWRWKHLUGHVLUHGORFDWLRQV7KHVHWRROVSURYLGHKRRNVIRUHYHQWKDQGOLQJ DVVRFLDWHGZLWK*8,FRPSRQHQWVW\SLFDOO\OHWWLQJ\RXFUHDWHDQGPDLQWDLQHYHQWKDQGOLQJFRGH E\FOLFNLQJRQWKH*8,FRPSRQHQWV 9LVXDO GHYHORSPHQW WRROV FRPPRQO\ SURYLGH D FODVV EURZVHU IRU YLHZLQJ DQG WUDYHUVLQJ WKH DSSOLFDWLRQ FODVV KLHUDUFK\ 7KH\ DOVR LQFOXGH D VRXUFH FRGH HGLWRU WKDW KLJKOLJKWV -DYD V\QWD[ HOHPHQWVXVLQJVSHFLDOFRORUV0RVWWRROVVXSSRUWDXWRPDWLFFRGHJHQHUDWLRQDQGDMXVWLQWLPH FRPSLOHU 6HFRQG JHQHUDWLRQ -DYD GHYHORSPHQW WRROV SURYLGH -DYD%HDQV VXSSRUW WHDP SURJUDPPLQJFDSDELOLWLHV-'%&GULYHUVIRUSRSXODUGDWDEDVHSURGXFWV&25%$FRPSDWLELOLW\ DQGWRROVWKDWVLPSOLI\FRQQHFWLYLW\ZLWKOHJDF\DSSOLFDWLRQV 6RIWZDUH GHYHORSHUV KDYH EHFRPH DFFXVWRPHG WR IXOO\ JUDSKLFDO GHYHORSPHQW HQYLURQPHQWV 5DSLGDSSOLFDWLRQGHYHORSPHQW 5$' WRROVVXFKDV3RZHU6RIW3RZHUEXLOGHU0LFURVRIW9LVXDO %DVLFDQG%RUODQG'HOSKLKDYHGUDVWLFDOO\LQFUHDVHGSURJUDPPHUSURGXFWLYLW\DQGHDVHRIXVH 7KHQ-DYDDOVRFDPHDORQJ7KH-'.ZDVGHVLJQHGWREHDEDVLFGHYHORSPHQWWRRONLWWKDWFRXOG EHXVHGRQYLUWXDOO\DQ\SODWIRUPRQZKLFK-DYD9LUWXDO0DFKLQHH[LVWHG)RUVRPHGHYHORSHUV WKHWRRONLWWKDWFRPHVSUHSDFNDJHGZLWKWKH-'.ZLOOEHSHUIHFWO\ILQH7KHIROORZLQJDUHVRPH RIWKHWRROVWKDWDUHXVHGWRGHYHORS-DYDDSSOLFDWLRQV-DYDGHYHORSPHQWFDQRFFXURQHYHU\ SRSXODURSHUDWLQJV\VWHPSODWIRUPDYDLODEOHWRGD\$GHYHORSHUXVLQJ6XQ6RODULVFDQLQVWDQWO\ WHVWKLVDSSOLFDWLRQRQ:LQGRZV0DFLQWRVKDQG8QL[PDFKLQHVUXQQLQJVLGHE\VLGH

SunSoft Java Workshop for Sun Solaris and Microsoft Windows 95/NT 7KHPRVWQRYHOGHYHORSPHQWSODWIRUPFRPHVIURPWKHFUHDWRURI-DYD6XQ0LFURV\VWHPV$Q HYDOXDWLRQFRS\FDQEHGRZQORDGHGIURP-DYD6RIW·V:HEVLWHDW KWWSZZZVXQFRPVXQVRIW'HYHOR=SHUSURGXFWVMDYD:RUNVKRS 7KH-DYD:RUNVKRSLVLQWHUHVWLQJEHFDXVHLWLVHQWLUHO\ZULWWHQLQ-DYD7KH:RUNVKRSHQDEOHV WKHGHYHORSHUWRRUJDQL]HZRUNLQWRSURMHFWVDQGFRPSLOHDQGUXQ-DYDDSSOLFDWLRQVXVLQJDVHW RI YLVXDO WRROV $W WKH FXUUHQW WLPH LW KDV QR FDSDELOLW\ WR PDQDJH GDWDEDVHRULHQWHG SURMHFWV DQG LW GRHV QRW DOORZ WKH XVHU WR YLVXDOO\ HGLW FODVV SURSHUWLHV DQG PHWKRGV 7KRXJK LW ZDV

Comp-U-Learn

317

Java Programming I

ZULWWHQ LQ -DYD KRZHYHU WKH :RUNVKRS UXQV DOPRVW LGHQWLFDOO\ DFURVV WKH SODWIRUPV LW LV DYDLODEOHIRU

Java Studio -DYD 6WXGLR IURP 6XQ 0LFURV\VWHPV KWWSZZZVXQFRPVWXGLR  LV D YLVXDO VRIWZDUH GHYHORSPHQW HQYLURQPHQW WKDW PD[LPL]HV WKH XVH RI SUH EXLOW -DYD%HDQV FRPSRQHQWV DQG PLQLPL]HVWKHQHHGIRU FRGLQJ-DYD 6WXGLR SURYLGHV DQ H[WHQVLYH VHW RI -DYD%HDQV DQG VHW RI WRROVIRULQWHJUDWLQJEHDQVLQWRDSSOHWVDQGDSSOLFDWLRQV -DYD VWXGLR SURYLGHV EHDQV WKDW VXSSRUW PXOWLPHGLD *8, GHYHORSPHQW GDWDEDVH DFFHVV GDWD IORZDQGPDWKHPDWLFDOFRPSXWDWLRQ-DYD6WXGLRLVEXLOWLQ-DYDDQGUXQVRQDOO-DYDSODWIRUPV WKDWVXSSRUWWKHFRUH$3,

JavaPlan -DYD3ODQ IURP /LJKWKRXVH 'HVLJQ /LPLWHG UHFHQWO\ SXUFKDVHG E\ 6XQ 0LFURV\VWHPV  LV DQ HQWHUSULVH ZLGH YLVXDO GHYHORSPHQW WRRO IRU -DYD DSSOHWV DQG DSSOLFDWLRQV KWWSZZZOLJKWKRXVHFRP3URGXFWKWPO -DYD3ODQFRQVLVWVRIDQLQWHJUDWHGVHWRIWRROVWKDW DUHDLPHGDWWKHGHYHORSPHQWRIUHXVDEOH-DYDFRPSRQHQWVVXFKDV-DYD%HDQV -DYD3ODQ VXSSRUWV JUDSKLFDO PRGHOLQJ RI DSSOLFDWLRQV YLD DQ HOHFWURQLF ZKLWHERDUG D WRRO WKDW HQDEOHVPXOWLXVHUFROODERUDWLRQRYHUDQHWZRUN,WSURYLGHVDUHYHUVHHQJLQHHULQJFDSDELOLW\IRU DQDO\]LQJFRPSLOHGE\WHFRGHILOHVDQGVXSSRUWVWKHSRUWLQJRI&DQG&OHJDF\DSSOLFDWLRQV -DYD3ODQDOVRSURYLGHVH[WHQVLYHGRFXPHQWDWLRQJHQHUDWLRQFDSDELOLWLHV-DYD3ODQUXQVRQ6RODULV DQG:LQGRZV17

Symantec Cafe for Apple Macintosh and Microsoft Windows 95/NT 6\PDQWHF&DIH KWWSFDIHV\PDQWHFFRP ZDVWKHILUVW*8,EDVHGGHYHORSPHQWHQYLURQPHQW IRU -DYD RQ WKH :LQGRZV SODWIRUP 7KH GHYHORSPHQW HQYLURQPHQW LV EDVHG RQ WKH SRSXODU 6\PDQWHF & FRPSLOHU EXW KDV EHHQ FXVWRPL]HG IRU -DYD DSSOHWDSSOLFDWLRQ GHYHORSPHQW )HDWXUHVLQFOXGHWKHIROORZLQJ ♦ ♦ ♦ ♦ ♦

GUI based debugger Object oriented class editor Drag and Drop resource editing App Express, a tool used to build default Java applets and application An optimizing Java compiler, which is billed as providing up to 10 time faster application performance. ♦ An optimized Java Virtual Machine, which is billed as providing double the performane of the JVM supplied by the JDK. ♦ VisualAge for Java

318

Comp-U-Learn

Appendix 3

VisualAge for Java 9LVXDO$JH IRU -DYD KWWSZZZVRIWZDUHLEPFRPDGYDMDYD  LV ,%0·V VROXWLRQ IRU -DYD IRU VRIWZDUH GHYHORSPHQW ,W XVHV WKH VDPH WHFKQRORJ\ DV RWKHU 9LVXDO$JH SURGXFWV DQG LV DQ HQWHUSULVH ZLGH -DYD VRIWZDUH GHYHORSPHQW HQYLURQPHQW WKDW IRFXVHV RQ WKH GHYHORSPHQW RI -DYD DSSOLFDWLRQV WKDW FRQQHFW WR H[LVWLQJ VHUYHU GDWD WUDQVDFWLRQV DQG DSSOLFDWLRQV ,W DOVR PDNHV H[WHQVLYH XVH RI -DYD%HDQV FRPSRQHQWV YLD WKH 9LVXDO$JH :HE5XQQHU 7RRO.LW DQG WRROVWKDWSURYLGHWKHFDSDELOLW\WRFRQYHUW$FWLYH;FRPSRQHQWVLQWR-DYD%HDQV9LVXDO$JHIRU -DYD LQFOXGHV D VRXUFH FRGH HGLWRU GHEXJJHU FODVV EURZVHU DQG H[WHQVLYH FODVV OLEUDU\ 7KHVH WRROV DUH SURYLGHG LQ D WHDPSURJUDPPLQJ HQYLURQPHQW 7KH (QWHUSULVH $FFHVV %XLOGHU WRRO IDFLOLWDWHV WKH FRQQHFWLRQ RI -DYD FRGH ZLWK OHJDF\ DSSOLFDWLRQV DQG GDWD 9LVXDO $JH IRU -DYD UXQV RQ :LQGRZV 17 :LQGRZV  :LQGRZV  DQG 26 7KH (QWU\ YHUVLRQ LV D IUHH GRZQORDG

Borland Latte for Microsoft Windows 95/NT %RUODQG/DWWHLVWKHORQJDZDLWHG*8,EDVHGGHYHORSPHQWHQYLURQPHQWIRU-DYD0XFKRIWKH ORRN DQG IHHO RI /DWWH LV EDVHG RQ WKH DZDUG ZLQQLQJ :LQGRZV ,'( %RUODQG 'HOSKL /LNH 6\PDQWHF·V &DIH /DWWH ZLOO LQFOXGH D *8, GHEXJJHU DQG D FRPSOHWH *8, EDVHG ,'( $OVR LQFOXGHG ZLWK /DWWH ZLOO EH WKH %RUODQG ,QWHU%DVH ,QWHU&OLHQW 7KLV LV ZULWWHQ HQWLUHO\ LQ  -DYD DQGZLOODOORZ,QWHU%DVHGDWDEDVHVWREHFRQQHFWHGXVLQJ-DYDDSSOHWV%RUODQGSODQVWRFRQWLQXH WRUROORXW-DYDEDVHGGHYHORSPHQWWRROVWRPHHWFRUSRUDWHGHPDQGVLQDUHDVVXFKDV'DWDEDVH DFFHVVDQG*8,GHYHORSPHQW

JBuilder Client/Server Suite -%XLOGHU&OLHQWVHUYHU ,QSULVH IRUPHUO\ E\ %RUODQG KWWSZZZERUODQGFRPMEXLOGHU  LV D FRPSRQHQW RULHQWHG YLVXDO GHYHORSPHQW HQYLURQPHQW IRU GHYHORSLQJ HQWHUSULVH ZLGH -DYD DSSOLFDWLRQV,WSURYLGHVFRQQHFWLYLW\WR64/GDWDEDVHVVXSSRUWLQJERWK-'%&DQG2'%&,W VXSSRUWV WHUP SURJUDPPLQJ DQG SURYLGHV GLVWULEXWHG REMHFW VXSSRUW WKURXJK &25%$ FRQQHFWLYLW\-%XLOGHUUXQVRQ:LQGRZV17:LQGRZVDQG:LQGRZV

Super Mojo 6XSHU 0RMR E\ 3QXPEUD 6RIWZDUH ,QF KWWSZZZSHQXPEUDVRIWZDUHFRP  XVHV D FRPSRQHQWRULHQWHGDSSURDFKWRGHYHORSLQJ-DYDVRIWZDUH,WFRQVLVWVRID*8,GHVLJQHU9LVXDO 6FULSWHU DQG D &RGHU 7KH 'HVLJQHU SURYLGHV GUDJ DQG GURS GHYHORSPHQW RI DQ DSSOHW RU DSSOLFDWLRQ·V *8, 7KH 9LVXDO 6FULSWHU LV XVHG WR DGG IXQFWLRQDOLW\ WR DQ DSSOLFDWLRQ·V YLVXDO GHVLJQ7KH&RGHURUJDQL]HVREMHFWVLQDZD\WKDWIDFLOLWDWHVFRGHGHYHORSPHQW$QLQWHJUDWHG FODVV DQG PHWKRG EURZVHU OHWV XVHUV YLHZ FRGH WKDW LV DXWRPDWLFDOO\ JHQHUDWHG 6XSHU 0RMR LV ZULWWHQLQ-DYDDQGUXQVRQDOOSODWIRUPVWKDWVXSSRUWWKH-DYDFRUH$3,

Comp-U-Learn

319

Java Programming I

JDesignerPro -'HVLJQHU3URFRQVLVWVRIDQDSSOLFDWLRQGHYHORSPHQWHQYLURQPHQWDQGDSSOLFDWLRQPLGGOHZDUH 7KH DSSOLFDWLRQ GHYHORSPHQW HQYLURQPHQW SURYLGHV WUDGLWLRQDO YLVXDO GHYHORSPHQW WRROV 7KH PLGGOHZDUHFRQVLVWVRIWKH-$**6HUYHUZKLFKSURYLGHV-'%&2'%&GDWDEDVHFRQQHFWLYLW\ %XOOHW3URRISODQVWRHQKDQFHWKH-$**6HUYHUWRKDQGOH,,23DQG&25%$FRQQHFWLYLW\7KLV LVZULWWHQLQ-DYDDQGUXQVRQ81,;:LQGRZV17:LQGRZVDQG:LQGRZV

Microsoft Visual J++ for Microsoft Windows 95/NT 0LFURVRIW9LVXDO-LVWKHQDPHIRU0LFURVRIW·V-DYDGHYHORSPHQWSODWIRUP 7KLVLQFOXGHVD *8,EDVHGGHYHORSPHQWHQYLURQPHQWLQDGGLWLRQWRD-DYD9LUWXDO0DFKLQHLPSOHPHQWDWLRQIRU WKH:LQGRZVSODWIRUP0LFURVRIWSODQVWRDXJPHQWVWDQGDUG-DYDIXQFWLRQDOLW\ZLWKLWV$FWLYH; FRPSRQHQW REMHFW WHFKQRORJ\ 0LFURVRIW SODQV WR ZUDS -DYD DSSOHWV ZLWK $FWLYH; 7KLV ZLOO DOORZ DSSOHWV WR EH VFULSWHG XVLQJ ODQJXDJHV VXFK DV -DYD6FULSW DQG 9%6FULSW EXW DOO RI WKHVH IHDWXUHVZLOOREYLRXVO\DIIHFWWKHFURVVSODWIRUPYLDELOLW\RIWKHVH-DYDDSSOHWV

320

Comp-U-Learn

Java Programming I

Java enabled browsers -DYD(QDEOHGEURZVHUVHQDEOH WRUXQ-DYDSURJUDPVLQDQ,QWHUQHW HQYLURQPHQW -DYD HQDEOHG EURZVHUVDUHDYDLODEOHIURPERWK6XQ0LFURV\VWHPVDQG1HWVFDSH

HotJava +RW-DYDLVWKHQDPHJLYHQE\6XQ0LFURV\VWHPVWRLWV-DYD:RUOG:LGH:HEEURZVHU+RW-DYD LVZULWWHQHQWLUHO\LQ-DYD$OWKRXJK+RW-DYD·VSXUSRVHLVWRYLHZDSSOHWVHPEHGGHGLQ+70/ GRFXPHQWVLWVHUYHVDVWKHEHVWH[DPSOHWRGDWHRIZKDWFDQEHGRQHLQD-DYDDSSOLFDWLRQ+RW -DYDSUHVHQWVWKHXVHUZLWKDYHU\FOHDQDQGVLPSOHLQWHUIDFH,WKDVDVHULHVRIPHQXVDFURVVWKH WRSDQGDVLQJOHVHWRIVL[EXWWRQVWKDWFDQEHXVHGIRUQDYLJDWLRQ,QRUGHUWKHVHEXWWRQVZLOO PRYHWRWKHSULRUSDJHPRYHWRWKHQH[WSDJHPRYHWRWKHKRPHSDJHUHORDGWKHFXUUHQWSDJH DQG VWRS ORDGLQJ SDJH DQG YLHZ +70/ HUURUV 6LQFH +RW-DYD LQFOXGHV D IXOO -DYD 9LUWXDO 0DFKLQHLWLVSRVVLEOHWRFUHDWH:HESDJHVZLWKDFWLYHG\QDPLFFRQWHQW

Netscape 1HWVFDSH LQ LWV 1HWVFDSH 1DYLJDWRU YHUVLRQ  LQFOXGHV -DYD FRPSDWLELOLW\ 7KH LQFOXVLRQ RI -DYD VXSSRUW LQ D 1HWVFDSH EURZVHU LV VLJQLILFDQW EHFDXVH 1HWVFDSH LV WKH GRPLQDQW EURZVHU YHQGRU:LWKMDYDVXSSRUWLQFOXGHGLQ1DYLJDWRU-DYDDSSOHWVDUHZLWKLQUHDFKRIPRVW:RUOG :LGH:HEXVHUV

Javac 7KH-DYD FRPSLOHULVWKH FRPSRQHQW RIWKH -DYD 'HYHORSHU·V .LW XVHG WR WUDQVIHU -DYD VRXUFH FRGHILOHVLQWRE\WHFRGHH[HFXWDEOHVWKDWFDQEHUXQLQWKH-DYDUXQWLPHV\VWHP,Q-DYDVRXUFH FRGHILOHVKDYHWKHH[WHQVLRQMDYD-DYDVRXUFHFRGHILOHVDUHVWDQGDUG$6&,,WH[WILOHVPXFK OLNH WKH VRXUFH FRGH ILOHV DQG FUHDWH H[HFXWDEOH -DYD E\WHFRGH FODVVHV IURP WKHP ([HFXWDEOH E\WHFRGHFODVVILOHVKDYHWKHH[WHQVLRQFODVVDQGWKH\UHSUHVHQWD-DYDFODVVLQLWVXVHDEOHIRUP -DYDFODVVILOHVDUHJHQHUDWHGRQDRQHWR²RQHEDVLVZLWKWKHFODVVHVGHILQHGLQWKHVRXUFHFRGH ,QRWKHUZRUGVWKH-DYDFRPSLOHUJHQHUDWHVH[DFWO\RQHFODVVIRUHDFKFODVVFUHDWHG7HFKQLFDOO\ LWLVSRVVLEOHWRGHILQHPRUHWKDQRQHFODVVLQDVLQJOHVRXUFHILOHLWLVWKHUHIRUHSRVVLEOHIRUWKH FRPSLOHUWRJHQHUDWHPXOWLSOHFODVVILOHVIURPDVLQJOHVRXUFHILOH:KHQWKLVKDSSHQVLWPHDQV WKDWWKHVRXUFHILOHFRQWDLQVPXOWLSOHFODVVGHILQLWLRQV -XVWLQWLPHFRPSLOHUVUHPRYHWKHUROHRIWKHUXQWLPHLQWHUSUHWHUE\FRQYHUWLQJ-DYDE\WHFRGHV WR QDWLYH FRGH RQ WKH IO\ EHIRUH H[HFXWLQJ D -DYD SURJUDP ,Q WKLV ZD\ MXVWLQWLPH -DYD FRPSLOHUVZRUNPRUHOLNHWKHEDFNHQGRIWUDGLWLRQDOODQJXDJHFRPSLOHUVLQWKDWWKH\JHQHUDWH FRGH IRU D QDWLYH SODWIRUP 6LPLODUO\ WKH -DYD FRPSLOHU ZRUNV PRUH OLNH WKH IURQW HQG RI D WUDGLWLRQDOFRPSLOHULQWKDWLWSDUVHV-DYDVRXUFHFRGHDQGJHQHUDWHVLQWHUQDOO\XVHIXOE\WHFRGH FODVVHV

312

Comp-U-Learn

Appendix 2

Java Interpreter 7KH -DYD UXQWLPH LQWHUSUHWHU LV WKH FRPSRQHQW RI WKH -DYD 'HYHORSHU·V .LW XVHG WR UXQ H[HFXWDEOH-DYDE\WHFRGHFODVVHV7KH -DYD LQWHUSUHWHU SURYLGHV D PHDQV WR UXQ -DYD SURJUDPV RXWVLGHRIDFRQYHQWLRQDO:HEEURZVHU7KH-DYDUXQWLPHLQWHUSUHWHULVDVWDQGDORQHYHUVLRQRI WKH-DYDLQWHUSUHWHUEXLOWLQWR-DYDFRPSDWLEOH:HEEURZVHUVVXFKDV1HWVFDSH1DYLJDWRU7KH UXQWLPH LQWHUSUHWHU SURYLGHV WKH VXSSRUW WR UXQ -DYD H[HFXWDEOH SURJUDPV LQ WKH FRPSLOHG E\WHFRGH FODVV IRUPDW %HFDXVH WKH LQWHUSUHWHU GRHV QRW GLUHFWO\ SURYLGH DQ\ PHDQV WR YLHZ JUDSKLFDO RXWSXW ZH DUH OLPLWHG WR XVLQJ LW WR H[HFXWH SXUHO\ WH[WXDO -DYD SURJUDPV DQG DSSOLFDWLRQVWKDWPDQDJHWKHLURZQJUDSKLFV,IZHZDQWWRUXQJUDSKLFDO-DYDDSSOHWVZHQHHG WRXVHWKH-DYDDSSOHWYLHZHURUD-DYDFRPSDWLEOHZHEEURZVHU7KHGLIIHUHQFHEHWZHHQD-DYD DSSOLFDWLRQDQGD-DYDDSSOHWLVWKDWDQDSSOLFDWLRQLVUHVSRQVLEOHIRUFUHDWLQJDQGPDLQWDLQLQJLWV RZQ ZLQGRZ LI LW UHTXLUHV WKH QHHG IRU JUDSKLFDO RXWSXW ZKHUHDV DQ DSSOHW UHOLHV RQ D :HE EURZVHUWRSURYLGHDZLQGRZRQZKLFKWRGLVSOD\JUDSKLFV6RWKH-DYDLQWHUSUHWHULVFDSDEOHRI H[HFXWLQJERWKWH[WXDO-DYDSURJUDPVDQGJUDSKLFDO-DYDDSSOLFDWLRQV

Appletviewer   7KH-DYDDSSOHWYLHZHULVDWRROXVHGWRUXQDSSOHWVZLWKRXWWKHQHHGIRUD:HEEURZVHU 7KH W\SLFDO PHWKRG RI H[HFXWLQJ D -DYD DSSOHW LV IURP ZLWKLQ D :HE EURZVHU WKDW KDV D :HE SDJH ORDGHG FRQWDLQLQJ WKH DSSOHW 7KLV LV WKH W\SLFDO VFHQDULR LQ ZKLFK PRVW :HE EURZVHUV FRPHLQWRFRQWDFWZLWK-DYDDSSOHWV7KHDSSOHWYLHZHULVDWRROWKDWVHUYHVDVDPLQLPDOWHVWEHG IRU -DYD DSSOHWV (YHQ WKRXJK WKH DSSOHWYLHZHU ORJLFDOO\ WDNHV WKH SODFH RI D :HE EURZVHU LW IXQFWLRQV YHU\ GLIIHUHQWO\ IURP D  :HE EURZVHU 7KH DSSOHW YLHZHU RSHUDWHV RQ +70/ GRFXPHQWVEXWDOOLWORRNVIRULVHPEHGGHGDSSOHWWDJVDQ\RWKHU+70/FRGHLQWKHGRFXPHQW LV LJQRUHG (DFK WLPH WKH DSSOHWYLHZHU HQFRXQWHUV DQ DSSOHW WDJ LQ DQ +70/ GRFXPHQW LW ODXQFKHVDVHSDUDWHDSSOHWYLHZHUZLQGRZFRQWDLQLQJWKHUHVSHFWLYHDSSOHW7KHRQO\GUDZEDFN RIWKHDSSOHWYLHZHULVWKDWLWZRQ·WVKRZKRZDQDSSOHWZLOOUXQZLWKLQWKHFRQILQHPHQWRID UHDO:HEVHWWLQJ%HFDXVHWKHDSSOHWYLHZHULJQRUHVDOO+70/FRGHVH[FHSWDSSOHWWDJVLWGRHV QRWHYHQDWWHPSWWRGLVSOD\DQ\RWKHULQIRUPDWLRQFRQWDLQHGLQWKH+70/GRFXPHQW

Java Archive(jar) $-$5ILOHLVDFRPSUHVVHGDUFKLYHILOHWKDWLVFUHDWHGXVLQJWKH-DYDDUFKLYHWRRO MDU ZKLFKLV VLPLODUWRWKH3.=,3SURJUDPGHYHORSHGE\3KLO.DW],WFRPELQHVPXOWLSOHILOHVLQWRDVLQJOH DUFKLYHILOHWKDWLVFRPSUHVVHGXVLQJWKH =/,% FRPSUHVVLRQ OLEUDU\ $OWKRXJK MDU LV D JHQHUDO SXUSRVHILOHDUFKLYHDQGFRPSUHVVLRQWRROLWVPDLQSXUSRVHLVWRFRPELQHWKHILOHVXVHGE\DQ DSSOHWLQWRDVLQJOHFRPSUHVVHGILOHIRUHIILFLHQWORDGLQJE\D-DYDHQDEOHG:HEEURZVHU $ GHVFULSWLRQ RI WKH =/,% FRPSUHVVLRQ IRUPDW LV DYDLODEOH DW WKH 85/ KWWS ZZZFGURPFRPSXELQIR]LS]OLE

Comp-U-Learn

313

Java Programming I

8VLQJMDUZLWKDSSOHWVFDQJUHDWO\LPSURYHEURZVHUSHUIRUPDQFH%HFDXVHDOORIWKHILOHVXVHGE\ DQ DSSOHW DUH FRPELQHG LQWR D VLQJOH ILOH D EURZVHU RQO\ QHHGV WR HVWDEOLVK D VLQJOH +773 FRQQHFWLRQZLWKD:HEVHUYHU7KLVUHGXFHVWKHFRPPXQLFDWLRQSURFHVVLQJRYHUKHDGRQERWK WKHEURZVHUDQGWKHVHUYHU)LOHFRPSUHVVLRQUHGXFHVWKHWLPHUHTXLUHGWRGRZQORDGDQDSSOHW E\RUPRUH7KLVEHQHILWVERWKWKHDSSOHW·VXVHUDQGSXEOLVKHU $QRWKHUIHDWXUHRI-$5ILOHVLVWKDWWKH\VXSSRUWWKHFDSDELOLW\WRVLJQDUFKLYHGILOHV7KLVDOORZV EURZVHUVWRGLIIHUHQWLDWH EHWZHHQGLVWUXVWHGDSSOHWVDQGWKRVHDSSOHWV WKDW PD\ EH WUXVWHG WR SHUIRUP  VHQVLWLYH SURFHVVLQJ LQ D VHFXUH PDQQHU EHFDXVH WKH\ DUH VLJQHG E\ D UHSXWDEOH LGHQWLW\ 7KHVHQVLWLYHSURFHVVLQJWKDWLVSHUPLWWHGRIWUXVWHGDSSOHWVLVGHWHUPLQHGE\WKHORFDO -DYDVHFXULW\SROLF\

Javah 7KH-DYDKHDGHUILOHDQGVWXEJHQHUDWRUMDYDKFUHDWHV&KHDGHUILOHVDQGFRGHVWXEVIRUZULWLQJ QDWLYHPHWKRGV7KLVLVRQHRIWKHOHVVHUNQRZQWRROVSURYLGHGLQ-'.,WFUHDWHVWZR&ILOHV IURP-DYDFODVVHV-DYDKFUHDWHVDKHDGHUILOHDQGDVWXEILOHIRUWKHQDWLYHPHWKRGVRIDFODVV 7KH KHDGHU ILOH GHFODUHV WKH IXQFWLRQV WKDW ZLOO LPSOHPHQW WKH FODVV PHWKRGV 7KH VWXE ILOH SURYLGHVWKHJOXHWKDWELQGVWKH-DYDPHWKRGLQYRFDWLRQDQGREMHFWUHIHUHQFHVWRWKH&FRGH,W LV WKH XVHU ZKR SURYLGHV DQRWKHU & ILOH FDOOHG WKH LPSOHPHQWDWLRQ ILOH ZLWK WKH IXQFWLRQV GHFODUHGLQWKHKHDGHU7KHVHWKUHH&ILOHVDOORZD-DYDFODVVWRFDOO&IXQFWLRQV,QWXUQWKH& IXQFWLRQVFDQUHIHUHQFHWKHREMHFW·VLQVWDQFHYDULDEOHV8OWLPDWHO\DOOWKHILOHVDUHFRPSLOHGLQWRD G\QDPLFDOO\ORDGHGOLEUDU\

Java Debugger (jdb) -GE LV WKH QDPH RI WKH GHEXJJHU VXSSOLHG E\ 6XQ LQ WKH -DYD 'HYHORSHU·V .LW -'.  ,W LV D FRPPDQGOLQHWRROWKDWFDQEHXVHGWRVWHSLQWRWKH-DYDFRGHDQGVWXG\WKHFRGH·VEHKDYLRUDW UXQWLPH-GEZDVGHVLJQHGWRKDYHVRPHVSHFLDOFDSDELOLWLHVQRWIRXQGLQPDQ\RWKHUODQJXDJH GHEXJJHUV7KHVHLQFOXGH ♦ An object oriented interface similar to that of the Java language ♦ Java language runtime features such as threads and monitors. ♦ Support for remote debugging 7KHGHEXJJHUZDVLPSOHPHQWHGXVLQJWKH-DYD'HEXJJHU$3,7KLV$3,ZDVSURYLGHGE\6XQLQ RUGHUWRIXOILOOWKHVHUHTXLUHPHQWVIRUDIXOOIHDWXUHG-DYDODQJXDJHGHEXJJHU$NH\IHDWXUHRI WKH'HEXJJHU$3,LVWKHFDSDELOLW\RIUHPRWHGHEXJJLQJ7KLVPHDQVWKDWDUHPRWHYLHZHUFDQ VHH LQWR D -DYD /DQJXDJH 5XQWLPH LI WKH VHFXULW\ SUHFDXWLRQV KDYH EHHQ WDNH FDUH RI &RPPXQLFDWLRQEHWZHHQWKHGHEXJJHUDQGWKHUXQWLPHLQWHUSUHWHURFFXUVXVLQJDVRFNHWEDVHG SURSULHWDU\SURWRFRO7KH6XQGRFXPHQWDWLRQVWUHVVHVWKDWMGEZDVLPSOHPHQWHGDVDSURRIRI

314

Comp-U-Learn

Appendix 2

FRQFHSW WRRO IRU WKH -DYD 'HEXJJHU $3, MGE LV VLPLODU LQ RSHUDWLRQ DQG IXQFWLRQDOLW\ WR WKH 81,;GE[VW\OHGHEXJJHU7KHGHEXJJHULVXVHGWRGHEXJDFXUUHQWO\UXQQLQJDSSOLFDWLRQ

Jarsinger 7KHMDUVLQJHUWRROLVXVHGWRVLJQDMDUILOHDQGWRYHULI\WKHVLJQDWXUH RIDVLJQHGMDUILOH,WLV LQYRNHGDVIROORZV

jarsinger [options] jarfile alias 7KH MDUVLQJHU DUJXPHQW LGHQWLILHV WKH QDPH RI WKH MDU ILOH WR EH VLJQHG RU YHULILHG 7KH DOLDV DUJXPHQW LV WKH DOLDV RI WKH NH\VWRUH HQWU\ FRQWDLQLQJ WKH SULYDWH NH\ XVHG WR JHQHUDWH WKH VLJQDWXUH7KHNH\VWRUHLVDGDWDEDVHRINH\VDQGFHUWLILFDWHVPDLQWDLQHGE\WKHNH\WRRO

Keytool The keytool is used to manage a local database of keys and certificates. It is invoked as follows NH\WRRO>FRPPDQGV@ (QWHULQJNH\WRROKHOSSURYLGHVDOLVWRINH\WRROFRPPDQGVDQGWKHLURSWLRQV7KHVHFRPPDQGV DQGRSWLRQVDUHGHVFULEHGLQWKH-'.GRFXPHQWDWLRQRIWKHNH\WRRO

Policytool 7KHSROLF\WRROLVD*8,EDVHGWRROWKDWSURYLGHVDFRQYHQLHQWZD\WRHGLWWKHVHFXULW\SROLF\RI DORFDO-'.LQVWDOODWLRQ7KLVWRROLVLQYRNHGDVIROORZV policytool

7KHSROLF\WRRORSHQVIURPWKH)LOHPHQXDQGWKHQVHOHFWVWKHSROLF\ILOHWKDWKDVWREHHGLWHG 7KH GHIDXOW SROLF\ LV MGN?OLE?VHFXULW\?MDYDSROLF\ 8VH $GG SROLF\ (QWU\ (GLW 3ROLF\ HQWU\ DQG5HPRYH3ROLF\(QWU\EXWWRQVWRHGLWWKHSROLF\DQGVHOHFW6DYHIURPWKH)LOHPHQXWRVDYH WKHXSGDWHGSROLF\

Comp-U-Learn

315

Index

Index A

C

Abstract, 43 46, 61, 62, 68, 81, 171, 188 Accessor, 61, 62 ActionListener, 195, 196, 197, 199, 200, 218, 286 Animation, 164, 167 API, 80, 81, 82, 255, 256, 258, 276 Applet Events, 193, 218 Applet Programming, 11 AppletContext, 81 Applets, 6, 11, 14, 147, 148, 150, 154, 167, 171, 218 -- 219, 288, 296 AppletStub, 81 Appletviewer, 8 ArithmeticException, 117 -- 118, 120 – 121 – 122 -- 123, 125, 131 ArrayIndexOutOfBoundsException, 117, 122, 125, 131, 273 – 274 Arrays, 32, 35, 36 ASCII, 87, 108, 214 Assignment operators, 23 AudioClip, 81 AWTException, 117

C, 4, 7 -- 9, 13, 28, 39, 40, 43, 52. 75, 98 -- 100, 102 -- 103, 105, 107, 110, 118 -128, 130 -- 131, 137, 142 -- 143, 256, 261, 268, 270 -- 271, 273 – 275 C++ , 4, 7, 13, 40, 75 , 275 Canvas, 171, 188 CardLayout, 223, 227, 237 Cells, 231 Check Boxes, 175 Classes, 42 -- 44, 46, 74, 79 -- 80, 87 -88, 108, 177, 178, 261 ClassNotFoundException, 117 Client, 280 – 281 Clipping, 156, 167 Cloneable, 73, 132 COBOL, 39 CODE, 151, 152, 275, 290, 293, 296 Colors, 159, 242, 244, 248 Commenting in Java, 26 Compile time error, 115 Connection, 262, 264 -- 265, 267, 269, 270 -- 272, 274, 275 Connection, 279, 293 – 294 Constructors, 53 -- 54, 58, 64 Container, 189 Container, 223, 239 Continue, 31 CORBA, 80 – 81

B BorderLayout, 223, 225 -- 226, 235, 239, 249 Break, 31 Browser, 151 BufferedStreams, 111 Button Events, 195, 196, 218 Button, 75 -- 76, 174 -- 175, 189, 195, 196, 197 -- 199, 218, 224, 226, 228, 230, 234 -- 235, 237 -- 240, 245, 247 -- 249, 263, 286, 290 ByteArrayInputStream, 88, 103 -- 106, 108 ByteArrayOutputStream, 88, 104

D Daemon Threads, 140 Data Abstraction, 42 – 44 Database Connectivity, 255 DatagramPacket, 280 -- 284, 286 -- 287, 297 Datagrams, 280, 282 DatagramSocket, 280 -- 287, 297—298 DataInputStream, 269, 291 – 294

Comp-U-Learn

321

Java Programming 1

DataInputStream, 88, 91 – 92 DataOutputStream, 103 DataOutputStream, 294 Date, 44, 48, 53, 64, 140 Decision Making, 27 Default Keys, 215 Default, 58, 59, 215 Dictionary, 82 Directories, 98, 111 DrawLine, 156 DrawRect, 156 DrawRoundRect, 156 DriverPropertyInfo Class, 260 DSN, 263, 268 Duplication, 285

G

E

H

Encapsulation, 42, 44 Encapsulation, 6 Error handling, 115 – 116 Escape Sequence, 21 Event, 186 -- 187, 203 -- 216, 218 -- 219, 237, 241, 243 – 244 -- 245, 247 – 290 Exception Handling, 115 –116, 186 Exceptions, 90, 116 -- 118, 123, 131, 143

Hashtable, 82 HTML pages, 147 HTTP, 4, 15, 284

GetConnection, 262 GetProperty, 89 GIF, 6, 160, 165 Graphics, 12, 70, 140, 149, 153, 154, 155, 156, 157, 158, 159, 161, 162, 165, 166, 167, 205, 206, 207, 209, 211, 212, 213, 216, 217, 240, 245, 249 Grid, 227, 228, 229, 250 GridBagLayout, 223, 229, 230, 231, 233 GridLayout, 223, 227, 228, 248, 289, 292 GUI, 4, 81, 82, 147, 171, 195

F File Dialog, 247 FileInputStream, 88, 90, 100 --103, 108, 281 – 282 FileInputStreamFilenameFilter, 99 –100 FileOutputStream, 88, 100 -- 103, 111 Files and Directories, 95 Final, 46, 50, 91 Finalize, 54 Finally, 4, 12, 128, 149, 164, 166 -- 177, 209, 210, 231, 243, 271 FlowLayout, 223 -- 224, 236, 239 -- 240, 286 Fonts, 158 Frames, 238 – 239 FTP, 4, 15, 291, 294

322

I Identifiers, 21-- 22, 36 IDS software, 262 IllegalThreadStateException, 131, 138 Implements, 88 InetAddress, 281 -- 283, 286 Inheritance, 6, 42, 47, 55 -- 56, 63 Inner classes, 74 Inner, 74 InputStreamReader, 103, 108, 109, 110 Insets, 186 -- 187, 235 -- 236, 249, 251, 292 Interfaces, 6, 67, 68, 83, 100 Internet Explorer, 8, 11, 132, 133, 151, 204 IOException, 90 -- 94, 101 -- 103, 106, 110, 117, 119, 120, 291, 292, 293 IOStream, 108 ItemListener, 202, 218

Comp-U-Learn

Index

NullPointerException, 89, 98, 117, 126, 132, 144

J Java tools, 7, 14 Java.applet, 80 Java.awt, 80 Java.io, 80 Java.lang, 80, 124 Java.net, 81 Java.security, 81 JavaBeans, 81 Javadoc, 8, 15 JavaScript, 6 JDBC, 255 -- 263, 266, 268, 276 JDK, 7, 80, 82 JFC, 80

O Oak, 3 Objects, 246, 247 Objects, 41 -- 45, 62 ODBC, 255 -- 256, 258, 262 -- 264, 268, 275 – 276 OOP, 6, 13, 39 -- 40, 42, 57, 63 Operators in Java, 22 Oracle, 263, 268 Overloading, 50, 53, 57, 58

P

L Label, 173 --174, 180, 182, 186, 233 – 234 Layout manager, 172 List, 15, 36, 75, 144, 167, 183 -- 184, 189, 219, 276 Literals, 21

M Member variables, 50 Memory allocation, 33 Menu item, 251 Menus, 241, 250 Message Communication, 62 Modifiers, 46 Motif, 82 Multithreading, 133, 143 Mutator, 61, 62

N Native JDBC Driver, 258 Netscape, 11, 151, 204 Network, 298 New, 41, 136, 137, 138 Not Runnable, 139

Package, 46, 76 – 77 Panel, 171, 189, 227, 236 -- 237, 251, 263 Parameter, 154 – 155 Pascal, 13 Polymorphism, 6, 42, 54, 57, 58 Port, 284 Prepared Statement, 265 Print, 87, 217 PrintStream, 87 -- 88, 110 – 111 Private protected, 80 Private, 49, 64, 79 – 80 Protected, 49, 79 -- 80, 83 Protocol, 258Protocol, 279, 284 Public, 10, 49, 79 -- 80, 296

R Radio Button, 176 Random Access File, 107 Reader, 108, 109, 111 References, 54, 71, 80 Return, 184, 296 RMI, 80 Runnable, 134, 138, 140 -- 141, 143, 165, 292

S Comp-U-Learn

323

Java Programming 1

Scope, 25 Server, 262 Server, 280, 283 Single Tier, 256 Sliders, 185 Socket, 279 -- 280, 284 -- 285, 288, 294, 297 – 298 SQL, 255, 262, 263, 265, 266 – 267 Stack, 82, 116, 117 Static, 10, 49, 61 Stream Tokenizer, 88, 107 Streams, 93, 100, 102, 105 -- 106, 110 – 111 Sub Class, 47 Sun Microsystems, 3, 4 Super Class, 47 Super, 47, 60 Swing, 80, 82, 148 Switch, 31

Transaction Processing, 266 Transient, 50 Try, 144 Two Tier, 257

U UDP, 279 UI Components, 172 URL, 96, 117, 161 -- 162, 166, 259, 260, 262, 264, 288 -- 289, 290 -- 294, 297

B Variables, 19, 20, 25, 50 Vector, 82, 258 Void, 10 Volatile, 51

W

T TextField, 179 -- 182, 188 -- 189, 195 -199, 201 -- 202, 225, 233 -- 234, 249, 286 Thread priority, 138 Thread, 132 -- 144, 165, 167, 287, 292 Three Tier, 257 Throw, 124 – 125 Throwable, 116 -- 117, 121, 124 -- 125, 129

Writer, 108 – 109 WWW, 3

Tiering, 256 Traditional Programming, 39

324

Comp-U-Learn


Related Documents

Java Book
November 2019 10
Java Book
November 2019 6
Java Turkish Book
December 2019 1
Java Basic Book 2
October 2019 24
Preview Java J2ee Book
November 2019 10
Address Book In Java
June 2020 8