Upload
malana
View
44
Download
0
Embed Size (px)
DESCRIPTION
Program Elements -- Introduction. We can now examine the core elements of programming Chapter 3 focuses on: data types variable declaration and use operators and expressions decisions and loops input and output. Primitive Data Types. - PowerPoint PPT Presentation
Citation preview
310417 2000 WEEK 2
1
-- Program Elements Intro -- Program Elements Introductionduction
• We can now examine the core elements of programming
• Chapter 3 focuses on:– data types– variable declaration and use– operators and expressions– decisions and loops– input and output
310417 2000 WEEK 2
2
Primitive Data Types Primitive Data Types
• A data type is defined by a set of values an d the operators you can perform on them
• Each value stored in memory is associated with a particular data type
• The Java language has several predefined t ypes, called primitive data types
• The following reserved words represent eig ht different primitive types:
– byte , short , int , long , float , double , boolean , char
310417 2000 WEEK 2
3
IntegersIntegers• There are four separate integer primiti
ve data types
• They differ by the amount of memory u sed to store them
Type
byteshortintlong
Storage
8 bits16 bits32 bits64 bits
Min Value
-128-32,768-2,147,483,648< -9 x 1018
Max Value
12732,7672,147,483,647> 9 x 1018
310417 2000 WEEK 2
4
Floating Point Floating Point
• There are two floating point types:
• The float type stores 7 significant digits
• The double type stores 15 significant digits
Type
floatdouble
Storage
32 bits64 bits
ApproximateMin Value
-3.4 x 1038
-1.7 x 10308
ApproximateMax Value
3.4 x 1038
1.7 x 10308
310417 2000 WEEK 2
5
CharactersCharacters
• A char value stores a single character from th e Unicode character set
• A character set is an ordered list of characters
• The Unicode character set uses sixteen bits pe r character, allowing for 65,536 unique characters
• It is an international character set, containing symbols and characters frommany world lang
uages
310417 2000 WEEK 2
6
CharactersCharacters
• The ASCII character set is still the basis for many other programming language
s
• ASCII is a subset of Unicode, including:uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters
A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...
310417 2000 WEEK 2
7
BooleanBoolean
•A boolean value represents a true or f alse condition
• They can also be used to represent any two states, such as a light bulb being o
n or off
• The reserved words true and false a re the only valid values for a boolean ty
pe
310417 2000 WEEK 2
8
WrappersWrappers• For each primitive data type there is a cor
responding wrapper class . For example:
• Wrapper classes are useful in situations w here you need an object instead of a primi
tive type
• They also contain some useful methods
Primitive Type
intdoublechar
boolean
Wrapper Class
IntegerDouble
CharacterBoolean
310417 2000 WEEK 2
9
VariablesVariables
• A variable is an identifier that represents a l ocation in memory that holds a particular ty
pe of data
• Variables must be declared before they can be used
• The syntax of a variable declaration is: data-type variable-name;
• For example: int total;
310417 2000 WEEK 2
10
VariablesVariables
• Multiple variables can be declared on t he same line:
int total, count, sum;
• Variables can be initialized (given an in itial value) in the declaration:
int total = 0, count = 20; float unit_price = 57.25;
• See Piano_Keys.java
310417 2000 WEEK 2
11
Assignment Statements Assignment Statements• An assignment statement takes the followi
ng form: variable-name = expression;
• The expression is evaluated and the result is stored in the variable, overwriting the va
lue currently stored in the variable
• See United_States.java
• The expression can be a single value or a m ore complicated calculation
310417 2000 WEEK 2
12
ConstantsConstants
• A constant is similar to a variable exce pt that they keep the same value throu
ghout their existence
• They are specified using the reservedword final in the declaration
• For example: final double PI = 3.14159; final int STUDENTS = 25;
310417 2000 WEEK 2
13
ConstantsConstants
• When appropriate, constants are bette r than variables because:– they prevent inadvertent errors bec
ause their value cannot change
• They are better than literal values because:– they make code more readable by gi
ving meaning to a value– they facilitate change because the v
alue is only specified in one place
310417 2000 WEEK 2
14
Input and Output Input and Output
• Java I/O is based on input streams and o utput streams
• There are three predefined standard streams:
• The print and println methods write to standard output
Stream
System.inSystem.outSystem.err
Purpose
reading inputwriting outputwriting errors
Default Device
keyboardmonitormonitor
310417 2000 WEEK 2
15
Input and Output Input and Output
• The Java API allows you to create many k inds of streams to perform various kinds
of I/O• To read character strings, we will conve
rt the System.in stream to another kind of stream using:
• BufferedReader stdin = new BufferedReader
• (new InputStreamReader (System.in));
• This declaration creates a new stream called stdin
• Wewill discuss object creation in more d etail later
310417 2000 WEEK 2
16
Escape Sequences Escape Sequences
• See Echo.java• An escape sequence is a special seque
nce of characters preceded by a backsl ash (\)
• They indicate some special purpose, su ch as:Escape Sequence
\t\n\"\'\\
Meaning
tabnew line
double quotesingle quotebackslash
310417 2000 WEEK 2
17
BuffersBuffers• As you type, the characters are stored in an
input buffer
• When you press enter, the program begins processing the data
• Similarly, output information is temporarily stored in an output buffer
• The output buffer can be explicitly flushed ( sent to the screen) using the flush method
• See Python.java
310417 2000 WEEK 2
18
Numeric Input Numeric Input
• Converting a string that holds an integer into the integer value can be done with a
method in the Integer wrapper class:
value = Integer.parseInt (my_string);
• A value can be read and converted in oneline:
num = Integer.parseInt (stdin.readLine());
• See Addition.java and Addition2.java
310417 2000 WEEK 2
19
ExpressionsExpressions• An expression is a combination of operator
s and operands
• The arithmetic operators include addition (+ ), subtraction (- ), multiplication (* ), and di
vision (/)
• Operands can be literal values, variables, o r other sources of data
• The programmer determines what is done with the result of an expression (stored, pri nted, etc.)
310417 2000 WEEK 2
20
DivisionDivision• If the operands of the / operator are bo
th integers, the result is an integer (the f ractional part is truncated)
• If one or more operands to the / operat or are floating point values, the result is
a floating point value• The remainder operator (% ) returns the i
nteger remainder after dividing the first operand by the second
• The operands to the % operator must beintegers
• See Division.java • The remainder result takes the sign of th
e numerator
310417 2000 WEEK 2
21
DivisionDivision
Expression
17 / 517.0 / 517 / 5.0
9 / 129.0 / 12.0
6 % 214 % 5-14 % 5
Result
33.43.4
00.75
04-4
310417 2000 WEEK 2
22
Operator Precedence Operator Precedence
• The order in which operands are evaluated in - an expression is determined by a well defined
precedence hierarchy
• Operators at the same level of precedence ar e evaluated according to their associativity (r
ight to left or left to right)
• Parentheses can be used to force precedence
• Appendix D contains a complete operator pre cedence chart for all Java operators
310417 2000 WEEK 2
23
Operator Precedence Operator Precedence• Multiplication, division, and remainder
have a higher precedence than additio n and subtraction
• Both groups associate left to rightExpression:
Order of evaluation:
Result:
5 + 12 / 5 - 10 % 3
6
43 21
310417 2000 WEEK 2
24
Operator Precedence Operator Precedence
Expression
2 + 3 * 4 / 2
3 * 13 + 2(3 * 13) + 23 * (13 + 2)
4 * (11 - 6) * (-8 + 10)
(5 * (4 - 1)) / 2
Result
8
414145
40
7
310417 2000 WEEK 2
25
The if Statement The if Statement
• The Java if statement has the following syntax:
if (condition)
statement;
• If the boolean condition is true, the stateme nt is executed; if it is false, the statement i
s skipped• This provides basic decision making capabilities
310417 2000 WEEK 2
26
The if Statement The if Statement
statement
conditionfalse
true
310417 2000 WEEK 2
27
Boolean Expressions Boolean Expressions• The condition of an if statement must
evaluate to a true or false result• Java has several equality and relationaloperators:
• See Temperature.java
Operator
==!=<<=><=
Meaning
equal tonot equal to
less thanless than or equal to
greater thangreater than or equal to
310417 2000 WEEK 2
28
Block Statements Block Statements
• Several statements can be grouped tog ether into a block statement
• Blocks are delimited by braces
• A block statement can be used wherev er a statement is called for in the Java s
yntax
• See Temperature2.java
310417 2000 WEEK 2
29
- The if else Statement - The if else Statement
• An else clause can be added to an if state ment to make it an - if else statement:
if (condition) statement1; else statement2;
• If the condition is true, statement1 is execut 2ed; if the condition is false, statement is ex
eeeeee• eee Temperature3.java eee Right_Triangle.java
310417 2000 WEEK 2
30
- The if else Statement - The if else Statement
statement1
conditionfalse
true
statement2
310417 2000 WEEK 2
31
Nested if Statements Nested if Statements
• The body of an if statement or else clause can be another if statement
• These are called nested if statements
• See Football_Choice.java
• Note: an else clause is matched to th e last unmatched if (no matter what t
he indentation implies)
310417 2000 WEEK 2
32
The while Statement The while Statement
• A while statement has the following syntax:
while (condition)
statement;
• If the condition is true, the statement is exec uted; then the condition is evaluated again
• The statement is executed over and over unti l the condition becomes false
310417 2000 WEEK 2
33
The while Statement The while Statement
statement
conditionfalse
true
310417 2000 WEEK 2
34
The while Statement The while Statement
• If the condition of a while statement i s false initially, the statement is neverexecuted
• Therefore, we say that a while statem ent executes zero or more times
• See Counter.java, Factors.java , and Powers_of_Two.java
310417 2000 WEEK 2
35
Infinite Loops Infinite Loops
• The body of a while loop must eventually make the condition false
• If not, it is an infinite loop , which will execu te until the user interrupts the program
• -- This is a common type of logical error al ways double check that your loops will ter
minate normally
• See Forever.java
310417 2000 WEEK 2
36
Program Development Program Development
• The creation of software involves four basic activities:
– establishing the requirements– creating a design– implementing the code– testing the implementation
• The development process is muchmor e involved that this, but these basic ste
ps are a good starting point
310417 2000 WEEK 2
37
RequirementsRequirements
• Requirements specify the tasks a progr ammust accomplish (what to do, not h ow to do it)
• They often address the user interface• An initial set of requirements are often
provided, but usually must be critiqued , modified, and expanded
• It is often difficult to establish detailed, unambiguous, complete requirements
• Careful attention to the requirements c an save significant time andmoney in t he overall project
310417 2000 WEEK 2
38
DesignDesign• A program follows an algorithm , which is a
- - step by step process for solving a problem
• The design specifies the algorithms and da ta needed
• - In object oriented development, it establis hes the classes, objects, and methods that are required
• The details of a method may be expressed i n pseudocode - , which is code like, but does
not necessarily follow any specific syntax
310417 2000 WEEK 2
39
ImplementationImplementation• Implementation is the process of translating
a design into source code
• Most novice programmers think that writing code is the heart of software development, b
ut it actually should be the least creative
• Almost all important decisions are made duri ng requirements analysis and design
• Implementation should focus on coding detai ls, including style guidelines and documenta
tion
310417 2000 WEEK 2
40
TestingTesting
• A program should be executed multiple ti mes with various input in an attempt to fi
nd errors
•Debugging is the process of discovering t he cause of a problem and fixing it
• Programmers often erroneously think tha t there is "only one more bug" to fix
• Tests should focus on design details as we ll as overall requirements
310417 2000 WEEK 2
41
Program Development Program Development• See Average.java
• Follow the process of requirements analysi s, design, implementation, and testing
• There are always multiple ways to design a nd implement a program
• Any design has advantages and disadvanta -ges; there are always trade offs
• See Average2.java