Computer Programming I
Computer Programming I CS 121
Popular in Course
Popular in ComputerScienence
This 114 page Class Notes was uploaded by Kylee VonRueden on Wednesday September 30, 2015. The Class Notes belongs to CS 121 at Pace University - New York taught by Staff in Fall. Since its upload, it has received 13 views. For similar materials see /class/217106/cs-121-pace-university-new-york in ComputerScienence at Pace University - New York.
Reviews for Computer Programming I
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/30/15
CS121IS232 Arrays of integers Files and databases store information on a disk not in memory RAM Disk access is much slower than memory access so when we have a lot of data it makes more sense to store it in RAM while we are working on it There are a number of ways to store information in memory We will start with arrays An array is an indexed list that in Java begins at zero These numbers might represent the ages of 10 animals In a program this array might be declared by private int animalAges new int 10 This says that animalAges is the name of an array of 10 integers We have to get a new instance of the array in order to allocate space in memory for it Elements in an array are referred to by their indices For an array of 10 elements the indices run from 0 to 9 To access a single element in the array we use its index animalAges 4 12 or animalAges 4 Sets the value in the location to 13 The number in the square brackets is the location index The value contents stored in the array is denoted by animalAges 4 The entire array is denoted by animalAges We use a counter to go through the array If we know how many elements are in the array we can use a for loop int sum 0 for int count 0 count lt 10 count sum sum animalAges count Arrays can be used in programs to store any data type If the datatype is one of the simple types elements can be assigned directly to a location We will look at these rst Arrays of simple data can be initialized when they are declared To create the array above we could use int animalAges 7 9 4 8 12 6 5 19 l 2 This is only useful when you know in advance what your data will be We can change the AnimalManager class and have it read the age data from the le into an array called animalAges Once the data is in the array we can use a for loop to add up the ages in the array and then compute the average age The example below has the changes As you can see it is not all that different from the version that computed the sum while reading in the data That method is more efficient but we will see other examples later where using an array is necessary package zoo import javaioFile import javaioFileNotFoundException import javautilScanner The AnimalManager class gets the data from the le and computes the average age public class AnimalManager private int animalAges private int noAnimals Scanner leScan public AnimalManager animalAges new int 20 try leScan new Scanner new File quotanimalstXtquot catch FileNotFoundException e Systemoutp1intln quotFile not foundquot constructor public void getAnimals int count 0 while leScanhasNeXt O String type leScanneXtLine 0 int age leScanneXtInt 0 String name leScanneXtLine animalAges count age count Systemoutp1intln quotThe quot type quot quot name quot is quot age quot years old quot noAnimals count Systemoutp1intln quotThe number of animals is quot noAnimals getAnimals private double averageAge double average double sum 0 for int count 0 count lt noAnimals count sum sum animalAges count average Mathround sum noAnimals 100 1000 return average public void displayAverage double average averageAge Systemoutp1intln quotThe average age of the animals is quot average AnimalManager Pace University 1 N L 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 Java Basics 31 32 33 34 35 36 37 38 39 Introduction to Java Programming Dr Lixin Tao httpcsispaceedulixin Computer Science Department Pace University October 10 2005 Table of Contents Computer Systems and Programming Languages 1 Problem vs problem instances 1 Structure of a personal computer 1 CPU 2 Memory 3 Disk le system 5 Display 7 Keyboard 8 Computer Software 8 Java programming language 9 Software In tallatinn 12 Installation of Java J2SE 5 SDK 12 Customizing properties of Windows Explorer 14 EditPad installation and customization 17 Typical process for creating and running a Java program 17 A basic tutorial on DOS 19 A note for storing programs on Lab PCs 20 21 Basic Hello World program 21 Code style and commandline arguments 23 Java package 25 Best practice for organizing multiple class projects 28 Local variables expressions and 39 30 Basic builtin data types and type casting 33 Commandline arguments and loops 38 Calculator with ifelse 41 Calculator with switch statement 44 Calculator with exception processing 47 310 Copyright Dr Lixin Tao Pace University ltao paceedu This document should not be copied partially or in full or published in any form without the permission of the author This tutorial is the core teaching material for Dr Lixin Tao s section of C5121 It has precedence over the textbook All course work including assignments projects quizzes and the final exam is based on this tutorial This tutorial will grow as the class progresses in Fall 2005 Make sure you download its latest version from time to time from the Course Documents of Pace Blackboard for C5121 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 Conditionally interrupting loops Arrays Method declaration and invocation Java J quot Scopes oflocal variables Formatting outth Timing the evaluation of 7T Matrix multiplication Interactive commandline data input Windowbased data 39 p r Text le 39 p p Recursive vs iterative methods factorial Recursive vs iterative methods Fibonacci mlmhers Algorithm and Towers of Hanoi Bubble sort Binary search 50 51 53 61 63 68 71 75 79 87 92 94 1 Computer Systems and Programming Languages 11 Problem vs problem instances There are many realworld problems that need be solved efficiently Examples include weather forecast mail sorting chess playing and the realtime control of a satellite A computer system is used to help people solve complex problems efficiently A problem is a type of challenge A problem is made up of many problem instances For example sorting rearranging integers into a nondecreasing sequence is a problem and sorting integers in set 2 5 3 1 into sequence 1 2 3 5 is a particular instance of the sorting problem A computer is designed for solving complex realworld problems fast It is a tool It is the human being that will instruct the computer how to solve problems A program is basically a sequence of such instructions A computer program is written to solve a particular problem When we feed data problem instance to our running program we will solve a particular problem instance For example we may want to write a program to address the sorting integer problem Such a program is supposed to be able to solve any instances of the sorting integer problem If a program can only solve a particular instance like sorting 2 l 3 this program is of little use because it can only solve a special case When we say that a program is correct it mean the program can solve all instances of the problem for which the program is designed for as long as the input data problem instance are meaningful as an example feeding a 2 b to this program is not meaningful In addition if the program can also behave gracefully and not to give wrong answers when it is fed wrong input data we also say that the program is robust as an example fed with a 2 b a robust integer sorting program should refuse to print out any sequence of the input values and it should print out a message that the input data are not all integers 12 Structure of a personal computer A useful personal computer includes hardware software and data The computer hardware can understand and execute a small set of lowlevel simple machine language instructions like storing an integer in a memory location summing two oatingpoint numbers like 12 24 or printing a letter on the screen The computer software is made up of computer programs which are sequences of machinelanguage instructions for the computer hardware to execute and solve problems The data represents problem instances and the solutions to them While the computer hardware is normally designed for general purpose a program that runs on it is designed to solve a particular problem Given input data for any instance of that problem the program will use the hardware resources to compute the solution to the problem instance Computer Program Figure 1 Computer as a data transformer Computer hardware is typically made up of one CPU central processing unit for computing one main memory for storing programs and data that are processed by the CPU a hard disk for storing programs and data on permanent basis surviving power shutdown a keyboard for getting user input and a display for displaying computer output All data processing is conducted by the CPU When you shutdown your computer all data in the CPU and main memory will be lost But programs and data saved on a hard disk will not be affected by power shutdown While hard disk is safe for storing large amount of programs and data it is too slow relative to the CPU s working speed The main memory functions like a highspeed copy of the active those currently processed by the CPU programs and data for improving the CPU s performance Disk Programs Data Keyboard Display System Bus Figure 2 Computer organization The CPU the main memory the hard disk the keyboard and the display are all devices connected through a system bus as shown in Figure 2 At any instance only one device can broadcast data on the system bus but every device on the system bus can listen to the data broadcast on the system bus 13 CPU All computing is conducted by the CPU CPU is like the brain or control center of a computer A CPU is designed to understand a small set of machinelanguage instructions The CPU is responsible for reading successive instructions as well as data needed by the instructions of a program stored in the main memory and carrying them out All CPU activities are synchronized by the cycles of a digital clock This clock repeats CPU cycles and the number of CPU cycles repeated during each second is called the number of Hz indicating the speed of the CPU A CPU uses a program counter PC to remember the address for the next program instruction in the memory to be executed Just before the execution of a program the program counter is set the memory address of the first in logical sense not necessarily the physical first instruction for example a program may start its execution from instruction 5 instruction of the program to be executed After the execution of each machine instruction the value of the program counter is updated for the address of the next instruction to be executed Since normally the instructions of a program are stored in successive memory locations and are supposed to be executed in that order the new value of the program counter is typically 1 plus its old value If a program needs to jump out of order say jumping back by ten instructions to execute an instruction at a particular memory address because some condition or event happened the particular memory address will be set in the program counter for replacing the default successive address A CPU uses a few from 8 to around 100 registers for speeding up its work A register is a small data storage just large enough to hold a memory word Registers are really scratch paper for storing the instruction under execution and the intermediate results of instruction execution For example to execute instruction Ml llt M9M10 this instruction will first be copied in an Instruction Register IR two general purpose registers will be used to hold value copies of memory words M9 and MlO another generalpurpose register will be used to hold the summation of the previous two registers and resulting value of the last register will be then copied into memory word Mll Since the registers are part of the CPU chip they work at the same speed as the CPU cycle which is much faster than the memory cycles the heartbeats used to synchronize memory accesses The execution of an instruction by the CPU is conducted in a few phases synchronized by the CPU clock cycles as described below and these phases repeat to execute a program 1 The program counter s value is used as a memory address to read out the instruction from the memory location with that address and the instruction is saved in the CPU s Instruction Register IR 2 The program counter s value is set to the memory address for the next instruction to be executed 3 The value of IR is decoded and the data needed for the execution of the instruction is read from memory and copied into some generalpurpose registers 4 The operation of the instruction is carried out and the result data is saved in a general purpose register 5 The result data is copied from the generalpurpose register to its destination memory location 6 Go back to step 1 The speed of a CPU is determined by CPU cycles per second and a CPU cycle is the basic time unit for the CPU to do some work Each machine instruction takes one to ten cycles to get executed to make our examples simpler we assume each machine instruction takes one CPU cycle to get executed Today s PC CPUs normally have a cycle of 15 GHz to 35 GHz where a GHz is one giga Hertz or 230 cycles per second 14 Memory The basic data storage unit of a computer is a bit A bit can store either 0 or 1 which may be used to represent false and true or off and on of an electrical switch respectively Eight consecutive bits make a byte A byte can hold an integer of values between 0 and 255 The value of a byte can represent a key that we type on the keyboard A computer word consists of two bytes 16 bits used by CPUs of 1970s four bytes 32 bits typical of today s PC that will soon be outdated eight bytes 64 bits for the coming generation of PCs and for business computing great effect for dynamic computer games or sixteen bytes 3 128 bits for supercomputers that need extremely high computing precision depending on the hardware CPU architecture and bus architecture The computer s main memory is a onedimensional array sequence of memory words Each word is assigned a unique address starting from zero 0 There are machine instructions for storing an integer into a memory word or reading out the value of a memory word A memory word is just a cell for storing program or data The most important properties of a memory are 0 When a new value is stored into a word the word s old value is erased and replaced with the new value 0 When the current value of a word is read the value is not modi ed by the reading process Other forms of data including alphabetic data oatingpoint numbers and machine instructions are encoded into integers and stored in one or multiple consecutive words If a piece of data takes four words to store say at addresses 200 201 202 and 203 then we say that the piece of data is stored at memory address 200 the smallest word address used for storing that piece of data A computer memory is for storing both computer programs and data to be manipulated by the programs We normally use symbol M to denote the main memory and use Mi to denote the ith word of memory M Here i is called an index of M or the address of the memory word Therefore the main memory is made up of a long sequence of computer words represented as M0 Ml M2 M3 M4 PCs main memory typically contains 256 MB mega bytes which is the same as 220 bytes 512 MB or 1 GB giga bytes which is the same as 230 bytes A useful but smaller memory unit is one KB k bytes which is the same as 210 1024 bytes For exaggerating the actual memory or disk size the computer memory and hard disk manufacturing companies usually use 103 to denote a K 106 an M mega and 109 a G giga which are smaller than our original definitions When a computer is shut off the power the data in the memory will be lost When a computer is turned on each memory word will have random data that we cannot predict One important task of a program is to initialize computer words that it uses before it starts to use those words in its computation Program OOOQQMbwwt O Data Figure 3 Memory with program and data Figure 3 shows an example main memory with 17 words The rst 9 words at addresses 0 through 8 are storing a program The last 8 words at addresses 9 through 16 are storing data At the very beginning the program counter PC has value 0 and machine instruction M9 lt 2 in memory word MO is executed which stores integer 2 into memory word M9 the memory word with address 9 Then the program counter PC automatically increases its own value by l to become 1 and points to the next machine instruction In the next CPU cycle machine instruction MlO lt l in Ml is executed which stores integer l in memory word MlO the memory word with address 10 The program counter PC then automatically increases its own value by l to become 2 and points to the next machine instruction In the next CPU cycle machine instruction Mll lt M9 M10 in M2 is executed which retrieves values in memory words M9 and MlO adds them together and stores the summation result into memory word Ml l the memory word at address 11 15 Disk le system Hard disk is used for storing programs and data on longterm basis Programs and data stored on a hard disk can survive power shutdowns Today s PC hard disks have capacities from 10 GB to 300 GB where GB means giga bytes or 230 bytes Today s computers normally boot up from its primary hard disk where a reserved disk space is for storing a special program for loading the core of an operating system into the main memory The programs and data are stored on hard disks in the unit of les A le is a named unit of binary or alphabetic text data of any length The name of a le typically has two parts separated by a period the le name stem and the le name extension For example a Java source code le may have name Welcomejava where Welcome is the le name stem which is supposed to be a concise name characterizing the purpose of the le and java is the le name extension which indicates the type of data that is stored in this le By convention java as a le extension is reserved by Java source code les The le name extension tells a computer how to interpret the data stored under a particular le name Since we are encouraged to choose meaningful le names it is possible that we incidentally create two les with the same name leading to le name con icts the data of the second instance will replace that of the rst instance This leads to the introduction of the concept of le system directories A le system directory can contain multiple les as well as other directories A le system directory is a special le containing a table of contents for all les under its control Two different les can have the same name as long as they belong to two different directories File system directories are also referred to as le system folders When a le directory is deleted all of its contents are deleted too C D cs121 Program Files 0138868 05389 baslcs homework Jalva pro 39ect classes projects prol39ect jdk10704 Welcome class Welcomejava bin1bjre javac exe java exe bin lib java exe Figure 4 A sample file system The le directories of a PC constitute a forest of directory trees one tree for each hard disk partition a disk partition is a logical disk a hard disk can contain multiple disk partitions In computer science the root of a tree is drawn at the top and its sons and descendants below the root All the entities in a tree are called nodes In our case a node is either a le or a directory There is a line connecting a father node and a son node in the trees Figure 4 is a simpli ed le system for a particular PC We assume that the PC has two hard disk partitions C and D and they are the roots of their own directory trees respectively Those nodes of the trees with names in Italic font are les and the others are directories The absolute path of a file or directory is the concatenation of all the node names on the path connected lines from the tree root to the le or directory separated by in Windows and in UnixLinux For example the absolute path of le Welcomejava in our example is Ccs12lbasicsprojectWelcomejava When we work in a Command Prompt window the Command Prompt window will work in a particular le system directory called the current working directory for each directory tree Inside a working directory you can use relative path to denote a le or directory under the sub tree rooted at the current working directory by concatenating all the node names on the path from the current working directory to that speci c le or directory excluding the current working directory separated by in Windows and in UnixLinux As an example if the Command Prompt window is currently working in directory Ccs121basics then the relative path of file Welcomejava from the current working directory is projectWelcomejava and if the Command Prompt window is currently working in directory Ccs121basicsproject then the relative path of le Welcomejava from the current working directory is Welcomejava Inside a Command Prompt window we can change the working directory by using the cd change directory command There are two special symbols used for representing two relative 6 directories for the current directory and for the parent directory Let us assume that the Command Prompt window is now working in directory Ccs121 The following are some examples for changing the working directory Working Command Comments 16 Display A display is a screen used to display program outputs and graphic user interfaces GUI for your programs Data printed by a program will go to one of the windows on the computer display Inside your program you will choose which window will be used to display your data If you are printing characters each window in text mode maintains a display cursor indicating where printing will happen The display cursor will be set initially to the first printable position of a window In a Command Prompt window the display cursor is represented by a blinking underscore The next character to be printed will be printed at the current location of the cursor and the cursor will move to the right by one space After a New Line character is printed the cursor will move to the beginning of the next line If you are drawing graphic objects like a dot a line or a circle the basic drawing unit is a pixel picture element and the drawing window in graphics mode will use a 2D coordinate system as show in Figure 5 where the origins are at the left upper comer the xaxis goes rightward and the yaxis goes downward Figure 5 also shows a pixel located at point 3 2 Each pixel can take on one of many possible colors 00 e x 1 062 3 V y Figure 5 Display coordinate system with a pixel at 3 2 A typical VGA display can support an array matrix of 640 x 480 pixels 640 rows each row having 480 pixels where each pixel can display various colors Most of today s displays have much higher screen resolution which means the number of pixels per unit length in each row or column of the screen 17 Keyboard A keyboard is used to enter input data to a program running on a computer A computer may run several programs at the same time but only one program is the active program for receiving input data from the keyboard Some programs run in windows To make the program behind a window active just click any where in the window The keyboard is used to enter various characters including alphabetic characters like a b A B numeric characters like 1 2 3 punctuation keys like and special function characters like PageUp PageDown Ctrl Control Alt Alternative and Esc Escape While most key strikes will generate visible characters some will not as Ctrl and Alt The space key the long key at the bottom middle of the keyboard the Enter key new line key and the Tab key can be used to generate white spaces A single space key strike will insert a single space character at the current cursor location of the display A single Enter key strike will insert a new line character A single Tab key strike will insert a single Tab character or a prede ned number of space characters We say that the space key the Enter key and the Tab key all generate white spaces 18 Computer Software Computer software is computer programs There are two categories of software system software and application software System software is for managing computer system hardware and software for their more efficient usage and providing proper abstraction of the computer system for easing the work of application developers and end users The most important example for system software is operating systems like Windows Unix and Linux Java compiler and Java virtual machine as well as CC compilers are also system software Application software is 8 software for solving problems in a particular application domain like word processing games engineering computation and bank transaction processing Computer software is implemented with programming languages The computer hardware can only understand very primitive machine instructions like adding two integers While in theory we can implement all software in machine instructions in practice it will be too complex and we may not be able to write correct programs when they are large Highlevel programming languages like C C and Java allow programmers to write readable programs with powerful statements similar to instructions or commands and let a compiler or an interpreter to convert the programmerfriendly programs into machine instructions before they are executed run Java is one of the most important highlevel programming languages 19 Java programming language Java is a highlevel programming language designed for problem solving Unlike natural languages that use very exible set of vocabulary and exible syntax a programming language uses a small set of key or reserved words and arranges these reserved words in very strict patterns to compose statements The computer hardware can only understand a set of lowlevel instructions of the socalled machine language Different computer hardware architectures define their unique machine languages Instructions at this level can only deal with basic operations like reading a key strike on the keyboard saving a number at a particular memory address reading value from a particular memory address and adding two numbers To solve a problem a programmer needs to write a very long sequence of such machine language instructions called a machinelanguage program Given the program and input data a computer can compute the output While a machine language is native to the computer hardware and therefore can be executed most efficiently the complexity of machinelanguage programs is overwhelming This motivated the creation of various highlevel programming languages Java is one of the latest highlevel programming languages In a highlevel language the instructions are called statements Each highlevel statement is the abstraction of a sequence of machine instructions As a result a high level program is much shorter than its machineinstruction counterpart and it is much easier to write and maintain understand and modify But a computer cannot understand a highlevel language program directly A highlevel language program is called source code which needs be translated into machine instructions also called executable code before computer hardware can understand and execute it A compiler is a computer program that transforms a highlevel language source code into machinelanguage executable code and saves the executable code in a computer file executable file for later execution The translation process takes time For the same source code the compiler needs only to translate it once Because the compiler can carefully analyze the complete source code a compiler can generate very efficient machinelanguage code in the sense that the latter is shorter and executes faster on the computer hardware Given a new set of input data we only need to run execute the machinelanguage code on it feed the data to the executable code to get computation results Languages aiming at high execution efficiency including C C COBOL FORTRAN and Pascal usually use this compilation approach 9 An interpreter is a computer program that reads the source code oneline at a time translates each source code line into a sequence of equivalent machine instructions executes them throws them away and repeats on the next source code line The final execution result of an interpreted program should be the same as that of a compiled program But in the interpreted case we don t need the separate compilation or translation phase Since we don t save the machine code resulted from the interpretation in a computer le we need to transform the source code lines again every time we use the program to solve a new problem instance Since the source code transformation is repeated each time we run it an interpreted language usually runs slower than its compilationbased counterparts Basic and Visual Basic are examples of interpreted programming languages Java as well as C uses a combination of the above two processes Fundamentally Java is an interpreted language since its main objective is not runtime efficiency but to fulfill its value proposition of write once and run everywhere A Java source code file is first compiled into a socalled bytecode f11e also called a class file which is a standardized binary representation of the source code We use Java command javac to compile a Java source code file When we need to run this Java program we use the Java interpreter also called the Java virtual machine to transform each bytecode statement of the program into a sequence of equivalent machine instructions for execution on the computer hardware We use Java command java to interpret or execute a Java bytecode file This twostep mechanism has a few advantages 1 The bytecode is hardware and operating system independent For each Java source code file we only need to compile it into its bytecode form once We can then distribute the same bytecode file to any computer on the Internet that needs to run the program 2 While Java source code is human or characteroriented a bytecode file is machine oriented The interpretation of bytecode statements into machine code is much more efficient than doing that directly from Java source code 3 Before computer hardware finally interprets each bytecode statement for execution it has a last chance to examine the byetecode statement to see whether it could be dangerous to the computer system If it does the interpreter could stop its execution and report problems to the user Java was developed by a team lead by James Gosling at Sun Microsystems in 1995 Java is a generalpurpose programming language and is based on the objectoriented computing paradigm Java is especially suitable for developing Web applications Much of Java s interesting functions do not have counterparts in C or C At a lower level a Java program is made up of a sequence of identifiers organized in a pattern satisfying the syntax requirement of a valid Java program An identi er is a sequence of letters digits underscores 7 and dollar signs and the first character of an identifier cannot be a digit Example identif1ers include class public x value Hellol HelloWorld and squareRoot Identifiers are case sensitive so x is different from X Java identifiers should be concise but meaningful indicating their intended usage An identifier is often the concatenation of a few words with the first letter of each word capitalized and the others in lowercase the first letter of the first word will be capitalized if the identifier is the name of a class in lowercase otherwise A few dozens of identifiers are called reserved words or keywords of Java and they have predef1ned meanings in Java and they cannot be used for other 10 purposes Identi ers class public static void and package are examples of reserved words Reserved words are all in lowercase Identi ers can be of any length At a higher level a Java program is made up of one or more classes and each class contains one or more methods A method is a sequence of operations to be executed by the CPU A class is a container for holding related methods Each class has a name with the first letter capitalized Each method has a name with the rst letter in lowercase The classes of a program may be distributed in a few Java source code les Java also uses variables for holding intermediate values A variable s name is an identi er with the rst letter in lowercase 2 Software Installation 21 N E 4 Installation of Java JZSE 5 SDK Visit StartlSettingleontrol PanellAddRemove Programs to remove any of existing installations of Java SDK or JRE Java runtime environment Make sure that you reboot the system before you install any new software After rebooting delete the installation directories for those removed installations Let a PC have multiple Java installations may lead to confusion Visit httpiava sun com i25e15 J 39 J isn with a Web browser Click on hyperlink Download JDK 50 Update 5 to get to the J2SE 5 SDK download page Check the checkbox for accepting license agreement In the section for Windows Platform 7 J2SE TM Development Kit 50 Update 5 section click on the hyperlink Windows Of ine Installation Multilanguage to download the installation le jdk175705windows i586pexe to your PC The le has 5749 MB In a Windows Explorer click on the downloaded le jdk175705windowsi586pexe to start its installation Accept the license agreement and take all default values By default your J2SE 5 installation directory will be CProgram FilesJavajdk150705 The installation of J2SE 5 will take about 450 MB of disk space The installation of JDK 15 includes the installation of an embedded JRE Java Runtime Environment 15 After the JDK 15 is installed you will be prompt for installing an external version of JRE into CProgram FilesJavajre150705 This external JRE s installation is important to you if you need to enable Java support in your Web browsers To run Java compiler javac and interpreter java on the commandline you need to add the bin directory of your J2SE 5 in the value of the environment variable PATH An environment variable is a memory location where the operating system keeps some values for programs to access When you type a command javac and then Enter in a Command Prompt window for example the operating system will try to find whether there is an executable le named javacexe javabat or javaccom with the value of your PATH The value of PATH is a sequence of directories separated by semicolon in Windows and colon in UnixLinux Period is used to represent the current working directory the directory in which the Command Prompt window is working The operating system will sequentially try to nd an executable le for javac in the directories listed in the value of PATH from left to right The rst executable le with le stem name javac will be executed If the operating system completed the search in all directories on the PATH speci ed by the PATH s value and none of the executable les for javac could be found the operating system will declare that javac is not recognized as an internal or external command operable program or batch file 4 Rightclick on My Computer and choose Properties from the popup menu In the System Properties window click on the Advanced tab Click on the Environment Variables button In the bottom System variables area of the Environment Variables pane click on button New to launch the New System Variable pane Enter value JAVAiHOME for variable name and value CProgram FilesJavajdk150705 for Variable value as shown below If you use a Java SDK installation at another directory you should update the variable value accordingly New System Variable variable name JAWLHOME variable yalue Prnqlam Fuss an as click on the OK button to compete the de nition Now click to highlight the line for Path in the System variables area and then click on the Edit button n e Vanable value textbox move the cursor to the left end and insert quotnJA AHOMEbin at the beginning as shown below Here VuTAVAiHOME W is to be replaced with the 39 39 39 m n7HOME b L 39 Edit System Variable Variable game Path Variable yalua SystEmRnnt osys Click on the OK button to complete the modi cation Now you also need to set up the value of environment variable CLASSPATH which is used by java and javac to nd needed Java classes When you type java Hello the mmand javaexe will follow the value of environment vana s om le to right to search for t e rst le Helloclass to execute The value of CLASS ATH is a sequence of directories for searching for Java class les Period represents the current working directory in which you type multiple instances of le Helloclass in different directories listed by the value of c s PATH only the rst one will be executed Lfthere is no le Helloclass in any ofthe directories listed b the value of CLASS command java will dec are that PATH Exczptlml m thrzad mam 39 java lung NaclassDefFoundErmr 2110 u don t set the value or y dault CLASSPATH has period for the current working directory as its value Cclasses This will be the directory Java class les In the bottom System variables area of the Environment Variables pane click on button New to launch the New System Variable pane Enter value CLASSPATH for variable name and value cclasses for Variable value as shown below The value of CLASSPATH is a list of semicolon 39 39 Th9 fir t npn39nd 4 39 39 In Windows Explorer create a new directory where we keep all New System Variable variable name lclkssrkru Variable lame click on the OK button to compete the de nition click on the OK button of the Environment Variables pane to shut it down click on the OK button of the System Properties windowto shut it own 6 To test whether you have done correctly click on Stan Run type cmd in the Open box and click on the OK button to start a Cummami Pmmpt window Type java and the Enter key in the window If you see usage information of javac you h n intintp 22 Customizing properties of Windows Explurer F r so ware developers Wmduws Explorer should show detailed view of les and le extensions ofknown types should be displayed all the time It will also be convenient ifwe can easily launch a new Cummzmd Pmmpt window from a Wmduws Explorer and change directory automatically to the directory that we choose in the Wmduws Explorer This section introduces some useful 39 39 n in uetter 39 39 1 click on StanlAll programslAccessorieleindows Explorer to launch an instance of Wmduws Explorer 2 click on V directory will a size type 3 click on Toolleolder Options to launch the Folder Opnuns pane In the Fulders Opnuns pane click on tab View Make sure that you have checked on options Display the full path in the address bar and unchecked options Hide extensions for known le types and Remember each folder s view settings as shown in the following screen capture ievaetails to tum on the detazled waw In the right pane each le or 5 Folder Optlons lGai39ieral VlEW Fiie g oiiiiiie Filasl Foldevviews E a Van can applytha View such as Deiaiis mTiies hatynu are usingiuimisiuidsiiu alltuldara Applym All Fnldars BeseiAii Fnldevs Advancad sanings Displaylhe lull path Willie address ha I D Displaythe iuii path lnthemlz ha DD quotattachethumbnails wniiie ypes a Dpevatmg system iiies Recommended asspaiais piueess O Show both pans and manage them individually 70 Show both pans buimanage as asingieiiie ype In the Registered le types list click on the line for older as shown below if you are using Windows 2000 NONE is replaced with NA Folder Opnons VlEW FHEWPES oiiiiiieFiies Regisieiediiie Mags Fiie Foldev eip and Suppun Cemei pmiueui gwoNE lmemetShnn NO e RealNelwmks sueaming Pvmncul Deiaiis im Fuldev iiie ype OpEnSWilh Liiaiius Ti change senings that aiiem all Fnldev iiies clickAdvanced 3mm 5 9 gt1 Click on the Advanced button to launch the Edit File Type window Click on the ew button in the Edit File Type window to launch the following New Action window In this New Action window type Command Prompt in the Action eld and cmdexe l in the Application used to perform action eld as shown below New Action Action 1 Command Prompt ApplicatioluseimeWDn Emdgxe 1 l gee DDE Click on the OK button to shut down the New Action window Click OK button again to shut down the Edit File Type window Click on OK button again to shut down the Folder Options window From now on if you need to open a Command Prompt window in a directory shown as a folder in the le pane of the Windows Explorer you just need to rightclick on that folder in the left pane of Windows Explorer and then click on the Command Prompt item in the popup menu The following example shows how I opened a Command Prompt window in Ccs121basics File Edit oBacK v l as EVIWBG Ei and a new instance View Favorites ZKB Expiore Operi Sharing arid Security ZKB 1K3 4K3 lKB 1K3 ZKB JKD lKB ZKB ZKB 1K5 lKB lKB lKB Upioad usirig strP Upioad Wizard v3 2 Scan for Viruses i r s of Command Prompt window popped up as below with Ccs121basics as its current working directory Microsoft lllindous XP Uersion 512609 C Copyright 19852001 Microsoft Corp 23 EditPad installation and customization Visit httpwwwediggadprocomeditpadlitehtml to download and install the free Editpad Lite text editor Now we are going to customize EditPad so it is more convenient for program development We will de ne a smaller tab size and replace each tab character with spaces The J ava source code developed on such customized EditPad can present themselves well in other text editors Start EditPad Click on OptionslPreferences Click on File Types in the new Preferences window In the left upper scroll pane scroll and choose Java source code if you cannot nd Java source code you can click on the New button under the le type list to create a new le type for Java associated with le name pattern java you enter Java source code in the Description textbox and enter java and Enter in the Extensions textbox In the lower right side of the window set T ab size to 2 Block indent to 2 and check the checkbox for Pressng Tab inserts spaces instead of tab characters Then click on the bottomApply button Hes FieTypes ShunMs System L Delete U r Ede Syntaxculmmg Assumamns Aummdem T b 2 j vessmgTabmsensspacesmstead m D7 is i behavejays DWWE39WS Eluckmdem 2 1 Mswbl2lmas 7 0 Physical mes D mdwvap anpgusmun u 31 2 5 Typical process for creating and running a Java program 1 Use EditPad to create a Java source le named Hellojava in directory Ccs121 If you don t have directon Ccs121 yet use a Windows Etplorer to create it Start EditPad If EditPad is already open for editing some other les click on FilelNew or the rst New icon to start an empty Untitled le Click on FilelSave As to launch the Save File window Use your mouse to click in the top half of the Save File window to navigate in your le system so that the Save box shows the destination directory cs121 under C Type le name Hellojava in the File name textbox Then click on the Save button to save the new empty le into a new le Ccs121Hello39ava The following gure is the screen capture for the Save File window Severn csl v ea r v 4 WWW 0mm r new U moments J WWW new Mm t J MMth some hexmmen cm lnEditPad enter the following contents into the new le Hellojava public class Hello public static void mainString args Systemoutprintln Hello World quot Finally click on FilelSave or the Save icon to save the new contents into le Hellojava en a Command Prompt window and change directory to Ccs121 see the next section for some tutorial on using DOS commands I you have followed my 39 ation of the Windows Explorer you could achieve this by rightclicking on folder Ccs121 in the le pane of a Window Explorer and then click on the Command Prompt item of the popup menu In the Command Prompt window type 39avac 7d Cclasses Hellojava to compile the source le Hellojava into a Java class le Helloclass in folder Cclasses The commandline switch d of javac command is used to specify the 18 destination of the class les resulting from the compilation Learn to use switch will save your time when you need to declare Java classes in Java packages as we will explain in the next section 4 In any Command Prompt window type 110 to run le Helloclass Since le Helloclass is in Cclasses and the latter is on our CLASSPATH the java command can nd it and run it The following is the screen capture of my session ofrunning the above steps 3 and 4 NDOWSSysKemIZcm Microsoft Windows XP Uersion 512800 c Copyright 19852001 Microsoft Corp Cc5121gtdir Uolume in driUe C has no label Uolume Serial Number is FC55393790 Directory oF Cc5121 08202005 12 03 PM ltDIRgt 08202005 12 03 PM ltDIRgt 08202005 118 Hellojaua 1 Fi1es 118 bytes 2 Dirs 181123H816 bytes Free Ccs121gtjauac d cclasses Hellojaua CclelgtjaUa Hello Hello World 25 A basic tutorial on DOS commands I you are serious in a programming career or using UnixLinux some experience in command line operation is necessary To start a Command Prompt window you can either use Starthun and then run or click on StartlAll ProgramslAccessorieleommand Prompt If you have customized your Window Egalorer as I explained earlier you can also rightclick on a directory in the le pane of a Window Explorer and then click on the Command Prompt item of the popup menu which will pop up a new Comm Prorrpt window and set the directory as the new Command Prorrpt window sworking directory You can change your working directory by using changing directory cd command as in the following examples o T ork on drive C suppose you are not on drive C now type C and Enter o To move up to the top level ofyour drive C type cd and Enter Suppose you are now at C To change directory to Ccs121 type cd cs121 19 0 To move up working directory by one level type cd To create a new directory named src in the current directory type md src Here md means Make Directory To delete a directory named src in the current working directory you rst need to make sure that directory src is empty Then you type rd src Here rd means Remove Directory To delete a le Helloclass in the current working directory type del Helloclass To delete all Java class les in the current directory type del class Normally Windows Explorer is easier for creatingrenamingdeleting directories and les To duplicate a Command Prompt window type start and Enter in the current Command Prompt window To check the de nitions of the environment variables on your PC type set and Enter To check the de nition of environment variable PATH just type pat and Enter To temporarily change the de nition of environment variable CLASSPATH to Aclasses type set CLASSPATHAclasses This change of value for CLASSPATH will only have effect in this current Command Prompt window This could be useful if you want to put your oppy disk s directory classes on the CLASSPATH If you need to type a long name of a le in the current directory you can type its initial letters and then type Tab for autocompletion For example for compiling the Hellojava le in my previous screen capture I could have typed javac 41 Cclasses H and then Tab and the command will be automatically completed as javac 7d Cclasses Hellojava 26 A note for storing programs on Lab PCs During lectures and lab sessions we will use lab PCs to work on Java programs Your les can be stored on drive C for better performance But the les on lab PCs will not survive PC reboot It is highly recommended that you copy your source les and folder classes from your oppy disk or USB memory stick to the drive C of your working lab PC at the start of a lab session work through the lab session on the drive C of your working lab PC and copy your Cclasses and other new source les created during the lab session to your oppy disk or memory stick for keeping them and porting them back to your home PC 20 3 Java Basics 31 l 2 E Basic Hello World program Open a Command Prompt window If your PC does not have directories Ccs121 and Ccs121basics following the following commands to create them Terminate each of the commands with the Enter key If one of the two directories is already present skip the corresponding md make directory command At each step you can use command dir directory to check the current working directory cs121 Create current Use EditPad to create a new le with FilelNew use FilelSave As to save the empty le with name Helloljava in directory Ccs121basics and type the following code in this file and save it public class Hellol public static void mainString args SystemoutprintlnquotHello World quot Explanation a A simple Java program is a single Java class which is the toplevel container for Java source code Each class has a name in this case Hellol In this example the first line identifies a class named Hellol It is a public class meaning that other classes can access it with no limitation we will see this after we have a program containing two classes A public class must be saved in a file whose name uses the class name as the file name stem and java as file name extension By convention a class name is an identifier with the first letter capitalized The class name is followed by a class body enclosed in a pair of curly braces as in public class ClassName A class contains one or more methods A method is the basic unit for performing some operations by a class A method has a name in our example main a parameter list for passing input data in our example String args meaning that input is an array sequence of character strings we will have better understanding after we discuss arrays and variable declaration a return data type for the type of data to be returned by the method to its invoker caller in our Fquot 21 example void meaning no return value and a method body that is a sequence of statements enclosed in a pair of curly braces A method quali ed by method modi er public is a method that can be accessed by any classes that have access to this class A method is quali ed by method modi er static if that method can be invoked against its containing class s name without creating an object of that class rst For example any class can invoke our method mainO by expression Hellolmainnull More explanation about public and static methods will be provided a er we have learned more about Java classes and objects in Section 4 When the Java interpreter runs a Java class it will rst try to run its method with c signature pattern exactly as public static void mainString args where the method body can contain any statements Please make effort to remember this pattern since we cannot Jlly explain this class yet d Each statement in the method body must be terminated with semicolon To print a message to the display and then move the display cursor to the beginning of the next line use Systemoutprintln message body println means and then a new line character 9 4 Now is time to compile the Java source code le Helloljava into its bytecode le also called clam le Hellolclass While the Command Prompt window is at Ccs121basics type command 39avac 7d cclasses Helloljava With a Windows Etplorer check that anew le CclassesHellolclass is created To run le Hellol class just type java Hello in any Command Prompt window V39 The following is a screen capture of my session for the above steps c wmnowsuysxemammd xe IE r oft windows XP Uersion 512600 c Copyright 1985 001 Microsoft Corp z Ccs121basicsgtdir Uolume in riUe C has no label Uolume Serial Number is FC55393790 Directorg 0F Cc5121basics 09052005 0H56 PM DIR 09052005 0H56 PM DIR 09052005 0H56 PM 1 i1es 1 g e 2 Dirs 1669570560 bytes Free 120 Hello1jaUa s Ccs121basicsgtjauac d Cclasses Hello1jaua Ccs121basicsgtjaua Hello1 Hello World 32 Code style and command line arguments 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code le named Hello2java in directory Ccs121basics with contents as below This is a demo program Please provide a name as commandline argument public class He1102 Entrance method to run first args is an array of commandline arguments public static void mainString args SystemoutprintquotHello quot System outprintargs 0 System outprint1nquot quot SystemoutprintlnquotHello quot argsO quotquot Explanation a Fquot 0 3 1 On any source code line signifies the start of a Java comment which ends at the end of the line A Java comment is ignored by the Java compiler as if it is a white space Comments are used for programmers to write notes about the code for himher self or for other programmers To improve the readability of a program the program authors are encouraged to insert enough comments to explain the purpose function and usage of each class and each method Java source code can be formatted for different display styles based on a few basic principles i In a Java source code file all the three types of white space characters are exchangeable except in character strings like Hello world ii A single white space character is equivalent to any number of consecutive white space characters except in character strings Source code files He1101java and Hello2java represent two styles of Java source code presentation different in the location of the opening curly braces The style used by He1101java puts an opening curly brace at the end of the first line of the class or method declaration and is thus more compact The style used by Hello2java puts the opening curly brace on a new line and aligns it with the first character of the class or method declaration In either styles the matching closing curly brace must be aligned with the first character of the class or method declaration and the class or method body inside the pair of curly braces must have an indentation of 2 or more but be consistent in a project space characters You can use either of the two styles but you should stick to one style in the same project Never mix up the styles in the same source code file The above Java source code style specification is critical for the readability and maintainability of Java programs and it will be strictly enforced in CSl21 23 Deviation from the suggested styles will lead to losing grade points even if your code works correctly To print a message to the display and leave the cursor immediately to the right of the last character in the message use Systemoutprintquotmessage bodyquot The strings after java Classname are called commandline arguments Normally a commandline argument cannot contain white space characters If you want an argument to contain white space characters you must put the argument value in a pair of double quotes as in quotLixin The first commandline argument is saved in argsO the second in argsl etc Array args is a sequence of strings Each string in this array is accessed throug an integer index value In Java C CH and C array indexes always have zero 0 as their first smallest index value instead of the more intuitive l Operator can be used to concatenate a few strings into a single string Therefore T 1 Fr quotLixin quotTaoquot is the same as quotLixin Tao If this program is run without commandline arguments array args will be empty containing zero or no cells for strings and the code for accessing argsO will lead to an array index out of bound error at index value 0 u 3 To compile the source code type javac d Cclasses He1102java You can use a Windows Explorer to check that a new file CclassesHelloZclass has been created 4 To run the new class type commands like the following two java HelloZ L1x1n java HelloZ quotLixin Taoquot The following is a screen capture for my test run session WINDOWSBysKemJ Zc Ccs121basicsgtjauac d cclasses He1102jaua Ccs121basicsgtjaua HelloZ Lixin Hello Lixin Lixin Ccs121basicsgtjaua HelloZ quotLixin Taoquot Hello Lixin Tao Lixin Tao Ccs121basicsgtjaua HelloZ Lixin Tao Hello 39 Hello Lixin Ccs121basicsgtjaua Helloz Hello Exception in thread quotmainquot jaualangarraylndexOutoraoundsException e He1102mainHe1102jaua10 33 Java package N Open a Command Prompt window Change directory to Ccs121basics Create a new directory path edupacecsis in the current working directory by typing Create md edupacecsis a new Java source code file named Hello3java in directory Ccs12lbasicsedupacecsis with contents as below package edupacecsis public class Hello3 public static void mainString args SystemoutprintlnquotHello World quot Explanation a Fquot 0 3 1 A project usually contains classes from several departments project teams or companies Since we are supposed to use meaningful class names it is easy for classes from different authors to have the same name This is called naming con icts If a project has more than one class with a particular class name only one of them will actually be deployed and used Java packages are introduced to reduce the possibility of naming con icts A class can be declared as part of a particular package A package can contain another package Package names are identifiers all in lower case In this example the top level package is edu which contains a nested package pace which in turn contains a nested package csis String edupacecsis which is a sequence of names of nested packages separated with period is called a package path package edupacecsis declares that the following class Hello3 is a member of package csis which in turn is a member of package pace which in turn is a member of package edu For avoiding naming con icts it is common practice to use the reverse of an organization s Web site URL as the Java package path base for this organization s Java classes Package declaration must be the first noncomment line of a source code f11e After the compilation of a class contained in packages each package of the class s package path will be implemented as a file system directory To run a class we must always qualify the class name with its full package path In our example to run class Hello3 we must use java edupacecsisHello3 If you don t qualify the class name with its package path the Java interpreter will declare that the class cannot be found The best practice for storing a Java source class le is to store the Java source class file inside a directory path corresponding to the class s package path relative to the working directory in which you plan to compile the class For our example here we plan to use Ccs121basics as our working directory for compiling all of our Java classes in this Section Therefore Hello3java should be stored in a directory path Ccs12lbasicsedupacecsis where the last three directories correspond to the package path for class Hello3 25 e To compile a class contained in packages you should use the d switch as shown in the following test runs 4 To compile the source code type javac d Cclasses edupacecsisHell03java You can use a Windows Explorer to check that a new le CclassesedupacecsisHello3class has been created To run the new class type commands like the following two java edupacecsisHello3 java Hello3 Error message that class Hell3 cannot be found Use Windows Explorer to delete file CclassesedupacecsisHello3class Recompile the class by typing javac d edupacecsisHell03java You will notice that a new file Ccs12lbasicsedupacecsisHello3class has been generated Repeat step 5 to run class Hello3 Use Windows Explorer to delete file Ccsl2lbasicsedupacecsisHello3class Recompile the class by typing javac edupacecsis Hello3 java You will notice that a new file Ccs12lbasicsedupacecsisHello3class has been generated The effect of this step is the same as that of step 6 If you don t use command line switch d the class file will by default be generated next to the source file 9 Repeat step 5 to run class Hello3 Use Windows Explorer to delete file Ccs12lbasicsedupacecsisHello3class Change working directory to Ccsl2lbasicsedupacecsis by typing cd edupacecsis Now you can use dir to see that source file Hello3 java is in the current working directory 12 Recompile the class by typing javac Hello3 java You will notice that a new file Ccs12lbasicsedupacecsisHello3class has been created in the current working directory Repeat step 5 to run class Hello3 You will find either approach fails Now you change working directory back to Ccs121basics by typing V39 O o D lb i bu UI Repeat step 5 to run class Hello3 The following is a screen capture for my test run session 26 a llgtlt l c I1Ih4I qut eu cu s1 zd pJoeESISHtllu3Jaua l sslmumeonu MIAht 1Hu3 anHM L c11halgtuuu Nlu3 raesolua lo lhrud 39nalnquot lavnangnnclx eanundErrur quotElla cslzlxllesgtess a eluoseeeslsxlsllua Viva rsslyloaslasgtluvs tdupac x Hzlln3 WV K7bn xzgtuv Hrtlgi xrrpllnn xu Ihrrud 39nuxn uualaoouuclssn FaundErrnr quotPIInJ aesgtvuou uupe ll 7 hayly o nellsa xrrnll n lhreuu u JiuulAnaNutlxss pffuundfrrur Hello rlt iquotlmugtnl on umer c 17lm my IlalLtLSS III r n drlurltl s u lahrL nr 5 I N s rnssealvn h33 Mello3elass lbs Huu3Jaua 57y hvles n5y7375 hvlzs free essgtur hasL smul nuum s resaezml nlm mmgt z 7 baxuzdu 5au Eduple s uslluJ Excrplxnn so Ihrrad yawnlungNuEXass rannndErrar sinpirrlzsxsl rlln eu ssl7louesxeuopseeselsgteu auuseessuello3 By now you should understand why we asked you to use javac d Cclasses ClassNamejava or javac d c assNarnejava to compile a Jaw source le classNamejava while most textbooks just let you use jawc assNamejava to compile me same Java source code le les since when we do code backup we only need to backup me Java source code les Second fol Java elasses contained u Java packages if we use javac ClassNamejav me 27 class le JavaNameclass will be created in the current working directory not in directories corresponding to the Java packages to which the class belongs we have to manually create a directory path corresponding to the package path for the class and move le ClassNameclass to the end directory of that directory path before we can run the class 34 Best practice for organizing multiple class projects A software project usually contains a few functional units and each functional unit contains a few Java classes Classes in the same functional unit are normally declared inside its own Java package If the functional units are implemented by different developers such an arrangement can avoid naming con icts or constant negotiations for class names For more efficient project backup in terms of both disk space and backup time it is a good practice to separate Java source code and Java class bytecodefiles One working directory will be chosen as the base ofthe Java class source files and one class directory say Cclasses or will be chosen as the base of the class files The class directory must be on the CLASSPATH Java class source code should be created inside directory paths parallel to the Java package paths that contain the classes relative to the working directory Java class files should be created inside directory paths parallel to the Java package paths that contain the classes relative to the class base directory For example let us use Ccs121basics as the source class base directory or working directory Cclasses as the class base directory and we have a class named Class that belongs to Java package project Then the Java source class file Classljava should be created inside relative directory path project or absolute directory path Ccs121basicsproject and its corresponding class file Classlclass should also be created inside relative directory path project but relative to the base class directory Cclasses Therefore the absolute directory path for file Classlclass is CclassesprojectClasslclass When we compile a Java class all the other classes that are referenced from that class directly or indirectly will be compiled too if their class files are not available on the CLASSPATH yet Normally for all projects in this course you only need to compile the main class that contains the entry method main actually called by the Java virtual machine first Compile the project by compiling the main class say MainClass belonging to package edupacecsis in the project s working directory with a command line like the following one javac d Cclasses edupacecsisMainClassjava To run the project type java edupacecsisMainClass in any Command Prompt window with any working directory By this organization the source code files and the class files will be in parallel directory structures relative to the working directory and the class base directory respectively If we choose not to separate the source code and the class files and use commandline switch d for command javac then the class files will stay in the same directories as their corresponding source files 28 Demo project 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code file named Classljava in directory Ccs121basicsproject with contents as below package project public class Classl public static String name quotClasslquot public static void mainString args SystemoutprintlnquotHello from Classlquot Class2mainnull 3 Create a new Java source code file named Class2java in directory Ccs121basicsproject with contents as below package project public class Class2 public static String name quotClass2quot public static void mainString args SystemoutprintlnquotHello from Class2 called from quot Classlname Explanation a Fquot 0 3 1 A class contains the declarations of methods and variables A variable at the class level inside the body ofa class but outside the body ofa method can be accessed by any methods in the class A public classlevel variable can be accessed by any classes that have access to the class A static classlevel variable is called a class variable and can be accessed from the class name in addition to from an object as we will see in Section 4 A variable at the class level can be initialized on its declaration line Without initialization classlevel variables will have initial values of either 0 or 00 for numerical types false for boolean type and null for class types Reserved word null represents a special value indicating that the variable holding it is not referring to any object For parameter args it will have value null if there are no commandline arguments to be passed to it To retrieve the current value of a static variable name of class Class we can use expression Classlname To invoke the static method main of class Class2 without passing any arguments to it we can use Class2mainnull Upon the invocation of method main of 29 class ClamZ the execution of the body of class ClmsI s mainO method is suspended the body of the called method is executed and then the control goes back to the body of method mainO of Class to resume its execution from where it le 4 To compile the source code type 39 7d Cclasses prujectClassljava You can use a 39 ws Explorer to check that new les CclassesprojectClassl class and CclassesprojectClassZclass have been crea d 5 To run the project type the following command j projectClassl 6 You can also run Cl s2 directly as we do below This shows that a Java project can have several entry points java prujectClassZ The following is a screen capture for my test run session cs121basicsgtjauac d Cclasses projectClassljaua Ccs121basicsgtjaua projectClass1 Hello From cl 139 Hello From 313552 called From 313551 Ccs121basicsgtjaua projectC assz Hello From classz called From ClasN 35 Local variables expressions and assignment 1 Open a Command Prom window Change directory to Cclelbasics 2 Create a new Java source code l amed LocalVariablejava Cclelbasics with contents as belo 39 in directory public class LocalVariable public static void mainString args int X int y 0 int 21 22 1 23 2 X l SystemoutprintlnquotX quot X X X l SystemoutprintlnquotX quot X X SystemoutprintlnquotX quot X X SystemoutprintlnquotX quot X X 2 SystemoutprintlnquotX quot X 21 1 x SystemoutprintlnquotX quot X quot zl quot 21 21 1 X SystemoutprintlnquotX quot X quot zl quot 21 y Z2 23 System outprintlnquoty quot y SystemoutprintlnquotX quot X quot X quot x SystemoutprintlnquotX quot X quot x quot X Explanation a Fquot O D A local variable is a named memory location for storing some values A local variable is declared inside a method and it is available from the point of its declaration to the closing curly brace matching the closest open curly brace before the local variable declaration At any time a variable can only hold one value Reading from a variable will not change the variable s value Writing a value into a variable will replace the old value in the variable with the new value Each variable has a data type In this subsection we focus on primitive data types int 32bit integer like 5 double 64bit oatingpoint number like 314 boolean true or false char character like 39c as well as the predefined data type String sequence of characters like quotHello worldquot A variable declared of int type cannot be used to store the value of another type like double type For this reason Java is called a strongly typed language The stronger typing of variables reduces the chances of storing data in wrong variables The name of a variable is an identifier with the first character in lowercase int X declares that X is the name of an integertyped variable We can think of X as the name of a memory cell in which we can only store an integer value that can be represented by 32 bits This declaration will only create the memory cell named X and the memory cell x will be lled up with random value A variable should not be read until it has been initialized with some value 31 quot1 W Pquot F B P 0 7 int y 0 combines two steps declaring that y is an integertyped variable and initializing variable y with value 0 Here y 0 means to initialize variable y with value 0 and it has nothing to do with equality between the values to the two sides of the operator Multiple variable declarations with the same data type can be combined into a single one as in int zl z2 1 z3 2 Here variables zl z2 and z3 are all declared to be of type integer zl is not initialized z2 is initialized to l and z3 is initialized to 2 In such a declaration the values will be initialized from left to right For example int zl z2 1 z3 z2 1 will have the same effect Here z3 zl 1 means that variable z3 is initialized with the current value of z2 plus 1 A variable can only be declared once in a method Multiple type declaration for a variable is an error An assignment has the form of variableName value or variableName expression In either case the left side of the operator is a variable and the right side of the operator is a value An assignment instructs the CPU to first evaluate the current value of the right side expression of the operator and then store the value in the variable to the left of the operator Operator is an action not a relationship for equality Therefore we never put a value to the left side of the operator For example 1 x doesn t make sense because 1 is not a variable and it cannot store the current value of variable x In a Java program constants like 1 314 true Hello and c are called integer literal double literal Boolean literal string literal and character literal respectively When CPU executes assignment statement x x 1 it will first find out the value of the expression to the right side of operator x l which is the current value of variable x plus 1 and then store the result back into variable x Put it another way assignment statement x x 1 increases the current value of variable x by 1 Expression x is called a preincrement expression It finds out the current value of variable x increases its current value by l and then returns the new value of variable as the value of expression x 4 77 X Expression x is called a postincrement expression It finds out the current value of variable x increases its current value by l and then returns the old value of variable x as the value of expression x Expression x is called a prealecrement expression It finds out the current value of variable x decreases its current value by l and then returns the new value of variable x as the value of expression x Expression x is called a postalecrement expression It finds out the current value of variable x decreases its current value by l and then returns the old value of variable as the value of expression x When a string value is combined with a value of different type with the operator the value of different type will first be converted into a new string and then concatenated with the old string value For example if variable x currently holds value 1 then quotx quot x will be converted into string quotx lquot Assignments like x l are expressions and here is a binary operator The return value of an assignment is the value assigned to the variable to the left of the operator Therefore the value of expression x l is 1 We can chain several assignments together as in x y l which is executed as x y l 4 77 X 32 E V39 The assignment operator is rightassociative the evaluation for a sequence of chained assignment operations is from right to le The above example chained assignment assigns value 1 into both variables x and Assignments like x l and as well as traditional expressions like x gt 1 are all called expressions in Java Mathematical expressions evaluation will value and not modify the value of variables in the expressions But expressions like x l and xi F modify the value of variables 39 e expression as well as return a value for the expression The latter expressions are called expressions with side effects Expressions with side effects can be used as statements Expressions with side effects make writing correct progmms much harder 5 To compile the source code type j vac 7d Cclasses LocalVariablejava You can use a Wind ws Explorer to CclassesLocalVariableclass has been created To run the new class type the following command LocalVariable Carefully read the explanations and make sure that you understand how the source code generates the printout check that a new le The following is a screen capture for my test run session NDOWSSystem31cm Ccs121basicsgtjauac d cclasses LocaanriablejaUa Ccs121basicsgtjaua Locaanriable 1 36 Basic builtiin data types and type casting l 2 Create Open a Command Prompt window Change directory to Ccs121basics e ava source code named BuiltinTypesjava Ccs121basics with contents as below in directory public class BuiltinTypes public static void mainString args Variable declaration and initialization int i 0 char c 39c39 String s quotHelloquot double d 1414 boolean isOK true Convert int string into int i IntegerparseIntquotl2quot SystemoutprintlnquotString quotl2quot is converted into int quot i Convert double string into double d DoubleparseDoublequot3 l4quot SystemoutprintlnquotString quot3l4quot is converted into double quot d Get a char from a string c scharAt0 SystemoutprintlnquotThe first character ofquotquot s quotquot is quot c quot quot Convert a boolean string into boolean isOK BooleanparseBooleanquotfalsequot SystemoutprintlnquotisOK now has value quot isOK int remainder operator Systemoutprintlnquot3 5 quot 3 5 Systemoutprintlnquot5 2 quot 5 2 Systemoutprintlnquot10 2 quot 10 2 Integer division and implicit type promotion Systemoutprintlnquot52 quot 52 Systemoutprintlnquot502 quot 502 Convert int into double implicitly i 12 d i System outprintlnquotd has now value quot d Convert double into int explicitly with type casting i intd System outprintlnquoti has now value quot i Conversion between int and char c a System outprintlnquotUnicode value for a is quot intc c charc l Systemoutprintlnquotc now has value quot c quot quot Relationship expressions and boolean 1 5 isOK i 5 equal to Systemoutprintlnquotl isOK quot isOK isOK i lt 5 less than or equal to Systemoutprintlnquot2 isOK quot isOK 34 isOK i gt 6 greater than or equal to Systemoutprintlnquot3 isOK quot isOK isOK i 6 not equal to Systemoutprintlnquot4 isOK quot isOK isOK isOK negation Systemoutprintlnquot5 isOK quot isOK isOK i gt 0 ampamp i lt 6 Are two conditions both true Systemoutprintlnquot6 isOK quot isOK isOK i lt 2 H i gt 6 At least one ofthe conditions is true Systemoutprintlnquot7 isOK quot isOK Common Math functions Systemoutprintlnquotabs2 quot Mathabs2 Systemoutprintlnquotceill5 quot Mathceill5 Systemoutprintlnquotceil2 quot Mathceil2 Systemoutprintlnquotceil15 quot Mathceill5 Systemoutprintlnquot oorl5 quot Math oorl5 Systemoutprintlnquot oor2 quot Math oor2 Systemoutprintlnquot oor15 quot Math oorl5 Systemoutprintlnquotexpl0 quot Mathexpl0 Systemoutprintlnquotlog100 quot Mathlog100 Systemoutprintlnquotmaxl 2 quot Mathmaxl 2 Systemoutprintlnquotminl 2 quot Mathminl 2 Systemoutprintlnquotpow20 30 quot Mathpow20 30 Systemoutprintlnquotsqrt20 quot Mathsqrt20 Systemoutprintlnquotrandom quot Mathrandom Explanation a Java uses exactly 32 bits to store an int value hardware and OS platforms independent b Java uses exactly 64 bits to store a double oatingpoint or real value hardware and OS platforms independent c If a numerical constant contains no decimal point it is interpreted as of type int otherwise as of type double d For int type the supported operators include and representing addition subtraction multiplication division and remainder e Assume that variables x and y are both integers Expression x y will return the remainder when dividing the value of y into the value of x If y 2 x 2 can be used to check whether value x is an even number f If both operands for operator are of type int is the integer division operator and the return value is the largest integer less than or equal to the division result For example 52 2 g If two operands of a binary operator have different data types the operand with a less precise type the type that takes less bits for its value storage will be implicitly promoted to the type of the another operand before the operator is applied to the operands This is called automatic type promotion Therefore 50 35 Pquot v F B v0 52 2 is first promoted to 50 20 before the oatingpoint division is applied to 50 and 20 In an arithmetic expression parentheses can be used recursively nested to override operator precedence and square braces and curly braces are not allowed to be used For example 2 x ly 1 means that x 1 will first be evaluated its result will then be divided by the value of y and the new result of the division will then be increased by l and the result of the summation will then be doubled Java uses 16 bits to store a char value which is the Unicode of a character A char constant must be enclosed in straight single quotes as in c A value of a lowerprecision type can be assigned into a variable of a higher precision type and a data type conversion promotion will happen implicitly As an example double d 1 will initialize double variable d with value 10 Here integer l is implicitly promoted to a more precise double type value 10 before it is used to initialize variable d This kind of data type promotion is also called implicit data type casting For preventing the loss of data precision Java normally doesn t allow a value of higherprecision to be assigned into a variable that is of a type with lower precision For example a double value is normally not allowed to be stored into an int variable since int only has 32 bits for data storage while a double value may use all of the allocated 64 bits for a double variable to store its value But if a programmer is sure that this is what she wants she can use the explicit data type casting mechanism to cast the more precise value into a less precise one before assigning it into a variable of a lowerprecision type For converting a value to a different type precede the value with the destination type in parentheses If the original value cannot be represented in the new type data truncation may happen For example int i int3l4 will first convert 314 into int value 3 before 3 is assigned into variable i Here the fraction part of the original value is truncated A boolean type variable can take on only one of two possible values true and false The value of a boolean variable is normally determined by the value of a relationship expression which is two values compared by a binary relational operator The popular relational operators include for equal to for not equal to lt for less than lt for less than or equal to gt for greater than and gt for greater than or equal to Attention is for assignment is for relationship The three most important operators on boolean values are ampamp H and called Boolean and conjunction Boolean or disjunction and Boolean negation respectively Given any Boolean expression a and b a ampamp b is true if and only if expressions a and b are both true a H b is false if and only if both a and b have value false and a is true if and only if a has value false To convert string 12 into int value use IntegerparseIntquot12quot To convert string 314 into double value use DoubleparseDoublequot314quot To convert string true into a Boolean value quotBooleanparseBooleanquotfalsequot To retrieve the first character in string quotcsl2lquot use quotcsl2lquotcharAt0 Internally char values are stored as Unicode a standard for encoding any international characters in 16 bits Given a char literal a we can get its Unicode value by casting it to an int value as in int a All lowercase letters have use 36 larger Unicode value than their uppercase counterparts All uppercase letters are assigned consecutive Unicode values so are all lowercase letters int Z l is the Unicode value for a Let us assume that c is a char variable holding an uppercase letter Systemoutprintlncharintc 26 will print out the lowercase counterpart of the value stored in c Java class javalangMath contains the following useful mathematical functions Since all classes in package javalang are always available to all classes and all the following functions are static methods they are supposed to be called against class name Math Never try to create an object of class Math because that is not allowed In the following table i1 and i2 represent any int values dl and d2 In Return Return a 3 To compile the source code type javac d Cclasses BuiltinTypes java You can use a Windows Explorer to check that a new file CclassesBuiltinTypesclass has been created 4 To run the new class type java Bu tiJlTypes The following is a screen capture for my test run session Since randomO returns random oatingpoint numbers between 0 and 1 you will get a different value from random every time you run the code 37 cs121basicsgtjaUa BuiltinT quot12 is conuerted into int 12 quot quot is conuerted into double 31H quotH 11 quot is 39H39 3920 2 718281828 0530 055 230258509299HOH6 2 1 30 80 1111112 5623730951 13 random 007067097H96759933 Ccs121basicsgt 37 Commandline arguments and loops Open a Command Prompt window Change directory to Cc5121basics 1 named CommandLineArgumenm ava in directory 2 Create a new Java source code file Cc5121basics with contenm as below public class CommandLineArguments public static void mainString args for int i 0 i lt argslength iH Systemoutprintlnargsi Sorting strings in args javautilAIrayssortargs intj while lt argslength ystemoutprintlnargs H J Explanation a b 0 3 1 D quot1 W Pquot When you run a Java class the strings after the class name are commandline arguments If a commandline argument s value contains white space characters the value must be enclosed in straight double quotes quot quot where the double quotes are not part of the argument value Method mainO has a parameter args whose data type is an array sequence of Strings The number of cells in this array is equal to the number of commandline arguments that are actually provided for the current run and this number is also available as the value of argslength which is an instance variable of data type String If no commandline argument is provided for a run args length will have value 0 and there will be no cells in array args Commandline arguments are sequentially stored in argsO argsl args2 For a particular run if the user provides 3 commandline arguments args length will have value 3 and the argument values will be stored in argsO argsl and args2 Arrays is a class with package path java util and class Arrays has a public static method sort that can be used to sort an array of strings or an array of numbers Statement javauti1Arrayssortargs sorts the string values in array args so they will be realranged in the lexicographic dictionary ordering A compound statement is a sequence of statements enclosed in a pair of curly braces like The body of a method is a compound statement You can declare local variables anywhere inside a compound statement Variables declared inside a compound statement will only be accessible from the point of the declaration to the end of the terminating curly brace for the compound statement No methods can be declared inside a compound statement Therefore the body of a class declaration is not a compound statement A compound statement can be used to replace any statement in a program without violating the syntax speci cation for Java A loop is a sequence of statements that will be executed by the CPU repetitively based on some Boolean true or false conditions The most popular loops are the while loop and thefor loop The while loop is of syntax while booleanExpression where while is the reserved word for while loop booleanExpression is any expression that can be evaluated to a boolean value true or false and is any compound statement If the compound statement contains only one statement the compound statement can be replaced with the single statement and the while loop will then look like while booleanExpression statemen The execution of a while loop is repeating the following sequence of actions until booleanExpression is false a Evaluate the Boolean expression booleanExpression If the evaluation result if false terminate this loop and execution resumes immediately after the loop body b Execute the body of the loop s compound statement c Go to step a A loop normally uses a loop variable to control its execution In our example the loop variable is j The boolean expression for a loop will check the value of the loop variable to see whether the loop should terminate The loop body will modify the value of the loop variable so the loop has a chance to terminate eventually 39 j A for loop is of syntax for loopVarInitialize booleanExpression changeLoopVariable where for is the reserved word for for loops loopVarInitialize is either a variable assignment or a local variable declaration with value initialization booleanExpression is any Boolean expression for checking whether the loop should terminate changeLoopVariable is for modifying the loop variable and is any compound statement loopVarInitialize booleanExpression changeLoopVariable is called the control block of a for loop If a component of the control block is not needed it can be empty but the two semicolons for separating the three control block components must always be present In the simplest form the for loop can be of form for which has no loop variable initialization the boolean expression is always true and the loop variable is not modi ed in the loop s control block but most likely the loop variable is modi ed in the compound statement If the compound statement contains only one statement the compound statement can be replaced with the single statement and the for loop will then look like for loopVarInitialize booleanExpression changeLoopVariable statement The execution of a for loop is repeating the following sequence of actions until booleanExpression is false a Execute loop variable initialization loopVarInitialize b Evaluate the boolean expression boolExpression to see whether its value is true If the evaluation value is false the loop terminates and the program execution resumes immediately after this loop body Execute the loop body Update the loop variable value by executing statement changeLoopVariable e Go to step b If a loop never terminates it is called an in nite loop An infinite loop can only be terminated by operating system operations like CtrlC or CtrlZ Any program that may run into an infinite loop is not a correct program Each execution of a loop s body is called one iteration of the loop The execution of a loop is made of many iterations of the loop If a loop variable is declared in the control block of a for loop the loop variable is only accessible inside the loop s body It is not accessible after thefor loop 7 99 B 5 To compile the source code type javac d Cclasses C0mmandLineArgumentsjava You can use a Windows Explorer to check that a new file CclassesCommandLineArgumentsclass has been created 6 To run the new class type like the following line and replace the commandline arguments with yours java CommandLineArguments Java is cool quotHello worldquot 21 1 The following is a screen capture for my test run session This program first prints the command line arguments in the same order that they are listed on the commandline and then prints them in the lexicographic order Note that in lexicographic order uppercase letters precede lower case letters numbers precede letters and short strings precede longer strings that use the short strings as the prefixes 40 be E WINDOWSSystemJZcmd exe cs121basicsgtjauac d Cclasses CommandL nenrguments Ccs121basicsgtjaua CommandLineRrguments JaUa is cool quotHello worldquot 21 1 JaUa rs cool Hello world 21 Calculator with ifielse statemenm Open a Command Prompt Window Change directory to Cc5121basics ate a new Ja source code le named Calculatorljava re in directory Cc5121basics with contents as below public class Calculatorl public static void mainString args if argslength 3 SystemoutprintlnquotUsage java Calculatorl double op doublenquot quotwhere op can be or quot Systemexit 1 double dl DoubleparseDoubleargs0 double d2 DoubleparseDoubleargs2 char op argslcharAt0 double result 0 if op result d1 d2 else if op 39 result dl d2 else if op 39 result dl d2 else if op 3939 result dl d2 else SystemoutprintlnquotError accepted operators are and quot System exit 1 Systemoutprintlnd1 quot quot op quot quot d2 quot quot result Explanation a Fquot 0 3 1 Each array has an instance variable named length that can be used to nd the length of the array number of cells in the array An instance variable is a variable that is de ned inside a class but outside of a method and that is not static If a classlevel variable is static it is called a class variable Inside a String literal constant n is used to introduce a New Line character and t is used to introduce a Tab character An if stateme has syntax if BooleanExpressitm Statement where if is a Java reserved word BoolExpression is any expression that has a value either true or false normally relational expressions and the statement can be a compound statement which is a sequence of statements enclosed in a pair of curly braces During execution of this ifstatement rst the Boolean expression is evaluated If the Boolean expression has value true the compound statement is executed Otherwise the compound statement is skipped and the CPU executes the following statement Reserved word else can be used to chain a list of ifstatements together into an if else statement For example when statement if BooleanExpressionJ statement else if BooleanExpressionZ 42 qorh Pquot You will see that directory and the program fails to run due to wrong number of commandline arguments statementZ else statementj is executed BooleanExpression is first evaluated If it is true statement is executed and execution then goes to the statement after statement3 If BooleanExpression is false then BooleanExpressionZ is evaluated If it is true statementZ is executed and execution then goes to the statement after statement3 If BooleanExpressionZ is false then statement3 will be executed and execution continues to the next statement In this if else statement exactly one of statement statementZ and statementj is executed The else statement3 part of the above ifelse statement is optional Without it if both BooleanExpression and BooleanExpressionZ have value false the execution just continues from the following statement There is no limitation on how many ifelse statements can be chained together Library class System has a static method exitint that can be used to terminate the execution of the current program Method exit nt takes one integer argument You can pass any positive or negative integer to method exit nt As a convention we use Systeexit0 to terminate a program normally and we pass a nonzero integer to method exit nt to indicate that a particular type of error happened before the program execution s termination At the operating system level we can check this termination status value used by the previous program for its termination This value can be used to decide which program should run next based on the status value of the previous program s termination For simple programs you don t need to terminate a program with Systemexitint When execution comes to the ending curly brace of the body of method mainO the program will be terminated implicitly You can use Systemexitint when you need to terminate a program before executing some other statements in sequence When you run a Java program that has graphic user interfaces you should call Systemexitint to explicitly terminate a program since such programs normally involve multiple concurrent threads covered in Section 5 waiting indefinitely for user inputs and they will not terminate by themselves This program uses lowercase x as the multiplication operator It cannot use for commandline operator since on commandline represents all file and directory names in the current working directory To compile the new class type javac d Cclasses Calculat0r1java To run this new class type lines like java Calculatorl 1 2 java Calculatorl 3 x 4 Insert the following loop at the beginning of method main for int i 0 i lt argslength i Systemoutprintlnargsi Recompile the source code Run the following line java Calculatorl 2 3 is replaced with all file and directory names in the working 43 6 omment off else from the source code recompile the code then run the following ine ja lculatorl 7 2 In this test is an operator not supported by the program Since no if statements Boolean expressions can be true and there is no else statement at the end of the if statements the program will not detect the illegal operator and it will let the last statement print garbage The following is a screen capture for my test run session Ccs121basicsgtjauac 39d Cclasses Calculator1jaua Ccs121basicsgtjaua Calculator1 1 2 10 20 30 Ccs121basicsgtjaua Calculator1 3 X H 30 X H0 120 Ccs121basicsgtrem Output from step 5 Ccs121basicsgtjaua Calculator1 2 x 3 Calculator1jaua Calculator2jaua Calculator3jaua e project Usage jaua Calculator1 double op double where op can be x or Ccs121basicsgtrem Output From step e Ccs121basicsgtjaua Calculator1 7 Z 2 39 Calculator with switch statement 1 Open a Command Prompt window Change directory to Cclelbasics Create a new Java source code le named Calculator2java in directory Cclelbasics with contents as below 44 public class Calculator2 public static void mainString args if argslength 3 SystemoutprintlnquotUsage java Calculator2 double op doublenquot quotwhere op can be X or quot SystemeXit l double dl DoubleparseDoubleargs0 double d2 DoubleparseDoubleargs2 char op argslcharAt0 double result 0 switch op case result d1 d2 break case result dl d2 break SystemoutprintlnquotError accepted operators are X and quot SystemeXit l Systemoutprintlnd1 quot quot op quot quot d2 quot quot result Explanation a CalculatorZ functions the same as Calculator Their only difference is that CalculatorZ uses a single switch statement to replace Calculator s if else statements b Java switch statement has the following syntax switch switchexpression case valuel statements break case value2 statements break default statements break where switch case default and break are Java reserved words switch eXpression is normally a variable of type int char or enum introduced in Section 45 5 and values after reserved word case must be literal constant values of the same data type as switchexpression case value is called a case label in which the value is called a case value Different case labels must have different case values The body of a switch statement is a compound statement in which some statements are preceded with case labels Each case label is a possible execution start point for the switch statement body During the execution of a switch statement the switch expression is first evaluated If its value is equal to the value of any of the case labels execution resumes from the statement qualified by that case label The execution will continue ignoring case labels until it meets a break statement which will stop the execution of the switch statement and the CPU will resume execution at the first statement after the body of this switch statement If the value of the switch expression does not match any of the case values then the execution starts from the statement qualified by the default label The default case of a switch statement is optional If the switch expression value does not match any case values and there is no default case specified the execution will just continue at the first statement after the body of this switch statement Be careful unless the default case is the last case or it terminates with a break statement or a statement that will terminate the execution of the program like System exit nt the execution will continue to the following cases As long as the statements for each switch case are terminated by a break statement the order of the cases in a switch statement is not important 0 P F W To compile class Calculator2 type 39a d Cclasses Calculat0r2java To run Calculator2 type lines like java Calculat0r2 1 2 java Calculat0r2 3 x 4 Reverse the order of the cases in the switch statement recompile the class run it to see whether any behavior of Calculator2 changed You should notice that the program behavior has not changed Delete the default case recompile the class run it with line java Calculat0r2 7 2 You should observe the same error as Calculatorl for the similar situation 5 V Q The following is the screen capture of my sample run of Calculator2 for steps 3 and 4 WINDOWSBystemJkaiexe cs121basicsgtjauac d Cclasses Calculator2jaua cs121basicsgtjaua CalculatorZ 1 2 10 20 30 cs121basicsgtjaua CalculatorZ 3 X H 30 X H0 120 cs121basicsgt 46 310 Calculator with exception processing 1 Open a CommandPrompt window Change directory to Ccsl2lbasics 2 Create a new Java source code le named Calculator3 java Ccsl2lbasics with contents as below in directory public class Calculator3 public static void mainString args if args1ength 3 quotwhere op can be X or quot SystemeXit l double dl 00 d2 00 try dl DoubleparseDoubleargs0 d2 DoubleparseDoubleargs 2 catch Exception e SystemeXit2 char op argslcharAt0 double result 0 switch op default SystemeXit3 case result d1 d2 break case result dl d2 break case 39X39 case X result dl d2 break case result dl d2 break Systemoutprintlnd1 quot quot op quot quot d2 quot quot result SystemoutprintlnquotUsage java Calculator3 double op doublenquot SystemoutprintlnquotError at least one of the operands is not a numberquot SystemoutprintlnquotError accepted operators are X and quot 47 Explanation a Fquot 0 3 1 D quot1 0 Calculatorj functions almost the same as CalculatorZ But Calculatorj supports both x and X as multiplication operators and it uses the Java exception handling mechanism to print more meaningful error messages when one of the operands is not a number This example reinforces the point that the default case can be anywhere in the body of a switch statement as long as its statements terminate the execution of the switch statement This example also reinforces the point that case labels are just labels for some statements in the body of a switch statement These labels indicate potential execution start points In this example both case labels case 39x39 and case X qualify statement result dl d2 Therefore if op has value either 39x or X39 execution will start from statement result dl d2 Java has another form of comments delimited by and This form of comments starts with and ends with Such comments can include a few lines while the form of comments must terminate at the end of the current line The Java compiler will ignore both forms of comments In addition to using comments as a form of Java source code documentation we can also use them for temporarily deleting some statements from the source code so we can recover them easily later During the execution of a method some illegal events may happen For example suppose that a method contains an assignment statement y 5x At code compilation time Java compiler has no idea what will be the value of variable x when this assignment is executed But during the execution of the expression 5x at runtime the value of x happens to be zero 0 It is illegal for zero to divide into any number and the Java runtime system will throw a DivideByZero exception to the method As another example when CalculateZ s method mainO uses IntegerparseDoubleargs0 to convert the string form of a number into a double value if the commandline argument args0 is not representing a number then method parseDoubleO will also throw an exception to method mainO informing it that something is seriously wrong It is common for a method to throw an exception object back to its invoker when it finds something seriously wrong If a method invocation statement receives an exception and it does not catch that exception the current method containing the method invocation statement will be terminated and the exception like a ball will be thrown to the invocation statement for the current method This chain reaction will continue until the current method is main which may lead to the termination of the program with lowlevel exception messages printed to the Command Prompt window Java provides an Exception Handling mechanism for a Java program to print meaningful error messages or recover from an exception when an exception happens If some statements may cause exceptions at runtime enclose them in a try catch block as below try try clause statements that may cause exceptions catch Exception e catch clause statements executed when exceptions happen 48 nally nally clause statements that will be executed no matter exceptions happened or not normally for recovering resources allocated in the try block where try catch and finally are Java reserved words the nally clause is optional and Exception is the root type class for all Java exception types When a trycatch block is executed the execution will start from the rst statement of the try clause If no exception is thrown during the execution of the statements in the try clause the body of the nally clause will be executed and execution resumes at the rst statement after the trycatch block If any statement in the try clause causes an exception the following statements of the try clause will be skipped and execution continues at the rst statement of the exception clause After the statements of the catch clause have been executed or before the current method terminates the statement of the nally clause will be executed if the catch clause terminates the program then the nally clause will not be executed The nally clause is used to execute some statements that must be executed no matter the exceptions happen or not A trycatch block can contain a list of catch clauses between the try clause and the nally clause each for catching a particular type of exceptions A catch clause has a parameter with an exception type In our example the parameter name is e and its type is Java library class Exception In the body of this catch clause we can access all information about this particular exception We can simply print the value of parameter e Later we will learn how to declare our own exception types which are Java classes The Exception class is the root class of all types of exceptions so our example catch clause can be used to catch all types of exceptions Pquot 3 To compile class Calculatorj type javac d Cclasses Calculat0r3java 4 To run class Calculator3 type lines like java Calculat0r3 2 x 3 java Calculat0r3 2 X 3 java Calculat0r3 2 x a Error message expected java Calculator2 2 x a Compare outputs for Calculator2 and Calculator3 5 Insert statement Systemoutprintlne as the rst statement of the catch clause recompile class Calculatorj and redo step 4 6 Add the following nally clause immediately after the catch clause Recompile class Calculatorj and redo step 4 nally SystemoutprintlnquotFinally clause executed quot The following is the screen capture of my test run for Calculatorj 49 C WINDOWSEysKemJka e cs121baslcsgtauac d c ciasses Calculator3JaUa cs121basicsgtjaua Ca1cu1ator3 2 x 3 20 X 30 60 cs121basicsgtjaua Calculator3 2 X 3 20 X 30 39 60 Ccs121basicsgtjaua Calculator3 2 x a Er o one of the operands is not a number Ccs121basicsgtjaua Calculatorz 2 x a 39 39 d quotmainquot jaualangNumberFormatException For input string quota at sunmiscFloatingDecimalreadJaUaFormatStringFloatingDecimaljaua12 2H at jaualangDoubleparseDoubleDoublejauaH82 at CalculatorzmainCalculator2Jaua Ccs121basicsgtrem after step 5 Ccs121basicsgtjaua Calculator3 a jaualangNumberFormatException For input string Error at least one of the operands is not a numbe Ccs121basicsgtrem after step e Ccs121basicsgtjaua Calculator3 2 x 3 Finally ciause executed a 60 Ccs121basicsgtjaua Calculator3 2 x a rr one of the operands is not a number Ccs121basicsgt The finally clause was not executed for the last step java Calculator3 2 x a because the Systemexit 2 statement in the catch clause terminated the program 311 Conditionally interrupting loops 1 Open a CommandPrampl Window Change directory to Cclelbasics 2 Create a new Java source code file named Looplnterruptionjava in directory Cclelbasics with contents as below public class Looplnterruption public static void mainString args int i for i lt lOiir Systemoutprintln Enter loop body i i if i 2 0 continue if i 7 break Systemoutprintln Leave loop body i i Systemoutprintln After loop i i The following is the screen capture of my test run Explanation a If a break statement is executed inside a loop the loop execution will be terminated and execu 39on will resume at the rst statement a er the loop containing the break statement If a continue statement is executed inside a loop the current execution of the loop body stops and the loop starts to prepare for its next iteration If the loop is a for loop a continue statement will stop the current loop body execution the loop varia le modi cation component of the for loop control block will be executed an then the Boolean expression in the for loop control block will be evaluated to determine whether the loop needs the next itemtion If the loop is a while loop a continue statement will stop the current loop body execution and the while loop s oolean expression will be evaluated to determine whether the loop needs the next iteration F 3 To compile class looplntermption type j vac d Cclasses Looplnterruptionjava 4 To run class looplnternqztion type java Looplnterruption cs121ba Ccs121ba pbd loop 1 Ccs121basicsgt 312 Arrays 1 Open a Command Prongzt window Change directory to Ccs121basicsquot 2 Create a new Java source code le named Arraysj ava in directory Ccs121basicsquot with contents as below public class Arrays public static void mainString args lD arrays int al new int6 for inti 0 i ltallength i ali i for inti 0 i lt al1ength i System0utprintquota1quot i quot quot ali quot quot System0utprintln add quotnquot int total 0 for inti 0 i lt al1ength i total a1 i SystemoutprintlnquotArray al has total value quot total int a2 24 12 18 45 14 5 8 for inti 0 i lt a2length i System0utprintquota2quot i quot quot a2i quot quot System0utprintln add quotnquot 2D arrays int a3 new int45 for inti 0 i lt a3length i for intj 0j lt a3ilength j a3im i at SystemoutprintlnquotC0ntents of array a3quot for inti 0 i lt a3length i for intj 0j lt a3ilength j System0utprinta3ij quot quot Systemoutprintln Add a quotnquot Explanation a A onedimensional array is a sequence of cells each with consecutive index values The smallest index value is 0 All cells of an array must have the same data type b Array variable declaration int al declares that al is a variable whose data type is an array of integers Array variable a1 only takes the xed 32 bits for storing the starting address for the rst cell of the array This array variable declaration does not allocate space for the array cells It does not limit the length of the array either c The array cells can be allocated with expressions like al new int6 Expression new int6 will allocate space for 6 cells each with 32 bits for an int value and return the starting address of the rst cell which is then saved in array variable a1 After this array space allocation the array cells will have random int values d Each cell of a onedimensional array is accessed through expressions like ali where a1 is an array variable and i is a valid integer index value for array 52 a1 For this particular case index i can only take on values from 0 to 5 inclusive e If we know that a onedimensional array needs just to hold a list of constant values we can combine the variable declaration and array space allocation in a form like int a2 24 l2 18 45 14 5 8 which declares that a2 is an array variable of type array of integers allocates space for an array of 7 cells since we listed 7 values in the pair of curly braces sets the rst cell s address in array variable a2 and initializes the array cells with the values given in the curly braces in the same order a20 24 a2l l2 a26 8 Similarly we can use int a3 new int4539 to declare that a3 is an array variable for a twodimensional array of integers and we use expression new int45 to allocate space for a twodimensional array of integers with 4 rows and 5 columns To access a cell in array a3 we use expression a3i wherei is an index value between 0 and 3 inclusive for the row and j is an index value between 0 and 4 inclusive for the column To nd the length of a particular row say row a3i we use expression a3ilength A twodimensional array can be viewed as a onedimensional array with each cell holding another onedimensional array for the column ralize the above pattern to declare 3D arrays int 23 new int45639 declares a 3D array made up of 4 planes each plane being a 2D array containing 5 rows and 6 columns To access the cell on plane 2 row 3 and column 4 use expression 23234 quot3 0f F 3 To compile class Arrays type javac d Cclasses Arraysjava 4 To run classArrays type java Arrays The following screen capture is for my test run of class Arrays WINDOWSSysiemJZcmd Xe Ccs121basicsgtjauac d Cclasses Rrragsjaua c cs121basicsgtjaua arrays a10 a a1 1 1 a12 2 a13 3 a1H u a15 5 31 has total Ualue 15 2H aZ1 12 aZ2 1s aZ3 H5 aZH 1H aZ5 5 a2s1 s 313 Method declaration and invocation 1 Open a Command Prompt window Change directory to Ccsl2lbasics 2 Create a new J ava source code le named Methodjava in directory Ccsl2lbasics with contents as below public class Method public static void mainString args int X 0 X square2 printX X maXX l 5 printX printmin5 2 8 static int squareint X return XX static int maXint Xl int X2 int X3 if Xl gt X2 ampamp X1 gt X3 return Xl else if X2 gt X3 return X2 else return X3 static int minint Xl int X2 int X3 int smaller Xl lt X2 Xl X2 return smaller lt X3 smaller X3 static void printint X SystemoutprintlnquotOutput quot X 7 Explanation a A program may contain some computation that needs be eXecuted multiple times Instead of repeating the source code for the common computation again and again we put them in a method for multiple invocations b A method needs be declared before it can be invoked Method declaration is contained in a Java class A method cannot be declared inside a method A method declaration includes a method return data type at the end of method eXecution what type of value will be sent back to the method invoker method name which is an identi er with the rst letter in lowercase a parameter list speci ed between a pair of parentheses input values to the method and a compound statement We also say that a method declaration includes a method signature and a method body where the method signature includes method return type method name and parameter list and method body is the compound statement 3 1 D quot1 Pquot W The parameter list is a list of type name pairs separated by comma where name is a parameter variable and type is the variable s data type A parameter variable from now on we just call it a parameter is part of the method body s local variable and can be accesses anywhere in the method body the compound statement The name of a parameter can be changed without affecting the function of the method as long as all occurrences of the parameter in the method body are changed accordingly too The order of parameter declarations in the parameter list is important and must be consistent with the way of method invocations Some methods have void as return type These methods will not return any value to the method invoker through the method return value mechanism it may use other mechanisms to pass some value back to the invoker as we will see in Section 4 when we discuss classtyped parameters When the execution of such method body comes to the end or a return statement of form return is executed the execution resumes in the invoker method at the statement immediately after the method invocation statement For a method that has a nonvoid return type every possible execution path of its method body must end with a return statement of form return expression where expression is any expression of the same data type as the method s return data type When execution comes to such a return statement the value of the expression in the return statement is evaluated and labeled as method return value the execution resumes in the invoker method at the expression that contains the method invocation the method invocation is replaced with the method return value and execution resumes with the evaluation of the resulting expression To invoke a method we use the method invocation expression like methodNameargumentl argument2 argumentN where N is the number of parameters listed in the parameter list of method methodName s declaration each argument is an expression that has the same data type as its corresponding parameter in the method declaration relative to order of the argument list and the parameter list Upon evaluation of this method invocation expression each argument expression is evaluated and the resulting value is copied into its corresponding parameter of the method the method containing the method invocation suspends its execution then the invoked method s body is executed with the initialized parameters treated as local variables Upon the completion of the method execution either by executing a return statement or coming to the end of statements of the method body the invoked method s execution is terminated the method invocation expression in the invoking method is replaced with the method return value if there is any and the CPU resume its execution at the resulting expression or statement remember expression is a special case of a statement Method declaration order in a class is not important A method s body can invoke methods declared after this invoking method The statements in a static method can only invoke static methods Since method main is static by Java speci cation all methods invoked from method main must be declared static too A static method can be invoked from another class with syntax ClassNamestaticMethod where staticMethod is a static method declared in class ClassName All methods in Java library class javalangMath are static methods 3 4 The following is the screen capture of my test run i A conditional expression can return the value of one of two different sub expressions depending on whether a Boolean expression is true or false A conditional expression has the following syntax l r 1 1 l a When this expression is evaluated the Boolean expression is rst evaluated If the evaluation result is true subexpressionl is evaluated and its evaluation result will be returned as the evaluation value of this entire conditional expression If the Boolean expression evaluates to value false subexpression2 is evaluated and its evaluation result will be returned as the evaluation value of this entire conditional expression Therefore expression 1 gt 2 3 4 will return value 4 since Boolean expression 1 gt 2 is false and expression 1 lt 2 3 4 will r value 3 since Boolean expression 1 lt 2 is true j In class Method we declared four methods Method int squareint x if for squaring the integer in parameter x Method int maxint x1 int x2 int x3 is for nding the maximum value among parameter values Method int minint x1 int x2 int x3 is for nding the minimum value among parameter values Method void printint x is for printing parameter value in a special way To compile class Method type javac d Cclasses Methodjava To run class Method type java Method WINDowsSystem31cmd exe Ccs121basicsgtjaua Method Output u Output 5 Output 2 Ccs121basicsgt 1 Jr 314 Java documentation comments Ni 5 Open a Command Prompt window Change directory to Ccs121basics Type copy Methodjava JavaDocDemojava in the Command Prompt window to make a copy of le Methodjava and name the copy as JavaDocDemojava Modify the contents of le JavaDocDemojma so it has contents as below gtxltgtxlt Class ltcodegtJavaDocDemoltcodegt shows example method declarations and invocations author Dr LiXin Tao version 10 gtxlt public class JavaDocDemo gtxltgtxlt Method ltcodegtmainltcodegt is the entrance method to be executed param args the array of command line arguments public static void mainString args int X 039 X square2 printX X maXX l 5 printX printmin5 2 8 gtxlt gtxlt Returns the squared value of parameter X param X the value to be squared retum the squared value of parameter X static int squareint X return XX gtxlt gtxlt Finds the maXimum of the input values param Xl the rst input value param X2 the second input value param X3 the third input value retum the maXimum of the input values static int maXint Xl int X2 int X3 if Xl gt X2 ampamp X1 gt X3 return Xl else if X2 gt X3 return X2 else return X3 gtxlt gtxlt Finds the minimum of the input values param Xl the first input value param X2 the second input value param X3 the third input value retum the minimum of the input values static int minint Xl int X2 int X3 int smaller Xl lt X2 Xl X2 return smaller lt X3 smaller X3 gtxlt gtxlt Prints input value in a special format param X value to be printed static void printint X SystemoutprintlnquotOutput quot X Explanation a Java class JavaDocDemo is basically the same as class Method eXcept that the class name is changed and Java doc documentation comments are added before the declaration of the class and each method Doc comments are for generating project documentation with a tool named javadoc exe A doc comment includes any string enclosed between a pair of and strings The contents of a doc comment can have multiple lines and each line can optionally start with a leading which is not considered as part of the doc comment A doc comment should immediately precede any class or method declarations as well as any class or instance variable declarations both will be introduced officially in Section 4 Doc comments inside a method declaration will be ignored c A doc comment should start with a concise sentence summarizing the function of a class or a method and end with an optional tag section The tag section contains a list of tag elements each starting with a tag like tagName and ending with contents for that tag The most popular tag names include i author for specifying program authors ii version for specifying version number of the program iii param for specifying a parameter for a method iv retum for specifying the return value of a method The contents of a doc comment can use inline tag ltcodegt ltcodegt to include a small piece of code or tag ltpregt ltpregt to include multiple lines of code aligned as it is You can also use other HTML tags in a doc comment But test the other tags before you actually use them so you know their impact on the generated Java documentation HTML files Fquot 4 Create a directory named JavaDoc in the current working directory by typing 58 md JavaDoc 5 To generate HTML documentation for class JavaDocDemo including class author and version number type java 0c d JavaDoc private author version JavaDocDemojava ere commandline a d is used to speci the location of the generated documentation les ag private is for generating documentation for all classes and methods no matter they are public or private ag author is for including author information in the generated documentation an ag version is for including program version information in the generated documentation If ag is not used it is equivalent to using ag d 7 which generates the documentation les in the current working directory 6 Start a Windows Explorer and use it to open the generated le Ccs12lbasicsJavaDocindeXhtml in a Web browser normally by doubleclicking on the le ow you can review your automatically generated program documentation 7 To generate HTML documentation for class JavaDocDemo without including class author and version number type j doc d JavaDoc private JavaDocDemojava Repeat step 6 to see the missing of author and version information in the generated ocumen a on 8 To generate HTML documentation for all Java source code in the current working directory excluding class author and version number type j c d JavaDoc private java project edupacecsis Repeat step 6 to review the generated documentation In general the arguments of command 39avadoc can be a list of Java source les and package names curren y accessible by command javac A package name in e argument list means that documentation needs be generated for all classes in that package The following is the screen capture of my test run for steps 46 cs121baslcsgtmd JaUaDoc cs121basics gtjauadoc d Jauanoc priuate author uersion Jauanocnemojaua source H e 39aua JaUaDocDemoJ mation g JaUaDocconstantUalueshtml 39 r the packages and classes ehtm1 a ehtm1 esnoFramehtm1 Ua e 1 JaUaDochelpdochtm1 Generating JaUaDocstglesheetcss Ccs121basicsgt 4 The following is a screen capture for the contents of the documentation generated by the previous steps 3 JavaDucDemu Micrnsn Internet Explmr 339 Elle Eth Mew Favontes Iools help mu 4 m E 393 Search Eavontes a iv 7 v D 3 vleo mks Aquot C1355 Package EETree Deprecated Index Help T J V DDCDEINO PREV cLAss NEXT CLASS FRAMES Nu FRAMES SUMMARV NESTED T HELD T CONSTR T METHOD DETAlL HELD T CONSTR T METHOD Class JavaDocDemo java lang Object LJavaDocDemo publlc class Javanocnemo extends javalang0bect m H I V I I I u Version 10 Alllllor Dr Lixin Tao lConstructor Summary l JavaDocDemo lMethod Summary l scat vuld mainjavalang5trlngl args Methodmamo 39 Done in My Computer u 1 The following is a screen capture afterI complete step 8 60 avaDncDemn rusn Internet Explurer Ede det Mew Egvontes 100 s e p eBack v J E quotsearch Favontes 11 v D 3 V Go mks All Classes Overview Package mTree Deprecated Index Help 7 PREVCLASS NExTrLAss FRAMES NUFRAMES packages SUMMARV NESTED HELD CONSTR METHOD DETA L HELD coNsTmMETHoD ltunnamed packagegt eclupacecsis pro39ect Class JavaDocDemo javalang0bect LJavaDocDemo All classes rrays ubblesmin publlc class JavaDocDemo 9 mm 5 extends javalang0bect alculato m I V alculato alculatore lass1 lassz 9394quot men s iConstructor Summaly Indlng I ormattingoutput JavaDocDemo 4ello1 IeoZ 03 npulDialog 1VIethod Summary JavaDocDemD Ke Downquot m BUD Wm ma1navalang5trlng args J LLOCENWME Method maln o is the entrance method to be executed LoopInteerption 7 ax1nt x1 mt x2 mt x3 Ma r39XMu39quot quotcamquot mm m Finds the maximum ofthe input Values Method Textlo v mamaE mun x1 m x2 m x3 7 pnvacey N Is v 7 7 Scan 111 um 7 SyMyComputer 315 Scopes of local variables 1 Open a Command Prompt window Change directory to Ccs121basics 2 Create a new Java source code le named VariableScopejava in directory Cc5121basics with contents as below 61 public class VariableScope public static void mainString args int X1 0 for inti 0 i lt 5 i i and square are only available in this for loop int square ii X1 square Systemoutprintlnquoti quot i quot X1 quot X1 Systemoutprintlnquoti quot i quot square quot square Cause error SystemoutprintlnquotX1 quot X1 ifX1 gt 15 int X2 2 X1 SystemoutprintlnquotX2 quot X2 SystemoutprintlnquotX2 quot X2 Cause error SystemoutprintlnquotX1 quot X1 Explanation a Parameters of a method are equivalent to initialized local variables declared at the beginning of the method body Therefore the parameters can be accessed anywhere in the method body A local variable is accessible from the point it is declared to the end of the compound statement in which it is declared including in the bodies of nested compound statements A local variable is not accessible outside the compound statement in which it is declared If the loop variable of a for loop is declared in the control block of the for loop the loop variable is only accessible inside the body of the for loop Fquot 0 3 1 3 To compile class VariableScope type javac d Cclasses Va ableScopejava 4 To run class VariableScope type java VariableScope 5 Uncomment the line for Systemoutprintlnquoti quot i quot square quot square Recompile the class to observe error messages Comment away this line again 6 Uncomment the line for SystemoutprintlnquotX2 quot X2 Recompile the class to observe error message Comment away this line again The following is the screen capture of my test run 62 c WINDOw55ystem31cmd exe X Ccs121basicsgtjauac d c c1asses UariableScopejaUa c cs121basicsgtjaua UariableScope 39 0 x1 0 l i i l c cs121basicsgtrem Try to access i and square out of the loop Ccs121basicsgtjauac d c c1asses UariableScopejaUa UariableScopejaUa10 cannot Find sgmbor mbo Uariable i UariableScope temoutprint1nquot i quot square square UariableScopejaUa10 s mbol Uariable s u location c1ass UariableScope Sgstemoutprint1nquot 39 quot square quot square cannot Find symbol are 2 errors Ccs121basicsgtreln Try to access X2 out of the if statement Ccs121basicsgtjauac d c c1asses UariableScopejaUa UariableScopejaUa16 cannot Find symbol bo uariabre x2 UariableScope Sgstemoutprint1nquotx2 39 2 Cause error 3 16 Format ng output 1 Open a CommandPrompt Window Change directory to Cc5121basics Create a new Java source code le named FormattingOutputjava in directory Cc5121basics with contents as below import javautilRandom public class FormattingOutput public static void mainString args int a new int55 double d new double5 5 Random r new Random Create a Random object for inti 0 i lt 5 i for intj 0j lt 5j aij rneXtIntlO di rneXtDouble 100 SystemoutprintlnquotContents of matrix Aquot for inti 0 i lt 5 i for intj 0j lt 5j Systemoutprintfquot6dquot ai System0utprintln SystemoutprintlnquotContents of matrix Dquot for inti 0 i lt 5 i for intj 0j lt 5j Systemoutprintfquot62f di System0utprintln double X d00 SystemoutprintlnquotWithout formatting X quot X System0utprintf quotWith formatting X 42f39 X Explanation a Fquot 0 Since this class uses a library class javautilRandom that belong to a different package than class FormattingOutput we need to import the Random class to make it available to class FormattingOutput If we delete the import statement import javautilRandom the program will still work if we replace all occurrences of Random with javautilRandom This shows that importing classes from other packages is not absolutely necessary but it will allow us to avoid qualifying those classes with their complete package paths in the source code A class declaration is like a stamp or stencil An object is like a particular pattern generated from a stamp or stencil A class can be used to create instantiate any number of objects of the same type as the class A class declaration does not take much memory space But each object of that class needs separate memory space allocated for holding the instance nonstatic variables of the class A class is a kind of data type A class s name can be used to declare reference variables that can be use to store references addresses of objects of that class type Each reference variable no matter it is for references of which type takes a f1Xed 32 bits of memory space 64 3 1 D quot1 W Pquot Let ClassName be the name of a class Operator new can be used to create an object of type ClassName with an expression like new ClassNameO which will allocate memory space and create a new object of type ClassName and return a reference address of the new object ClassName x will declare that x is a reference variable of type ClassName A reference variable is used to store the reference of an object while a normal variable like those declared with primitive data types int double and char are used directly to store values of those types Statement Random r new Random declares that r is a reference variable for type Random instantiates an object of type Random and stores the object s reference in reference variable r The memory structure for the reference variable r and the Random object is described in Figure 6 for contrast we also included memory structure for int x 2 in the same gure r x Figure 6 Reference variable vs primitive variable Here an a1row from memory box for r to the Random object means that the memory box for r holds the reference address of the Random object Class Random has a nonstatic method nextntz39nt which returns a random integer between 0 and the integer argument s value minus 1 both sides inclusive Therefore rnextInt10 will return random integers between 0 and 9 Class Random has a nonstatic method nextDoubleO which returns a random double value between 00 inclusive and 10 exclusive Therefore expression rnextDouble100 returns random double values between 00 inclusive and 100 exclusive Method Systemoutprint can be used for better formatting data outputs Method Systemoutprintf accepts variable number of arguments The first argument must be a string called the formatting string The formatting string may contain formatting substrings of form like 6d or 62f which are placeholders for integers and double values respectively String 6d indicates that an integer will be printed at this location with a width of 6 characters If the integer contains less than 6 digits space characters will be added to the beginning of the string form of the integer to make it a string of 6 characters If the integer contains more than 6 digits the integer will be printed with its actual length Here 6 is just an example width for printing integers and you can change it to any positive integer Similarly string 62f indicates that a double value will be printed at this location with a width of 6 characters including both the integer part the decimal point and the fraction part and the fraction part will take exactly 2 characters Therefore a double value will be printed with 3 digits before the decimal point padding space at the beginning if necessary and 2 digits after the decimal point padding 0s at the end if necessary Here 6 and 2 are just example values and you can change them to any positive integers that you need If the double value has more fraction digits than allowed to print the fraction part will be properly 65 rnunded A ere mu t he I 1 After I 39 i exactly as many extra arguments to method pnntfo as the number of formatting L mm 2 e values u an of these extra arguments must be of the same type as their conesponding argument must match the type of the rst formatting substiing the type of the 39 39 39 etc and the values of these arguments will be printed in formats speci ed by their conesponding formatting substrings 3 To compile class Formattingattput type javac rd as es FonnattingOutputjava 4 To run class mealtmgOulpul type java FonnaningOutput INDuwsmystsmazicmd 1b auac aua FnrmattingOHtpnt 7 uithnut fa natt a teana x gt uith fnrma Cc121b 4 317 Timing the evaluation 0 Mxneltlelt 3 5 7 ain i rsay L r In reality we part o n we can 39 When we increase the number of terms in the square brackets the approximate as we scan through the terms ofTUA from le to right value of n will diminish gradually 39 L simple loop and 1 m window quotL L eiiudsi 2 Create a new Java source code le named FindingPijava in directory Ccs121basics with contents as below public class FindingPi public static void mainString args long startTime System currentTimeMillis record start time double current 10 current approximate value of Pi4 double last 00 last approximate value of Pi4 double sign 10 current last term39s sign double denominator 10 current last term s denominator double tolerance 0000000001 allowed tolerance while Math abscurrent last gt tolerance sign 10 negate the sign for the sign ofthe next term denominator 20 get the denominator for the next term last current current approximate becomes the last one current sign denominator next approximate becomes the current one Systemoutprintf quotPi 97fnquot 40current long stopTime SystemcurrentTimeMillis record stop time SystemoutprintlnquotThis program has spent quot stopTimestartTime quot msecs runningquot Explanation a Java has another primitive data type long for representing large integers While an Fquot 0 int value only takes 32 bits for its storage a long value takes 64 bits for its storage Java static method SystemcurrentTimeMillisO returns the number of milliseconds that has passed since zero clock of January 1 1970 Since this is a large number we need to use long type variables to hold such counts For nding out how long a program runs we can get the current time at the beginning of the method mainO an at the end of method main and then report the difference between these two times We use a loop to approximate the value of 71 Before the loop is executed variable current holds the sum of the first one term of 71 4 or 10 variable last holds the sum of the first zero terms of 71 4 or 00 variable Sign holds the sign of the last term in sum current which is 1 and variable denominator holds the value of the denominator of the last term of sum current which is 10 the first term is 1010 During each iteration we add the following term to the sum current The sign of the following term is the negation of that of the current last term The denominator of the following term is that of the current last term plus 20 We let last hold the value of current and update current by adding the following term to it Therefore after the first loop iteration current holds the sum of the first two terms of 714 last holds the sum of the first one term of 714 Sign is the sign of the second term which is 1 and denominator holds the denominator for the second term of 714 The loop will repeat this process until the difference between current 67 and last is smaller than a preset tolerance level A smaller tolemnce will signi cantly increase the program running time Many oatingpoint real numbers need in nite number of digits to hold their values For example 1030 03333 in Which the faction part has in nite number of digit 3 But a Java double value has only 64 bits to store such values Therefore Java double values are only approximations of real World oating point numbers As a consequence When We need to test Whether a double variable holds a speci c value We should not use equal opemtor or notequal opemtor 1 but to use the lt or gt operators to check Whether the variable s value and the speci c value are close enough For example suppose We use a loop to modify the value of a double variable until the variable has value 30 the following loop may lead to nite loop ifthe loop variable only takes on values 2399999999999 or 3000000000001 both are reasonable approximations of 30 instead of the exact value 30 double d 00 While d l 30 update value ofd P1 A better version for the above loop is double d 0 039 double tolerance 00000001 While Mathabs30 7 d gt tolemnce update value ofd Where the value of tolerance can be adjusted based on the need of the progmm s application 3 To compile class FindingPi type 39avac 7 Cclasses FindingPijava 4 To run class FindingPi type ja a FindingPi The following is the screen capture of my test run of class FindingP39 1 nowsuysxemmcm exe Ccs121basicsgtjauac d Cclasses FindingP1aUa A c cs121basicsgtjaua FindingPi Pi 31u15927 This program has spent 21311 msecs running 318 Matrix multiplication This subsection uses matrix multiplication to practice our skills on nested loops arrays formatted output and methods Let a b and c are both 71 X 7 matrices with both row and column indices running from 0 through nl Assume matrices a and b have both been initialized with values Let c a X b For all combinations of 0 S 139 lt n and 0 S j lt n cz39j can be calculated with the following formula cm game x bkj Informally cz39j az390 gtlt b0j az39l gtlt blj az39 n l X bn l39 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code le named MatriXMultiplicationjava in directory Ccs121basics with contents as below 69 import javautilRandom public class MatriXMultiplication public static void mainSt1ing args int a new int55 int b new int55 int c new int55 Random r new Random Create a Random object rsetSeedl Initialize arrays a and b with random integers 09 for inti 0 i lt 5 i for intj 0j lt 5 j aiLi rneXtInt10 biLi rneXtInt10 Calculate C A X B c multiplya b Print arrays printMatriXa quotContents of matrix Aquot quot5dquot printMatriXb quotContents of matriX Bquot quot5dquot printMatriXc quotContents of matrix Cquot quot5dquot static void printMatriXint X String title String format Systemoutprintlntitle for inti 0 i lt Xlength i for intj 0j lt X0lengthj Systemoutprintfformat XlU Systemoutp1intln Calculate C A X B static int multiplyint a int b c has the same size as a int c new intalengthaOlength for inti 0 i lt clength i for intj 0j lt cOlengthj int sum 0 for int k 0 k lt cOlength k sum ai1lt bkm cilb39 sum return c Explanation a Class javautz39lRandom has a method nextlnt nt that can return a random integer between 0 inclusive and the argument integer eXclusive b Normally every time you run a program that uses a Random object the Random object will generate different series of random values But there are times when 70 we need to repeat the same sequence of random numbers so we can debug the program Class java utilRandom has a method setSeedt nt that can be used to initialize the Random object with any integer which is called a seed for the random generator As lon as ou use the same random seed integer as the ar ument for method setSeedint the Random object will genemte the same sequence of mndom numbers 3 To compile class MatrixMuln39plica on type javac 7d Cclasses Matrimetiplicationjava 4 To run class MatrixMu 39 hcatwn ty 8 ava MatrlxMultipllc on 5 Uncomment the rsetSeedl statement and redo steps 3 and 4 6 Change the constant 1 in the rsetSeedl statement to other integers and redo steps 3 and4 The following is the screen capture for my test run of class MatrixMultiplication Ccs121baslcsgtauac d 0 classes MatrlxnultlpllcatlonJaua Ccs121basicsgtjaua MatrixMultiplication r39x 9 Contents of ma 1 H 5 3 1 3 dandewmmwnm 319 Interactive commandiline data input 1 Open a Command Prompt window Change directory to Ccs121basics C eate a new Java source code le named Keyboardlnputjava in directory Ccs121basics with contents as below import javautil public class KeyboardInput public static void mainString args Scanner keyboard new ScannerSystemin SystemoutprintquotPlease enter an integer quot int nl keyboardnextInt SystemoutprintlnquotYou have just entered integer quot nl SystemoutprintquotPlease enter a oatingpoint number quot double d keyboardnextDouble SystemoutprintlnquotYou have just entered oatingpoint number quot d SystemoutprintquotPlease enter a string containing no spaces quot String s keyboardnext SystemoutprintlnquotYou have just entered a string quotquot s quotquotquot s keyboardnextLine consume the quotnquot on the current line SystemoutprintquotPlease enter a few strings quot s keyboardnextLine SystemoutprintlnquotYou havejust entered line quotquot s quotquotquot SystemoutprintquotPlease enter two integers on the same line quot nl keyboardnextInt int n2 keyboardnextInt SystemoutprintlnquotYou have just entered integers quot nl quot and quot n2 Explanation a Java Systemjn is an object representing the primitive keyboard input data stream working at character level which is not convenient for getting int double or String data from keyboard J2SE 5 introduced a new helper class javautz39lScanner to make interactive keyboard data input easier b Statement Scanner keyboard new ScannerSystemin instantiates a Scanner object that will get input from Systemjn or keyboard and assigns the reference of this object in Scanner reference variable keyboard c When a program is ready to accept some data input from a program user a prompt string should be printed first to remind the user what kind of data should be typed next d Class Scanner has a method nextIntO for returning the next integer that the user types in the Command Prompt window running this program e Class Scanner has a method nextDoubleO for returning the next oatingpoint value that the user types in the Command Prompt window running this program f Class Scanner has a method next for returning the next string containing no space in the string that the user types in the Command Prompt window running this program g Class Scanner has a method nextLineO for returning the strings from the current keyboard cursor position up to the end of the current line that the user types in the Command Prompt window running this program The new line character at the end of the line is consumed used up by the nextLineO method but not returned as part of the return string of nextLineO 72 h The rst s keyboardnextLin6 statement in this class is called when the cursor is still on the previous line and the new line character for the line has not been used up read yet This statement is used to consume up evious line from the current keyboard cursor position up to the end of that line including the new line character so that the next call to nextLineO will return what the user types on the next line i Except for nextLineO other methods of Scanner will return the next value starting from the current keyboard cursor position using white space characters which e Jpace Tab and new line characters as delimiters Therefore you can type several input values on the same line separating each other with space or type one input value on each line The input strings cannot be accessed by the Scanner object until the Enter key is typed 3 To compile class Keyboardlnput type 39 vac 7 Cclasses Keyboardlnputjava 4 To run class Keyboardlnput type java Keyboardlnput The following is the screen capture of my test run of class Keyboardlnput WlNDOWSSystem31emd x Ccs121basicsgtjaua Kegboardlnput nter an inte er 1 u haue just entered integers 11 and 22 Ccs121basicsgt 4 320 Windowebased data inputoutput 1 Open a Command Prompt window Change directory to Ccs121basics Cra new Java source code le named InputDialogjava in directory Ccs121basics with contents as below import javaxswingJOpti0nPane public class InputDialog public static void mainString args String input JOptionPaneshowInputDialognull quotEnter an integerquot int n IntegerparseIntinput String message quotInput value is quot n quotnquot quotSquare ofquot n quot is quot nn JOptionPaneshowMessageDialognull message Systemexit0 Explanation a Java library class javaxswingJOptionPane supports two static methods for getting user inputs and posting messages to users through graphic windows For getting user input we can use method JOptionPaneshownputDialognull prompt where prompt is a string explaining what input is expected and the return value of the method is the string the user typed in the input window popped up by this method c For posting a message to the user we can use method JOptionPaneshowMessageDialognull message where message is the string for being displayed to the user in a new message window A Java program with graphic user interfaces normally contains multiple threads of computing like having multiple CPUs running different pieces of code at the same time some are waiting for user input and some are doing computing at the background and the completion of the execution of method mainO may not terminate all the threads thus may not terminate the program s execution This is also a platform dependent issue To make sure that our programs always terminate properly Java programs with graphic user interfaces should terminate program execution explicitly with the Systemexit0 statement Fquot 3 1 3 To compile class InputDz39alog type javac d Cclasses InputDialogjava 4 To run class InputDialog type java InputDialog The following is the screen capture of my test run of class InputDialog 74 Ccs121basicsgtjaua Inputnialog 5 mm mlue s a Squaren ls 16 Enter an agar r 0K Em 321 Text le inputoutput 1 Open a CommandPrampt window Change directory to Ccs121basics 2 Create a new Java source code file named TextFileIOjava in directory Ccs121basics with contents as below importjavaio import javautilRandom public class TeXtFileIO public static void mainString args throws IOException File le new FilequottemptXtquot if leeXists if le temptXt does not exist create an output stream to it PrintWriter output new PrintWriternew FileWriter le generate 100 random integers Random r new Random for inti 0 i lt 10 i for intj 0jlt10j outputprintfquot4dquot rneXtInt100 outputprintln close the output stream outputclose open an input stream from le temptXt BufferedReader input new BufferedReadernew FileReaderquottemptXtquot int total 0 String line null while line inputreadLine null String token linetrimsplitquotsquot for inti 0 i lt tokenlength i total IntegerparseInttokeni SystemoutprintlnquotTotal is quot total close input stream inputclose Explanation a Java programs use les to store permanent data Most Java classes supporting le inputoutput are in package java 1390 Since we need to import multiple classes from package javajo we use importjavaio to import all classes in this package Importing classes do not take runtime memory space If a class is imported we can use the class s name in the current class source le without qualifying the 76 Fquot 0 3 1 D quot1 0 class name with its complete package path Therefore class importing is only for more concise source code Most le inputoutput operations may throw IOException a kind of prede ned Java exception for le or network inputoutput We need to enclose these operations in trycatch blocks before compiling the source code containing these le operations A lazier approach is to add a throws IOException clause at the end of the containing method s signature It declares that IOException may be thrown during the execution of its body and if it does happen the current method will terminate its execution and the IOException will be thrown back to the current method s invoker Since our method is main the program execution will terminate if IOException is thrown with the message of the IOException printed in the current Command Prompt window We use this lazier approach here so the main logic of the method body can be easier to read Java has a class javaioFile that can instantiate objects representing all meta data attributes not contents about a le or directory Statement File le new Filequottemptxtquot declares that variable file is a reference variable for class File instantiates a File object for a le named temptxt and assigns the reference of the File object to the reference variable file Class javaioFile has a Boolean method exits that returns true if the le exists in the le system or false otherwise This program checks whether the le named temptxt exists in the current working directory If it is not in existence then it will be created with 100 random integers between 0 and 99 ten integers per row Both le input and output uses a file cursor When a le is opened or created its le cursor is at the rst character position of the le Each le read or write operation will start from the le cursor position and advance the le cursor forward or to the next line as the Command Prompt window s cursor does when we print to or read data from the Command Prompt window Class javaioFileWriter can support basic text write functions to the text le speci ed as the argument of its constructor a constructor of a class has syntax of the class name followed by a parameter list it is executed when a new object of that class type is instantiated Class java ioPrintWriter can wrap up aFileWriter object to provide higherlevel operations like print println and printf Declaration PrintWriter output new PrintWriternew FileWriter le declares that output is a reference variable of type PrintWriter creates a new FileWriter object connected to the File object speci ed by variablefile wraps up the F ileWriter object inside aPrintWriter object and then assigns the reference of the PrintWriter object to reference variable output We also say that this declaration opens le temptxt for text output You can print data to variable output as you print data to Systemout The difference is that the former prints to the le temptxt while the latter prints to the computer display A F ileWriter or PrintWriter object takes signi cant amount of operating system resources for data buffering in the main memory An operating system can only open a limited number of les for input or output a time Therefore it is a good practice to close a le when its IO inputoutput is completed Class F ileWriter has a method close for this purpose Statement outputclose releases all operating system resources allocated for le temptxt By the same token statement inputclose also releases all operating system resources allocated for le temptxt after we finish reading its contents 77 h Java class javaioFileReaaler opens a text le for lowlevel reading operations Java class javaioBu quoteredReader can wrap up a FileReaaler object to support higherlevel buffered operations like readLineO Declaration BufferedReader input new BufferedReadernew FileReaderquottemptxtquot declares that input is a reference variable for Bu redReader objects instantiates a FileReaaler object for text le temptxt wraps the FileReaaler object inside a Bu redReader object and then assigns the reference of the BufferedReader object in reference variable input Class Bu eredReader has a method readLineO which returns the next line in its underlying file starting from the current position of the file cursor to the end of the current line If the file cursor has come to the end of file method readLineO will return null Boolean expression line inputreadLine null first evaluates the assignment subexpression to the left of the operator The value of an assignment expression is the value assigned If inputreadLineO returns null null will be assigned in variable line and null is also the value of the assignment expression line inputreadLine This will lead to value false for the Boolean expression of the while loop thus terminate the while loop To put it simple the while loop will read one line from file temptxt during its each iteration If there is no line to be read the while loop terminates j Type String is actually class java langString Since Java automatically imports all classes in package javalang we never need to explicitly import javalang Class String has a method trim which strips off any leading and trailing white space characters of the string that invokes method trim and then returns the resulting string Class String also has a method splitquotsquot that can use white space characters as delimiters to split the string that invokes this splitquotsquot method into a list of substrings containing no white space characters and return the substrings in an array of String This process is also called parsing the invoking string into a list a tokens separated by white space characters The size of the returned array is equal to the number of substrings found In Java method invocations can be chained if the return value of the previous method invocation is of type that implements the current method invocation Declaration String token linetrimsplitquotsquot declares that token is a reference variable for array of Strings replaces linetrim with the return value of method trim which is a new string obtained by removing leading and trailing white space characters in the value of line invokes method splitquotsquot against the resulting string to split it into an array of substrings containing no white space characters and finally assigns the reference for this array into reference variable token F 3 To compile class TextIO type javac d Cclasses TextIOjava 4 To run class TextIO type java TextIO The following is the screen capture of my test run of class TextIO Remember that the new text file temptxt will be generated only if it is already in existence You can force its generation by first deleting it 78 WINDOWSSystem31md x cs121basicsgtjauac d Cclasses TextIOjaUa Ccs121basicsgtjaua TextIO Total is H837 Ccs121basicsgttgpe temp 37 28 an 32 an 58 322 Recursive vs iterative methods factorial A method can call invoke another method As a special case a method can call itself If a method can call itself the method is called a recursive method On the other hand if a method doesn t contain calls to itself directly or indirectly like method a0 calls method 170 and method 170 calls method a0 then it is called an iterative method because its signi cant running time must be spent in some loops In theory recursion and loops are equally powerful Any problem that can be solved With loops only can also be solved With recursive methods only and any problem that can be solved With recursive methods only can also be solved With loops Many problems are de ned recursively in nature and it is much easier to design recursive solutions for them But in general recursive solutions take much more memory space and 39 ti than their loopbased counter parts Therefore if possible We should avoid using recursive solutions When a method invokes another method the Java runtime system will allocate a chunk of main memory called an activation record for storing the values of the invoked method s parameters and other local variables as Well as for storing the return address for the machine instruction of the invoking method that is to be executed When the method invocation is over When the method invocation is over this activation record Will be returned to the Java runtime system for memory space reuse the return value will be passed to a xed location in the invoking method s activation record and the return address saved in the invoked method s activation record Will be used to resume the execution of the invoking method Figure 7 shows how method mainO invokes method m10 and method m10 invokes method M20 and then method m10 resumes how an activation record is created for each method invocation and how an activation record is deleted When its corresponding method completes its execution mlo mzo m3 AR ml AR m1AR main AR main AR Method invocation Method return Figure 7 Chained method invocations and their activation records Therefore even if a method calls itself different invocations to the same method will use different activation records to store its parameter values local variable values and return addresses and these values for different invocations will not be mixed up As an example of recursive methods this subsection introduces both recursive and iterative solutions to the evaluation of the factorial of a nonnegative integer Given a nonnegative integer n its factorial n can be defined recursively as below 1 n0 ngtltn l ngt0 Therefore 3 3X2 3X2Xl 3X2X1X0 3X2X1Xl 6 But the factorial of n can also be defined as nlgtlt2gtltgtltn which obviously leads to a solution based on a simple loop This definition tells us that 3 l X 2 X36 80 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code le named Factorialjava in directory Ccs121basics with contents as below public class Factorial public static void mainString args int n 0 input integer try n IntegerparseIntargs 0 if n lt 0 throw new ExceptionquotInput value is negativequot if n gt 20 throw new ExceptionquotInput value is too largequot catch Exception e Systemoutprintlne System outprintlnquotUsage java Factorial nonnegativeintegerquot SystemeXit l long answer 0 answer recursiveFactorialn SystemoutprintlnquotRecursive Factorial gets answer quot answer answer iterativeFactorialn SystemoutprintlnquotIterative Factorial gets answer quot answer static long recursiveFactoriallong n if n 0 return 1 0 1 else return nrecursiveFactorialn l static long iterativeFactorialint n long answer l for int i l i lt n i answer i return answer Explanation a Factorial of an integer grows very fast so we use data type long to declare variables for holding factorial results While an int variable takes 32 bits of memory for its value storage a long variable takes 64 bits of memory for its value storage But even a variable of type long can only hold the factorial of up to 20 81 Fquot 0 3 1 That is why when you run this program you need to make sure that the input integer is between 0 and 20 If we detect that something is wrong we can throw a new Exception object and we can pass a message to the constructor of class Exception to record the reason for the exception Expression new Exception reason for this exception instantiates a new Exception object initialized with the reason for this exception and Java reserved word throw is used to throw out this exception object In our trycatch block there are four reasons that can lead to the throw of an exception object If there is no commandline argument args0 will throw a java lanArraylndexOutOfBoundsException object If the commandline argument is not representing an integer IntegerparseIntargs0 will throw a java langNumberFormatException object If the input integer is less than zero or larger than 20 we throw a new Exception object respectively These exception objects will all be caught by the catch clause and the parameter e of the catch clause will be initialized to the reference of the thrown exception object by the Java runtime system In the catch clause we print out the exception object which will actually print out the reason for the exception print out a usage message for how to run the program and then terminate the program s execution The following Figure 8 shows how the activation records work when we call recursiveFactoria3 Each invocation to this method creates a new activation record for holding its local variables return value and return address return address is omitted here The new activation record will always be put on top of the existing ones The CPU will always act on the top activation record at any time and the activation records below the top one are temporarily hidden away The life cycle of activation records actually implements a popular data structure called stack for which the data are organized so the first in stored into the stack will be the last out removed from the stack In this case the rst activation record created will be the last one to be destroyed recycled n0 returnl n nl return7 return n2 n2 n2 return return return n3 gt n3 gt n3 gt n3 return return 7 returner return7 nil return n2 n2 return2 return n3 n3 n3 return6 return return Figure 8 Evolution of activation records for recursiveFactorial3 82 e Since data type long can only hold around 20 digits we cannot see the running time difference be ween the recursive and iterative solutions But method invocation incurs penalty in terms of both memory space for the activation 39ng time Therefore the iterative version is more ef cient The difference in running time will be more signi cant in the Fibonacci number example in the following subsection since the recursive solution for Fibonacci number evaluation introduces many redundant method calls calls to the same method with the same argumenm repeatedly 3 To compile class Factorial e W javac rd Cclasses Factorialjava 4 To run class Factorial type ct java Fa orlal java Factorial error java Factorial a error java Factorial 72 error java Factorial 21 error You can replace the above 3 with any integer between 0 and 20 The following is the screen capture of my test run of class Factorial ccs121bas csgtJ Uac cclasses Factor a1JaUa Ccs121basicsgtjaua Factorial 3 Recursiue Factorial gets answer 6 lteratiue Factorial gets answer 6 Ccs121basicsgtjaua Factorial jaualangnrraglndexOutOFBoundsException 0 Usage jaua Factorial nonnegatiUeinteger Ccs121basicsgtjaua Factorial 39 alangNumberFormatException For input string U age jaua Factorial nonnegatiUeinteger Ccs121basicsgtjaua Factorial 39 jaua1angExceptio Input Ualue is negatiue Usage jaua Factorial nonnegatiUeinteger Ccs121basicsgtjaua Factorial 21 jaua1angExceptio Input u lue is too Usage jaua Factorial large nonnegatiUeinteger 323 Recursive vs iterative methods Fibonacci numbers This subsection starts with a story on F39ibonacci numbers and then shows how to evaluate Fibonacci numbers with both recursive and iterative approaches The story begins in the ear 83 13th century when the great Italian mathematician Fibonacci posed the following simple problem A man puts a pair of baby rabbits into an enclosed garden Assuming that each pair of rabbits in the garden bears a new pair every month which from the second month on itself becomes productive how many pairs of rabbits will there be in the garden after one year Like most mathematics problems you are supposed to ignore such realistic happenings as death escape impotence or whatever It is not hard to see that the number of pairs of rabbits in the garden in each month is given by the numbers in the sequence 1 l 2 3 5 8 13 etc This sequence of numbers is called the Fibonacci sequence The general rule that produces it is that each number after the second one is equal to the sum of the two previous numbers So 11 2 12 3 23 5 etc This corresponds to the fact that each month the new rabbit births consists of one pair to each of the newly adult pairs plus one pair for each of the earlier adult pairs Once you have the sequence you can simply read off that after one year there will be 377 pa1rs Most popular expositions of mathematics mention the Fibonacci sequence usually observing that the Fibonacci numbers arise frequently in nature For example if you count the number of petals in various owers you will find that the answer is often a Fibonacci number much more frequently than you would get by chance For instance an iris has 3 petals a primrose 5 a delphinium 8 ragwort 13 an aster 21 a daisy 34 and michaelmas daisies 55 or 89 petals 7 all Fibonacci numbers Fibonacci numbers can be naturally defined recursively as 0 n0 fibn 1 n1 fibn 2fibn l ngtl Now we develop a Java class to evaluate Fibonacci numbers for any value of index n 1 Open a CommandPrompt window Change directory to Ccsl2lbasics 2 Create a new Java source code file named Fibonaccijava in directory Ccsl2lbasics with contents as below public class Fibonacci public static void mainSt1ing args int n 0 input integer try n IntegerparseIntargs0 if n lt 0 throw new ExceptionquotInput value is negativequot if n gt 50 throw new ExceptionquotInput value is too largequot catch Exception e Systemoutp1intlne Systemoutp1intlnquotUsage java Fibonacci nonnegativeintegerquot SystemeXitl long answer 0 long startTime SystemcurrentTimeMillis record start time answer recursiveFibonaccin long stopTime SystemcurrentTimeMillis record stop time SystemoutprintlnquotRecursive Fibonacci gets answer quot answer quot in quot stopTime startTime quot millisecondsquot startTime SystemcurrentTimeMillis record start time answer iterativeFibonaccin stopTime SystemcurrentTimeMillis record stop time SystemoutprintlnquotIterative Fibonacci gets answer quot answer quot in quot stopTime startTime quot millisecondsquot static long recursiveFibonaccilong n ifn0Hn 1 return 11 b0 0 bl l e se return recursiveFibonaccin2 recursiveFibonaccinl static long iterativeFibonacciint n ifn0Hn 1 return 11 b0 0 bl 1 long previous 0 b0 long current 1 bl long neXt 0 b2 b3 bn for inti 2 i lt n i evaluate neXt bi and make previous oldcurrent current neXt neXt previous current previous current current neXt return neXt Explanation a We limit the value of the input integer to be no more than 50 Otherwise the recursive version of the solution takes too long time to complete The iterative version is much more complex than the recursive version If the input value n is 0 or 1 the answer is returned right away Otherwise the loop will sequentially nd f1b2 fib3 f1bn At the beginning of iteration i of the loop body variables previous and current hold values of the last two Fibonacci values f1bi2 and f1bil and variable next will be used to store the next Fibonacci number f1bi which is the summation of the previous two Fibonacci numbers f1bi2 and f1bil stored in variables previous and current respectively Then the loop body prepares for the next loop iteration From the point of view of the next iteration il the current value becomes the previous value and the next value becomes the current value The recursive version runs much slower than the iterative one because the former conducts many redundant method calls Let us look at the evaluation process of recursiveFaibonacci4 The following Figure 9 shows the method invocations spawned by recursiveFaibonacci4 b4 Fquot 0 b2 b3 b0 b1 b1 b2 b0 b1 Figure 9 Fib4 method invocation spawn tree We can see from this method spawn tree that f1b2 is called 2 times f1bl is called 3 times and f1b0 is called 2 times During my test run with n 40 the iterative version took less than one millisecond to complete while the recursive version took 9203 milliseconds The difference in running times between the two versions grow very fast when n grows in its value This con rms our suggestion that if possible try to avoid using recursive methods 3 To compile class Fibonacci type javac d Cclasses Fibonaccijava 4 To run class Fibonacci type java Fibonacci 3 java Fibonacci 10 java Fibonacci 20 java Fibonacci 30 java Fibonacci 40 The following is the screen capture of my test run of class Fibonacci c WINDOWSsysKem31cm exe I Ccs121basicsgtjaUac 39d Cclasses Fibonacc Ccs121basicsgtjaUa Fibonacci 3 RecursiUe Fibonacci gets answer 2 in 0 milliseconds lteratiUe Fibonacci gets answer 2 in 0 milliseconds Ccs121basicsgtjaUa Fibonacci 10 RecursiUe Fi onacci gets answer 55 in 0 milliseconds lteratiUe Fibonacci gets answer 55 in 0 milliseconds Ccs121basicsgtjaUa Fibonacci 20 RecursiUe Fi onacci gets answer 6765 in 0 milliseconds lteratiUe Fibonacci gets answer 6765 in 0 milliseconds Ccs121basicsgtjaUa Fibonacci 30 RecursiUe Fi onacci gets answer 8320H0 in 81 milliseconds lteratiUe Fibonacci gets answer 8320H0 in 0 milliseconds Ccs121basicsgtjaUa Fibonacci H0 RecursiUe Fi onacci gets answer 10233H155 in 9203 milliseconds lteratiUe Fibonacci gets answer 10233H155 in 0 milliseconds 324 Algorithm and Towers of Hanoi An algorithm is a wellde ned procedure for solving a problem satisfying two conditions 1 Each step of an algorithm is wellspeci ed so it can be precisely carried out with no ignity 2 The execution of an algorithm can always terminate with correct answer for any input data valid for the problem Cooking recipe is a simple example of algorithm A recipe tells us detailed steps in cooking An algorithm is the essential idea for solving a problem and it is normally described in natural languages like English An algorithm itself is independent of programming languages but computing algorithms are normally implemented in programming languages so they can execute on computers A program that can sometimes run into some in nite loops cannot implement algorithms Over the last half century we have identi ed many important computing tasks and designed various algorithms for their solutions Learni good a1 orithms for solving important problems can prevent us from reinventing wheels Therefore one important topic for computer science study is the study of algorithms For a given problem there are many ideas thus algorithms for solving it Some are more straightforward some are more complicated or subtle Some take more main memory space for their execution and some take less memory space for their execution Some take more CPU time for their execution and some take less CPU time for their execution For practical reasons computer scientists evaluate the quality of an algorithm based on two major criteria its execution time ef ciency an e amount of memory space it takes to run The former is called the time complexity of an algorithm and the latter is called the space complexity of an algorithm 87 The running time of a program indicates the time complexity of the algorithm implemented by the program But running time is not the same as time complexity of an algorithm Time complexity is about the quality of an algorithm only while the running time of a program depends on computer speed amount of available main memory the programming language used and the quality of the compiler or interpreter that transforms the program source code to machine code In this course we will learn some basic but important computer science algorithms and learn to be conscientious about program running time or time efficiency There are many general categories for problemsolving and recursion is one of them In this sub section we will see how recursion can be a powerful problemsolving strategy and how we use it to design an algorithm to solve a hard problem named Towers of Hanoi In the Towers of Hanoi problem there are n 21 disks of different diameters and three pegs named A B and C Initially all the n disks are on peg A sorted from small to large with the largest at the bottom and pegs B and C are empty The objective is to move all the disks from peg A to peg C with the help of peg B The only allowed operation is to move a top disk from one peg to the top of another peg At any time no disk can be on top of a smaller one on any of the three pegs Figure 10 a shows the initial configuration for n 3 and Figure 10 d shows the final configuration for its solution A B C a 4 B b A B C C d 88 Figure 10 Tower of Hanoi problem and its solution strategy Now we use recursion as the approach to design an algorithm for solving this problem The idea is very similar to the mathematical proof process by induction We first have the following two observations 0 The designation of the starting peg and the destination peg is not significant For example if we know how to move 71 disks from peg A to peg B with the help of peg C we can certainly use a similar approach to move 71 disks from peg A to peg C with the help of peg B If some larger disks are at the bottom of a peg we can ignore them and treat the peg as an empty one when we move disks smaller than them This is because the larger disks at the bottom of the peg will not cause violations to the constraint that no disk can be on top of a smaller one Now let us describe our solution strategy based on induction or recursion I If n l we know how to solve the problem we just move the only disk from peg A to peg C Let us assume that we already know how to solve the problem when the number of disks is less than n Put it another way if the number of disks is less than n we already know how to move the disks from any starting peg to any destination peg Now let us show how we can move 71 disks from peg A to peg C with the help of peg B We solve this problem in three steps 0 We first move 71 disks from peg A to peg B with the help of peg C Since the largest disk at the bottom of peg A is not causing problem and thus can be ignored and by our induction hypothesis in the previous step that we know how to move 71 disks from any starting peg to any destination peg we know how to complete this step Figure 10 b shows the result of this step when n 3 Since peg A now only has the largest disk and peg C is empty we can move the largest disk from peg A to peg C Figure 10 c shows the result of this step when n 3 Since the largest disk on peg C can be safely ignored what we need to do now to complete the solution is to move the 71 smaller disks from peg B to peg C with the help of peg A This step can be done due to the same reasons as for first step Figure 10 d shows the final disk placement for n 3 I Therefore we can conclude that for any number of disks we can solve the Towers of Hanoi problem 0 0 Now we develop a Java class to print out the disk move steps for solving the Towers of Hanoi problem for any positive integer n 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code file named Towerjava in directory Ccs121basics with contents as below public class Tower public static void mainString args int n 0 input integer try n IntegerparseIntargs 0 if n lt I throw new ExceptionquotInput value is no positivequot if n gt 15 throw new ExceptionquotInput value is too largequot catch Exception e Systemoutprintlne System outprintlnquotUsage java Tower positiveintegerquot SystemeXit l long startTime SystemcurrentTimeMillis record start time towern A 39C 39B long stopTime SystemcurrentTimeMillis record stop time SystemoutprintlnquotProblem is solved in quot stopTime startTime quot millisecondsquot gtxlt gtxlt Move ltcodegtnltcodegt disks from peg ltcodegtfromPegltcodegt to peg ltcodegttoPegltcodegt with the help ofpeg ltcodegthelpPegltcodegt param n number of disks param fromPeg starting peg param toPeg destination peg param helpPeg auxiliary peg static void towerint n char fromPeg char toPeg char helpPeg if n lt 0 return if n gt 1 towernl fromPeg helpPeg toPeg SystemoutprintlnquotMove disk from peg quot fromPeg quot to peg quot toPeg if n gt 1 towern l helpPeg toPeg fromPeg Explanation a We limit the value of the input integer to be between 1 and 50 Otherwise the recursive solution takes too long time to complete The memory space taken by the activation records for the recursive invocation to method tower grows very fast as number of disks grow so your PC may crash when the number of disks 90 exceeds 15 You should rhcremeatauy mcrease the number of drsks when you run thrs program c7 eLhod towero rmpterhehts the algonLhm we ouleed before It 15 basrcauy a srrhpte paraphrase rh Java statements for our mformal algonthm desmptron 1t 15 a more concrse yersron equw alert to the followmg more rhturtrye one statrc yord wwemntn char fmmpeg chartopeg charhelpPeg 1f h lt o retum 1f h 1 System out prlnLln Move drsk from peg omPeg to peg toPeg retum Lowernr1 romPeghe1pPegtoPeg System outpnntlnC Move drsk from peg fromPeg peg topeg Lowermrl helpPeg toPeg fromPeg 8 The yersron that we adopted ayorded the duphcate prrht statement 3 To comprle c1ass Tawer type 39avac rd cc1asses anerjzvz 4 Torunclass Tower type java Tuwer 4 The followmg 15 the screen capture ofmy test run of class Tower a n a c n c a e n c e a c n a n a c n c n a c a n e c a n a c n c 325 Bubble sort Sorting data means to rearrange data in either increasing or decreasing order Sorting is one of the most important building blocks of many reallife applications In this subsection we learn one of the simplest algorithms for data sorting named bubble sort In bubble sort data are initially stored in a onedimensional array Assume that there are 71 numbers in the array to be sorted The algorithm goes through nl loop iterations During each iteration we scan the data from left to right compare successive numbers and keep swapping the largest value that we have seen so far in this iteration called the bubble to the right At the end of such an iteration the largest value bubble found in this iteration is at its nal destination and doesn t need be considered in the following loop iterations Now we are ready to develop a Java class for bubble sort 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code file named BubbleSortjava in directory Ccs121basics with contents as below 92 import javautilRandom public class BubbleSort public static void mainString args int d new int10 Random r new Random create a Random object for int i 0 i lt dlength i di rnextInt50 generate random numbers between 0 and 49 SystemoutprintquotData before sorting quot printArrayd bubbleSortd System outprintquotData after sorting quot printArrayd static void bubbleSortint a for int limit a length 1 limit gt 0 limit for intj 0j lt limitj imam gt aU1D swap values in ab and a l int temp ah ah aU1 a l temp static void printArrayint a for int i 0 i lt alength i Systemoutprintai quot quot39 System outprintln Explanation a Method bubbleSortint consists of two nested loops The outer loop uses limit as its loop variable Variable limit is initialized to point to the last cell of the array a Each iteration of the outer loop nds the largest value in a0limit and moves it to alimit Initially limit holds the index of the last array cell so we nd the largest value in the entire array and then leave it in the last array cell In the next iteration we reduce the value of limit by 1 so we exclude the previous largest value from further consideration We repeat this process until limit has value 1 and we make sure that the larger value in a0 1 will be in al The nested loop uses j as its loop variable During each iteration we call the largest value that we have met so far a bubble We view the right end of the array as the water surface and we let the bubble go up to the water surface Initially Fquot 93 loop variable j has value 0 and the value in a0 is the bubble or the largest value we have seen in this iteration For each iteration of the nested loop we compare the current value in af with the next value in afl and swap them if af gt afl Therefore after the jth iteration of the nested loop afl has the largest value in a0jl The largest value for loop variablej to take on is limit 7 1 so at the end of one complete execution of the nested loop alimit has the largest value in a0 limz39t We should always avoid writing repeated code We can use methods to implement the common functions and call these methods whenever we need their functions Method printArray nt is one of our examples here The main objective of a method is to encapsulate some mctions in it so it can be used at multiple places of a program for performing similar tasks The programmers who invoke a method don t need to understand the implementation of the methods functions In case the method implementer nds a more ef cient way for the methods implementation heshe has the full freedom to update the body of the method as long as heshe doesn t change the method name method arameters and method semantics Because similar mctions are abstracted into a single method we avoid the nasty scenario in which we need to modify function implementations at multiple source code locations if some bug needs be xed 0 3 To compile class BubbleSort type 39avac d Cclasses BubbleSort java 4 To run class BubbleSort type java BubbleSort The following is the screen capture of my test run of class BubbleSort Because we sort random numbers every run will generate different number sequences WNDOWSsysiem31mdaxe Ccs121basicsgtjauac 39d Cc1asses BubbleSortjaUa Ccs121basicsgtjaua BubbleSort Data before sorting HQ 33 25 15 19 2H 28 28 5 27 Data after sorting 5 15 19 2H 25 27 28 28 33 HH Ccs121basicsgt 326 Binary search Many applications need to maintain a large set of data records and then check whether a 39 ar data record is in the data set Each data record consists of a few data elds For a human resource personnel record a data record normally includes data elds like social security number last name rst name date of birth date of joining the company current monthly salary etc Some times these data records have a special key eld that has a unique value for each record For example human resource of ces normally use social security number as the key eld for each employer s personnel record Given the value of a key eld we are o en asked to search for any data record or all data records that have the same value for that eld When the data set is very large the ef ciency of data search can be signi cant 94 To simplify the problem so we can focus on the fundamental idea of the data search problem let us use a set of integers to represent the data sets and store the integers in a onedimensional array Given a key integer value we need to report the index of that key value in the array or 1 if the key value is not in the may If there are multiple occurrences of the key value in the array we can return the index for any occurrence of that key value in the array The most natural approach to solve this data search problem is to use sequential search Let us assume that the integers are stored in array d and the key value is stored in variable key We can use the following loop to sequentially check each array cell to see whether the key value is stored there If the answer is true we return the current index value Otherwise if we have not come to the end of the array we repeat the check in the next array cell int sequentialSearchint d int key for inti 0 i lt dlength i if di key return i return 1 This sequential search works but its time efficiency is a problem Let us assume that array d has n integers The search time for a key value in d is in general proportional to n But in real life we normally do better that sequential search A White Book for telephone numbers stores telephone entries according to their owners names in lexicographical order When we look up a friend s telephone entry in a White Book we don t start from page one and do a sequential search Instead we make a guess based on the name that we are looking for and we go and check a page normally in the middle of the book If we are lucky we find our friend s entry on that page and we are done Otherwise if the page contains names smaller than the one that we are looking for in lexicographical order we know that we can safely ignore the first half of the book and we repeat the above process in the second half of the book On the other hand if the page contains names larger than the one that we are looking for in lexicographical order we know that we can safely ignore the second half of the book and we repeat the above process in the first half of the book This is the fundamental idea of binary search If we always start the search at the middle of the data range that we have not checked yet each iteration will allow us to halve the size of data set that we still need to look into and the worstcase running time for a binary search is therefore log2 n Binary search is much more efficient than sequential search But before we can conduct binary search we have to sort the data set in a particular order This is the onetime overhead If the problem at hand needs to maintain a stable large set of data and search particular data items repeatedly it pays off to sort the stable data set once and then we can enjoy the faster binary search from then on On the other hand if the data set is very dynamic or the data set is very small sequential search may prove to be a better solution It is good time to introduce the concepts of best case time complexity worst case time complexity and average case time complexity of an algorithm The execution time of an algorithm first depends on the size of the problem instance on which we run the algorithm For the data search problem the size of a problem instance can be naturally defined as the number of values in the array that we need to search into Let us use n to represent this problem instance 95 size It is easy to see that solving a larger problem instance in general takes more CPU time than solving a smaller problem instance If the execution time of an algorithm is independent of problem instance sizes we say that the time complexity of the algorithm is 01 meaning that the running time is a constant If the execution time of an algorithm is proportional to the problem instance size we say that the time complexity of the algorithm is 0n meaning that the running time is proportional to the size of the problem instance The constant running time 01 is always better than 0n when the size of the problem instances grow large But even for the same problem instance size the execution time of an algorithm is in general problem instance dependent Let us think about the sequential search algorithm first If we are lucky the key value is in the first array cell In this case we say that the sequential search algorithm has a bestcase time complexity of constant time the running time is independent of n the number of data records in the a1ray or 01 If we are not lucky the key value is not in the array at all but we don t know this fact until we have checked into each cell of the array Therefore the worstcase time complexity of sequential search is proportional to n and we use symbol 0n to represent proportional to 71 Suppose the key takes on any value in the array with the same probability Then the averagecase time complexity of the sequential search algorithm is roughly half of the array size or n2 which is still proportional to n or 0n Now let us study the case of running binary search for a key value in a data set with n values If we are lucky the value at the middle of the data array is holding the key value Therefore the bestcase time complexity for binary search is 01 If we are not lucky and the key value is not in the data array we have to halve the size of the array section to be searched into repeatedly until the array section contains only one value and this process takes time proportional to log2 n 21quot n Ifn 8 the array section to be searched into will be halved from 8 to 4 then to 2 then to 1 We use symbol Olog2 n to mean that the running time is proportional to log2 n Therefore the worstcase time complexity of binary search is Olog2 n which grows much slower than 0n Further study shows that the averagecase time complexity of binary search is also Olog2 71 When we talk about algorithm time complexity unless we specify otherwise we assume the worstcase time complexity Now we are ready to develop a Java class for binary search 1 Open a CommandPrompt window Change directory to Ccs121basics 2 Create a new Java source code file named BinarySearchjava in directory Ccs121basics with contents as below 96 import javautil public class BinarySearch public static void mainSt1ing args int d new int10 Random r new Random create a Random object for inti 0 i lt dlength i di rneXtInt50 generate random numbers between 0 and 49 BubbleSortbubbleSortd SystemoutprintquotData to be searched into quot BubbleSortprintArrayd SystemoutprintquotPlease enter an integer to search for quot creat a Scanner object for keyboard Scanner keyboard new ScannerSystemin int V keyboardneXtInt int indeXl binarySearchd V int indeX2 javautilArraysbinarySearchd V search by library method if indeXl l Systemoutp1intlnquotValue quot V quot is not in array dquot SystemeXit0 SystemoutprintlnquotOur implementation Value quot V quot is in dquot indeX1quotquot SystemoutprintlnquotLibrary implementation Value quot V quot is in dquot indeX2 quotquot Returns the indeX of key in array a if key is in a 1 otherwise param a the array of data to be searched in param key the value to be searched for static int binarySearchint a int key int leftLimit 0 int rightLth alength 1 while leftLimit lt rightLimit int middle leftLimit rightLimit2 if amiddle key return middle if amiddle lt key leftLimit middle l key can only be in amiddlel1ightLimit else amiddle gt key rightLth middle 1 key can only be in aleftLimitmiddlel return 1 Explanation 97 a We used the static method bubbleSortO of our class BubbleSort to sort the random integers in array d We could also have used java wilArmstortO to do the same sorting This is an example ofcode reuse b We also used the static method printArmyO of our class BubbleSort to print out the data in an array This is also an example of code reuse c Java class javautilArrays also supports a static method bimrySearchO with the same signature as ours We invoke both implementations of binary search to show that they provide the same answers d During each iteration of the loo of the binary search method the key value is searche in array section ale LimitrightLimit Initially this array section is a0alength1 or the whole array The middle index for the array section is then evaluated If amiddle is equal to the key value we return the value of the middle index If amiddle is smaller than the key value we r eat the same process in the following loop iteration in array section amiddleFlrightLimit Otherwise if amiddle is larger than the key value we repeat the same process in the following loop iteration in array section ale Limitmiddle1 3 To compile class BinarySearch type 39avac rd Cclasses BinarySearch java 4 To run class BimrySearch ty e java BinarySearch The following is the screen capture of my test run of class BinarySearch Because we use random numbers every run will generate a different number sequence WINDOWSsystem31cmd exe I Ccs121basicsgtjauac d c ciaeses BinargSearchjaUa Ccs121basicsgtjaua BinargSearch Be a to be sear hed 39nt s 9 9 13 20 21 35 33 H5 us 39 20 Librarg implementation Ualue 20 is in dH Ccs121basicsgtjaua BinargSearch Be a to be searched into 5 1 8 1e 1H 15 19 2H 32 H3 Please enter an integer to search For 11 Ua ue 11 is not in array d CS121IS223 ZooKeeper Example with Two Classes The following two classes make up a project called Zoo The rst class is the one where execution begins Execution begins with its main method That method instantiates the second class Panda It then runs the instance of the Panda class Created on Jan 22 2007 Created by Carol Wolf Course CS l2lIS 223 package zoo The zoo keeper manages the data for the animals in the zoo public class ZooKeeper public static void mainSt1ing args Panda panda new Panda 0 pandadisplayData main ZooKeeper Created on Jan 24 2007 Created by Carol Wolf Course CS l2lIS 223 package zoo A class that describes a panda Pandas are native to China and eat bamboo shoots public class Panda private String name quotMei Lingquot private int age 6 public void displayData Systemoutp1intln name quot displayData Panda s age is quot age Editing compiling and running a program The editor is used to create the java le The compiler then translates the Java programming language into Java bytecode This is an intermediate code that can be run on a number of computers The Java Virtual Machine JVM executes the program Errors can occur both in compiling and running The compiler checks for syntax errors But there still may be runtime errors These you have to nd yourself when the program is run on the JVM SyntaX errors are errors in grammar using the language Runtime errors are errors in semantics what the programmer intended They are usually much harder to nd SyntaX errors are things like missing semicolons Runtime errors can be incorrect computations or errors in logic They are often called bugs You usually have to work on the after a break Otherwise you can get stuck and not see where you have made a mistake The following diagram shows the process Java Virtual Java Compiler l eclipse ed1tor l javac Machlne JVM l 1 java ZooKeeperjava Output to screen Panda java ZooKeeperclass Pandaclass CS121IS223 Using loops When we have a number of things to do that are similar we use a loop Java has three types a for loop a while loop and a do while loop The for loop is the simplest but the while loop is best for reading from les and we will do that the most We will discuss them in the order given above The for loop is used when we know how many items are to be processed The form for this is for int count 0 count lt 10 count Systemoutp1intln quotCount quot count This loop will count from 0 to 9 since the counter started with zero and stopped at the number one less than 10 If we want to add up all the numbers from 1 to 10 we will need a variable to hold the sum The following loop will do this This is sometimes called a running sum int sum 0 for int count 1 count lt 10 count sum sum count Systemoutp1intln quotSum quot sum It is often helpful to trace the execution of a loop This is a way to look at each variable as it changes throughout execution count 12 3 4 5l6 7 8 9lw sumll3610152128364555 A for loop is called a count controlled loop since we know before it starts how many times it will execute The limits may be read in before the loop begins int noNumbers sum 0 Systemoutp1intln quotEnter the number of numbers quot noNumbers scannextInt 0 for int count 0 count lt noNumbers count sum sum count Systemoutp1intln quotSum quot sum In many cases we do not know how many times the loop will be executed We need a while or do while loop when this happens The while loop executes as long as a condition is true When the condition changes to false the loop is terminated If more that one statement is done inside the loop curly braces are needed to indicate that several statements are to be performed int sum 0 count 1 while count lt 5 sum sum count count count l Systemoutp1intln quotSum quot sum The trace above is the same for this loop as for the for loop above Actually the for loop is implemented by the compiler with the while loop shown int sum 0 int count l int sum 0 int count 1 while count lt 5 sum sum count count count l sum sum count count count l Another example reads prices from the keyboard and adds them up int total 0 double price Systemoutp1intln quotEnter the rst price quot price scanneXtDouble 0 while price gt 0 total total price Systemoutp1intln quotEnter the neXt price quot price scanneXtDouble 0 This loop reads prices until a zero or negative price is entered This is called reading to a sentinel The loop stops when the sentinel here a zero price is entered In order to get the rst price we have to read it before entering the loop Then we must read again at the end of the loop This way the zero will not be added into the total Adding a zero won t make a difference in the total but if the sentinel is some nonzero value it will An example might be averaging temperatures The sentinel might be a negative number such as 30 If the temperature is measured in Celsius a zero temperature might be a possible value But 30 Celsius is much below any eXpected value int total 0 noTemps 0 double temp Systemoutp1intln quotEnter the rst temperature quot temp scanneXtDouble While temp gt 30 total total temp noTemps noTemps 1 Systemoutp1intln quotEnter the neXt temperature quot temp scanneXtDouble 0 double average total noTemps Here we do not want to add the sentinel 30 into the total Reading it at the end means that when it is read in the loop will be terminated The last loop is a do while loop Here execution continues while the condition is true It ends when the condition changes to false Systemoutp1intln 2 count count count 1 count 1 true Systemoutprintln 2 count count count 1 While count lt 5 false This loop is a natural in some situations but it really isn t used all that often For loops and While loops are much more common A class that tests a menu that could be used for an ATM Instead of calling methods to carry out the actions such as displaying the balance it just prints out the choice public class TestMenu public static void main String args Menu menu new Menu 0 menumakeSeveralChoices 0 class TestMenu This class displays the menu and gets the users choice It gets choices until the user decides to quit class Menu private char choice public void displayMenu Systemoutp1intln quotB display balancequot Systemoutp1intln quotD make depositquot Systemoutp1intln quotW make withdrawalquot Systemoutp1intln quotM display menuquot Systemoutp1intln quotQ quitquot method displayMenu public boolean makeChoice boolean quit false Systemoutp1int quotEnter your choice quot choice ReaderreadChar 0 switch choice case b case B Systemoutp1intln quotBalancequot break case d case D Systemoutp1intln quotDepositquot break case w case W Systemoutp1intln quotWithdrawalquot break case m case M displayMenu 0 break case q case Q quit true break default Systemoutp1intln quotInvalid entry try againquot switch return quit method makeChoice public void makeSeveralChoices boolean quit false do displayMenu quit makeChoice 0 while quit Systemoutp1intln quotThank you come again quot method makeSeveralChoices class Menu class Reader Reads a character from the keyboard and returns it to the calling method public static char readChar char ch BufferedReader stdin new BufferedReader new InputStreamReader Systemin try ch charstdinread 0 catch IOException e ch 39 2 return ch method readChar public class Reader Computer Science 121 Arrays 1 Array declarations Examples int grades new int 10 double averages new double 10 String names new String 5 2 Accessing elements name 0 S grades 5 6 averages 3 32 if name 0 S while grades i lt 10 averages 3 grades 3 40 3 Using loops to work with arrays for count 0 count lt 10 count grades count ReaderreadInteger 0 int size 0 double prices new double 20 double price price ReaderreadDouble 0 while price gt 0 size prices size price price ReaderreadDouble 0 4 Arrays as function arguments public int sumArray double prices int size double sum 0 for int count 0 count lt size count sum sum prices count return sum method sumArray 5 Searching an array for the location of a key value Return the location if key is found return size otherwise int ndKey const int grades int key int size boolean found false int loc 0 While found ampamp loc lt size if grades loc key found true else loc return loc method ndKey public int ndKey int grades int key int size int loc 0 While loc lt size ampamp grades loc key loc return loc If key is not found loc will be equal to size 6 Finding the location of the smallest value in an array int locSmallest const int grades int size int curismallest grades 0 smallestilocation 0 count for count 0 count lt size count if grades count lt curismallest curismallest grades count smallestilocation count return smallestilocation Sorting an Array 1 Sorting an array selection sort Primary and secondary keys Often an array of structures one of the elds in the struct is the key eld 2 Selection sort If array has n elements requires nl passes Each pass goes through the array and locates the smallest value remaining pass2 pass3 pass5 In a selection sort the smallest number in the array is located rst and then it is interchanged with the one in the rst location location 0 Then the smallest number in the array starting at location 1 is found It is interchanged with the one in location 1 This continues until the neXt to the last one is found and interchanged At that time all of the values are in order import simpleIOReader public class SortArray public static void main String args ArrayClass list new ArrayClass list llList listsortList listdisplayList 0 method main class SortArray class ArrayClass private nal int maXSize 10 private int list private int listSize public ArrayClass list new int maXSize listSize 0 constructor public void llList Systemoutprint quotItem quot int item ReaderreadInteger While item 0 ampamp listSize lt maXSize list listSize item listSize Systemoutp1int quotItem quot item ReaderreadInteger 0 While method llList public void displayList for int count 0 count lt listSize count Systemoutp1int quot quot list count Systemoutp1intln quotquot method displayList public void sottList int small locSmall for int pass 0 pass lt listSize 1 pass small list pass locSmall pass for int count pass 1 count lt listSize count if list count lt small small list count locSmall count list locSmall list pass list pass small method sottList public void bubbleSott int temp boolean success do success true for int count 0 count lt listSizel count if list count gt list countl temp list count list count list countl list countl temp success false while succcss method bubblCSOI t class ArrayClass
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'