You are on page 1of 77

Al-Quds University

Faculty of Science and Technology Computer Science Department

Java La !anual
"#ersion $%

"For CS&'$( )rogramming Fundamentals%

)repared y( *asser Jaffal

Java La !anual y *asser Jaffal "$''+%

&

Table of Contents
Session &,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.T!L and /e dis0 "1evision%,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&,& Creating /e )ages using .T!L,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&,$ Adding Content to /e )age,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2 Session $,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5 6ntroduction to Java,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5 $,& )rogramming Languages,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5 $,$ Java )rogramming Language,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5 $,7 Setting Up *our !achine for Java Development,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5 $,- /riting8 Compiling and 1unning *our First Java Application,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,9 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&& La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&& Session 7,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&$ /or0ing :ith ;et<eans 6D3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&$ 7,& 6D3 Soft:are,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&$ 7,$ ;et<eans 6D3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&$ 7,7 De ugging *our )rogram,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&7,- 3rror Types in Java,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&5 La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&5 Session -,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&= #aria les8 Data Types and >perations,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&= -,& #aria les and Data Types,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&= -,$ >perations on #aria les,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,&9 -,7 Conversion et:een Data Types,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$$ -,- Literal #alues and 34pressions,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$7 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$Session 2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$2 /or0ing :ith Java Applets,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$2 2,& 6dea of Applets,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$2 2,$ /riting and Compiling Applets,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$2 2,7 3m edding Applets into .T!L,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$5 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$= Session 5,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$+ Conditional Statements and User 6nput,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$+ 5,& if and if-else Statements,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$+ 5,$ 1eading User 6nput,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$9 5,7 Decision !a0ing <ased on User 6nput,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,7' 5,- s:itch-case Statement,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,7& 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,7La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,7Session =,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,75 Decision-Tree Applet,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,75 =,& Adding User Controls to Applets,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,75 =,$ .andling 3vents of User Controls,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,7+ =,7 Applets :ith ;et<eans,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,79 Java La !anual y *asser Jaffal "$''+% $

34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-' La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-' Session +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-& Loops and #aria le scope,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-& +,& /hat Are Loops?,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-& +,$ :hile and do-:hile Loops,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-& +,7 for Loop,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-7 +,- #aria le Scope,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-2 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-5 La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-= Session 9,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-+ Arrays and Strings,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-+ 9,& /hat Are Arrays?,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-+ 9,$ Using Arrays in Java,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-+ 9,7 !ultidimensional Arrays "Arrays of Arrays%,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2& 9,- String as Arrays,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,27 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,27 La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2Session &',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,22 Applications on Arrays "Data ases%,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,22 &',& /hat Are Data ases?,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,22 &',$ 6mplementing Data ases using Arrays,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,22 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,25 Session &&,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2= Applets and @raphics,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2= &&,& paint"% !ethod,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2= 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,29 Session &$,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5' !ethods,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5' &$,& /hat Are !ethods,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5' &$,$ /riting and Calling !ethods,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5& &$,7 )assing y #alue and )assing y 1eference,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,57 &$,- 1ecursion,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,57 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5Session &7,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,52 > Aect->riented )rogramming( Classes and !em ers,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,52 &7,& /hat is > Aect->riented )rogramming?,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,52 &7,$ /riting Classes in Java,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,52 &7,7 Different )roperties of Class !em ers,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,5= &7,- !ethods and Constructors >verloading,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,59 34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=' La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=& Session &-,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=7 34ceptions and 3rror .andling,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=7 &-,& 34ception-Thro:ing !ethods,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=7 &-,$ try-catch 34ception .andling,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=&-,7 /riting Custom 34ceptions,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=5 La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=5

Java La !anual y *asser Jaffal "$''+%

Session 1 HTML and Webdisk (Revision)


Objectives:

Creating :e pages :ith rich contents, Uploading :e pages to /e dis0, Accessing :e pages from the 6nternet, Adding content to an uploaded :e page,

1.1 Creating Web Pages using HTML


As you have learned in CS&'&8 :e use .T!L language to :rite :e pages, )ages :ritten :ith .T!L could contain te4t8 ta les8 images and other media, /hat you are as0ed to do today is to create a :e page and uploading it to your /e dis08 this tas0 is achieved y follo:ing the instructions elo:, First of all8 you have to create you personal :e folder "if you havenBt do so yet%, To create the :e folder8 follo: the follo:ing steps( &, $, 7, -, 1un Internet Explorer. @o to :e page( http(CCmail,alDuds,edu 3nter your student profile login information to access your mail o4, From the tool ar8 clic0 Webdisk icon,

2, Under operation field8 :rite public_html and clic0 on MkDir utton8 y doing this8 you are creating a folder named public_html8 this is the folder in :hich you :ill put your :e pages, 5, Clic0 on public_html to open it, 6t is no: the current :or0ing directory, =, 6nside public_html8 create another folder called lab1, After preparing your /e dis08 you are ready to create a :e page and upload it8 to create a simple .T!L page8 follo: the follo:ing steps( &, Start the notepad from Start --E All Programs --E Accessories --E Notepad "or simply type notepad in the run dialog Start --E Run% $, 3nter the follo:ing te4t( <html> <body> <h1> This is a Major Heading </h1> <ul> <li> List item one <li> List item two </ul> </body> </html> 7, Save your file as inde4,html -, <ac0 to /e dis08 under upload field8 ro:se for your file "inde4,html% and clic0 on Upload to upload your file to the server8 ma0e sure to upload it inside la & folder, 2, Using ro:ser8 confirm page at http(CCmail,alDuds,eduCFs999Cla & ":here s999 should e replaced y your student profile login id%, Java La !anual y *asser Jaffal "$''+% -

1.2 Adding Content to Web Page


To add an image to your :e page8 use the follo:ing code( <img src= image_name ></img> Also8 you can add a ta le to your page y using the follo:ing code "Suppose :e are creating a $ y $ ta ls% y adding the follo:ing code, <table border=1> <tr> <td> !ow 1 "olumn <td> !ow 1 "olumn </td> <tr> <td> !ow # "olumn <td> !ow # "olumn </tr> </table>

1 </td> # </td> 1 </td> # </td>

The ta le that resulted from the a ove code is sho:n in figure &,& elo:,

Figure &,&( .T!L Ta le To lin0 t:o pages together8 :e user the .yperlin08 to create a .yperlin0 to another .T!L page8 use the follo:ing synta4( <a hre$= target_page > Display Text </a>

Exercises
&, Create a page named inde4,html and upload it to Gla &H folder in your pu licIhtml directory, $, !odify inde4,html y adding a, A ta le8 , A .yperlin0 to universityBs homepage "http(CC:::,alDuds,edu%8 and c, At least one image,

Java La !anual y *asser Jaffal "$''+%

Session 2 Introduction to Java


Objectives: 6ntroduce programming languages, 6ntroduce Java programming language, Sho: ho: to set up your system environment for Java development, /rite8 compile and run your first Java application J.ello /orldJ,

2.1 Programming Languages


<y programming language8 :e mean a set of voca ulary8 grammar and li raries that construct a language :e can use to :rite computer programs, A programming language consists of the follo:ing( #oca ulary( set of meaningful keywords that have specific meaning in the programming language "also called reserved words%, Synta4 "grammar%( set of rules that constraint the :ay in :hich programs are :ritten, A program that does not follo: these rules has one or more syntax errors, Soft:are Development Kit "SDK% that contains the follo:ing( Li raries( also 0no:n as Application )rogramming 6nterface "A)6%8 these files are previously :ritten classes and methods that contain some common functionality, Compiler( the program that translates files :ritten in Java language "human language% into inary files "machine language% in order for the computer to e a le to e4ecute them, 6nterpreter( some programming languages does not compile the source code file into directly e4ecuta le form "native code%8 ut they instead compile it into partially compiled file that could e e4ecuted y a program called interpreter,

2.2 Java Programming Language


Java programming language is an interpreted programming language8 that is8 :hen the source code is compiled into inary file8 it needs an interpreter called Java #irtual !achine "J#!% to run it, Java compiler is called javac.exe8 and interpreter is called java.exe, Figure $,& sho:s a Java technology overvie:,

Figure $,&( Java technology

2.3 etting !" #our Mac$ine %or Java &eve'o"ment


To e a le to :rite8 compile and e4ecute Java applications8 you need a set of tools called Java Soft:are Development Kit "JSDK%. This SDK could e o tained from Java official site at Java La !anual y *asser Jaffal "$''+% 5

http(CCAava,sun,com, After do:nloading the installation file "a out 5' !<% you are ready to start the installation process, Follo: the follo:ing procedure to prepare your machine, Step &( Dou le clic0 on jdk-1_5_0_06-windows-i586-p.exe icon8 the setup :iLard appears as in figure $,$,

Figure &,$( First step of JDK setup :iLard Select I accept the terms in the license agreement and clic0 on Next, Custom setup dialog appears as in figure $,7,

Figure $,7( Setup options 6t is advisa le that you change the installation path y clic0ing on Change utton and selecting the path "C:\jdk" as installation directory, After you have done changing the path8 clic0 on Next to start the installation and :ait until its done, /hen installation is complete8 clic0 on Finish to terminate installation :iLard, Java La !anual y *asser Jaffal "$''+% =

Step $( *ou need no: to define some environment varia les to e a le to use the tools youBve Aust installed, To define an environment varia le8 right-clic0 on y Computer icon on the des0top or start menu8 then select Properties from the pop-up menu, The System Properties dialog appears8 from the top of the dialog o4 select Advanced ta as sho:n in figure $,-, From Advanced ta 8 clic0 on !nvironment "aria#les utton8 3nvironment #aria les dialog appears as sho:n in figure $,2,

$,-( /indo:s advanced settings To add ne: environment varia le8 clic0 on New utton in $ser "aria#les field8 note that you may not modify system varia les unless you have administrator privileges, >nce you clic0 on New utton8 varia le addition dialog appears as in figure $,5, 6n "aria#le name field enter the name of your varia le8 in "aria#le value field enter the value of the varia le then clic0 on %&. *ou need to add t:o varia les to use :ith JDSK( PATH( points to bin directory in JSDK home directory "e, g, c:\jdk\bin% CLASSPATH( points to the folder in :hich you :ill create you Java programs "e, g, c:\ oc!"en#s$%nd$Se##in&s\S#!den#\ esk#op\j%'%%, *our computer is ready no: to e used for Java development,

Java La !anual y *asser Jaffal "$''+%

Figure $,2( 3nvironment #aria les

Figure $,5( Adding ne: environment varia le dialog o4

2.( Writing) Com"i'ing and *unning #our +irst Java A""'ication


To :rite a Java program8 open the command prompt y selecting run from start menu and entering the command c"d in the dialog o48 the command prompt console appears8 sho: in figure $,=, Change to the directory you have selected as Java directory "for e4ample c:\Documents and Settings\Student\Desktop\java% y using cd command,

Figure $,=( Command prompt To :rite a ne: Java program using the notepad8 enter the command no#ep%d$filename, For instance8 :e :ill :rite a class named HelloWorld8 so :e :ill use the command no#ep%d$ He((o)o*(d.j%'% "Figure $,+%, ;ote that :e use a .j%'% e4tension for all Java source files8 and :e al:ays use upper case characters in the eginning of a class name, After starting the notepad8 it :ill Java La !anual y *asser Jaffal "$''+% 9

as0 you :hether you :ish to create a ne: file :ith the name specified8 confirm file creation, 6t is important to 0eep in mind that file name and class name must e the same8 other:ise the compiler :ill generate an error message and the file :ill not compile,

Figure $,+( notepad command :ith parameters 6n the notepad8 :rite the follo:ing code "al:ays 0eep in mind that Java is case-sensitive language8 for e4ample if you typed Class instead of class the compiler :ill report a synta4 error% //HelloWorld.java /* T is is m! "irst java program. */ class HelloWorld# pu$lic static void main%String&' args(# S!stem.out.println%)Hello World*)(+ S!stem.out.println%)Ho, r u -da!.)(+ ///end o" main met od ///end o" class /hen you are done :ith code :riting8 save the file and e4it notepad, *our source code file is no: ready for compilation8 to compile a Java source code file8 use the command j%'%c$filename, 6n our e4ample8 j%'%c$He((o)o*(d.j%'%, 6f everything is alright8 the compiler :ill terminate :ithout any messages and go ac0 to command prompt as sho:n in figure $,9, After compilation8 if you run di* command8 you :ill notice that the compiler generated a ne: file called He((o)o*(d.c(%ss8 this is the inary file J#! :ill e4ecute, To run you application8 use the command j%'%$ClassName 8 for our program8 :e :ill use j%'%$He((o)o*(d8 if everything is alright8 you shall see the program output on the screen, ;otice that some lines in the program egin :ith CC8 these are called comments8 compiler does not read comments8 so :hatever your :rite in them it :ill not affect the functionality of your program8 the notations CM and MC declare the eginning and ending of a loc0 of comments8 so :e call them multi'line comments,

Figure $,9( successful compilation

Java La !anual y *asser Jaffal "$''+%

&'

Exercises
&, Change the .ello/orld,Aava program so that it displays Hola 0undo* instead of Hello World* $, Try printing the follo:ing strings8 :hat do they do? 1. )Hello \t World) -. )Hello \n World) 7, Try to use print method instead of println. -, Consider the follo:ing 2seless class, Compile and run it8 :hat does it do? pu$lic class 2seless# pu$lic static void main%String&' args(# S!stem.out.println%java.util.3ocale.getDe"ault%((+ //

Lab Extras
<atch files are common in e4ecuting a series of shell commands8 for e4ample8 you can :rite a atch file to create and delete folder instantly8 y :riting the appropriate commands in the notepad and saving the file :ith , at e4tension, The file :ill loo0 li0e the follo:ing( 0D 0!4older 5D 0!4older ;ote that :e put each command in separate line, *ou can create a Java program that runs every:here y putting it together :ith a atch file that does the follo:ing steps( &, Adds the current folder to CLASS)AT. y using the command S6T C37SS87TH9. $, Compiles the .java file, 7, 34ecutes the program, Try to :rite a atch file that holds your name and runs a Java program that types your name on the command line, Add 872S6 command at the end of the atch file in order to freeLe the screen after program e4ecution to e a le to see the results,

Java La !anual y *asser Jaffal "$''+%

&&

Session Workin! "it# $et%eans I&'


Objectives: Sho:ing ho: 6D3 soft:are facilitates the process of programming, 6ntroduce the asics of ;et<eans 6D3, 6ntroducing de ugging and its importance, 6ntroducing error types in Java and understanding error messages Discriminating et:een run-time "semantic% errors and compile-time "synta4% errors,

3.1 ,&E o%t-are


6D3 stands for 6ntegrated Development 3nvironment8 6D3 is a soft:are that helps us to :rite8 compile8 run and de ug programs, 6D3 programs vary and each one of them usually targeted to certain programming language8 the follo:ing ta le sho:s :ell-0no:n 6D3 programs( )rogramming Languages Java

6D3 ;et<eans Forte for Java <orland J<uilder !icrosoft #isual Studio <orland CNN !acromedia Dream:eaver !icrosoft #isual Studio ,;3T Sharp Develop

CCCNN ).)CJS)CAS) AS),;3T

/e can notice from ta le a ove that :e have various rands of 6D3s8 since :e are interested in Java programming language in this course8 :e :ill focus on its 6D3s, ;et<eans is the est offered 6D3 for us as Java learners8 ecause it is free compared to J<uilder8 more advanced and sta le compared to Forte, So lets start having a loo0 at ;et<eans,

3.2 .et/eans ,&E


Figure 7,& sho:s the main screen of ;et<eans 6D3 "version 2,'%, *ou can do:nload ;et<eans from http(CCAava,sun,com8 >nce you have JDK &,2 installed8 ;et<eans installation is a straight-for:ard process, To use ;et<eans for :riting and running your Java programs8 Follo: these steps( &, Create a ne: proAect y going to File > New roject8 or y clic0ing on New roject b!tton on the tool arO all programs :ritten using ;et<eans must e included in proAects to e a le to e compiled and run, )roAect creation is a simple process consists of t:o steps, First step is defining project cate"or# and t#pe, 6n our case8 :e leave the default settings8 that is8 $eneral category and %ava &pplication type, Second step is specifying project na'e and 'ain class, Java La !anual y *asser Jaffal "$''+% &$

Figure 7,&( ;et<eans 6D3 main screen $, After creating a proAect8 you are ready to start coding8 on the project explorer you :ill see a tree that has the proAect name you specified as root, )roAect is split into four folders( (o!rce packa"es8 )est packa"es8 *ibraries and )est libraries, (o!rce packa"es is the folder containing the source code files ",Aava files% and hence it is the folder :e are interested in, Source code is usually split into pac0ages8 so :e can group classes of related functionality together, >nce you create a proAect8 a default pac0age that holds proAect name is created, 7, 6n the code editor8 you :ill see the created 0ain class8 :ith its main method already coded8 so you need Aust to start programming, -, 6n the main method8 try to :rite some statements youBve learned from session &8 after you are done8 you may compile and run the program y selecting +!n > +!n 'ain project8 pressing F5 0ey on the 0ey oard8 or clic0ing +!n b!tton on the tool ar 2, The o!tp!t window appears at the ottom of the 6D3 and sho:s the outputs of compilation and running processes, Java La !anual y *asser Jaffal "$''+% &7

3.3 &ebugging #our Program


The importance of de ugging arises from the a ility to trace the code statement y statement and monitor values of varia les at every moment, ;et<eans allo:s you to de ug your program and trace any run time errors that may e4ist, De ugging in ;et<eans 6D3 means that you define one or more #reak points in your code8 rea0 point is a sign you may put on any line of your program to have the de ugger stop at it8 :hen the e4ecution of the program reaches a rea0 point8 it hangs allo:ing you to revie: the values of varia les at that moment, To add a rea0 point8 clic0 on the left of the line you :ant to insert the rea0 point in, Figure 7,$ sho:s a rea0 point added in some lines,

Figure 7,$( <rea0 points To sho: ho: de ugging :or0s8 ma0e a small test y follo:ing the procedure elo:( &, /rite the HelloWorld program from session &, $, Add a rea0 point in the second line "S!stem.out.println%)Ho, r u -da!.)(+%, 7, De ug the program y pressing F2 0ey on the 0ey oard or y clic0ing on Deb!" b!tton on the tool ar, -, > serve the output of the program8 :hat do you notice? 2, ;otice that :hen de ugger reaches a rea0 point8 it turns to green8 this means that this is the ne4t statement :ill e e4ecuted8 as :e put a rea0 point on the second line8 the statement is not e4ecuted until :e select to continue8 this can e done y pressing Ctrl NF2 or y clic0ing on Contin!e b!tton on the tool ar, 5, To stop de ugging8 press SiftNF2 on the 0ey oard8 or clic0 on (top b!tton on the tool ar,

3.( Error T0"es in Java

6n Java "and other programming languages% there are t:o maAor types of errors( Compile-Time errors "Synta4 errors%, &-

Java La !anual y *asser Jaffal "$''+%

1un-Time errors8 these errors fall into t:o categories( e4ceptions and semantic errors, Compile time errors are those the compiler detects :hile translating your program from Java language to machine language8 the most common reason for these errors is there is something in your code does not follo: Java synta4 "thatBs :hy :e call them synta4 errors%, The follo:ing e4amples sho: some of these errors(

1. -. :. ;. <. =.

S!stem.out.println%)Hello,)( s!stem.out.println%)Hello)(+ S!stem.out.println%)Hello(+ class Hello World# Class HelloWorld# pu$lic Static void main%string&' args(#

>K8 letBs start :ith statement &8 :hat is :rong :ith it? Clearly .ello donBt have J:J at the end of itP .o:ever8 this is not the error :e are loo0ing for8 :e are loo0ing for violation of Java language rules not 3nglish language rules, As :e 0no:8 each statement in Java should e terminated :ith semicolon J+J :hich is a sent in our case, The message the compiler :ill generate in this case is J>+> expectedJ8 error message also includes the line in :hich error e4ists as sho:n in figure 7,7,

Figure 7,7( Compile-Time error message, 6n statement $8 you can notice that s!stem is :ritten in lo:er case8 as :eBve learned efore8 Java is case sensitive8 and as S!stem is a class in Java8 it starts :ith upper case letter, The message you :ill see in this case is JCannot "ind s!m$olJ, This message means the 0ey:ord or mem er name you are calling is not recogniLed as valid one, The most common reason for this error is a spelling mista0e, 6n statement 7 8 the error message is Junclosed string literalJ8 ecause the opening dou le Duotation ")% does not have a matching closing one, 6n statement -8 the error is that the given class name is not valid8 as class name cannot have spaces according to naming conventions in Java "as :e shall see in ne4t session%, The error message in this case is J>#> expectedJ8 the compiler assumes that class name finishes :hen it finds space8 after the space it is e4pecting the opening rac0et J#J, 6n statement 28 the message generated is Jclass or inter"ace expectedJ8 it is clear that class 0ey:ord must start :ith lo:er case letter as all 0ey:ords in Java do so, 6n statement 58 the message generated is J?identi"ier@ expectedJ8 ecause Static is not a valid 0ey:ord, ;otice that in this statements :e have another error :hich is Jcannot "ind s!m$olJ ecause string is :ritten mista0enly in lo:er case8 ut it :ill not e detected until first error is fi4ed ecause it appears first, 1un-Time errors appear :hen program run8 the compiler cannot detect them ecause there are no errors or rules violations, First category of run-time errors is exceptions8 e4ception is a non e4pected error happens :hile e4ecuting a code8 an e4ample of e4ceptions is Java La !anual y *asser Jaffal "$''+% &2

7rit metic6xception :hich occurs :hen you try to divide y Lero, The second category are semantic errors8 those are not actual errors detected y compiler8 nor e4ceptions occur at runtime8 ut they are une4pected results or outputs of your program8 for e4ample8 if your program is supposed to calculate the sum of three num ers8 and :e give it &8 $ and 7 as inputs8 its output should e 58 other:ise :e have a semantic error, ;et<eans can detect synta4 errors :hile you type your program8 so you can find them efore compiling you program, The statement containing an error is underlined y red line8 and you can see the error message y positioning the mouse pointer over the line as sho:n in figure 7,-, /e :ill have a closer loo0 at run-time errors and ho: to deal :ith them in the coming sessions,

Figure 7,-( 3rror detection in ;et<eans

Exercises
&, Create a proAect using ;et<eans called !yFirst)roAect8 and type a program to print your name and student 6D each in separate line using only one println statement, $, /hat is the error message e4pected from each of the follo:ing statements? "Also sho: if there is more than one error8 and mention :hich one is detected first% 1. S!stem.out.println%Hello World*(+ -. S!stem.out.pint%)Ho, are !ou.)(+ :. pu$lic static void main%String&' args(+# ;. class 0! Class# <. pu$lic static void main%String%( args(# =. S!stem.out.8rint ln%)Hi man*)(+ A. S!stem.out.print%>W at>s up>(+ B. S!stem.out.println%)C ,onder , ere is t e error.\m)(+

Lab Extras
*ou can add a ne: class to your default pac0age and ma0e it the default class to e run instead of 0ain class, To do this8 right-clic0 pac0age in the project explorer8 open &dd menu and select %ava ,lass from the list, 3nter ne: class name and clic0 O- to see your ne:ly added class, ;ote that the !ain class is still open and you can navigate et:een t:o class using ta s a ove so!rce editor, To ma0e your ne: class the default one "that is8 it :ill run :hen you run the proAect%8 rightclic0 the proAect icon "Java cup% in the project explorer and select roperties from the menu, This :ill open up roject roperties dialog, From the tree on the left8 select +!n category8 and type your class name in place of !ain in Main ,lass te4t field, <e :are not to delete pac0age name mista0enly, ;o: type a main method in your ne: class and put some code in it8 run the proAect and you :ill see the result, *ou may also run a non-default class y right-clic0ing it in the proAect e4plorer and selecting run or using Shift N F5 0eys :hile opening its code in the editor, Java La !anual y *asser Jaffal "$''+% &5

Session ( )ariables* &ata T+,es and -,erations


Objectives: 6dentifying varia les and data types in Java, Discriminating et:een primitive data types and classes "user-defined data types%, Applying operations to varia les, Converting et:een data types, Understanding literal values and e4pressions,

(.1 1ariab'es and &ata T0"es


#aria les are reserved areas in computer memory8 holding uniDue name and e4pecting some data format to store called data type, Data types in Java fall into t:o categories( primitive data types and user-defined data types "classes%, )rimitive data types are Java uilt-in data types representing most common data types li0e num ers and characters, )rimitive data types are declared using special 0ey:ords, Ta le -,& sho:s primitive data types in Java,

Ta le -,&( )rimitive data types in Java To declare a varia le8 use a statement :ith the follo:ing format( datat!pe varia$leDame+ Data type is one of primitive data types sho:n in ta le -,&8 varia le name is a valid Java Java La !anual y *asser Jaffal "$''+% &=

varia le name8 the name is valid if it( 6s not a reserved :ord, 6s not the name of a previously defined varia le8 even of different type "uniDue%, Starts :ith a letter "B7B to BEB or BaB to BFB%8 a dollar sign BQB or an underscore BGB, Contains only letters8 dollar signs BQB8 underscores BIB and num ers, .as no spaces, 6n addition to previous conditions8 :e have some optional conventions ut they are highly recommended to follo: them in order to stay up :ith the glo al standards of Java, >ne of these conventions is to start class name "and each fragment in the name if it has more than one% :ith an upper-case letter li0e ClassDame and 0!4irstHavaClass, /e :ill e tal0ing a out conventions as they appear, .ere are some e4amples of declaring data types( int anCnt+ dou$le d+ "loat average+ $oolean done+ long x1I x-I x:+ As you can see8 the first part is a primitive data type from ta le -,&8 and the second type is a valid name, *ou can notice from the last statement that :e can define several varia les of the same type y using commas BIB et:een names on the follo:ing format( datat!pe varG1I varG-I ...I varGn+ A nota le naming conventions in Java is the one :eBve used in the first statement8 a varia le name should start :ith a small letter8 and each follo:ing fragment :ith a capital letter li0e varia$leDame and averageJ"0arks, So :hats ne4t? /e have to assign some values in the varia les :e have Aust declared, #alue and varia le must e of the same type8 for e4ample8 you cannot store A.:; in a varia le of type int "unless you convert%, Ta le -,$ sho:s e4amples of values and their appropriate data types,

Ta le -,$( 34amples of values and data types Java La !anual y *asser Jaffal "$''+% &+

As you can see8 numerical values :ith decimal point are treated as dou$le y default8 if you :ant to assign them to a "loat varia le8 you have to explicitly define it as "loat using 4 after the value, The value $5,==e7 is eDual to $5,== M &'7, To assign a value to a declared varia le8 :e use assignment operation denoted y eDuality sign BRB in the follo:ing format varia$le 9 value+ for e4ample8 to assign a value 1K to some integer x int x+ x 9 1K+ Assignment can e done in the same statement in :hich :e declare the varia le "loat average 9 B1.<"+ $oolean $ 9 "alse+ S!stem.out.println%average(+//prints )B1.<) S!stem.out.println%$(+//prints )"alse)

(.2 2"erations on 1ariab'es


As :e have seen8 most primitive data types are numerical8 so :e can perform inary operations on them "addition8 su traction8 multiplication and division%8 those arithmetic operations are called #inary operations ecause they are used :ith e4actly t:o operands, Ta le -,7 sho:s arithmetic operators, >peration Assignment Addition Su traction !ultiplication Division >perator Usage R N M C var& R var$ var& N var$ var& S var$ var& M var$ var& C var$

!odulus "division remainder% T var& T var Ta le -,7( Arithmetic operations /e have seen assignment efore8 and :e 0no: that is stores the value of right operand on the varia le on the left operand, Addition8 su traction8 multiplication and division operations generate expressions8 an e4pression is a series of calculations that produces a single value, .ere are some e4amples of e4pression( int a 9 c 9 d 9 aI $I cI dI e 9 :+ //varia$les de"inition $ 9 <+ //multiple assignment =+ c L a+//d 9 1 &9

Java La !anual y *asser Jaffal "$''+%

e 9 e M %a M $ * c N d(+//expression evaluation %e 9 :A( S!stem.out.println%)T e value o" e is ) M e(+ Comments on the previous code( 6t is valid to define multiple varia les in the same statements and assign values to them "statement &%, *ou can assign single value to multiple varia les in the same statement "statement $%, /e can use rac0ets B"B and B%B to specify :hich e4pressions must e evaluated first "precedence overriding%, <y default8 multiplication has the highest precedence8 follo:ed y division then addition and su traction "in statement 28 $ * c is calculated first%, !od operator calculates the remainder :hen dividing first operator on the second, /e can concatenate a string :ith an integer y using JNJ operator "last statement%, /e have some shortcuts :ith inary operations8 for e4ample8 e4pression a 9 a M $8 could e :ritten in the form a M9 $8 this :ay is valid for other operations as ta le -,- illustrates, 34pression a 9 a M $ a 9 a O $ a 9 a * $ a 9 a / $ a 9 a L $ a 9 a M 1 Shortcut a M9 $ a O9 $ a *9 $ a /9 $ a L9 $ aMMI MMa

a 9 a N 1 aOOI OOa Ta le -,-( shortcuts of e4pressions The difference et:een aMM and MMa is the value of the e4pression itselfO at the end8 oth of them increment the value of a y one8 ut the value of aMM :hen evaluated is the original value of a8 and the value of MMa is the incremented value, The follo:ing e4ample sho:s the difference, int aI $I c+ a 9 $ 9 c 9 1+ a 9 MM$ M c+ S!stem.out.println%)a 9 ) M a M )I $ 9 ) M $ M )I c 9 ) M c(+ $ 9 aMM O 1+ S!stem.out.println%)a 9 ) M a M )I $ 9 ) M $ M )I c 9 ) M c(+ c 9 a M aMM M OO$ M $+ S!stem.out.println%)a 9 ) M a M )I $ 9 ) M $ M )I c 9 ) M c(+ 6f you compile and run the a ove program8 you should see the follo:ing output( a 9 :I $ 9 -I c 9 1 a 9 ;I $ 9 -I c 9 1 a 9 <I $ 9 1I c 9 1K Java La !anual y *asser Jaffal "$''+% $'

To clearly understand ho: it :or0s8 letBs monitor the value of $ efore8 during and after the e4ecution of the statement a 9 MM$ M c+, <efore the e4ecution8 it is clear that R &8 once the statement MM$ e4ecuted8 the value of $ is incremented y &8 then the rest of e4pression is evaluated using the ne: value of $, This happened ecause :e used pre-increment, 6f :e use post-increment8 the value of $ :ill also e incremented8 ut :hen $MM itself is evaluated8 it gives the old value of $ efore increment8 so post increment does not affect the e4pression in :hich it is8 ut the follo:ing e4pressions, <oolean varia les have different set of unary and inary operations according to the special data type they store8 :hich is logical, Ta le -,2 sho:s primary oolean operations, >peration Logical A;D Logical A;D Logical >1 Logical >1 Logical ;>T >perator PP P QQ Q Usage op1 PP opop1 P opop1 QQ opop1 Q op-

* *op1 Ta le -,2( logical operations

Discussing the difference et:een PP and P8 and Q and QQ8 :hen :e use PP or QQ8 op- is not evaluated :hen the value of the :hole e4pression could e determined y the value of op1 and the operation, For e4ample8 true QQ "alse e4pression does not evaluate the second operand8 ecause the logical >1 et:een true and any other oolean e4pression is al:ays true8 similarly8 "alse PP true does not evaluate the second operand ecause logical A;D et:een "alse and any other oolean e4pression is al:ays "alse, 6n addition to these operations8 there are also comparison operations :hich :e apply to numerical varia les to get oolean results8 ta le -,5 sho:s comparison operations, >peration 3Duals @reater than @reater or eDuals Less than Less or eDuals >perator 99 @ @9 ? ?9 Usage op1 99 opop1 @ opop1 @9 opop1 ? opop1 ?9 op-

*9 op1 *9 opDoes not eDual Ta le -,5( Comparison operations The follo:ing e4ample evaluates some oolean e4pressions and prints their results, $oolean $1I $-I $:+ $1 9 true QQ "alse+ $- 9 $1 PP %< @ :(+ $: 9 $- PP %1: 99 =(+ S!stem.out.println%)$19) M $1 M )I $-9) M $- M )I $:9) M $:(+ Java La !anual y *asser Jaffal "$''+% $&

6f you compile and run the a ove code you should get the follo:ing output( $19trueI $-9trueI $:9"alse >nce again8 :e have used concatenation to convert the :hole output to string8 the ne4t section focuses more on conversion,

(.3 Conversion bet-een &ata T0"es


/e can convert the value of a varia le to the format of another varia le of different type and ma0e an assignment et:een them8 conversion is different from another operation called casting8 the follo:ing discussion sho:s the difference et:een them, int i+ "loat "+ dou$le d+ i 9 1+ " 9 ;.;"+ d 9 <.<+ d 9 i+ i 9 %int("+ " 9 %"loat(d+ S!stem.out.println%)i 9 ) M i M ) " 9 ) M " M ) d 9 ) M d(+ The a ove code does the follo:ing( Converts the value of i to dou$le and stores it in d, This conversion is done automatically y the compiler8 ecause dou$le data type is normally :ider than int8 there is a solutely no ris0 storing int in dou$le, 6n the follo:ing t:o statements8 notice that :e ut a large value into a smaller data type8 in this case8 a possi le loss of data occurs in :hich :e have to e a:are of, <ecause that8 compiler " y default% refuses to store "loat value in int8 or dou$le in "loat, <ecause of that8 :e use casting to tell to compiler that :e 0no: :hat :e are doingP Another :ay to convert et:een varia les is using some defined methods that converts et:een varia les, >ne of them is a :ell 0no:n method that converts a String to integer :hich is Cnteger.parseCnt%( method8 the follo:ing e4ample sho:s ho: to use it, String s 9 )11<)+ int x 9 Cnteger.parseCnt%s(+ xMM+ S!stem.out.println%x(+ //prints 11= Similarly8 :e can also use Dou$le.parseDou$le%(8 4loat.parse4loat%( and 3ong.parse3ong%(, A common method among all o Aects in Java is toString%( method :hich converts the o Aect to a string8 toString%( method :ill e covered in more details later, Types of conversion mentioned a ove are called explicit conversion8 ecause :e reDuest that Java La !anual y *asser Jaffal "$''+% $$

conversion e4plicitly8 another type of conversion is called implicit conversion "promotion%8 ecause it is done automatically :ithout reDuiring the programmer to reDuest that conversion8 for e4ample8 concatenating an integer or a character :ith a String converts them automatically to a string, int x 9 1K+ String s 9 )x eRuals ) M x+ 6n the a ove code8 the value of x :hich is &' is converted from integer to string and concatenated :ith the previous string )x eRuals ), )romotion also occurs :hen an e4pression of values from different types is evaluated, 6n general8 promotion converts all operands to the largest data type among them, The follo:ing code sho:s an e4ample, int x 9 1K+ dou$le d 9 1-.<+ "loat " 9 1.<"+ dou$le result 9 %d/"( M x+ S!stem.out.println%)T e result is ) M result(+ 6f you run the a ove code8 you :ill see the output GThe result is &+,77777777H, The e4pression :as evaluated as the follo:ing( &, The value of " is converted to dou$le and d/" is evaluated8 clearly8 the result is of type dou$le, $, The value of x is converted to dou$le and added to the previous e4pression, 7, The :hole e4pression is evaluated to type dou$le And stored in result,

(.( Litera' 1a'ues and Ex"ressions


6t is important to realiLe that a value of any type can e e4pressed in different :ays8 and all of them are eDuivalent, The follo:ing e4ample sho:s ho: to e4press integer value of + in different :ays, int int int int x ! F , 9 9 9 9 B+ < M :+ Cnteger.parseCnt%)B)(+ %x M !( / -+ //literal value //Constant expression //0et od return t!pe //6xpression

From the a ove e4ample :e can notice different e4pression types( literal val!e: y defining the value :e :ish to store in the varia le literally, For e4ample8 assigning B directly to an integer8 >a> directly to a character or )Hello) directly to a string, Expression: e4pressions are evaluated in runtime to generate a single value8 for e4ample8 the e4pression 1 M : N < evaluate at runtime and generate a final value of O1, Met.ods: Some methods returns a value of certain type8 one of them is the previously discussed parseCnteger%( method :hich returns an integer generated from some string,

Java La !anual y *asser Jaffal "$''+%

$7

Exercises
&, Assuming that a 9 :I $ 9 <I c 9 1I x 9 -I ! 9 O-I and F 9 = and follo:ing precedence rules, 3valuate each e4pression of the follo:ing independently and mention any changes in the varia le values after e4pression is evaluated "all varia les are integers%( %a / c( M F / a cMM M $ / x N ! x M MMx * xOO OOa * MMa N %FMM * FMM( %true PP %< @ A(( QQ %%: ?9 1K( PP *"alse(( %: ? =( QQ %cMM 99 x( $, /rite a program that evaluates all the e4pressions in e4ercise & and prints the result on the screen, 7, /rite a program that calculates a M $ M c M d and prints the result on the screen :here( aI $I c and d are integers, a is assigned a literal value of 7, $ is assigned a value of 5 using an arithmetic e4pression of 7 literal values, c is assigned a value of $ generated from an e4pression of a and $, d is assigned a value of - converted from a string using parseCnt%( method, The result is printed directly :ithout defining a ne: varia le to store the result,

Lab Extras
Some varia les are declared using "inal 0ey:ord8 "inal means that the value remains constant at the time of e4ecution and it is assigned during compile time, The value of a final varia le cannot e modified once it is assigned, The final 0ey:ord is used efore specifying data type in varia le declaration, "inal int 07SGT7326 9 1KK+ 6t is important to realiLe that you can assign a value to a final varia le only once, *ou can only assign the value in the same statement in :hich you define the varia le8 so the follo:ing statements are invalid, "inal int 07SGT7326+ 07SGT7326 9 1KK+

//6rror

As you can see8 the naming convention of final varia les is to use upper letters and underscores JIJ,

Java La !anual y *asser Jaffal "$''+%

$-

Session . Workin! "it# Java /,,lets


Objectives:

/riting and compiling Applets, 3m edding Applets into :e pages,

3.1 ,dea o% A""'ets


So far8 :e can claim that our Java applications are console applications8 ecause the run mainly on console "command prompt in /indo:s8 shell in Uni4%, Applets are something different8 from the conte4t in :hich they run, 6n general8 Applets are Java programs that are :ritten :ith *.java file e4tension and compiled using javac command8 ut they are different from another perspective(

*ou cannot run Applets using java command, Applets have no main%String&' args( method8 instead8 there is a method called init%(, To run an Applet8 you have to em ed it in a .T!L page using special tag, Applets are graphical8 not command-line applications,

3.2 Writing and Com"i'ing A""'ets


Applets are :ritten in ordinary Java source files that has the name of the class inside it, The follo:ing code sho:s a simple e4ample "read comments carefully%, //T ese t,o classes are necessar!I so ,e //need to import t em "rom t e li$raries import java.a,t.Urap ics+ import java.applet.7pplet+ //T is is t e ,a! to de"ine an 7pplet class pu$lic class Hello7pplet extends 7pplet# //T is code ,ill $e executed , en 7pplet runs pu$lic void init%(# //Setting 7pplet ,indo, siFe resiFe%1<KI-<(+ / //We use t is code to dra, on t e applet pu$lic void paint%Urap ics g(# //Dra,ing text on t e speci"ied point g.dra,String%)Hello ,orld*)I <KI -<(+ / / Java La !anual y *asser Jaffal "$''+% $2

There are some important notes a out :riting Applet code( /e use import 0ey:ord to get classes from li raries into our source files, Class should e declared using pu$lic 0ey:ord8 this ena les access to it from :e ro:sers, To let Java deal :ith this class as Applet8 add extends 7pplet to class declaration, Applets have t:o important methods( init%( method( This method is li0e main%String&' args( method in Java applications8 the Applet starts e4ecution from this method, paint%Urap ics g( method( This method is dedicated for painting on the Applet8 the varia le g "called o#(ect% has a lot of dra:ing methods li0e dra,String%(8 dra,3ine%(8 dra,Jval%( and so on, /e :ill discuss them in details later, After :riting the class8 :e compile it as usually :ith javac command, To run the applet8 :e need to put it inside .T!L page, The follo:ing section discusses this tas0,

3.3 Embedding A""'ets into HTML


After compiling the code in section 2,$8 you get a file called Hello7pplet.class, To run this file8 create an .T!L page "in the same folder% and add the follo:ing .T!L code in it, ? tml@ ?$od!@ <applet code= Hello%pplet ?/$od!@ ?/ tml@

width=&'' height=#''></applet>

The highlighted part is the most important tag in out page8 ?applet@ tag tells the ro:ser :here to add the Applet8 code property specifies the name of the class from :hich the Applet should e loaded, Saying it again8 the name of the class8 not the name of the )ile8 so donBt add the e4tension ,class to the name, /hen you open the :e page8 and everything is alright8 youBll get the result sho:n in figure 2,& elo:,

Figure 2,&( .ello /orld Applet

Java La !anual y *asser Jaffal "$''+%

$5

;otice that our Applet does nothing e4cept dra:ing the te4t G.ello /orldH at the point "2'8 $2% of the frame, To see e4actly :here this point is located8 :e have to understand the coordinations of the Applet, .ave a loo0 at figure 2,$ elo:, () "2'8 $2%

"'8 '% y)

%getWidt %(I getHeig t%(( Figure 2,$( Coordinations of Applet As you can see8 the upper-left corner has the coordinates "'8 '%, The value of 4 increases from left to right8 and the value of y increases from up to do:n, So to locate the point "2'8 $2%8 start from the upper-left corner and ta0e 2' pi4els to right then $2 pi4els do:n:ard, To get the :idth of the :hole Applet8 call getWidt %( method8 to get the height of the :hole Applet8 call getHeig t%( method,

Exercises
&, /rite the .elloApplet class and compile it, $, Create a :e page to run .elloApplet, 7, Create a ne: folder in your pu licIhtml folder on /e dis0 named la $ and upload .elloApplet,class and the :e page into it, -, 1un your Applet from the :e ,

Java La !anual y *asser Jaffal "$''+%

$=

Session 0 Conditional State1ents and 2ser In,ut


Objectives 6ntroducing the logic of i" and i"Oelse statements, 1eading user input, !a0ing decisions ased on user input, Using s,itc Ocase statement to ma0e decisions ased on some value,

4.1 if and if-else tatements


Sometimes :e need to ma0e a decision et:een t:o choices or t:o actions ased on some information or conditions, The statements in y :hich :e ma0e this decision are called conditional statements, Choices are made y one or more conditions eing satisfied or not8 :e e4press those conditions y oolean e4pressions8 that is8 if the result of the oolean condition is true then the condition is met and the appropriate action"s% is made, /e use i" statement to determine :hither the condition is me or not, The format of i" statement is as follo:s( i"%condition(# //statement(s) to be executed if the condition is true / For e4ample8 :e can chec0 :hether some value is positive or negative( int x 9 <+ i"%x @ K(# S!stem.out.println%)x is positive)(+ / else# S!stem.out.println%)x is negative)(+ / ;otice that :e use else loc0 to enclose statements that :e :ant to perform if the condition is ;>T met, The pro lem of the a ove statement is that K is considered negative, To solve this pro lem8 :e can use @9 operator instead of @8 ut if :e :ish to detect ' itself8 :e can use nested i" statement inside the loc0 of else as follo:s( int x 9 <+ i"%x @ K(# S!stem.out.println%)x is positive)(+ / else# i"%x 99 K(# S!stem.out.println%)x is Fero)(+ / Java La !anual y *asser Jaffal "$''+% $+

else# S!stem.out.println%)x is negative)(+ / / Using techniDue li0e on in the a ove e4ample may ma0e the code more comple4 and harder to understand8 instead8 :e can use elseOi" statement8 y :hich :e can chec0 unlimited num er of condition8 and ma0ing decision for each one separately, The format of if-else statement is the follo:ing( int x 9 <+ i"%x @ K(# S!stem.out.println%)x is positive)(+ / else i"%x ? K(# S!stem.out.println%)x is negative)(+ / else i"%x 99 K(# S!stem.out.println%)x is Fero)(+ / Using else efore each if statement means that if one of the conditions is met no other condition :ill e chec0ed,

4.2 *eading !ser ,n"ut


*ou can read input from the user using Vu""ered5eader class in this :ay( Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ String input 9 in.read3ine%(+ <efore using Vu""ered5eader8 e sure to import the li rary :hich contain this class8 this li rary is called java.io8 in order to import it8 :e use import statement as follo:s, import java.io.*+ <y using character * here :e identify that :e import all classes in this li rary, import statements are used efore class definition, To use Vu""ered5eader class8 you need to deal :ith the e4ception it thro:s through read3ine%( method :hich is CJ6xception8 for instance8 :e :ill do this y changing the definition of main%( method to thro: that e4ception, pu$lic static void main%String&' args( t ro,s CJ6xception# <utting it all together8 a simple program that reads user name and prints it on screen,

Java La !anual y *asser Jaffal "$''+%

$9

import java.io.*+ class 5ead4rom2ser# pu$lic static void main%String&' args( t ro,s CJ6xception# String userDame+ Vu""ered5eader in+ in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ S!stem.out.println%)6nter !our name: )(+ userDame 9 in.read3ine%(+ S!stem.out.println%)Welcome ) M userDame(+ / / The a ove code as0s the user to enter his name8 reads the input using read3ine%( method :hich returns a String value that represents user input from 0ey oard8 then concatenates it :ith J/elcomeJ and prints it on the screen,

4.3 &ecision Ma5ing /ased on !ser ,n"ut


6t is clear no: that you can :rite a program that responds to user actions depending on the input provided y user, For instance8 :e :ill :rite a program that uses if-else to determine that the num er provided y user is positive8 negative or Lero8 as :ell as determining :hether the num er is odd or even, import java.io.*+ class Dum$ers# pu$lic static void main%String&' args( t ro,s CJ6xception# Vu""ered5eader in+ in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ int x+ String userCnput+ S!stem.out.print%)6nter a num$er: )(+ userCnput 9 in.read3ine%(+ x 9 Cnteger.parseCnt%userCnput(+ i"%x 99 K(# S!stem.out.println%)Fero)(+ / //x is positive else i"%x @ K(#

Java La !anual y *asser Jaffal "$''+%

7'

//x is even i"%x L - 99 K(# S!stem.out.println%)positive and even)(+ / //x is odd else# S!stem.out.println%)positive and odd)(+ / / //x is negative else# //x is even i"%x L - 99 K(# S!stem.out.println%)negative and even)(+ / //x is odd else# S!stem.out.println%)negative and odd)(+ / / ///end o" main%( ///end o" class As you can see8 :e converted the String :e read from user to integer ecause it is easier to compare8 another reason may lead us to this conversion8 is that s,itc Ocase statement accepts only integers and numerical values or characters8 and it cannot accept strings, The follo:ing section covers s,itc Ocase statement,

4.( switch-case tatement


This statement is a special type of decision ma0ing techniDues8 it ma0es choice among several options ased on a numerical value, The format of s,itc Ocase statement is the follo:ing( s,itc %variable(# case value_1: //Statement%s( to $e executed i" //varia$le 9 valueG1 $reak+ case value_2: //Statement%s( to $e executed i" //varia$le 9 valueG$reak+ . . . case value_n: Java La !anual y *asser Jaffal "$''+% 7&

//Statement%s( to $e executed i" //varia$le 9 valueGn $reak+ / As you can see8 :e put some varia le in s,itc then follo: it y several case loc0s, 34ecution goes through cases one y one comparing each one :ith the value of the varia le specified in s,itc statement8 then e4ecutes it and all cases that follo:s8 unless :e use $reak 0ey:ord to avoid the e4ecution from e4panding to un:anted statements, The follo:ing e4ample sho:s ho: to use s,itc Ocase statement, import java.io.*+ class S,itc CaseDemo# pu$lic static void main%String&' args( t ro,s CJ6xception# Vu""ered5eader in+ in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ S!stem.out.println%)1. 8rint !our name)(+ S!stem.out.println%)-. 8rint !our age)(+ S!stem.out.println%):. 6xit)(+ int c oice+ c oice 9 Cnteger.parseCnt%in.read3ine%((+ s,itc %c oice(# case 1: S!stem.out.print%)6nter !our name: )(+ String name 9 in.read3ine%(+ S!stem.out.println%)Welcome ) M name)(+ $reak+ case -: S!stem.out.print%)6nter !our age: )(+ String age 9 in.read3ine%(+ S!stem.out.println%)Wou are ) M age(+ $reak+ case :: S!stem.exit%K(+ ///6nd s,itc ///6nd main ///6nd class The follo:ing code sho:s ho: cases are e4ecuted8 the follo:ing program enters all cases,

Java La !anual y *asser Jaffal "$''+%

7$

int x 9 1+ s,itc %x(# case 1: S!stem.out.println%)x 9 1)(+ case -: S!stem.out.println%)x 9 -)(+ case :: S!stem.out.println%)x 9 :)(+ / *ou can notice that the value of x meets the first case only8 ut all three cases are e4ecuted8 this states that s,itc Ocase statement does not automatically e4it after one a case value is met, So the output of the previous code is the follo:ing( x 9 1 x 9 x 9 : To prevent such ehavior8 use $reak statement after the end of each case8 :hich e4its the :hole s,itc loc0, A special case that is e4ecuted :ithout chec0ing the value of the varia le is called default case8 :e use de"ault 0ey:ord instead of case 0ey:ord to specify the default case, <ecause :e usually use $reak after each case8 default loc0 is e4ecuted :hen the value of the varia le did not match any of specified cases value, To see ho: this :or0s8 add a default case to our previous S,itc CaseDemo class "sho:n in oldface% and try to enter any value other than &8 $ and 7, s,itc %c oice(# case 1: S!stem.out.print%)6nter !our name: )(+ String name 9 in.read3ine%(+ S!stem.out.println%)Welcome ) M name)(+ $reak+ case -: S!stem.out.print%)6nter !our age: )(+ String age 9 in.read3ine%(+ S!stem.out.println%)Wou are ) M age(+ $reak+ case :: S!stem.exit%K(+

de$ault* //+ser did not enter 1, # or .ystem/out/println0 1n2alid choice 34


///6nd s,itc

Java La !anual y *asser Jaffal "$''+%

77

Exercises
&, /rite a program that specifies :hether a given num er "4% falls in one of the follo:ing categories "give 4 a value from the code8 donBt read from user%( ' to 9 &' to &9 $' to $9 ;one of the categories For e4ample8 if 4 R 28 program should print )K to 1K)8 and if 4 R -- it should print )Done). .int( use i" statements :ith oolean e4pressions com ined using PP, $, /rite a program that reads t:o integers and prints their sum li0e the code elo: "te4t sho:n in oldface is supposed to e user input%, 6nter t e "irst num$er: 6nter t e second num$er: & -. T e sum is A 7, /rite a program that as0s the user to enter t:o numerical values "integers% and then select an operation "addition8 su traction8 multiplication and division% then prints the result ased on operation selected, The code elo: sho:s e4amples of the output "te4t sho:n in oldface is supposed to e user input%, 6nter "irst num$er: & 6nter second num$er: # 1. -. :. ;. 7ddition %M(. Su$traction %O(. 0ultiplication %*(. Division %/(.

6nter operation num$er: T e result is B

Lab Extras
There is an easier :ay to read from user8 :hich depends on sho:ing a dialog o4 for the user and let him enter his input in a te4t o4 inside that dialog, To use this input dialog :e import the li rary called javax.s,ing8 this li rary contains classes that deal :ith @U6, /hat :e interested in among the classes of this li rary is a class called HJption8ane and a method inside it called s o,CnputDialog%(, The follo:ing e4ample sho:s ho: to use this techniDue to read from user, import javax.s,ing.*+ class 6as!5ead# Java La !anual y *asser Jaffal "$''+% 7-

pu$lic static void main%String&' args(# String userCnput+ userCnput 9 Hoption8ane.s o,CnputDialog%)!our name: )(+ S!stem.out.println%)Hello ) M userCnput M ) *)(+ / / *ou can notice here that :e do not declare any o Aects and no e4ceptions to thro:, An easy and straight for:ard method, The output of the a ove code is a dialog o4 li0e the image =,&, 6f user clic0s >K the input is read and returned as String8 if he clic0 Cancel dialog o4 closes :ithout returning any input entered,

6mage 5,&( 6nput Dialog

Java La !anual y *asser Jaffal "$''+%

72

Session 3 &ecision4Tree /,,let


Objectives:

Adding user controls to Applets, .andling events of user controls, 1eading and :riting values to user controls, 6ncluding e4ternal pac0ages,

6.1 Adding !ser Contro's to A""'ets


So far8 :e have een creating Applets that do nothing ut dra:ing te4t on the screen, /ell8 applets can do more, The main o Aective of Applets is to provide a dynamic user interface on the :e 8 so it is reasona le to start learning ho: to add user controls " uttons8 te4t fields8 ,,,8 etc% to the Applet, Adding user controls is a simple yet relatively long process8 to summariLe8 it involves the follo:ing steps( &, 6mporting the li rary in :hich they are located "java.a,t%, $, Declaring user controls varia les "or o Aects%, 7, 6nitialiLing the controls, -, Adding the controls to the Applet, 2, .andling controls events, For no:8 lets focus on the first four steps and leave step 2 to the ne4t section, Lets no: discuss these steps in details, 6mporting the li rary is achieved y using import statement follo:ed y li rary name and class name, To import all classes in a li rary8 :e use M, The follo:ing code sho:s the necessary import statement, import java.a,t.*+ The second step is to declare the controls varia les, These controls have data types Aust li0e primitive data types discussed in session 7 ut their initialiLation is slightly different, For e4ample8 if :e :ant to add a utton and a te4t field to our Applet8 :e use code li0e the follo:ing, Vutton $+ Text4ield t+ ;otice that these types start :ith upper-case letter8 unli0e primitive data types, 6t is important to realiLe that you need to declare these varia les outside init%(8 in other :ords8 they should e declared directly inside the class ody, Up to no:8 :e have Aust declared these controls8 this means that :e have reserved the varia les names for them8 ut they does not actually e4ist, The initialiLation step is the one :hich ma0es them really e4ist, 6t is advisa le that you initialiLe these controls at the eginning of init%( method, Java La !anual y *asser Jaffal "$''+% 75

pu$lic void init%(# $ 9 ne, Vutton%)Click 0e*)(+ t 9 ne, Text4ield%)T!pe in me*)(+ / As the a ove code sho:s8 :e use the ne, 0ey:ord to initialiLe the controls, The statement that follo:s ne, 0ey:ord is a call to the constructor8 :hich is a special type of methods :ritten specifically to initialiLe o Aects, DonBt other yourself :ith it no:, The string :e pass to Vutton constructor is the te4t :e :ant to appear on it, Similarly8 the te4t :e pass to Text4ield constructor is the default te4t that :ill appear in it, /e have no: declared and initialiLed controls8 the step left is to add these controls to the Applet, Although these controls are declared inside AppletBs class8 they are not graphically added hence not yet visi le to the user, To ma0e them visi le8 :e add them to the Applet using add%( method, Code elo: sho:s a full e4ample, //Step 1: import import java.a,t.*+ import java.applet.7pplet+ pu$lic class Simple7pplet extends 7pplet# //Step -: declare controls Vutton $1I $-+ Text4ield t"+ pu$lic void init%(# //Step :: initialiFe controls $1 9 ne, Vutton%)Vutton 1)(+ $- 9 ne, Vutton%)Vutton -)(+ t" 9 ne, Text4ield%)T!pe somet ing)(+ //Step ;: add controls %adding order a""ects appearance( add%$1(+ add%t"(+ add%$-(+ / / 6f you compile and run the a ove Applet8 youBll get something li0e this "figure =,&%,

Figure =,&( Simple Applet

Java La !anual y *asser Jaffal "$''+%

7=

6.2 Hand'ing Events o% !ser Contro's


The last thing remained in this session is to add some functionality to these controls8 at the end8 there is no point in adding uttons that do nothing and te4t fields :e are not a le to readC:rite to, First step of adding this functionality is to import the necessary li rary8 :hich is java.a,t.event, import java.a,t.event.*+ ;e4t8 :e need to alter the definition of our class8 in addition to eing Applet8 our class should no: serve as 7ction3istener8 that is8 eing a le to handle actions raised y controls "mainly uttons%, So the definition of the class :ill e the follo:ing, pu$lic class 0!7pp extends 7pplet implements %ctionListener ;otice the addition "implements 7ction3istener% at the end of the class definition, This addition reDuires you to :rite a ne: method called action8er"ormed%(, pu$lic void action8er"ormed%7ction6vent e(# / >ne thing left8 letting the current Applet e the event handler for uttons :e have added8 this is achieve y calling add7ction3istener%( from uttonBs o Aect, //7ssume t at Vutton $ is alread! de"ined... $.add7ction3istener%t is(+ *our Applet is ready no: for event handling8 ut ho:? /hen user clic0s on a utton8 the method action8er"ormed%( is e4ecuted, The follo:ing code sho:s ho: can you decide :hich utton :as clic0ed "modified version of Simple7pplet%, !odifications are sho:n in oldface, //Step import import import 1: import java.a,t.*+ ja2a/awt/e2ent/54 java.applet.7pplet+

pu$lic class Simple7pplet extends 7pplet implements %ctionListener# //Step -: declare controls Vutton $1I $-+ Text4ield t"+ pu$lic void init%(# //Step :: initialiFe controls $1 9 ne, Vutton%)Vutton 1)(+ $- 9 ne, Vutton%)Vutton -)(+ t" 9 ne, Text4ield%)T!pe somet ing)(+ //Step ;: add controls %adding order a""ects appearance( add%$1(+ add%t"(+ Java La !anual y *asser Jaffal "$''+% 7+

add%$-(+ //.tep 6* add action listener b1/add%ctionListener0this34 b#/add%ctionListener0this34 / //This method will run when buttons are clic7ed/ public 2oid action8er$ormed0%ction92ent e3: ;bject cause = e/get.ource034 i$0cause == b13: t$/setTe(t0 <utton 1 =as "lic7ed 34 > else i$0cause == b#3: t$/setTe(t0 <utton # =as "lic7ed 34 > > / Code inside action8er"ormed%( method needs some e4planation8 :e call e.getSource%( to 0no: :hich utton :as clic0ed8 then store it in cause, Then :e compare cause :hich all uttons :e have to find out :hich utton :as clic0ed in order to perform the appropriate action, To change the value displayed in the te4t field8 call setText%( method and pass a String representing te4t you :ant to appear in it, To read the te4t typed in the te4t field call its getText%( method, String valueJ"Text4ield 9 t".getString%(+ *ou can also use a control name 3a$el to add te4t la els to the Applet, 3a$el l 9 ne, 3a$el%)Some text)(+ add%l(+

6.3 A""'ets -it$ .et/eans


;et<eans facilitates developing Java Applets y using applet viewer tool8 this tool can run your Applet :ithout the need of creating .T!L page, To do the e4ercises at the end of this session8 you need to add an e4ternal li rary that is not present in JDK8 this li rary is called 0odel7,$.jar and can e do:nloaded from the follo:ing lin0 http(CCmail,alDuds,eduCFf72=5C&'$CresourcesC!odelA: ,Aar, After do:nloading the file8 you have to add it to your ;et<eans proAect8 to do this8 follo: the follo:ing steps( &, $, 7, -, 34pand your proAect tree from proAect e4plorer "on the left%, 1ight-clic0 li raries node and select GAdd JA1CFolderH <ro:se for 0odel7,$.jar file8 select it and clic0 G>penH, *ou can no: use the statement import a,$.*+

Java La !anual y *asser Jaffal "$''+%

79

Exercises
&, /rite a calculator Applet that has t:o int fields "Use a,$.Cnt4ield class%8 named register and accumulator8 and four uttons named set5egI set7ccumI add and po,er, The ehavior of these uttons should e as the follo:ing( /!tton Set 1eg Set Accum Add %ob Sets register int field to ' Sets accumulator int field to ' Sums the values in register and accumulator and leaves the result in accumulator 1aises accumulator value to the po:er of the value of register leaving the result in accumulator

)o:er

*our Applet should loo0 li0e figure =,$,

Figure =,$( 34ercise &

Lab Extras
*ou can specify the :idth of te4t field y providing the num er of columns in the constructor, For e4ample8 the follo:ing code creates a te4t field :ith $' columns :idth, Text4ield t 9 ne, Text4ield%-K(+ Text7rea a 9 ne, Text7rea%-KI -K+ //Text "ield ,it multiple lines

Java La !anual y *asser Jaffal "$''+%

-'

Session 5 Loo,s and )ariable sco,e


Objectives Understanding the concept of loops, Using , ile and doO, ile loops, Using "or loop, #aria le scope,

7.1 W$at Are Loo"s8


/e use loops to ma0e one or more statements repeat for specified num er of times, Clearly this have an importance :hen :e :ish to ta0e more than one input from user or do some calculations, For e4ample8 to calculate the sum of num ers from & to &'8 :e define a varia le named sum8 initialiLe it :ith '8 then use another varia le i to have values from & to &', The follo:ing sections discuss loops in more details,

7.2 while and do-while Loo"s


This is the simplest type of loops8 it consists of a condition " oolean e4pression% and a #ody :hich contain one or more statementsO as long as condition is true8 statement"s% in the ody 0eep to e4ecute8 after each e4ecution8 the condition is chec0ed again8 this implies that if the condition :as initially false8 statements in loop ody :ill never e4ecute, The format of , ile loop is the follo:ing, , ile%condition(# //Statement%s( to execute as long as condition is true. //7lso kno,n as loop body. / .ere is an e4mple of , ile loop( class 3oops# pu$lic static void main%String&' args(# //8rints num$ers "rom 1 to 1K int x 9 1+ , ile%x ?9 1K(# S!stem.out.println%x(+ xMM+ / / / The output of the a ove program is the follo:ing( 1 Java La !anual y *asser Jaffal "$''+% -&

: ; < = A B X 1K 6t is clear that the value of 4 affected the e4ecution of the loop8 as you can derive from the output8 the condition is true until 4 reaches &&, /e can also use $reak to e4it the loop, int x 9 1+ , ile%true(# //in"inite loop S!stem.out.println%x(+ i"%x 99 1K(# $reak+ / / using $reak in the a ove code e4its the loop :hen x 9 1K, The doO, ile loop li0e , ile loop uses oolean e4pression to determine :hether or not go to ne4t iteration, The difference et:een it and , ile loop is the seDuence of e4ecution8 doO, ile loop ody appears efore the condition8 this implies that even if the condition is false8 the loop :ill e4ecute at least one time, The format of the do-:hile loop is the follo:ing, do# //3oop $od! /, ile%condition(+ if :e repeat the last e4ample using do-:hile8 the code :ill loo0 li0e this( int x 9 1+ do# S!stem.out.println%xMM(+ /, ile%x ?9 1K(+ The output :ill e the same of previous e4ample, So ho: can :e clearly see the difference? Consider the follo:ing t:o loops, //, ile //doO, ile int x 9 K+ int x 9 K+ , ile%x *9 K(# S!stem.out.println%x(+ / +!#p!#: do# S!stem.out.println%x(+ /, ile%x *9 K(+ +!#p!#: 0 Java La !anual y *asser Jaffal "$''+% -$

As you can see8 although the condition :as initially false8 doO, ile loop e4ecuted one time8 ut , ile loop :as not e4ecuted,

7.3 for Loo"


The ase of "or loop is similar to , ile and doO, ile loopsO ut there is slight different in format that ma0es "or loop more po:erful8 specially :ith numerical values, LetBs first have a loo0 at "or loop format8 after that :e :ill discuss its contents, "or%initialization+ test-condition+ post-statements(# //Loop body / /e can notice that "or loop consists of three maAor parts( Initiali0ation: a statement to e e4ecuted efore the loop egins8 this statement is usually used to define a varia le or set of varia les that control the flo: of the loop, )est1condition: This is the oolean e4pression that is used to determine :hether or not the loop should e4ecute the ne4t iteration8 similar to conditions previously discussed in , ile and doO, ile loops, ost1state'ents: a set of statements "separated y commas BIB% to e e4ecuted after each iteration, These statements are usually used to change "increment or decrement% the value of controlling varia le"s% declared in initialiLation8 sometimes :e call it post'increment,

To etter understand the concept of "or loop8 :rite and e4ecute the follo:ing program, class 4or3oopDemo# pu$lic static void main%String&' args(# "or%int x 9 1+ x ?9 1K+ xMM(# S!stem.out.println%x(+ / / / The flo: of e4ecution of "or loop is the follo:ing( &, 6nitialiLation is e4ecuted once, $, Test-condition is chec0ed to determine :hether or not loop ody should e e4ecuted, 7, Loop ody e4ecution, -, )ost-statement are e4ecuted, 2, <ac0 to step $ through - until the stop condition is false8 then loop e4its, Another e4ample of "or loop is the program that prints out the results of multiplications from & to &$, class 0ultiplicationTa$le# pu$lic static void main%String&' args(# "or%int i 9 1+ i ?9 1-+ iMM(# "or%int j 9 1+ j ?9 1-+ jMM(# Java La !anual y *asser Jaffal "$''+% -7

int k 9 i * j+ S!stem.out.println%i M ) * ) M j M ) 9 ) M k(+ / / / / 6n the a ove e4ample8 :e used nested loops8 that is8 a loop inside the ody of another loop8 :e can use as many levels of nesting as :e need, <e :are that :hen :e use nested loops8 the inner loop e4ecutes until the end in one iteration of the outer loop8 ecause the :hole inner loop is one statement in the ody of outer loop, Com ining loops and conditional statements8 :e can uild po:erful applications that do comple4 Ao s, For instance8 :e :ill create a program that determines :hether a given num er is a prime or not, import javax.s,ing.*+ class 8rime# pu$lic static void main%String&' args(# int x+ String userCnput+ userCnput9HJption8ane.s o,CnputDialog%)6nter a num$er)(+ x 9 Cnteger.parseCnt%userCnput(+ //1I - and : are prime num$ers i"%x 99 1 QQ x 99 - QQ x 99 :(# S!stem.out.println%x M ) is prime)(+ / //7ll even num$ers @ - are not prime else i"%x L - 99 K(# S!stem.out.println%x M ) is not prime)(+ /else# //We ave to c eck using division remainder //,e initiall! suppose t at x is prime $oolean prime 9 true+ //Do num$er as "actor greater t an it>s al" "or%int i 9 :+ i ?9 x / -+ iMM(# i"%x L i 99 K(# //We ave "ound a "actor //so x is not prime prime 9 "alse+ $reak+ / / i"%prime(# S!stem.out.println%x M ) is prime)(+ / else# S!stem.out.println%x M ) is not prime)(+ / Java La !anual y *asser Jaffal "$''+% --

/ / / To get more familiar8 try to understand the follo:ing program that 0eeps reading num ers "integers% from user until input is '8 then prints average8 sum8 ma4imum and minimum, import java.io.*+ class Dum$ers# pu$lic static void main%String&' args( t ro,s CJ6xception# int minI maxI xI sum 9 KI count 9 K+ $oolean "irstDum$er 9 true+ Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ , ile%true(# S!stem.out.print%)6nter a num$er: )(+ x 9 Cnteger.parseCnt%in.read3ine%((+ i"%x 99 K(# $reak+ /

i"%"irstDum$er(# min 9 max 9 x+ "irstDum$er 9 "alse+ / sum M9 x+ i"%x @ max(# i"%x ? min(# countMM+ / S!stem.out.println%)Sum 9 ) S!stem.out.println%)7verage S!stem.out.println%)0inimum S!stem.out.println%)0aximum / / M 9 9 9 sum(+ ) M sum / count(+ ) M min(+ ) M max(+ max 9 x+ min 9 x+ / /

7.( 1ariab'e co"e


<y varia le scope8 :e mean the region or loc0 the varia le is visi le :ithin8 any access of varia le out of its scope :ill e reported as compilation error, Consider the follo:ing code,

Java La !anual y *asser Jaffal "$''+%

-2

int x 9 O:+ i"%x ? K(# int ! 9 x * O1+ S!stem.out.println%)7$solute value o" ) M x M ) is ) M !(+ / 6n the previous code8 x has scope inside and outside i" loc08 :hile ! is only visi le inside i" loc08 if you try to call ! from outside i" loc08 you :ill get error message )Cannot resolve s!m$ol), int x 9 O:+ i"%x ? K(# int ! 9 x * O1+ / S!stem.out.println%)7$solute value o" ) M x M ) is ) M !(+ //6rror #aria le scope e4tends from outer loc0 to inner loc0s regardless of the num er of levels8 ut not vise-versa, //Tisi$le: Done "or%int i 9 1+ i ?9 1-+ iMM(# //Tisi$le: i "or%int j 9 1+ j ?9 1-+ jMM(# //Tisi$le: iI jI k int k 9 i * j+ S!stem.out.println%i M ) * ) M j M ) 9 ) M k(+ / //Tisi$le: i / //Tisi$le: Done

Exercises
&, /rite a program that reads &' num ers from the user then prints out ho: many positive num ers and negative num ers user has entered "consider ' a positive num er%, $, !odify calculation program in session - e4ercise 7 y adding the follo:ing Duestion at the end of the program( Do !ou ,ant to make anot er calculation. 1. Wes -. Do 6nter !our option: 6f user selects yes " y entering &%8 program :ill as0 him again to enter ne: t:o num ers and select operation8 if user selects no " y entering $%8 program e4its, Use appropriate loop to accomplish this, 7, /rite a program that as0s the user to enter certain num er8 after that as0s him to enter Java La !anual y *asser Jaffal "$''+% -5

another $' num ers8 after entering them all8 it prints out the num er of occurrences of the first num er, See the elo: e4ample "te4t sho:n in oldface is supposed to e user input%, 6nter num$er to searc "or: #

6nter a num$er: (20 times) # - 6? @ A # & 6 6 ? # #1 -- 1A -# BB ' -# 1'' #' T e num$er %-( occurred : times in !our input. -, /hat is the output of the follo:ing program? "or%int i 9 K+ i ? <+ iMM(# "or%int j 9 K+ j ? i+ jMM(# S!stem.out.print%) )(+ / S!stem.out.print%i * j(+ S!stem.out.println%))(+ /

Lab Extras
/e use continue 0ey:ord to s0ip some statements inside loop ody and start ne: iteration8 consider the follo:ing program that prints out factors of 7', "or%int i 9 1+ i ?9 :K+ iMM(# i"%:K L i *9 K(# continue+ / S!stem.out.println%i(+ / As you can see8 :hen 7' is not divisi le y i8 :e use continue to Aump to the ne4t iteration :ithout e4ecuting the ne4t line that prints the output,

Java La !anual y *asser Jaffal "$''+%

-=

Session 6 /rra+s and Strin!s


Objectives Understand the concept of arrays, Defining and using arrays in different types, !ultidimensional arrays, Strings as arrays,

9.1 W$at Are Arra0s8


Arrays are special data types that let us store specified num er of varia les from the same type using one varia le name, 6magine the situation that you need to store $' names of students as strings and $' integers as mar0s8 then you need to define -' varia les8 and this is clearly very hard and not practical8 in such case you need to use arrays, Arrays are indexed data types8 that means they are storing different elements discriminating et:een them using uniDue inde4 for each one, Figure 9,& sho:s the structure of an array,

Figure 9,&( Array Structure As Figure 9,& sho:s8 the siLe of an array is fi4ed8 :e :ill refer to array ma4imum siLe as array length8 it is also clear that indices of an array are Lero- ased8 that is8 they start from ' to length S &O for e4ample8 the array sho:n in Figure 9,& has a length of &' "stores up to &' elements%8 and the last inde4 is 9,

9.2 !sing Arra0s in Java


Declaring and using an array in Java is similar to declaration of any varia leO you have to specify data type and name8 in addition to this8 you have also to specify the length of the array efore using it, Array definition format is as follo:s( DataT!pe&' arra!Dame+ To initialiLe the array8 use ne, 0ey:ord and specify the length, arra!Dame 9 ne, DataT!pe&lengt '+ .ere are some e4amples of array declaration( int&' a 9 ne, int&='+ //7rra! o" integers o" lengt = String&' $ 9 ne, String&1K'+ //7rra! o" strings o" lengt

1K

Java La !anual y *asser Jaffal "$''+%

-+

To access array mem ers8 use array name :ith desired inde4 specified et:een sDuare rac0ets U V, int&' x 9 ne, int&:'+ x&K' 9 <+ //Store < in t e "irst index x&1' 9 1K+ //Store 1K in t e second index x&-' 9 1<+ //Store 1< in t e t ird index S!stem.out.println%x&-' M x&1'(+ //8rints -< 6f you try to access an inde4 out of the range of array "greater or eDuals array length% J#! :ill thro: an CndexJutJ"5ange6xception, int&' x 9 ne, int&:'+ //Talid indices are KI 1 and x&:' 9 A+ //CndexJutJ"5ange6xception Another techniDue to declare an array is to directly provide its mem ers et:een rac0ets # and /8 separated using commas BIB, int&' x 9 #1KI 1<I -KI -<I 1KK/+ //3engt S!stem.out.println%x&:'(+ //8rints -< 9 <

String&' da!s 9 #)Sat)I )Sun)I )0on)I )Tue)I )Wed)I )T u)I )4ri)/+ //We are leaving in 0onda! S!stem.out.println%)We are leaving in ) M da!s&-'(+ 6t is common to deal :ith arrays using for loop8 :e can use lengt property to determine the length of the array, The follo:ing code stores multiples of 7 in an array then prints them from greater to smaller, int&' a 9 ne, int&-K'+ "or%int i 9 K+ i ? a.lengt + iMM(# a&i' 9 i * :+ / "or%int i 9 a.lengt N 1+ i @9 K+ iY(# S!stem.out.print%a&i' M ) )(+ / The follo:ing e4ample stores names and num ers of n students and performs search, import javax.s,ing.*+ class Students# pu$lic static void main%String&' args(# int&' num$ers+ String&' names+ String input 9 HJption8ane.s o,CnputDialog%)6nter num$er o" students)(+

Java La !anual y *asser Jaffal "$''+%

-9

int siFe 9 Cnteger.parseCnt%input(+ num$ers 9 ne, int&siFe'+ names 9 ne, String&siFe'+ "or%int i 9 K+ i ? num$ers.lengt + iMM(# names&i' 9 HJption8ane.s o,CnputDialog%)6nter Student name)(+ input 9 HJption8ane.s o,CnputDialog%)6nter Student num$er)(+ num$ers&i' 9 Cnteger.parseCnt%input(+ / /* Do, ,e ave all num$ers and namesI index ,ill $ind t,o arra!s toget erI t at isI student in index < as is name in names&<' and is num$er stored in num$ers&<' */ //Searc "or student int x+ do# input 9 HJption8ane.s o,CnputDialog%)6nter student num$er)(+ x 9 Cnteger.parseCnt%input(+ $oolean "ound 9 "alse+ "or%int i 9 K+ i ? num$ers.lengt + iMM(# i"%num$ers&i' 99 x(# HJption8ane.s o,0essageDialog%nullI )Dame: ) M names&i'(+ "ound 9 true+ $reak+ / / i"%*"ound(# Hoption8ane.s o,0essageDialog%nullI )Dot "ound)(+ / //7sk i" t e user ,ants to per"orm anot er searc . input 9 Hoption8ane.s o,CnputDialog%)Searc /, ile%*input.eRualsCgnoreCase%)D)((+ / / again. W/D)(+

Comments on the previous program( Array inde4 could e used to relate data from different arrays together, Java La !anual y *asser Jaffal "$''+% 2'

>utput could e provided using HJption8ane.s o,0essageDialog%( method "1emem er to provide null as first parameter "parent :indo:% %, String class has method called eRualsCgnoreCase that compares t:o strings together regardless of their case, There is also another method called eRuals that ma0es casesensitive comparison et:een strings,

9.3 Mu'tidimensiona' Arra0s :Arra0s o% Arra0s;


Up to this point8 :e :ere storing elements in linear manner8 that is8 :e provide one inde4 to locate the element in one-dimensional structure, Java also provides arrays o) arrays8 this means :e create an array8 each element in that array is an array itself, These arrays are also called multidimensional arrays, Lets first consider the declaration of multidimensional arrays, DataT!pe&'&' arra!Dame+ arra!Dame 9 ne, DataT!pe&ro,s'&columns' The follo:ing e4ample sho:s a definition of a 2 y - array of integers, int&'&' x 9 ne, int&<'&;'+ //i indicates ro, %ro, $! ro,( "or%int i 9 K+ i ? <+ iMM(# //j indicates column %column $! column( "or%int j 9 K+ j ? ;+ jMM(# x&i'&j' 9 i * j+ / / //8rint arra! "or%int i 9 K+ i ? x.lengt + iMM(# "or%int j 9 K+ j ? x&i'.lengt + jMM(# S!stem.out.print%x&i'&j' M ) )(+ / S!stem.out.println%))(+ / *ou can see from the previous e4ample that :e deal :ith each element in the array as array itself8 for e4ample8 :e call x&i'.lengt 8 this means that x&i' is an array of integers that may has its o:n length8 ecause it is not necessary that all ro:s have the same num er of columns, The follo:ing e4ample sho:s that, int&'&' a 9 # #K/I //a&K' #KI 1/I //a&1' #KI 1I -/I //a&-' #KI 1I -I :/ //a&:' /+ "or%int i 9 K+ i ? a.lengt + iMM(# "or%int j 9 K+ j ? a&i'.lengt + jMM(# Java La !anual y *asser Jaffal "$''+% 2&

S!stem.out.print%a&i'&j' M ) )(+ / S!stem.out.println%))(+ / The output of the a ove code is the follo:ing( K K 1 K 1 K 1 - : As you can see8 :e filled the array a ove :ith su -arrays, T:o dimensional arrays are common in representing matrices8 for e4ample8 :e can :rite a program that adds t:o matrices "remem er that matrices must have same num er of ro:s and same num er of columns :hen it comes to addition%, import javax.s,ing.*+ class 0atrices# pu$lic static void main%String&' args(# String input+ int ro,sI columns+ input 9 HJption8ane.s o,CnputDialog%)6nter num$er o" ro,s)(+ ro,s 9 Cnteger.parseCnt%input(+ input 9 HJptio8ane.s o,CnputDialog%)6nter num$er o" columns)(+ columns 9 Cnteger.parseCnt%input(+ int&'&' matrix1 9 ne, int&ro,s'&columns'+ int&'&' matrix- 9 ne, int&ro,s'&columns'+ String m1 9 )6nter "irst matrix elements\n)+ String m- 9 )6nter second matrix elements\n)+ "or%int i 9 K+ i ? ro,s+ iMM(# "or%int j 9 K+ j ? columns+ jMM(# input 9 HJption8ane.s o,CnputDialog%m1M)&)MiM)'&)MjM)')(+ matrix1&i'&j' 9 Cnteger.parseCnt%input(+ / / "or%int i 9 K+ i ? ro,s+ iMM(# "or%int j 9 K+ j ? columns+ jMM(# input 9 HJption8ane.s o,CnputDialog%m-M)&)MiM)'&)MjM)')(+ matrix-&i'&j' 9 Cnteger.parseCnt%input(+ / Java La !anual y *asser Jaffal "$''+% 2$

/ int&'&' result 9 ne, int&ro,s'&columns'+ String output 9 ))+ "or%int i 9 K+ i ? ro,s+ iMM(# "or%int j 9 K+ j ? columns+ jMM(# result&i'&j' 9 matrix1&i'&j' M matrix-&i'&j'+ output M9 result&i'&j' M )\t)+ / output M9 )\n)+ / HJption8ane.s o,0essageDialog%nullI )5esult is\n) M output(+ / /

9.( tring as Arra0s


/e can deal :ith strings as array of characters8 this could e accomplished through t:o methods in String class called lengt %( and c ar7t%(8 the follo:ing e4ample prints a string putting each character in separate line, String s 9 )7lOZuds)+ "or%int i 9 K+ i ? s.lengt %(+ iMM(# S!stem.out.println%s.c ar7t%i((+ / <e :are of the difference et:een strings and arrays :hen accessing lengthO lengt in arrays is a varia#le so :e call it :ithout rac0ets8 ut in string8 lengt %( is a method so :e call it :ith rac0ets, c ar7t%( method simply returns the character contained in the provided Lero- ased inde4 :ithin the string8 for e4ample8 calling c ar7t%:( in the previous e4ample returns >Z>, The follo:ing e4ample counts ho: many spaces there are in certain string, String a 9 )a string ,it int count 9 K+ "our spaces)+

"or%int i 9 K+ i ? a.lengt %(+ iMM(# i"%a.c ar7t%i( 99 > >(# countMM+ / / S!stem.out.print%)T ere are ) M count M ) spaces in t e string)(+

Exercises
&, /rite a program that reads &' integers from the user and then prints them out in reverse order, $, /rite a program that reads names and mar0s of &' students then prints the names of the Java La !anual y *asser Jaffal "$''+% 27

students :ith the highest and lo:est mar0s, 7, /rite a program that reads &5 integers from the user8 stores them in 2 y - matri48 the last ro: of the matri4 should contain the sums of the columns "see figure 9,$% calculated y your program, Then the :hole matri4 is printed, User input 7 & + = + 7 & & 9 2 + 2 2 5

Sum &5 &9 &9 $Figure 9,$ "34ercise 7%

Lab Extras
*ou may have noticed that :hen :e declare the main method :e specify an array of strings String&' args, This array stores command-line arguments and it could e used as input method in addition to input methods :e discussed earlier, To see ho: it :or0s8 first :e should 0no: ho: to provide command line arguments8 :hen :e run a class :e use the follo:ing command, java ClassDame argG1 argG- ... argGn The arguments :e provide after class name are stored in args array8 the num er of arguments determine the length of the array8 notice that arguments are separated y spaces, The follo:ing e4ample sho:s ho: to read num ers from command line and print their sum, class ZuickSum# pu$lic static void main%String&' args(# int sum 9 K+ "or%int i 9 K+ i ? args.lengt + iMM(# sum M9 Cnteger.parseCnt%args&i'(+ / S!stem.out.println%)sum 9 ) M sum(+ / / .ere is an e4ample of the the e4ecution of the a ove code, java ZuickSum : ; = sum 9 1< 6n ;et<eans 6D38 you can add command line arguments y opening proAect properties8 selecting JrunJ node from properties tree on the left8 then entering arguments in JArgumentsJ field separated y spaces,

Java La !anual y *asser Jaffal "$''+%

2-

Session 17 /,,lications on /rra+s (&atabases)


Objectives:

Understand the concept of data ases, 6mplementing data ases using arrays, )erforming search and update,

1<.1 W$at Are &atabases8


Data ases are used to store large amount of data in one or more ta les8 in the large picture8 these ta les have relations et:een them, /hat :e are interested in right no: is to understand the concept of ta les and ho: to implement them using Java arrays, Consider for e4ample that :e have a ta le to store data a out cars8 this ta le is sho:n elo: "ta le &',&%, 2endor !aLda .onda Fiat .onda ;issan Model &9++ &992 $''' $''$ $''' Ta le &',&( Cars data ase ,olor 1ed Silver <lue 1ed <lac0

/hat :e are :illing to do no: is to see ho: can :e represent this ta le in Java and modify or retrieve data from it,

1<.2 ,m"'ementing &atabases using Arra0s


6n Java8 you can use arrays to simulate ta les of data ases, This is a simple tas0 ased in array inde4, For e4ample8 if :e :ish to represent the ta le &',& using arrays8 :e have to do the follo:ing( &, Specify appropriate data type for each column, $, Declare an array for each column of its selected data type, 7, 6nsert data to arrays y putting each ro: entry in the same inde4 in all arrays, Lets say that :e have selected String data type for oth G#endorH and GColorH columns and int for G!odelH, /e have to declare three arrays for them, String&' vendor 9 ne, String&<'+ String&' color 9 ne, String&<'+ int&' model 9 ne, int&<'+ >ne thing left8 :hich is adding data to this ta le, 3ach ro: in the ta le :ill ta0e a common inde4 in all arrays8 for e4ample8 :e represent the first ro: y setting the follo:ing, Java La !anual y *asser Jaffal "$''+% 22

vendor&K' 9 )0aFda)+ color&K' 9 )5ed)+ model&K' 9 1XBB+ To represent the :hole ta le8 :e can declare arrays as follo:ing, String&' vendor 9 #)0aFda)I )Honda) I )4iat)I )Honda)I )Dissan)/+ String&' color 9 #)5ed) I )Silver) I )Vlue)I )5ed) I )Vlack) /+ int&' model 9 # 1XBB I 1XX< I -KKK I -KK- I -KKK /+ 6t is possi le no: to search inside this ta le8 for e4ample8 to find the cars manufactured in year $'''8 :e can do something li0e this, "or%int i 9 K+ i ? model.lengt + iMM(# i"%model&i' 99 -KKK(# S!stem.out.println%vendor&i' M ) O ) M color&i'(+ / / 6n a similar :ay8 :e can search y color or y vendor, Additionally8 :e can update ta le data y updating arrays contents, For e4ample8 the follo:ing code sets all cars colors to red, "or%int i 9 K+ i ? color.lengt + iMM(# color&i' 9 )5ed)+ /

Exercises
&, /rite Java Applet that implements cars ta le, *our applet should have three uttons8 a te4t field and a te4t area "Text7rea class is li0e Text4ield ut have multiple lines%, 6t should loo0 li0e figure &',$ elo:, The follo:ing ta le sho:s ho: should this Applet ehave, /!tton #endor !odel Color /e.avior )erforms search using carBs vendor and gives full details a out each matching car in the te4t area Similar to G<y #endorH8 ut performs search using model Similar to G<y #endorH8 ut performs search using color

Figure &',$( Cars Applet

Java La !anual y *asser Jaffal "$''+%

25

Session 11 /,,lets and 8ra,#ics


Objectives:

Using paint%( method to dra: on Applets, Calling getUrap ics%( to dra: after Applet initialiLation, 6ntroducing different methods of Urap ics o Aect,

11.1 paint() Met$od


As you have seen in session 28 Applets have t:o important methods8 init%( and paint%(, /e have discussed init%( method earlier8 and it is no: the time to have a loo0 at paint%(, The code elo: sho:s this method, class 0!7pp extends 7pplet# pu$lic void paint%Urap ics g(# / / The o Aect g is used to dra: on the Applet8 for e4ample8 :e can dra: a line from the upper-left to lo:er-right corners of the Applet, This e4ample is sho:n in the code elo:, 1esult is sho:n in figure &&,& "in the ne4t page%, import java.a,t.*+ import java.applet.7pplet+ pu$lic class 3ine7pp extends 7pplet# pu$lic void init%(# resiFe%-KKI -KK(+ / pu$lic void paint%Urap ics g(# g.dra,3ine%KI KI getWidt %(I getHeig t%((+ / / The :ea0ness of paint%( method is that it is called automatically each time Applet repaints8 so you cannot control :hich graphics should e dra:n at runtime, To solve this pro lem8 :e o tain Urap ics o Aect from any other method using getUrap ics%( method,

Java La !anual y *asser Jaffal "$''+%

2=

Figure &&,&( Line Applet The follo:ing e4ample dra:s a circle at the upper-left corner of the Applet :ith the specified radius, ;otice ho: do :e use dra,Jval%( method, import java.a,t.*+ import java.a,t.event.*+ import java.applet.7pplet+ pu$lic class Circles extends 7pplet implements 7ction3istener# Text4ield value+ Vutton dra,+ pu$lic void init%(# resiFe%;KKI ;KK(+ dra, 9 ne, Vutton%)Dra,)(+ value 9 ne, Text4ield%(+ dra,.add7ction3istener%t is(+ add%value(+ add%dra,(+ / pu$lic void action8er"ormed%7ction6vent e(# Craphics g = getCraphics034 int diameter 9 Cnteger.parseCnt%value.getText%(( * -+ g/draw;2al0', ', diameter, diameter34 / / Figure &&,$ on the ne4t page sho:s an e4ample of circles Applet, Java La !anual y *asser Jaffal "$''+% 2+

Figure &&,$( Circles Applet

Exercises
&, /rite a Java Applet that has 2 int fields8 named x18 x-8 !18 !- and radius, Add t:o uttons to your Applet named GlineH and GcircleH, The ehavior of these uttons should e as sho:n in ta le &&,7 elo:, /!tton Line Circle F!nctionalit# Dra:s line from "x18 !1% to "x-8 !-% Dra:s circle centered on "x18 !1% and has the radius of the value entered in radius te4t field Ta le &&,7

Figure &&,- sho:s ho: should your Applet loo0 li0e,

Figure &&,-( 34ercise & Java La !anual y *asser Jaffal "$''+% 29

Session 12 Met#ods
Objectives 6ntroducing method structure, /riting and calling methods, Understanding return types and void methods, Differentiating et:een passing y value and passing y reference,

12.1 W$at Are Met$ods


6n programming8 there are some common procedures :e occasionally use8 li0e reading input from user8 printing output on the screen and so on8 those procedures are called methods, So far8 :e have introduced a num er of 0no:n methods li0e println and read3ine8 these methods are previously :ritten y developers of Java8 so :e can directly call and use them8 and it is clear this ma0es our :or0 easier, To :rite a method8 use the follo:ing definition format, static eturn!ype method"ame%param_1I param_2I ...I param_n(# //0et od $od! return return#alue+ / Using static 0ey:ord is not part of the format and there are more options for definition8 ut right no:8 and as :e :ill e calling our methods from the main method8 :e :ill use static in method definition, The contents of method definition are the follo:ing( static( ecause :e :ill e calling our methods from the main method :hich is static8 :e shall define our methods as static, 1eturn type( data type of the value this method :ill return8 for e4ample8 Cnteger.parseCnt%( method returns integer data type8 and println method does not return any thing8 so :e call it void method, To define a void method8 use void 0ey:ord instead of return type in definition, !ethod name( the name :e :ill use to call our method8 this name must e a valid varia le name ":e discussed naming rules earlier%, The naming convention for method name is li0e varia le nameO first :ord starts :ith lo:er case letter8 and rest of :ords start :ith upper case letters, List of parameters( method parameters provide an interface for providing input to method8 those parameters are varia les specified y data type and name8 separated y commas, !ethod could ta0e Lero to infinity parameters8 for e4ample8 println method ta0es one parameter as string and prints that string on the console, !ethod ody( statements of the method8 these statements are e4ecuted :hen method is called, return( :hen a method has return type "not void%8 :e have to terminate it using return 0ey:ord follo:ed y the varia le8 value or e4pression that represents the value method should return,

Java La !anual y *asser Jaffal "$''+%

5'

12.2 Writing and Ca''ing Met$ods


The follo:ing e4ample sho:s ho: to add t:o num ers using method calling, TechniDue &( method ta0es parameters and prints the sum( class 7ddition# pu$lic static void main%String&' args(# int x 9 <+ int ! 9 A+ sum%xI !(+ / static void sum%int aI int $(# int c 9 a M $+ S!stem.out.println%c(+ / / From the previous code you can notice the follo:ing( ;o method is defined in the ody of another one8 so :e define additional methods out of the loc0 of main method8 ut is still in the loc0 of the class, !ethod calling is simple and straight for:ard8 all :e have to do is to specify method name and pass the parameters, The method :e have :ritten is void8 so it does not contain return statement, /hen method is called8 the value of x is copied into matching method parameter :hich is a8 similarly8 the value of ! is copied into $8 so :hen c is calculated8 it contains the sum of x and !, TechniDue $( method returns integer that contains the sum of t:o num ers, class 7ddition# pu$lic static void main%String&' args(# int x 9 <+ int ! 9 A+ int F 9 sum%xI !(+ S!stem.out.println%F(+ / static int sum%int aI int $(# int c 9 a M $+ return c+ / / This time :e specified integer as return type of the method8 so :e call it and assign the return value to a ne: varia le F8 similar to parameter copying8 the value of c returned from the method is copied in F, The advantage of returning the value is that gives programmer more options to do :ith the result Java La !anual y *asser Jaffal "$''+% 5&

instead of Aust printing it out8 consider the situation in :hich :e need to use our method to calculate the sum of four values instead of t:o8 it can e reached using second techniDue through calling the method more than one time, int F 9 sum%sum%-I :(I sum%1I =((+//F 9 16n the a ove e4ample8 sum is called 7 times8 first time :ith $ and 7 so it returns 28 second time :ith & and 5 so it returns =8 and the third time :ith the result of t:o previous calls 2 and = so it returns &$ :hich is the final result that is stored in F, Lets have a loo0 at more comple4 methods8 and more useful ones, 6n the ne4t e4ample8 :e :ill try to simplify the process of reading input y putting all of its steps in a single method :ith single call, import java.io.*+ class 5eadingSimpli"ier# pu$lic static void main%String&' args(# String name 9 readString%)6nter !our name:)(+ int age 9 readCnt%)6nter !our age:)(+ S!stem.out.println%)Welcome ) M name(+ S!stem.out.println%)Wour $irt !ear is ) M %-KKA N age((+ / static String readString%String message(# S!stem.out.print%message(+ Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ tr!# String input 9 in.read3ine%(+ return input+ /catc %6xception e(#/ return ))+ / static int readCnt%String message(# String input 9 readString%message(+ return Cnteger.parseCnt%input(+ / / *ou can see ho: :e simplified reading from user y putting all necessary statements in a method called readString that ta0es a string as parameter8 this string is the message that :ill e displayed for the user as input prompt8 readString also returns a string that represents the value entered y user, /e use tr! and catc instead of thro:ing the e4ception8 this eases code :riting y handling the e4ception so :e no more need to declare our methods to thro: it, The second method :e used is called readDum$er8 it ta0es a string to display for the user8 passes it to readString and get the value returned from it8 then converts the returned value to integer and returns it, Java La !anual y *asser Jaffal "$''+% 5$

12.3 Passing b0 1a'ue and Passing b0 *e%erence


/hen methods are called8 there are t:o different :ays to pass parameters to method ody8 the common :ay is pass #y value8 in :hich values are copied from the parameters to the local values of the method8 consider the follo:ing code, //main # int x 9 K+ add%x(+ S!stem.out.println%x(+ / static void add%int i(# iMM+ / 6f you compile and run the code a ove8 the output you :ill see is '8 ecause the value of x :as copied into i8 then the value of i :as incremented8 ut x itself had never affected8 ecause :e did not pass x8 rather :e passed its value, >n the other hand8 all o Aects in Java are passed y reference8 that is8 the o Aect itself is passed to the method, A common e4ample of o Aects passed y reference is passing an array o Aect, Consider the follo:ing code, //main # int&' a 9 #KI 1/+ add%a(+ S!stem.out.println%a&K'(+ / static void add%int&' x(# x&K' M9 x&1'+ / 6f you compile and run the a ove code8 the output is &, <ecause arrays are passes y reference8 any change :e ma0e on the array x inside add method is reflected on array a8 ecause a and x are t:o references to the same o Aect,

12.( *ecursion
/e can :rite a method that calls itself8 these methods are called recursive methods8 a recursive method calls itself :ith different parameters to do certain Ao , For e4ample8 consider the follo:ing method that calculates the factorial of a given integer n, static int "actorial%int n(# //Vase case i"%n 99 K QQ n 99 1(# return 1+ / Java La !anual y *asser Jaffal "$''+% 57

//5ecursive call return n * "actorial%n N 1(+ / As you can see8 :e uild recursive methods using a #ase case and a recursive call8 the ase case is the condition at :hich :e stop the recursion, 6n the a ove code8 for e4ample8 the ase case is :hen n is eDual to ' or &8 oth num ers have the factorial &, The recursive call is e4ecuted if the ase case is not reached yet "i,e, there are more recursive calls until Ao is done%8 in case of factorial8 :e uild our recursive call using the mathematical fact :hich states that n* 9 n %n N 1(*8 so :e return n multiplied y the factorial of n N 1, For e4ample8 if :e tried to get the factorial of -8 the e4ecution of the method :ill flo: li0e this( &, "n R -% 6s - R ' or - R &? ;o8 so return - M "- S &%P "recursive call% $, "n R 7% 6s 7 R ' or 7 R &? ;o8 so return 7 M "7 S &%P "recursive call% 7, "n R $% 6s $ R ' or $ R &? ;o8 so return $ M "$ S &%P "recursive call% -, "n R &% 6s & R ' or & R &? *es8 so return & " ase case% 2, & is returned to the previous call and multiplied y $ 5, The result of multiplication "$% is returned to the previous call and multiplied y 7 =, The result of multiplication "5% is returned to the previous call and multiplied y +, The result of multiplication "$-% is returned y the method as final result,

Exercises
&, /rite a method named max8osition that ta0es an array of integers as array and returns the inde4 of the ma4imum element in the array, $, /rite a method named countC ar that ta0es t:o parameters( a string and a character8 then returns an integer representing num er of occurrences of the character in the string, 7, /rite a method named average that ta0es array of dou les as parameter then returns the average of the values inside the array, Sum calculation process should also e included in method called sum that ta0es the array as parameter and returns the sum of its elements, -, /rite a void method called reverse that ta0es a string as parameter and prints it in reverse order and inverted letter case8 for e4ample if the input is )Hava)8 the output should e )7T7j), .int( use integer values of characters to determine upper and lo:er cases, 2, *ou :ill e given a la on recursion on separate sheet and you have to solve it,

Java La !anual y *asser Jaffal "$''+%

5-

Session 1 -b9ect4-riented :ro!ra11in!; Classes and Me1bers


Objectives Understanding the concept of > Aect->riented programming, 6ntroducing classes and o Aects and differences et:een them, Understanding class mem ers and their properties, Understanding polymorphism and method C constructor overloading,

13.1 W$at is 2b=ect>2riented Programming8


> Aect->riented programming is ased on representing real life o Aects using soft:are8 this representation includes oth attri utes and ehavior8 for e4ample8 if :e :ant to represent a car in Java8 :e have to specify its attri utes and ehavior as the follo:ing( Attri utes( 3ngine ;o, Chassis ;o, Color, !anufacturer, !odel name, !anufacturing year, Transmission "Automatic8 ;ormal% ;um er of :heels, <ehavior( !ove for:ard, !ove ac0:ards, Steer right, Steer left, Shift up, Shift do:n, Start engine, Stop moving, Stop engine,

/e define this set of attri utes and ehavior in a class called Car8 after creating this class8 :e can define several o#(ects of this class8 that is8 the class defines common properties among all cars8 and each o Aect represents different car8 so :e may have8 for e4ample8 o Aects li0e these( &, Car A( Color( red8 !anufacturer( ;issan8 !an, year( &99+8 Transmission( ;ormal, $, Car <( Color( lac08 ;um er of :heels( 5, 7, A,Start engine8 A,!ove for:ard and so on, <y the same :ay8 :e can represent any real-life o Aect or any other o Aect at any field8 li0e circles and triangles in representation of geometrical shapes,

13.2 Writing C'asses in Java


So far8 you have een :riting a lot of classes8 ut these :ere far from the idea of representing real-life o Aects8 their rule :as only to include the main method that :e use to run the program, /e :ill start no: to :rite classes that represent real-life o Aects8 these classes does not necessarily have main method and hence are not e4ecuta le, For simplicity8 :e :ill leave the car e4ample to something more simpleO a class that represents circle shape, class Circle# //5adius is enoug to determine all circle attri$utes pu$lic dou$le radius+ Java La !anual y *asser Jaffal "$''+% 52

//Constructor pu$lic Circle%dou$le r(# radius 9 r+ / //0et ods pu$lic dou$le get5adius%(# return radius+ / pu$lic dou$le get7rea%(# return %radius * radius( * 0at .8C+ / pu$lic dou$le getCircum"erence%(# return - * 0at .8C * radius+ / pu$lic dou$le getDiameter%(# return radius * -+ / / The a ove class contained mem ers declared using pu lic 0ey:ord8 this 0ey:ord means that the mem er is accessi le from outside the class8 that is8 :hen :e declare an o Aect from the class Circle8 :e can access all pu lic mem ers8 even if :e declare the o Aect outside Circle class, *ou can also notice a method that holds the same name of the class and does not has a return value8 actually8 :e call it constructor8 constructors are used to determine the initial values necessary to uild o Aects and are used after ne, 0ey:ord in declaration8 for e4ample8 :hen declaring a Circle o Aect8 :e need to specify the radius of that circle8 ecause all circle measurements are ased on the radius8 so :e :rite a constructor that ta0es radius as dou le, 6f :e donBt :rite a constructor for our class8 Java creates a de)ault constructor that ta0es no parameters8 ut once :e :rite a constructor8 the default constructor is no more availa le, To declare a Circle o Aect8 :e use something similar to varia le declaration, Circle c1 9 ne, Circle%1K(+ Circle c- 9 ne, Circle%1-(+ S!stem.out.println%)c1 7rea is ) M c1.get7rea%((+ S!stem.out.println%)c- Diameter is ) M c-.getDiameter%((+ As sho:n a ove8 declaring o Aects is straight for:ard8 all you have to do is to specify class name from :hich you create the o Aect follo:ed y o Aect name8 then you initialiLe the o Aect using ne, 0ey:ord follo:ed y a constructor :ith necessary parameters, /hen :e call a mem er from the o Aect8 :e use dot >.> to access the mem ers then specify mem er name, As :e declared radius to e pu lic8 :e can access it Aust li0e any other mem ers to change the radius after declaration, Circle c1 9 ne, Circle%1K(+ Java La !anual y *asser Jaffal "$''+% 55

S!stem.out.println%)c1 7rea is ) M c1.get7rea%((+ c1.radius 9 1<+ S!stem.out.println%)c1 7rea is no, ) M c1.get7rea%((+

13.3 &i%%erent Pro"erties o% C'ass Members


<y properties of mem ers8 :e mean set of access rules that controls ho: these mem ers are accessed and called from the class or an o Aect of that class8 :e have introduced one of these properties in Circle class :hich is pu$lic, .ere is a list of access rules and their use( pu$lic( states that the mem er is accessi le from outside the class "from another class%, private( in the contrary of pu$lic8 private states that the mem er is accessi le only from :ithin the same class "a method or constructor inside the class%, static( y static8 :e specify that a certain mem er can e called :ithout declaring an o Aect " y calling class name follo:ed y dot then mem er name%, This is clear :hen declaring main method8 ecause :hen :e run our class :e do not declare an o Aect from it, 6t is important to 0no: that static mem ers cannot y called from non-static mem ers and vice versa8 thats :hy :e :ere declaring methods using static 0ey:ord8 ecause main is static8 :e have to declare any method :e :ish to call from main as static also, >n the varia le level8 the static varia le is shared among all o Aects of the class, For no:8 these properties are enough for us, The follo:ing e4ample clearly e4plains the difference et:een pu lic and private mem ers( class 7# private int value 9 1K+ pu$lic int getTalue%(# return value+ / pu$lic void setTalue%int ne,Talue(# value 9 ne,Talue+ / / class V# pu$lic static void main%String&' args(# 7 a 9 ne, 7%(+ S!stem.out.println%a.value(+ //6rrorI value is private / / Trying to access private mem er from outside the class reports compile-time error, 6t is a common practice in > Aect->riented that :e declare mem ers that store values as private and create set and get methods to access them8 set methods are called mutators8 and get methods are called accessors, 6n the a ove e4ample8 :e can use accessors and mutators methods o access the value stored in class 7 as the follo:ing( class V# pu$lic static void main%String&' args(# 7 a 9 ne, 7%(+ a.setTalue%::(+ //C anges t e value $! mutator met od S!stem.out.println%a.getTalue%((+ //prints :: Java La !anual y *asser Jaffal "$''+% 5=

/ / The follo:ing e4ample sho:s the difference et:een static and non-static varia les( class StaticTest# private static int a+ private int $+ pu$lic StaticTest%(# a 9 K+ $ 9 K+ / //7ccessors pu$lic static int get7%(# return a+ / pu$lic int getV%(# return $+ / //0utators pu$lic static void set7%int ne,7(# a 9 ne,7+ / pu$lic void setV%int ne,V(# $ 9 ne,V+ / / class 0ain# pu$lic static void main%String&' args(# StaticTest s1 9 ne, StaticTest%(+ StaticTest s- 9 ne, StaticTest%(+ S!stem.out.println%)s1 values:)(+ S!stem.out.println%)a 9) M s1.get7%( M )I $ 9) M s-.getV%((+ S!stem.out.println%)s- values:)(+ S!stem.out.println%)a 9) M s-.get7%( M )I $ 9) M s-.getV%((+ s1.set7%<(+ s1.setV%:(+ S!stem.out.println%)\ns1 values:)(+ S!stem.out.println%)a 9) M s1.get7%( M )I $ 9) M s-.getV%((+ S!stem.out.println%)s- values:)(+ S!stem.out.println%)a 9) M s-.get7%( M )I $ 9) M s-.getV%((+ / / Compiling and running the a ove code sho:s the follo:ing output( s1 values: a 9KI $ 9K s- values: a 9KI $ 9K

Java La !anual y *asser Jaffal "$''+%

5+

s1 values: a 9<I $ 9: s- values: a 9<I $ 9K So :hat can e concluded from the output? The value of $ is different for each o Aect8 changing the value of $ in o Aect s1 did not affect the value of $ in s-8 :hich is not the situation :ith a8 ecause changing the value of a in s1 had its effect in a :hen called from s-8 thats ecause static mem ers are shred among all o Aects as stated8 varia le a and methods related to it could e called from the class name directly as sho:n elo:( StaticTest.set7%1:(+ S!stem.out.println%s1.get7%( M ) ) M s-.get7%((+ 6n the a ove code8 println method :ill print &7 t:o times, 1emem er to declare static methods :hen dealing :ith static varia les8 ac0 to StaticTest class definition8 for e4ample8 you can notice that get7 and set7 methods are declared static,

13.( Met$ods and Constructors 2ver'oading


>verloading means to have more than one constructor or more than one method having the same name8 ecause there are more than one :ay to discriminate et:een methods8 including name and num er and type of parameters, To see ho: parameters can help in overloading8 consider the follo:ing constructors, class 5ectangle# private dou$le

eig tI ,idt + I dou$le ,(#

pu$lic 5ectangle%dou$le eig t 9 + ,idt 9 ,+ /

pu$lic 5ectangle%dou$le d(# eig t 9 ,idt 9 d+ / pu$lic 5ectangle%(# eig t 9 ,idt 9 1+ / / As the a ove e4ample illustrates8 :e have three constructors having the same name8 :hen :e call a constructor after ne, 0ey:ord8 depending on parameters :e specify a matching constructor is selected, 5ectangle a 9 ne, 5ectangle%(+//T ird constructor 5ectangle $ 9 ne, 5ectangle%<(+//Second constructor Java La !anual y *asser Jaffal "$''+% 59

5ectangle c 9 ne, 5ectangle%:I ;(+//4irst constructor 6t is important to realiLe that discriminating et:een constructors and methods holding the same name are( &, ;um er of parameters, $, >rder of parameters, 7, Types of parameters, So it is important to 0no: that parameter name has nothing to do :ith overloading8 the follo:ing e4ample sho:s this, //T is code generates error message. class 7# private int value+ pu$lic void setTalue%int t(# value 9 t+ / pu$lic void setTalue%int s(# value 9 s+ / / To etter understand classes and o Aects8 lets analyLe a :ell-0no:n statement :eBve een using repeatedly( S!stem.out.println%)Hello World)(+ S!stem is a name of a class8 inside S!stem class8 there is a pu lic and static mem er "o Aect% of class 8rintWriter8 the name of this o Aect is out, 6nside 8rintWriter class8 there is a pu lic8 non-static method called println that has several overloads,

Exercises
&, /rite a class that represents triangle named Triangle8 the class must have the follo:ing mem ers( private dou$le eig t+//Heig t private dou$le $ase+//Vase lengt pu$lic Triangle%dou$le I dou$le $(+//Constructor pu$lic void setHeig t%dou$le x(+//Sets eig t pu$lic dou$le getHeig t%(+//Uets eig t pu$lic void setVase%dou$le x(+//Sets $ase lengt pu$lic dou$le getVase%(+//Uets $ase lengt pu$lic dou$le get7rea%(+//5eturns t e area o" t e triangle $, /rite a class 6mplo!ee that represents an employee of some organiLation8 the class should contain the follo:ing mem ers( private int id+//6mplo!ee id private String name+//6mplo!ee name private int t!pe+//1 9 emplo!eeI - 9 manager Java La !anual y *asser Jaffal "$''+% ='

private dou$le $aseSalar!+//Vase salar! pu$lic 6mplo!ee%int GidI String Gname(+//Constructor pu$lic void setCD%int x(+//id mutator pu$lic void setDame%int x(+//name mutator pu$lic int getCD%(+//id accessor pu$lic String getDame%(+//name accessor pu$lic dou$le getSalar!%(+ //i" managerI add 1KL to $ase salar! pu$lic void setVaseSalar!%dou$le $s(+//sets $ase salar!.

Lab Extras
/hen :e :ish to specify a mem er from the class8 :e can use t is 0ey:ord8 t is refers to the current o Aect of the class, For e4ample8 to discriminate et:een local and glo al varia les in a class that have the same name8 :e use t is to specify :hich one in in the scope of :hole class, class SRuare# private int side3engt + pu$lic SRuare%int side3engt (# t is.side3engt 9 side3engt + / pu$lic void setSide3engt %int side3engt (# //glo$al local t is.side3engt 9 side3engt + / / As you can see8 :e have t:o varia les called side3engt 8 one is glo al for the :hole class and it is :here :e store the value8 and other is local for the constructor "or method%8 :hen :e call t is.8 :e are returning ac0 to the scope of the class8 so if :e are to specify any mem er after t is8 it has to e a glo al mem er, Another use of t is 0ey:ord is to call a constructor from :ithin another constructor8 t is itself represents the call8 so :hat you have to do is to pass parameters to t is Aust li0e the :ay you pass them to any constructor, This techniDue is common :hen :riting default constructor that does not reDuire user to specify parameters, class Tector# private dou$le lengt + private dou$le angle+ pu$lic Tector%dou$le lengt I dou$le angle(# t is.lengt 9 lengt + t is.angle 9 angle+ / pu$lic Tector%(# /* Calling t e previous constructorI Java La !anual y *asser Jaffal "$''+% =&

passing 1 as lengt t is%1I K(+ / /

and K as angle */

6f you need to specify additional statements in the constructor from :hich you are calling another constructor8 these statements should e specified after t is call8 in other :ords8 :hen using t is to call another constructor8 it should e in the first statement,

Java La !anual y *asser Jaffal "$''+%

=$

Session 1( '<ce,tions and 'rror Handlin!


Objectives: Understanding e4ception-thro:ing methods, Using tr!Ocatc to handle e4ceptions, Understanding and :riting custom e4ceptions,

1(.1 Exce"tion>T$ro-ing Met$ods


1untime errors appear in Java as e4ceptions8 e4ception is a special type of classes that could e thrown to indicate a runtime error and provide additional data a out that error, 6f a method is declared to thro: an e4ception8 any other method calls it should deal :ith this e4ception y thro:ing it "if it appears% or handle it, 1ecalling reading from user using Vu""ered5eader class8 :e used to declare main method from :hich :e call read3ine%( using t ro,s CJ6xception8 this ecause read3ine%( is declared to thro: that e4ception, import java.io.*+ class 5ead4rom2ser# pu$lic static void main%String&' args( t ro,s CJ6xception# . . . / / 6f :e :ish to :rite a method that simplifies reading from user8 you may :ant to declare it to thro: CJ6xception, import java.io.*+ class 5ead4rom2ser# pu$lic static void main%String&' args( t ro,s CJ6xception# String in 9 read%)6nter !our name: )(+ / pu$lic static String read%String message( t ro,s CJ6xception# S!stem.out.print%message(+ Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ String input 9 in.read3ine%(+ return input+ / / 6n the previous code8 if an e4ception occurs in read3ine%( method8 this e4ception is thro:n as it Java La !anual y *asser Jaffal "$''+% =7

is to read method8 :hich originally called it8 ecause this last one is also declared to thro: that e4ception8 it also thro:s it as it is to main method8 :hich originally called it8 finally8 the e4ception is thro:s to J#! :hich prints it out on the screen so the user can 0no: there :as error,

1(.2 try-catch Exce"tion Hand'ing


Another techniDue for handling runtime errors is to use tr!Ocatc loc0 to handle different types of e4ceptions and ta0e appropriate action instead of thro:ing them to the user, The format of tr!Ocatc loc0 is the follo:ing, tr!# //Statement%s( t at ma! t ro, exceptions /catc %6xception e(# //Statement%s( to andle exception. / For e4ample8 :e can place read3ine%( method :hich thro:s CJ6xception in a tr!Ocatc loc0 as the follo:ing, Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ String input+ tr!# input 9 in.read3ine%(+ /catc %CJ6xception e(# S!stem.out.println%)6rror occurred)(+ / /hen :e are e4pecting more than one e4ception8 :e can use several catch loc0s8 each one for different type of e4ceptions, For e4ample8 :hen reading a string using Vu""ered5eader and converting it to integer8 you can e4pect t:o different e4ceptions( CJ6xception and Dum$er4ormat6xception :hich occurs :hen the provided string cannot e converted to integer, Vu""ered5eader in 9 ne, Vu""ered5eader% ne, CnputStream5eader%S!stem.in((+ String input+ tr!# input 9 in.read3ine%(+ int x 9 Cnteger.parseCnt%input(+ /catc %CJ6xception e(# S!stem.out.println%)6rror reading input)(+ /catc %Dum$er4ormat6xception err(# S!stem.out.println%)T is is not a valid num$er)(+ /

1(.3 Writing Custom Exce"tions


6n some cases :hile developing our o:n applications8 :e need to specify custom types of Java La !anual y *asser Jaffal "$''+% =-

e4ceptions to handle custom errors that may occur during program e4ecution, A custom e4ception is a class that inherits 6xception class or any of its su classes8 since inheritance is eyond the scope of this course8 :e :ill define it as using extends 6xception in class declaration, class 0!Custom6xception extends 6xception# private String message+ pu$lic 0!Custom6xception%String message(# t is.message 9 message+ / pu$lic String toString%(# return message+ / / To use your custom e4ception8 declare an o Aect of it and thro: that o Aect using t ro, 0ey:ord, 6t is optional to declare the method containing t ro, statement :ith t ro,s 0ey:ord, 6n the follo:ing e4ample8 the program reads student id8 this id should e of length = and consists only of digits8 other:ise it thro:s an e4ception,

class CnvalidCD6xception extends 6xception# private String message+ pu$lic CnvalidCD6xception%String message(# t is.message 9 message+ / pu$lic String toString%(# return message+ / / Cmport javax.s,ing.*+ class StudentsData# pu$lic static void main%String&' args(# String idI name+ name 9 HJption8ane.s o,CnputDialog%)6nter student name)(+ id 9 HJption8ane.s o,CnputDialog%)6nter student CD)(+ tr!# ver"!CD%id(+ / catc %CnvalidCD6xception e(# Hoption8ane.s o,0essageDialog%nullI e.toString%((+ / Java La !anual y *asser Jaffal "$''+% =2

/ pu$lic static void veri"!CD%String id( t ro,s CnvalidCD6xception# i"%id.lengt %( *9 A(# t ro, ne, CnvalidCD6xception%)C eck CD lengt )(+ / tr!# 3ong.parse3ong%id(+ / catc %6xception err(# t ro, ne, CnvalidCD6xception%)CD can contain onl! digits)(+ / / /

Exercises
&, /rite a program that count ho: many prime num ers et:een minimum and ma4imum values provided y user, 6f minimum value is greater than or eDual to ma4imum value8 the program should thro: a Cnvalid5ange e4ception and handle it to display a message to the user on the follo:ing format(6nvalid range( minimum is greater than or eDual to maximum. For e4ample8 if the user provided &' as ma4imum and $' as minimum8 the message should e( 6nvalid range( $' is greater than or eDual to &',

Lab Extras
6n order to access the e4ception from the class it uses8 there is an important aspect one should e a:are of :hich is packaging8 pac0aging means putting t:o or more classes in the same package y stating pac0age name efore declaring class "and also e4ceptions%, /hen t:o classes are in the same pac0age8 it is possi le to access any one of them from the other8 for e4ample8 if :e have a class named Student that represents a student8 another class named 0ain to run a program that manages student information8 and a third class called StudentData6xception that represent any errors in student information8 :e can access Student and StudentData6xception classes from 0ain class and define several o Aects of it if :e use the follo:ing statement efore each class declaration( package studentin"o+ 6n ;et<eans 6D38 there is no need to manually :rite the a ove statement8 y adding ne: class to any pac0age of your proAect8 that class is automatically declared as a part of that pac0age, Figure &-,& sho:s pac0ages and classes in ;et<eans 6D3 proAect e4plorer,

Java La !anual y *asser Jaffal "$''+%

=5

Figure &-,&( )ac0ages "sho:n as golden cu es% and classes in ;et<eans 6D3 proAect e4plorer To access a class from its pac0age :e simply provide pac0age name follo:ed y dot B.B then desired class name, For e4ample8 :e can access !ain class sho: in Figure &-,& y calling it in the follo:ing statement( linkedlist.0ain

Java La !anual y *asser Jaffal "$''+%

==

You might also like