You are on page 1of 20


Java Programming: From Problem Analysis to Program Design, 5e

Chapter 1 An Overview of Computers and Programming Languages Chapter Objectives Learn about different types of computers Explore the hardware and software components of a computer system Learn about the language of a computer Learn about the evolution of programming languages Examine high level programming languages Chapter Objectives (continue ! !iscover what a compiler is and what it does Examine how a "ava program is processed Learn what an algorithm is and explore problem solving techni#ues $ecome aware of structured and ob%ect oriented programming design methodologies "ntro uction Computers have greatly affected our daily lives & helping us complete many tas's Computer programs (software) are designed specifically for each tas' *oftware is created with programming languages "ava is an example of a programming language An Overvie# o$ the %istory o$ Computers +he first device 'nown to carry out calculations was the abacus +he abacus uses a system of sliding beads on a rac' for addition and subtraction $laise Pascal invented the calculating device called the Pascaline in 1,-. An Overvie# o$ the %istory o$ Computers (continue ! /n 10112 "oseph "ac#uard2 a 3rench weaver2 discovered that the weaving instructions for his looms could be stored on cards with holes punched in them /n the early and mid 10..s2 Charles $abbage2 an English mathematician and physical scientist2 designed two calculating machines4 the difference engine and the analytical engine An Overvie# o$ the %istory o$ Computers (continue ! +he first computer li'e machine was the 5ar' / & $uilt in 11-& 6sed punched cards to feed data into the machine & 78 feet long2 weighed 7. tons2 and had 97.2... parts /n 11-,2 E:/AC (Electronic :umerical /ntegrator and Calculator) was built at the 6niversity of Pennsylvania & Contained 102... vacuum tubes and weighed some ;. tons An Overvie# o$ the %istory o$ Computers (continue ! /n 11712 6:/<AC (6niversal Automatic Computer) was built and sold the 6* Census $ureau /n 117,2 the invention of the transistors resulted in smaller2 faster2 more reliable2 and more energy efficient computers +his era also saw the emergence of the software development industry with the




+his era also saw the emergence of the software development industry with the introduction of 3O=+=A: and CO$OL2 two early programming languages /n 119.2 the microprocessor2 an entire CP6 on a single chip2 was invented An Overvie# o$ the %istory o$ Computers (continue ! /n 11992 *tephen >o?nia' and *teven "obs designed and built the first Apple computer in their garage /n 11012 /$5 introduced its personal computer (PC) 5odern day computers are very powerful2 reliable2 and easy to use & Can accept spo'en word instructions and imitate human reasoning through artificial intelligence An Overvie# o$ the %istory o$ Computers (continue ! A computer is an electronic device capable of performing commands +he basic commands that a computer performs are input (get data)2 output (display results)2 storage2 and performance of arithmetic and logical operations &lements o$ a Computer 'ystem A computer has two components & @ardware & *oftware %ar #are Components o$ a Computer Central processing unit (CP6) 5ain memory Central Processing (nit Arithmetic and logical operations are carried out inside the CP6 )ain )emory Ordered se#uence of cells (memory cells) & Each has a uni#ue location in main memory call the address !irectly connected to CP6 All programs must be brought into main memory before execution >hen power is turned off2 everything in main memory is lost 'econ ary 'torage Provides permanent storage for information Examples of secondary storage4 & @ard dis's & 3loppy dis's & 3lash memory & A/P dis's & C! =O5s & +apes "nput Devices !efinition4 devices that feed data and computer programs into computers Examples & Beyboard & 5ouse & *econdary storage Output Devices !efinition4 devices that the computer uses to display results Examples


1; 117





11 8.


Examples & Printer & 5onitor & *econdary storage "nput*Output Devices 'o$t#are *oftware consists of programs written to perform specific tas's +wo types of programs & *ystem programs & Application programs 'ystem Programs *ystem programs control the computer +he operating system is first to load when you turn on a computer Operating 'ystem (O'! O* monitors overall activity of the computer and provides services Example services & 5emory management & /nputCoutput & Activities & *torage management Application Programs >ritten using programming languages Perform a specific tas' =un by the O* Example programs & >ord processors & *preadsheets & Dames +anguage o$ a Computer Analog signals waveform eEgE Audio +ape 5achine language4 the most basic language of a computer A se#uence of .s and 1s (!igtial signal) Every computer directly understands its own machine language A bit is a binary digit2 . or 1 A byte is a se#uence of eight bits +anguage o$ a Computer (continue ! &volution o$ Programming +anguages Early computers programmed in machine language Assembly languages were developed to ma'e programmerFs %ob easier /n assembly language2 an instruction is an easy to remember form called a mnemonic Assembler4 translates assembly language instructions into machine language "nstructions in Assembly an )achine +anguage &volution o$ Programming +anguages @igh level languages ma'e programming easier Closer to spo'en languages Examples & $asic & 3O=+=A: & CO$OL




87 8,

89 80



& CO$OL & CCCGG & "ava &volution o$ Programming +anguages (continue ! +o run a "ava program4 1E "ava instructions need to be translated into an intermediate language called byte code 8E +hen the byte code is interpreted into a particular machine language &volution o$ Programming +anguages (continue ! Compiler4 a program that translates a program written in a high level language into the e#uivalent machine language & /n the case of "ava2 this machine language is the byte code "ava <irtual 5achine ("<5)4 hypothetical computer developed to ma'e "ava programs machine independent (run on many different type of computer platforms) Processing a Java Program Processing a Java Program +wo types of "ava programs4 applications and applets *ource program4 written in a high level language Loader4 transfers the compiled code (byte code) into main memory /nterpreter4 reads and translates each byte code instruction into machine language and then executes it +he programs that you write in "ava are typically developed using an integrated development environment (/!E)E +he /!E contains many programs that are useful in creating your programE Processing a Java Program (continue ! "nternet, ,orl ,i e ,eb, -ro#ser, an Java +he /nternet is an interconnection of networ's that allows computers around the world to communicate with each other /n 11,12 the 6E*E !epartment of !efenseFs Advanced =esearch Pro%ect Agency (A=PA) funded research pro%ects to investigate and develop techni#ues and technologies to interlin' networ's +his was called the internetting pro%ect2 and the funding resulted in A=PA:E+2 which eventually became 'nown as the H/nternetI +he /nternet allows computers to be connected and communicate with each other "nternet, ,orl ,i e ,eb, -ro#ser, an Java (continue ! >orld >ide >eb (>>>)2 or >eb2 uses software programs that enable computer users to access documents and files (including images2 audio2 and video) on almost any sub%ect over the /nternet with the clic' of a mouse Computers around the world communicate via the /nternetJ the >orld >ide >eb ma'es that communication a fun activity "nternet, ,orl ,i e ,eb, -ro#ser, an Java (continue ! +he primary language for the >eb is 'nown as @ypertext 5ar'up Language (@+5L) "ava applets are programs that run from a >eb browser and ma'e the >eb responsive and interactive +wo well 'nown browsers are 5o?illa 3irefox and /nternet Explorer "ava applets can run in either browser +hrough the use of applets2 the >eb becomes responsive2 interactive2 and fun to use Problem.Analysis.Co ing.&/ecution Cycle


;1 ;8

;; ;-






;1 -.


Problem.Analysis.Co ing.&/ecution Cycle Programming is a process of problem solving Algorithm4 a step by step problem solving process in which a solution is arrived at in a finite amount of time Problem.'olving Process 1E Analy?e the problem and outline the problem and its solution re#uirements 8E !esign an algorithm to solve the problem ;E /mplement the algorithm in a programming language2 such as "ava -E <erify that the algorithm wor's 7E 5aintain the program by using and improving it and modifying it if the problem domain changes Problem.Analysis.Co ing.&/ecution Cycle (continue ! Programming )etho ologies +wo basic approaches to programming design & *tructured design & Ob%ect oriented design 'tructure Design 1E A problem is divided into smaller sub problems 8E Each sub problem is solved ;E +he solutions of all sub problems are then combined to solve the problem +his process of implementing a structured design is called structured programmingE +he structured design approach is also 'nown as top down design2 bottom up design2 stepwise refinement2 and modular programmingE


