




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Class: Computer Programming II; Subject: Computer Science; University: Pace University-New York; Term: Fall 2005;
Typology: Study notes
1 / 100
This page cannot be seen from the preview
Don't miss anything!





























































































1
Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University
October 10, 2005
Table of Contents
1 Computer Systems and Programming Languages .................................................................. 1 1.1 Problem vs. problem instances ....................................................................................... 1 1.2 Structure of a personal computer .................................................................................... 1 1.3 CPU................................................................................................................................. 2 1.4 Memory........................................................................................................................... 3 1.5 Disk file system............................................................................................................... 5 1.6 Display ............................................................................................................................ 7 1.7 Keyboard......................................................................................................................... 8 1.8 Computer Software ......................................................................................................... 8 1.9 Java programming language ........................................................................................... 9 2 Software Installation ............................................................................................................. 12 2.1 Installation of Java J2SE 5 SDK................................................................................... 12 2.2 Customizing properties of Windows Explorer .............................................................. 14 2.3 EditPad installation and customization ........................................................................ 17 2.4 Typical process for creating and running a Java program ............................................ 17 2.5 A basic tutorial on DOS commands.............................................................................. 19 2.6 A note for storing programs on Lab PCs ...................................................................... 20 3 Java Basics ............................................................................................................................ 21 3.1 Basic Hello World program .......................................................................................... 21 3.2 Code style and command-line arguments ..................................................................... 23 3.3 Java package ................................................................................................................. 25 3.4 Best practice for organizing multiple class projects ..................................................... 28 3.5 Local variables, expressions, and assignment............................................................... 30 3.6 Basic built-in data types and type casting..................................................................... 33 3.7 Command-line arguments and loops ............................................................................ 38 3.8 Calculator with if-else statements................................................................................. 41 3.9 Calculator with switch statement .................................................................................. 44 3.10 Calculator with exception processing ........................................................................... 47
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 high-speed copy of the active (those currently processed by the CPU) programs and data for improving the CPU’s performance.
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.
1.3 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 machine-language 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
PC
(^01) (^23) (^45) (^67) (^89) (^1011) (^1213) (^1415) 16
Program
Data 2
Programs Data
Disk
Keyboard Display
System Bus
M[9]M[10]←← (^21) M[11]←M[9]+M[10]
(^21) 3
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 “M[11]←M[9]+M[10]”, 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 M[9] and M[10], another general-purpose 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 M[11]. 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 heart-beats 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.
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 1.5 GHz to 3.5 GHz, where a GHz is one giga Hertz, or 2 30 cycles per second.
1.4 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
Figure 3 Memory with program and data
Figure 3 shows an example main memory with 17 words. The first 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 “M[9] ← 2” in memory word M[0] is executed, which stores integer 2 into memory word M[9], the memory word with address 9. Then the program counter PC automatically increases its own value by 1 to become 1 and points to the next machine instruction. In the next CPU cycle, machine instruction “M[10] ← 1” in M[1] is executed, which stores integer 1 in memory word M[10], the memory word with address 10. The program counter PC then automatically increases its own value by 1 to become 2 and points to the next machine instruction. In the next CPU cycle, machine instruction “M[11] ← M[9] + M[10]” in M[2] is executed, which retrieves values in memory words M[9] and M[10], adds them together, and stores the summation result into memory word M[11], the memory word at address 11.
1.5 Disk file system
Hard disk is used for storing programs and data on long-term 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 2^30 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 files. A file is a named unit of binary or alphabetic (text) data of any length. The name of a file typically has two parts separated by a period: the file name stem , and the file name extension. For example, a Java source code file may have name “Welcome.java”, where “Welcome” is the file name stem, which is supposed to be a concise name characterizing the purpose of the file; and “java” is the file name extension, which indicates the type of data that is stored in this file. By convention, “java” as a file extension is reserved by Java source code files. The file name extension tells a computer how to interpret the data stored under a particular file name.
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
Program
Data
M[9]← 2 M[10]← 1 M[11]←M[9]+M[10]
2 1 3
Since we are encouraged to choose meaningful file names, it is possible that we incidentally create two files with the same name, leading to file name conflicts (the data of the second instance will replace that of the first instance). This leads to the introduction of the concept of file system directories. A file system directory can contain multiple files as well as other directories. A file system directory is a special file containing a table of contents for all files under its control. Two different files can have the same name as long as they belong to two different directories. File system directories are also referred to as file system folders. When a file directory is deleted, all of its contents are deleted too.
Figure 4 A sample file system
The file 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 file or a directory. There is a line connecting a father node and a son node in the trees. Figure 4 is a simplified file 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 files, 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 file or directory, separated by “\” in Windows and “/” in Unix/Linux. For example, the absolute path of file “Welcome.java” in our example is “C:\cs121\basics\project\Welcome.java”. When we work in a Command Prompt window, the Command Prompt window will work in a particular file system directory called the current working directory , for each directory tree. Inside a working directory, you can use relative path to denote a file 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 specific file or directory, excluding the current working directory, separated by “\” in Windows and “/” in Unix/Linux. As an example, if the Command Prompt window is currently working in directory “C:\cs121\basics”, then the relative path of file “Welcome.java” from the current working directory is “project\Welcome.java”; and if the Command Prompt window is currently working in directory “C:\cs121\basics\project”, then the relative path of file “Welcome.java” from the current working directory is “Welcome.java”. 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
C:\
cs
basics
project
homework
Program Files
Java
jdk1.5.0_
classes
project
Welcome.class
D:\
cs
classes projects
bin lib jre
javac.exe
java.exe
java.exe bin^ lib
Welcome.java
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.
1.7 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 predefined number of space characters. We say that the space key, the Enter key, and the Tab key all generate white spaces.
1.8 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 C/C++ compilers, are also system software. Application software is
x
y
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. High-level 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 programmer-friendly programs into machine instructions before they are executed (run). Java is one of the most important high-level programming languages.
1.9 Java programming language
Java is a high-level programming language designed for problem solving. Unlike natural languages that use very flexible set of vocabulary and flexible 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 low-level instructions of the so-called 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 machine-language 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 machine-language programs is overwhelming. This motivated the creation of various high-level programming languages. Java is one of the latest high-level programming languages. In a high-level language, the instructions are called statements. Each high-level statement is the abstraction of a sequence of machine instructions. As a result, a high- level program is much shorter than its machine-instruction counter-part, and it is much easier to write and maintain (understand and modify).
But a computer cannot understand a high-level language program directly. A high-level 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 high-level language source code into machine-language 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 machine-language 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 machine-language 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.
purposes. Identifiers “class”, “public”, “static”, “void”, and “package” are examples of reserved words. Reserved words are all in lower-case. Identifiers 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 first letter in lower-case. The classes of a program may be distributed in a few Java source code files. Java also uses variables for holding intermediate values. A variable’s name is an identifier with the first letter in lower-case.
2.1 Installation of Java J2SE 5 SDK
Right-click 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 “JAVA_HOME” for variable name, and value “C:\Program Files\Java\jdk1.5.0_05” for “Variable value”, as shown below. (If you use a Java SDK installation at another directory, you should update the variable value accordingly.)
Click on the OK button to compete the definition. Click on the OK button of the “Environment Variables” pane to shut it down. Click on the OK button of the “System Properties” window to shut it down.
2.2 Customizing properties of Windows Explorer
For software developers, Windows Explorer should show detailed view of files, and file extensions of known types should be displayed all the time. It will also be convenient if we can easily launch a new Command Prompt window from a Windows Explorer and change directory automatically to the directory that we choose in the Windows Explorer. This section introduces some useful customizations to your Windows Explorer for better supporting Java programming.
Click on button “Apply to All Folders” so all Window Explorer instances will have the same folder options as this one.
2.3 EditPad installation and customization
Visit http://www.editpadpro.com/editpadlite.html 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 define a smaller tab size, and replace each tab character with spaces. The Java source code developed on such customized EditPad can present themselves well in other text editors.
Start EditPad. Click on “Options|Preferences…” Click on “File Types” in the new Preferences window. In the left upper scroll pane, scroll and choose “Java source code” (if you cannot find “Java source code”, you can click on the “New” button under the file type list to create a new file type for Java associated with file 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 Tab size to 2, Block indent to 2, and check the checkbox for “Pressing Tab inserts spaces instead of tab characters”. Then click on the bottom Apply button.
2.4 Typical process for creating and running a Java program
In EditPad , enter the following contents into the new file “Hello.java”:
Finally click on “File|Save” or the Save icon to save the new contents into file “Hello.java”.
public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } }