Professional Documents
Culture Documents
Java Lab Manual: Al-Quds University
Java Lab Manual: Al-Quds University
Java La !anual
"#ersion $%
&
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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,$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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,=34ercises,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=5 La 34tras,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,=5
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,
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 "$''+% -
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,
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,
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,
&'
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,
&&
6D3 ;et<eans Forte for Java <orland J<uilder !icrosoft #isual Studio <orland CNN !acromedia Dream:eaver !icrosoft #isual Studio ,;3T Sharp Develop
/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,
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
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,
6n Java "and other programming languages% there are t:o maAor types of errors( Compile-Time errors "Synta4 errors%, &-
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,
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
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)
!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
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-
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,
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,
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,
$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,
$-
*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,
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,
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:,
$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 ,
$=
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,
$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,
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,
//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,
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(+
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 %/(.
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,
72
Adding user controls to Applets, .andling events of user controls, 1eading and :riting values to user controls, 6ncluding e4ternal pac0ages,
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 =,&%,
7=
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(+
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
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
-'
: ; < = 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,
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+ / /
-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,
-=
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,
1K
-+
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)(+
-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,
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(+ / /
"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
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,
2-
Understand the concept of data ases, 6mplementing data ases using arrays, )erforming search and update,
/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,
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
25
Using paint%( method to dra: on Applets, Calling getUrap ics%( to dra: after Applet initialiLation, 6ntroducing different methods of Urap ics o Aect,
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+
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
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,
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.( *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,
5-
/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,
//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
/ / 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
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,
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 "$''+% =&
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,
=$
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,
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,
=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
==