CS 101 Algorithms and Programming I: Section 01, 05
CS 101 Algorithms and Programming I: Section 01, 05
CS 101 Algorithms and Programming I: Section 01, 05
Outline
Computer Processing Hardware Components Networks The Java Programming Language
Computer Processing
We first need to explore the fundamentals of computer processing
components of a computer how those components interact how computers store and manipulate information computer networks the Internet and the World Wide Web programming and programming languages an introduction to Java
Hardware the physical, tangible parts of a computer keyboard, monitor, disks, wires, chips, etc. Software programs and data a program is a series of instructions A computer requires both hardware and software
Primary storage area for programs and data that are in active use
Main Memory
non-volatile
Hard disks Flash memory ZIP disks Writable CDs Writable DVDs Floppy disks Tapes Hard Disk
Main Memory
Writable DVD
Monitor screen Keyboard Mouse Joystick Bar code scanner Touch screen
Printer
Main Memory
Software Categories
Operating System controls all machine activities provides the user interface to the computer manages resources such as the CPU and memory Windows Vista, XP, Unix, Linux, Mac OS X
Application program generic term for any other kind of software Ex: word processors, spread sheet programs, Internet browsers, missile control systems, games
Analog continuous, in direct proportion to the data represented music on a record album - a needle rides on ridges in the grooves that are directly proportional to the voltages sent to the speaker
Digital the information is broken down into pieces, and each piece is represented separately music on a compact disc - the disc stores numbers representing specific voltage levels sampled at specific times
Digital Information
Computers store all information digitally: numbers text graphics and images video audio program instructions In some way, all information is digitized - broken down into pieces and represented as numbers
H i , CS101 class.
Binary Numbers
Once information is digitized, it is represented and stored in memory using the binary number system A single binary digit (0 or 1) is called a bit Devices that store and move information are cheaper and more reliable if they have to represent only two states A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values
Bit Permutations
1 bit 0 1 2 bits 00 01 10 11 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 1000 0001 1001 0010 1010 0011 1011 0100 1100 0101 1101 0110 1110 0111 1111
Bit Permutations
Each permutation can represent a particular item There are 2N permutations of N bits Therefore, N bits are needed to represent 2N unique items 1 bit ? 21 = 2 items How many items can be represented by 2 bits ? 3 bits ? 22 = 4 items
3
2 = 8 items
24 = 16 items 25 = 32 items
4 bits ?
5 bits ?
Outline
Computer Processing Hardware Components Networks The Java Programming Language
A Computer Specification
Consider the following specification for a personal computer:
2.66 GHz Core 2 Quad (4 processors) 4 GB RAM 320 GB Hard Disk 16x DVDRW Optic 17 Video Display with 1280 x 1024 resolution
A Computer Specification
Consider the following specification for a personal computer:
2.66 GHz Core 2 Quad (4 processors) 4 GB RAM 320 GB Hard Disk 16x DVDRW Optical Drive 17 Video Display with 1280 x 1024 resolution
Memory
9278 9279 9280 9281 9282 9283 9284 9285 9286
Main memory is divided into many memory locations (or cells)
Each memory cell has a numeric address, which uniquely identifies it
Storing Information
9278 9279 9280 9281 9282 9283 9284 9285 9286
10011010
Each memory cell stores a set number of bits (usually 8 bits, or one byte) Large values are stored in consecutive memory locations
Storage Capacity
Every memory device has a storage capacity, indicating the number of bytes it can hold Capacities are expressed in various units: Unit kilobyte megabyte gigabyte terabyte Symbol KB MB GB Number of Bytes 210 = 1024 220 (over 1 million) 230 (over 1 billion)
TB
40
(over 1 trillion)
Memory
Main memory is volatile - stored information is lost if the electric power is removed Secondary memory devices are nonvolatile Main memory and disks are direct access devices information can be reached directly The terms direct access and random access often are used interchangeably
Compact Discs
A CD-ROM is portable read-only memory A microscopic pit on a CD represents a binary 1 and a smooth area represents a binary 0 A low-intensity laser reflects strongly from a smooth area and weakly from a pit
DVDs
A DVD is the same size as a CD, but can store much more information The format of a DVD stores more bits per square inch A CD can store 650 MB, while a standard DVD can store 4.7 GB A double sided DVD can store 9.4 GB
fetch
execute
Carry out the instruction
decode
Determine what the instruction is
Control Unit
Registers
Monitor
The size of a monitor (17") is measured diagonally, like a television screen Most monitors these days have multimedia capabilities: text, graphics, video, etc.
A monitor has a certain maximum resolution , indicating the number of picture elements, called pixels, that it can display (such as 1280 by 1024) High resolution (more pixels) produces sharper pictures
Outline
Computer Processing Hardware Components Networks The Java Programming Language
Networks
A network is two or more computers that are connected so that data and resources can be shared Most computers are connected to some kind of network Each computer has its own network address, which uniquely identifies it among the others A file server is a network computer dedicated to storing programs and data that are shared among network users
Network Connections
Each computer in a network could be directly connected to every other computer in the network These are called point-to-point connections Adding a computer requires a new communication line for each computer already in the network
This technique is not practical for more than a few close machines
Network Connections
Most networks share a single communication line
Network traffic must take turns using the line, which introduces delays
Often information is broken down in parts, called packets, which are sent to the receiving machine and then reassembled
Local-Area Networks
A Local-Area Network (LAN) covers a small distance and a small number of computers
LAN
A LAN often connects the machines in a single room or building
Wide-Area Networks
A Wide-Area Network (WAN) connects two or more LANs, often over long distances
LAN A LAN usually is owned by one organization, but a WAN often connects groups in different countries
LAN
The Internet
The Internet is a WAN which spans the entire planet The word Internet comes from the term internetworking It started as a United States government project, sponsored by the Advanced Research Projects Agency (ARPA) originally it was called the ARPANET The Internet grew quickly throughout the 1980s and 90s
TCP/IP
A protocol is a set of rules that determine how things communicate with each other The software which manages Internet communication follows a suite of protocols called TCP/IP The Internet Protocol (IP) determines the format of the information as it is transferred The Transmission Control Protocol (TCP) dictates how messages are reassembled and handles lost information
Domain Names
The last part of a domain name, called a top-level domain (TLD), indicates the type of organization: edu com org net educational institution commercial entity non-profit organization network-based organization
New TLDs have recently been added: biz, info, tv, name
Domain Names
A domain name can have several parts
Unique domain names mean that multiple sites can have individual computers with the same local name
When used, an Internet address is translated to an IP address by software called the Domain Name System (DNS) There is no one-to-one correspondence between the sections of an IP address and the sections of an Internet address
Outline
Computer Processing Hardware Components Networks The Java Programming Language
Introduction To Java
Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language
1-43
1-44
1-45
Netscape Incorporated made its Web browser capable of running Java programs (1995)
Other companies follow suit
1-46
1-47
Terminology Comparisons
Other high-level languages have constructs called procedures, methods, functions, and/or subprograms
These types of constructs are called methods in Java All programming constructs in Java, including methods, are part of a class
1-48
1-49
Applets
A Java applet (little Java application) is a Java program that is meant to be run from a Web browser
Can be run from a location on the Internet Can also be run with an applet viewer program for debugging Applets always use a windowing interface
In contrast, application programs may use a windowing interface or console (i.e., text) I/O
1-50
1-51
System.out.println
Java programs work by having things called objects perform actions
System.out: an object used for sending output to the screen
1-52
System.out.println
Invoking or calling a method: When an object performs an action using a method
Also called sending a message to the object Method invocation syntax (in order): an object, a dot (period), the method name, and a pair of parentheses Arguments: Zero or more pieces of information needed by the method that are placed inside the parentheses
System.out.println("This is an argument");
1-53
Variable declarations
Variable declarations in Java are similar to those in other programming languages
Simply give the type of the variable followed by its name and a semicolon
int answer;
1-54
Using = and +
In Java, the equal sign (=) is used as the assignment operator
The variable on the left side of the assignment operator is assigned the value of the expression on the right side of the assignment operator answer = 2 + 2;
In Java, the plus sign (+) can be used to denote addition (as above) or concatenation
Using +, two strings can be connected together
System.out.println("2 plus 2 is " + answer);
Copyright 2008 Pearson Addison-Wesley. All rights reserved
1-55
Machine language: A language that a computer can understand Low-level language: Machine language or any language similar to machine language Compiler: A program that translates a high-level language program into an equivalent low-level language program
This translation process is called compiling
1-56
In contrast, the Java compiler translates Java programs into byte-code, a machine language for a fictitious computer called the Java Virtual Machine
Once compiled to byte-code, a Java program can be used on any computer, making it very portable
1-57
1-58
Program terminology
Code: A program or a part of a program Source code (or source program): A program written in a high-level language such as Java
The input to the compiler program
1-59
Class Loader
Java programs are divided into smaller parts called classes
Each class definition is normally in a separate file and compiled separately
Class Loader: A program that connects the bytecode of the classes needed to run a Java program
In other programming languages, the corresponding program is called a linker
1-60
Each class is compiled with the command javac followed by the name of the file in which the class resides
javac FirstProgram.java The result is a byte-code program whose filename is the same as the class name followed by .class FirstProgram.class
1-61
Follow the run command by the name of the class only (no .java or .class extension)
java FirstProgram
1-62
1-63
1-64
1-65
Identifiers
Identifier: The name of a variable or other item (class, method, object, etc.) defined in a program
A Java identifier must not start with a digit, and all the characters must be letters, digits, or the underscore symbol Java identifiers can theoretically be of any length Java is a case-sensitive language: Rate, rate, and RATE are the names of three different variables
1-66
Identifiers
Keywords and Reserved words: Identifiers that have a predefined meaning in Java
Do not use them to name anything else public class void static
Predefined identifiers: Identifiers that are defined in libraries required by the Java language standard
Although they can be redefined, this could be confusing and dangerous if doing so would change their standard meaning System String println
1-67
Naming Conventions
Start the names of variables, classes, methods, and objects with a lowercase letter, indicate "word" boundaries with an uppercase letter, and restrict the remaining characters to digits and lowercase letters
topSpeed bankRate1 timeOfArrival
Start the names of classes with an uppercase letter and, otherwise, adhere to the rules above
FirstProgram MyClass String
1-68
Variable Declarations
Every variable in a Java program must be declared before it is used
A variable declaration tells the compiler what kind of data (type) will be stored in the variable The type of the variable is followed by one or more variable names separated by commas, and terminated with a semicolon Variables are typically declared just before they are used or at the start of a block (indicated by an opening brace { ) Basic types in Java are called primitive types int numberOfBeans; double oneWeight, totalWeight;
1-69
Primitive Types
1-70
An expression consists of a variable, number, or mix of variables, numbers, operators, and/or method invocations
temperature = 98.6; count = numberOfBeans;
1-71
1-72
1-73
1-74
which is equivalent to
Variable = Variable Op (Expression) The Expression can be another variable, a constant, or a more complicated expression Some examples of what Op can be are +, -, *, /, or %
1-75
Equivalent To:
count = count + 2;
Assignment Compatibility
In general, the value of one type cannot be stored in a variable of another type
int intVariable = 2.99; //Illegal The above example results in a type mismatch because a double value cannot be stored in an int variable
1-77
Assignment Compatibility
More generally, a value of any type in the following list can be assigned to a variable of any type that appears to the right of it
byteshortintlongfloatdouble char Note that as your move down the list from left to right, the range of allowed values for the types becomes larger
An explicit type cast is required to assign a value of one type to a variable whose type appears to the left of it on the above list (e.g., double to int) Note that in Java an int cannot be assigned to a variable of type boolean, nor can a boolean be assigned to a variable of type int
1-78
Constants
Constant (or literal): An item in Java which has one specific value that cannot change
Constants of an integer type may not be written with a decimal point (e.g., 10) Constants of a floating-point type can be written in ordinary decimal fraction form (e.g., 367000.0 or 0.000589) Constant of a floating-point type can also be written in scientific (or floating-point) notation (e.g., 3.67e5 or 5.89e-4)
Note that the number before the e may contain a decimal point, but the number after the e may not
1-79
Constants
Constants of type char are expressed by placing a single character in single quotes (e.g., 'Z') Constants for strings of characters are enclosed by double quotes (e.g., "Welcome to Java") There are only two boolean type constants, true and false
Note that they must be spelled with all lowercase letters
1-80
1-81
1-82
1-83
Precedence Rules
1-84
When two operations have equal precedence, the order of operations is determined by associativity rules
1-85
1-86
Computers actually store numbers in binary notation, but the consequences are the same: floating-point numbers may lose accuracy
1-87
When both operands are integer types, division results in an integer type
Any fractional part is discarded The number is not rounded 15/2 evaluates to 7
Be careful to make at least one of the operands a floatingpoint type if the fractional portion is needed
1-88
The % Operator
The % operator is used with operands of type int to recover the information lost after performing integer division
15/2 evaluates to the quotient 7 15%2 evaluates to the remainder 1
The % operator can be used to count by 2's, 3's, or any other number
To count by twos, perform the operation number % 2, and when the result is 0, number is even
1-89
Type Casting
A type cast takes a value of one type and produces a value of another type with an "equivalent" value
If n and m are integers to be divided, and the fractional portion of the result must be preserved, at least one of the two must be type cast to a floating-point type before the division operation is performed double ans = n / (double)m; Note that the desired type is placed inside parentheses immediately in front of the variable to be cast Note also that the type and value of the variable to be cast does not change
1-90
When the value of an integer type is assigned to a variable of a floating-point type, Java performs an automatic type cast called a type coercion
double d = 5;
In contrast, it is illegal to place a double value into an int variable without an explicit type cast
int i = 5.5; // Illegal int i = (int)5.5 // Correct
1-91
The decrement operator (--) subtracts one from the value of a variable
If n is equal to 4, then n-- or --n will change the value of n to 3
1-92
When either operator follows its variable, and is part of an expression, then the expression is evaluated using the original value of the variable, and only then is the variable value changed
If n is equal to 2, then 2*(n++) evaluates to 4
1-93
1-94
Concatenation of Strings
Concatenation: Using the + operator on two strings in order to connect them to form one longer string
If greeting is equal to "Hello ", and javaClass is equal to "class", then greeting + javaClass is equal to "Hello class"
Any number of strings can be concatenated together When a string is combined with almost any other type of item, the result is a string
"The answer is " + 42 evaluates to "The answer is 42"
1-95
1-96
1-97
String Methods
The String class contains many useful methods for stringprocessing applications
A String method is called by writing a String object, a dot, the name of the method, and a pair of parentheses to enclose any arguments If a String method returns a value, then it can be placed anywhere that a value of its type can be used String greeting = "Hello"; int count = greeting.length(); System.out.println("Length is " + greeting.length()); Always count from zero when referring to the position or index of a character in a string
1-98
1-99
1-100
1-101
1-102
1-103
1-104
1-105
1-106
String Indexes
1-107
Escape Sequences
A backslash (\) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character
The character following the backslash does not have its usual meaning Although it is formed using two symbols, it is regarded as a single character
1-108
Escape Sequences
1-109
String Processing
A String object in Java is considered to be immutable, i.e., the characters it contains cannot be changed There is another class in Java called StringBuffer that has methods for editing its string objects However, it is possible to change the value of a String variable by using an assignment statement
String name = "Soprano"; name = "Anthony " + name;
1-110
Character Sets
ASCII: A character set used by many programming languages that contains all the characters normally used on an Englishlanguage keyboard, plus a few special characters
Each character is represented by a particular number
Unicode: A character set used by the Java language that includes all the ASCII characters plus many of the characters used in languages with a different alphabet from English
1-111
Naming Constants
Instead of using "anonymous" numbers in a program, always declare them as named constants, and use their name instead
public static final int INCHES_PER_FOOT = 12; public static final double RATE = 0.14; This prevents a value from being changed inadvertently It has the added advantage that when a value must be modified, it need only be changed in one place Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore character
1-112
Comments
A line comment begins with the symbols //, and causes the compiler to ignore the remainder of the line
This type of comment is used for the code writer or for a programmer who modifies the code
A block comment begins with the symbol pair /*, and ends with the symbol pair */
The compiler ignores anything in between This type of comment can span several lines This type of comment provides documentation for the users of the program
1-113
Program Documentation
Java comes with a program called javadoc that will automatically extract documentation from block comments in the classes you define
As long as their opening has an extra asterisk (/**)
1-114
1-115