Object.Oriente Design (OOD! /n OO!2 a program is a collection of interacting ob%ects An ob%ect consists of data and operations *teps in OO! 1E /dentify ob%ects 8E 3orm the basis of the solution ;E !etermine how these ob%ects interact A programming language that implements OO! is called an ob%ect oriented programming (OOP) languageE Object.Oriente Design (OOD! cont $ecause a data element in a complex program usually has many operations2 to separate operations from each other and use them effectively and in a convenient manner2 you use methods to implement algorithmsE 3inally2 to wor' with ob%ects2 you need to 'now how to combine data and operations on that data into a single unitE /n "ava2 the mechanism that allows you to combine data and operations on the data into a single unit is called a classE Chapter 'ummary A computer system is made up of hardware and software components Computers understand machine languageJ it is easiest for programmers to write in high level languages A compiler translates high level language into machine language





"ava steps to execute a program4 edit2 compile2 load2 and execute Chapter 'ummary (continue ! Algorithm4 step by step problem solving process in which a solution is arrived at in a finite amount of time +hree steps to problem solving4 analy?e the problem and design an algorithm2 implement the algorithm in a programming language2 and maintain the program +wo basic approaches to programming design4 structured and ob%ect oriented


Java Programming: From Problem Analysis to Program Design, 5e

Chapter 2 Basic Elements of Java


Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols, and identifiers Explore primitive data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Explore how mixed expressions are evaluated Chapter Objectives (continue ! earn about type casting Become familiar with the !tring type earn what an assignment statement is and what it does Discover how to input data into memory by using input statements Become familiar with the use of increment and decrement operators Chapter Objectives (continue ! Examine ways to output results using output statements earn how to import pac"ages and why they are necessary Discover how to create a Java application program Explore how to properly structure a program, including using comments to document a program "ntro uction Computer program# a se$uence of statements whose ob%ective is to accomplish a tas" &rogramming# process of planning and creating a program A Java Program #asics o$ a Java Program Java program# collection of classes 'here is a (main) method in every Java application program 'o"en# smallest individual unit of a program #asics o$ a Java Program (cont! !yntax rules# tell you which statements *instructions+ are legal, or accepted by the programming language, and which are not, !emantic rules# determine the meaning of the program instructions &rogramming language# - set of rules, symbols, and special words used to construct programs, Comments !ingle.line comments begin with // and can be placed anywhere in the line, Everything encountered in that line after // is ignored by the compiler, 0ultiple.line comments are enclosed between /1 and 1/, 'he compiler ignores anything that appears between /1 and 1/ %pecial %ymbols &eserve 'or s ((ey)or s! int

6 7

2: 22




24 25

26 27 28 29

int float double Char !ee -ppendix void public static throws return Java " enti$iers -re names of things, such as variables, constants, and methods, that appear in programs, 'he consist of# ; etters ; Digits ; 'he underscore character *<+ ; 'he dollar sign *=+ 0ust begin with a letter, underscore, or the dollar sign, are case sensitive, and can not be redefined, Java " enti$iers (cont! &redefined identifiers that you will encounter fre$uently are print, println, and printf, which are used when generating output, and next>nt, nextDouble, next, and next ine, which are used to input data, &redefined identifiers can be redefined, but it would be unwise to do so, "llegal " enti$iers Data *ypes Data type# set of values together with a set of operations Primitive Data *ypes "ntegral Data *ypes +alues an ,emory Allocation $or "ntegral Data *ypes Primitive Data *ypes ?loating.point data types ; ?loat value# precision @ 6 or 7 ; Double value# precision @ 25 Each of the 65536 values of the Anicode character set represents a different character, ?or example, the value 65 represents B-B, and the value 43 represents BCB, 'hus, each character has a specific non.negative integer value in the Anicode character set, which is called a collating se$uence, of the character, boolean# two values *logical *Boolean+ expression+ ; true ; false Primitive Data *ypes (cont! 'o represent real numbers, Java uses a form of scientific notation called floating.point notation, *'able 2.3 p,35+









notation, *'able 2.3 p,35+ 'he maximum number of significant digits, that is, the number of decimal places, in float values is 6 or 7, 'he maximum number of significant digits in values belonging to the double type is typically 25, 'he maximum number of significant digits is called the precision, !ometimes float values are called single precision, and values of type double are called double precision, -iterals (Constants! >nteger literals, integer constants, or integers# e,g, 23 and .67 ?loating.point literals, floating.point constants, or floating.point numbers# e,g, 22,34 and 25,6: Character literals, character constants, or characters# e,g, BaB and B5B Arithmetic Operators an Operator Prece ence ?ive arithmetic operators ; C addition ; . subtraction ; 1 multiplication ; / division ; D mod *modulus or remainder+ -n arithmetic expression is constructed by using arithmetic operators and numbers, 'he numbers and alphabetical symbols in the expression are called operands, Anary operator# operator that has one operand Binary operator# operator that has two operands Or er o$ Prece ence 2, 1 / D *same precedence+ 2, C . *same precedence+ Eote# anyway do everything in parentheses * + first Fperators in 2 have a higher precedence than operators in 2 *-ssociativity+ Ghen operators have the same level of precedence, operations are performed from left to right ./pressions >ntegral expressions ?loating.point or decimal expressions 0ixed expressions "ntegral ./pressions -ll operands are integers Examples 2C315 3Cx;y/7 x C 2 1 *y ; H+ C 28 Floating0Point or Decimal ./pressions -ll operands are floating.point numbers Examples 22,8 1 27,5 ; 34,5: x 1 2:,5 C y . 26,2 ,i/e ./pressions Fperands of different types Examples 2 C 3,5 6 / 4 C 3,9 >nteger operands yield an integer resultI floating.point numbers yield floating.point









>nteger operands yield an integer resultI floating.point numbers yield floating.point results >f both types of operands are present, the result is a floating.point number &recedence rules are followed *ype Conversion (Casting! Ased to avoid implicit type coercion 'o avoid implicit type coercion, Java provides for explicit type conversion through the use of a cast operator, -lso called type conversion or type casting !yntax *data'ypeEame+ expression Expression evaluated first, then type converted to data'ypeEame Examples *int+*7,9 C 6,7+ @ 24 *int+*7,9+ C *int+*6,7+ @ 23 *he class %tring -re used to manipulate strings !tring, character string, string literal or string constant ; !e$uence of Hero or more characters ; Enclosed in double $uotation mar"s ; Eull or empty strings have no characters ; Eumeric strings consist of integers or decimal numbers ; ength is the number of characters in a string %trings an the Operator 1 Fperator C can be used to concatenate two strings or a string and a numeric value or character Example 2.2: J'he sum @ J C 22 C 26 .-fter this statement executes, the string assigned to str is# J'he sum @ 2226JI %trings an the Operator 1 (cont! Consider the following statement# J'he sum @ J C *22 C 26+ >n this statement, because of the parentheses, you first evaluate num2 C num2 ; Because num2 and num2 are both int variables, num2 C num2 @ 22 C 26 @ 38 ; -fter this statement executes, the string assigned to str is# J'he sum @ 38JI "nput Eamed constant# ; - memory location whose content is not allowed to chang during program execution ; Declared by using the reserved word final ; >nitialiHed when it is declared Example 2.22 final double CEE'>0E'EK!<&EK<>ECL @ 2,54I final int EF<F?<!'ADEE'! @ 2:I final char B -EM @ B BI final double &-N<K-'E @ 25,75I "nput (continue ! Oariable# *name, value, data type, siHe+ ; - memory location whose content may change during program execution ; 0ust be declared before it can be used



0ust be declared before it can be used 0ay not be automatically initialiHed >f new value is assigned, old one is destroyed Oalue can only be changed by an assignment statement or an input *read+ statement Example 2.22 double amountDueI int counterI char chI int num2, num2I "nput (continue ! 'he assignment statement ; variable @ expressionI - variable is said to be initialiHed the first time a value is placed in the variable, >n Java, @ *the e$ual sign+ is called the assignment operator Example 2.23 int num2I //variable declaration int num2I double saleI char firstI !tring strI num2 @ 4I //assignment statement num2 @ 4 1 5 . 22I sale @ :,:2 1 2:::I first @ BDBI str @ J>t is a sunny day,JI "nput (continue ! Example 2.24 2, num2 @ 28I 2, num2 @ num2 C 27I 3, num2 @ num2I 4, num3 @ num2 / 5I 5, num3 @ num3 / 4I "nput (continue ! "nput (continue ! "nput (cont! Declaring an "nitiali2ing +ariables Declare and initialiHe these variables at the same time, ?or Example# ; int first @ 23I ; int second @ 2:I ; char ch @ B BI ; double x @ 22,6I ; double y @ 223,456I EF'E# 'here are 2 ways to initialiHe variable# ; -ssignment statement ; Kead statement "nput (continue ! !tandard input stream ob%ect# !ystem,in >nput numeric data to program

; ; ; ;


36 37 38




; !eparate by blan"s, lines, or tabs 'o read data# 2, Create an input stream ob%ect of the class !canner 2, Ase the methods such as next, next ine, next>nt, and nextDouble "nput (continue ! static !canner console @ new !canner*!ystem,in+I Example 2.26 static !canner console @ new !canner*!ystem,in+I int feetI int inchesI !uppose the input*you enter+is# 23 7 feet @ console,next>nt*+I // ine 2 inches @ console,next>nt*+I // ine 2 !ample run# feet @ 23 inches @ 7 "ncrement an Decrement Operators CC increments the value of its operand by 2 .. decrements the value of its operand by 2 !yntax &re.increment# CCvariable &ost.increment# variableCC &re.decrement# ..variable &ost.decrement# variable.. Output !tandard output ob%ect# !ystem,out 0ethods print println !yntax *output statements+ !ystem,out,print*stringExp+I !ystem,out,println*stringExp+I !ystem,out,println*+I Commonly 3se .scape %e4uences Pac5ages, Classes, ,etho s, an the import %tatement &ac"age# collection of related classes Class# consists of methods and are used to create Java programs, either application or appletI it is used to group a set of related operationsI and it is used to allow users to create their own data types, 0ethod# are designed to accomplish a specific tas" import %tatement Ased to import the components of a pac"age into a program Keserved word import %ava,io,1I ; >mports the *components of the+ pac"age %ava,io into the program &rimitive data types and the class !tring



43 44




; &art of the Java language ; DonPt need to be imported Creating a Java Application Program !yntax of a class



!yntax of the main method Creating a Java Application Program (cont! !ome predefined or standard methods, such as next>nt, print, and println, are already written and are provided as part of the system, 'ogether, the import statements and the program statements constitute the Java source code, 'o be useful, this source code must be saved in a file, called a source file, that has the file extension ,%ava 'he first line of the method main is called the heading of the method main, ?or example ; public static void main*!tringQR args+ 'he statements enclosed between braces * S and T+ form the body of the method main, 'he body of the method main contains two types of statements# ; Declaration statements are used to declare things such as variables, ; Executable statements perform calculations, manipulate data, create output, accept input, and so on, Debugging: 3n erstan ing an Fi/ing %ynta/ .rrors Ghen you type a program, typos and unintentional syntax errors are li"ely to occur 'herefore, when you compile a program, the compiler will identify the syntax error

49 5:

'he compiler produces the following errors# &rogramEum,%ava#9# BIB expected int num U &rogramEum,%ava#26# reached end of file while parsing T U 2 errors
52 52 53 54 55 56


Programming %tyle an Form Mnow common syntax errors and rules Ase blan"s appropriately !emicolon# also called statement terminator ; 'he set of rules that gives meaning to a language is called semantics ; &rompt lines are executable statements that inform the user what to do, >mportant to have well.documented code Vood practice to follow traditional rules for naming identifiers Avoi ing #ugs: Consistent, Proper Formatting an Co e 'al5through Java is a free.format language in the sense that programming instructions need not



be typed in specific columns -s you will discover, consistent and proper formatting will ma"e it easier to develop, debug, and maintain programs 'hroughout the boo", you will see consistent and predictable use of blan"s, tabs, and newline characters to separate the elements of a program Ghen you write programs, unintentional typos and errors are unavoidable 'he Java compiler will find the syntax rules and give some hints how to correct themI however, the compiler may not find logical *semantic+ errors Avoi ing #ugs: Consistent, Proper Formatting an Co e 'al50*hrough (continue ! 'ypically, programmers try to find and fix these problems themselves by wal"ing carefully through their programs !ometimes after multiple readings, a programmer may not be able to find the bug because the programmer may overloo" the piece of the code that contains the bug and therefore may see" outside help >f your program is properly formatted and you have used good names for identifiers, the person reading your program will have an easier time reading and debugging the program ,ore on Assignment %tatements variable @ variable 1 *expression+I is e$uivalent to variable 1@ expressionI !imilarly, variable @ variable C *expression+I is e$uivalent to variable C@ expressionI Chapter %ummary Basic elements of a Java program include# ; 'he main method ; Keserved words ; !pecial symbols ; >dentifiers ; Data types ; Expressions ; >nput ; Futput ; !tatements Chapter %ummary (continue ! 'o create a Java application, it is important to understand# ; !yntax rules ; !emantic rules ; Low to manipulate strings and numbers ; Low to declare variables and named constants ; Low to receive input and display output ; Vood programming style and form

59 6:




Java Programming: From Problem Analysis to Program Design, 5e

Chapter 3 Introduction to Objects and Input/Output


Chapter Objectives Learn about objects and reference variables Explore how to use predefined methods in a program ecome familiar with the class !tring Learn how to use input and output dialog boxes in a program Chapter Objectives (continue ! Explore how to format the output of decimal numbers with the !tring method format ecome familiar with file input and output Object an "e#erence $ariables "eclare a reference variable of a class t#pe $ In %ava& variables such as str are call reference variables $ 'llocate memor# space for data $ Instantiate an object of that class t#pe !tore the address of the object in a reference variable Object an "e#erence $ariables (continue ! int x( //Line ) !tring str( //Line * x + ,-( //Line 3 str + .%ava /rogramming.( //Line , Object an "e#erence $ariables (continue ! Object an "e#erence $ariables (continue ! Object an "e#erence $ariables (continue ! %sing Pre e#ine Classes an &etho s in a Program 0here are man# predefined classes 1pac2ages3& and methods 1collection of instructions3 in %ava Class Libraries4 collection of pac2ages /ac2age4 contains several classes Class4 contains several methods 5ethod4 set of instructions %sing Pre e#ine Classes an &etho s in a Program (continue ! 0o use a method& #ou must 2now4 $ 6ame of the class containing method 15ath3 $ 6ame of the pac2age containing class 1java7lang3 $ 6ame of the method 8 1pow3& it has two 1actual3 parameters $ 5ath7pow1x& #3 + x# %sing Pre e#ine Classes an &etho s in a Program (continue ! Example method call import java7lang( //imports pac2age 5ath7pow1*& 33( //calls power method // in class 5ath "ot 173 operator4 used to access the method in the class is called the member access operator 'he class (tring !tring variables are reference variables 9iven4 !tring name(

: ; < = )>







!tring name( $ !imilar statements4 name + new !tring1.Lisa %ohnson.3( name + .Lisa %ohnson.( 'he class (tring (continue ! ' !tring object is an instance of class !tring 0he address of a !tring object with the value .Lisa %ohnson. is stored in name !tring methods are called using the dot operator 'he class (tring (continue ! sentence + ./rogramming with %ava.( (ome Commonly %se (tring &etho s (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! (ome Commonly %se (tring &etho s (continue ! )nput*Output Input data ?ormat output Output results ?ormat output @ead from and write to files Formatting Output +ith print# ' s#ntax to use the method printf to produce output on the standard output device is4 !#stem7out7printf1format!tring3( or4 !#stem7out7printf1format!tring& argumentList3( format!tring is a string specif#ing the format of the output& and argumentList is a list of arguments Formatting Output +ith print# (continue ! argumentList is a list of arguments that consists of constant values& variables& or expressions If there is more than one argument in argumentList& then the arguments are separated with commas Formatting Output +ith print# (continue ! !#stem7out7printf1.Aello thereB.3( consists of onl# the format string& and the statement4 !#stem7out7printf1.0here are C7*f inches in Cd centimeters7Cn.& centimeters / *7-,& centimeters3( consists of both the format string and argumentList Formatting Output +ith print# (continue ! C7*f and Cd are called format specifiers # default& there is a one8to8one correspondence between format specifiers and the arguments in argumentList 0he first format specifier C7*f is matched with the first argument& which is the expression centimeters / *7-,

): ); )< )= *> *)







expression centimeters / *7-, 0he second format specifier Cd is matched with the second argument& which is centimeters Formatting Output +ith print# (continue ! 0he format specifier Cn positions the insertion point at the beginning of the next line ' format specifier for general& character& and numeric t#pes has the following s#ntax4 0he expressions in sDuare brac2ets are optional( the# ma# or ma# not appear in a format specifier Formatting Output +ith print# (continue ! 0he option argumentEindex is a 1decimal3 integer indicating the position of the argument in the argument list $ 0he first argument is referenced b# .)F.& the second b# .*F.& etc7 0he option flags is a set of characters that modif# the output format 0he option width is a 1decimal3 integer indicating the minimum number of characters to be written to the output Formatting Output +ith print# (continue ! 0he option precision is a 1decimal3 integer usuall# used to restrict the number of characters 0he reDuired conversion is a character indicating how the argument should be formatted Formatting Output +ith print# (continue !



*= 3> 3) 3* 33 3, 33: 3; 3< 3= ,> ,) ,*

Parsing ,umeric (trings Parsing ,umeric (trings (continue ! Parsing ,umeric (trings (continue ! 370o convert a string consisting of a decimal number to a value of the t#pe double& we use the following expression4 "ouble7parse"ouble1strExpression3 "ouble7parse"ouble1.3,-7;<.3 + 3,-7;< "ouble7parse"ouble1.8;<*7<;3.3 + 8;<*7<;3

,3 ,,

Parsing ,umeric (trings (continue ! Parsing ,umeric (trings (continue ! parse?loat is a method of the class ?loat and is used to convert a numeric decimal string into an eDuivalent value of the t#pe float parse"ouble is a method of the class "ouble& which is used to convert a numeric



,: ,; ,< ,= ->




-, --


parse"ouble is a method of the class "ouble& which is used to convert a numeric decimal string into an eDuivalent value of the t#pe double %sing Dialog #or )nput*Output Gse a graphical user interface 19GI3 class %Option/ane $ Contained in pac2age javax7swing $ Contains methods showInput"ialog and show5essage"ialog !#ntax str + %Option/ane7showInput"ialog1strExpression3 /rogram must end with !#stem7exit1>3( %sing Dialog #or )nput*Output (continue ! Parameters #or the &etho sho+&essageDialog JOptionPane Options #or the Parameter message'ype JOptionPane /.ample Formatting the Output %sing the (tring &etho #ormat Example 38)3 double x + )-7:;,( double # + *3-7;3( double H + =-*-7=<:,( int num + <3( !tring str( File )nput*Output ?ile4 area in secondar# storage used to hold information Iou can also initialiHe a !canner object to input sources other than the standard input device b# passing an appropriate argument in place of the object !#stem7in Je ma2e use of the class ?ile@eader File )nput*Output (continue ! !uppose that the input data is stored in a file& sa# prog7dat& and this file is on the flopp# dis2 ' 0he following statement creates the !canner object in?ile and initialiHes it to the file prog7dat !canner in?ile + new !canner 1new ?ile@eader1.prog7dat.33( File )nput*Output (continue ! 6ext& #ou use the object in?ile to input data from the file prog7dat just the wa# #ou used the object console to input data from the standard input device using the methods next& nextInt& next"ouble& and so on File )nput*Output (continue ! File )nput*Output (continue ! %ava file I/O process 1!0E/!3 )7 Import necessar# classes from the pac2ages java7util and java7io into the program *7 Create and associate appropriate objects with the input/output sources 37 Gse the appropriate methods associated with the variables created in !tep * to input/output data ,7 Close the files File )nput*Output (continue ! Example 38): !uppose an input file& sa# emplo#ee"ata7txt& consists of the following data4 Emil# %ohnson ,- )37->


Emil# %ohnson ,- )37-> !canner in?ile + new !canner 1new ?ile@eader1.emplo#ee"ata7txt.33( !tring first6ame( !tring last6ame( double hoursJor2ed( double pa#@ate( double wages( first6ame + in?ile7next13( last6ame + in?ile7next13( hoursJor2ed + in?ile7next"ouble13( pa#@ate + in?ile7next"ouble13( wages + hoursJor2ed K pa#@ate( in?ile7close13( //close the input file (toring (0riting! Output to a File 0o store the output of a program in a file& #ou use the class /rintJriter "eclare a /rintJriter variable and associate this variable with the destination !uppose the output is to be stored in the file prog7out (toring (0riting! Output to a File (continue ! Consider the following statement4 /rintJriter out?ile + new /rintJriter1.prog7out.3( 0his statement creates the /rintJriter object out?ile and associates it with the file prog7out Iou can now use the methods print& println& and printf with out?ile just the same wa# the# have been used with the object !#stem7out (toring (0riting! Output to a File (continue ! 0he statement4 out?ile7println1.0he pa#chec2 is4 F. L pa#3( stores the outputM0he pa#chec2 is4 F-:-7;<M in the file prog7out 80his statement assumes that the value of the variable pa# is F-:-7;< (toring (0riting! Output to a File (continue ! !tep , reDuires closing the file( #ou close the input and output files b# using the method close in?ile7close13( out?ile7close13( Closing the output file ensures that the buffer holding the output will be emptied( that is& the entire output generated b# the program will be sent to the output file thro+s Clause thro+s Clause (continue !





:) :*


:3 :,



If an output file cannot be created or accessed& the program throws a ?ile6ot?oundException ?or the next few chapters& we will simpl# throw the exceptions ecause we do not need the method main to handle the ?ile6ot?oundException exception& we will include a command in the heading of the method main to throw the ?ile6ot?oundException exception (1eleton o# )*O Program Programming /.ample: &ovie 'ic1et (ale an Donation to Charity Input4 movie name& adult tic2et price& child tic2et price& number of adult tic2ets sold& number of child tic2ets sold& percentage of gross amount to be donated to charit# Output4 Programming /.ample: &ovie 'ic1et (ale an Donation to Charity (continue ! Import appropriate pac2ages 9et inputs from user using %Option/ane7showInput"ialog /erform appropriate calculations "ispla# output using %Option/ane7show5essage"ialog Programming /.ample: (tu ent 2ra e Input4 file containing studentNs first name& last name& five test scores Output4 file containing studentNs first name& last name& five test scores& average of five test scores Programming /.ample: (tu ent 2ra e (continue ! Import appropriate pac2ages 9et input from file using the classes !canner and ?ile@eader @ead and calculate the average of test scores Jrite to output file using the class /rintJriter Close files Chapter (ummary /rimitive t#pe variables store data into their memor# space @eference variables store the address of the object containing the data 'n object is an instance of a class Chapter (ummary (continue ! Operator new is used to instantiate an object 9arbage collection is reclaiming memor# not being used 0o use a predefined method& #ou must 2now its name and the class and pac2age it belongs to 0he dot 173 operator is used to access a certain method in a class Chapter (ummary (continue ! 5ethods of the class !tring are used to manipulate input and output data "ialog boxes can be used to input data and output results "ata can be read from and written to files "ata can be formatted using the !tring method format