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
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
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
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
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.
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!”); } }
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
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); } }
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.
: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
,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
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
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
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
//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.
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); } }
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!"); } }
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
$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.
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.
:KDWDUHWKHWZRGDWDW\SHVDYDLODEOH" :KDWLVDOLWHUDOLQ-DYD" ([SODLQORFDOYDULDEOHV :KDWLVWKHXVHRI RSHUDWRU" /LVWRXWWKHPHWKRGVDYDLODEOHLQ6WULQJFODVV IV. Define the Following
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
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
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
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
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
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
7KHNH\ZRUGSXEOLFPHDQVWKDWDQ\FODVVLQDQ\SDFNDJHFDQ DFFHVVWKHYDULDEOHVRUPHWKRGV 0HWKRGVGHFODUHGDVSXEOLFDUHDFFHVVLEOHWRDOO Example 3:3 public void shape() { }
Protected
$Q\FODVVLQWKHVDPHSDFNDJHDVWKHFODVVLQZKLFKLWLVGHFODUHGFDQDFFHVVSURWHFWHGYDULDEOHV RUPHWKRGV)RUH[DPSOHLQSDFNDJH3DFN class A { protected int min; }
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
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
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();
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);
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
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); }
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.
7KHWUDGLWLRQDOPRGHOGRHVQRWVLPXODWHUHDOZRUOGSUREOHPV -DYDVXSSRUWVPXOWLSOHLQKHULWDQFH &RQVWUXFWRUVDUHLQYRNHGDWWKHHQGRIWKHFODVV 7KHPHWKRGWR6WULQJ LVDYDLODEOHLQWKH'DWHFODVV 3ULYDWHDFFHVVVSHFLILHGGDWDDQGPHWKRGVFDQEHDFFHVVHGDQ\ZKHUHLQWKHSDFNDJH III. One line Answers
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 }
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[WHQGDQRWKHULQWHUIDFHOLNHWZRH[WHQGVRQHDQGKDVWZRPHWKRGV[[DQG\\ EXW DQ LQWHUIDFH FDQQRW H[WHQG D FODVV DQG D FODVV FDQQRW H[WHQG DQ LQWHUIDFH D FODVV FDQ LPSOHPHQWDQLQWHUIDFH $FODVVFDQMXVWLPSOHPHQWDOOPHWKRGVRIDQLQWHUIDFHFOLPSOHPHQWV WZR RULWFDQKDYHLWVRZQPHWKRGVDOVRLQDGGLWLRQWRWKHPHWKRGVRIWKHLQWHUIDFHFOKDVLWV 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(); } }
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.
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(); } ................. }
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.
+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
♦ 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(); } }
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
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
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
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
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
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()
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\UHDGWKHDFWXDOE\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
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
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\,QSXW6WUHDPE\WHDUUD\>@ %\WH$UUD\,QSXW6WUHDPE\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)
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")));
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.
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
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
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
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>
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 }
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>
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 "); } }
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>
+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
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>
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
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
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)
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
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.
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>