Transcript Document

CISC121
to: “Introduction to Computing Science I”
• Prof. McLeod ([email protected]), GOO550
• TA’s are Ana and Krista.
• Web site:
http://www.cs.queensu.ca/home/cisc121
Summer 2007
CISC121 - Prof. McLeod
1
Administration…
• Please give me your name, SN, QLink ID and
preferred E-mail address (if not QLink).
• While Ana and Krista are here – we should
discuss the use of the lab (GOO 458 – right
across from the elevator and stairs in Goodwin
Hall) and tutorials/tutoring.
• And: I would also like to find out what kind of
programming experience you have.
Summer 2007
CISC121 - Prof. McLeod
2
Course Content
• This is not a “Java Course”!
• But, we need a language to demonstrate and
practice the concepts to be discussed.
• Java is the language of choice.
– A modern, platform-independent, Object-Oriented
language.
– We could have used many other languages equally
well: C#, C++, VB, Delphi, Pascal, Turing, etc.
Summer 2007
CISC121 - Prof. McLeod
3
Course Content, Cont.
• First, a review of the Java language, then:
Practical Topics
Theory Topics
Algorithm Topics
Coding Style
Analysis of
Complexity
Data Structures
Documentation
Numerical Storage
& Computation
Recursion
Testing &
Debugging
Sorting
Assertions &
Invariants
Searching
Summer 2007
CISC121 - Prof. McLeod
4
Course Content, Cont.
Practical Topics
Theory Topics
Algorithm Topics
Coding Style
Analysis of
Complexity
Data Structures
Documentation
Numerical
Storage &
Computation
Recursion
Testing &
Debugging
Sorting
Assertions &
Invariants
Searching
• These topics are not Language-Dependant!
Summer 2007
CISC121 - Prof. McLeod
5
Course Content, Cont.
• There is no single optimum way to navigate these
topics:
• From example programs in class:
– See examples (I hope!) of good coding style.
– See examples of testing & debugging (I’m sure!).
– Measure time of execution to verify complexity
analyses.
– Test the effect of finite memory used to store numbers.
– Code and demonstrate the data structures and
algorithms discussed.
Summer 2007
CISC121 - Prof. McLeod
6
Course Content, Cont.
• Assignments and exercises will:
– At first, be used to practice fundamental Java language
concepts.
– Later, to explore concepts introduced in lecture.
– And then to apply some of the algorithms learned to
practical situations.
• There is a set of exercises posted and an
assignment due next week – we’ll have a look
shortly when we check out the course web site.
Summer 2007
CISC121 - Prof. McLeod
7
Course Content, Cont.
• Lectures will be shared with many examples and
class problems (as well as “breaks” in the
sunshine and/or Tim Hortons!).
• Some notes (the really boring ones…) may be
assigned as “reading”, and will not be presented
in class.
• Your questions are very important!! They will
really help to make the lectures more interesting!
Summer 2007
CISC121 - Prof. McLeod
8
How to Pass
• Evaluation:
– 25% Assignments (5% each?)
– 25% Midterm
– 50% Final Exam
• The midterm date could be July 24 or 26 instead
of a lecture (date is negotiable!).
• The Final Exam date (not set by me) is Aug. 15.
• Let me know if you anticipate having problems
making any of these dates.
Summer 2007
CISC121 - Prof. McLeod
9
How to Pass – Cont.
• Do all the assignments and all practice questions
yourself. Do not look at solutions until you have
tried them.
• Ask if you have questions:
– Ask Ana or Krista – in lab, by E-mail.
– Ask me – during lecture, by E-mail, after lectures.
• Read lecture notes.
• Many other resources are listed on the web site.
• Textbook – up to you!
Summer 2007
CISC121 - Prof. McLeod
10
Resources
• Web site:
– http://www.cs.queensu.ca/home/cisc121
– Assignments, assignment solutions, lecture notes,
reading notes, exercises, course topics and references
are available from the web site.
• E-mail
–
–
–
–
Me: [email protected]
Ana: [email protected]
Krista: [email protected]
Make sure I have your correct E-mail address! Some
important notices will be sent out by E-mail.
Summer 2007
CISC121 - Prof. McLeod
11
Assignments
• One, possibly two(!) per week.
• Individual submission only – no group
assignments.
• Submit code only (*.java file(s)) through course
WebCT site. Instructions on course web site.
• Ana or Krista will be grading them, not me!
• Assignment 1 is posted.
Summer 2007
CISC121 - Prof. McLeod
12
Exercise Problems
• Are linked off the web site.
• You don’t hand them in.
• Exercise 1 is very straightforward – you can start
it after you have your Java environment of choice
installed.
Summer 2007
CISC121 - Prof. McLeod
13
Exams
•
•
•
•
Yuk!
Midterm July 24 or 26 – 2 hours.
Final August 15 – 3 hours.
Both exams are written on paper with no aids
except for a supplied aid sheet (Java syntax
summary).
Summer 2007
CISC121 - Prof. McLeod
14
Warning!
• Most of the contents of a first year programming
course like APSC142 or CISC101 will be reviewed
in two or three lectures.
• If you do not have any programming background
nor a strong aptitude for coding, you might have
problems keeping up!
• If you need more time with basic Java, pick up a
first year-level textbook (from me or the library)
and/or see if you can spend more time with Ana or
Krista.
Summer 2007
CISC121 - Prof. McLeod
15
Java “6.0”
• Also called JDK 1.6.0
• The Java language has recently undergone some
very positive changes (especially since 5.0).
• Only recently have the development tools caught
up with this new release of Java.
• The lab machines may not yet use this new
version of Java, but you might wish to use it at
home.
• See the Resources page for instructions on how
to get the software tools you need.
Summer 2007
CISC121 - Prof. McLeod
16
Today
• (Is it break time yet??)
• Check out the course web site.
• I’ll assume you have used WebCT before?
• Look at our first code sample to see what’s
ahead!
• Start reviewing fundamental Java, Eclipse demo.
Summer 2007
CISC121 - Prof. McLeod
17
Code Sample 1
•
•
•
•
•
Can a computer generate random numbers?
Is any part of a computer’s operation random?
How does generateNums work?
Why is the current time used?
Which sort do you think will be faster? The longer
one or the shorter one?
• Which one is faster? Why?
• Can you decide which one will be faster through
analysis?
• Do you recognize either sorting algorithm?
Summer 2007
CISC121 - Prof. McLeod
18
A Simple Java Program
public class HelloProg
{
public static void main (String [] args)
{
System.out.println ("Hello there!");
} // end main method
} // end HelloProg class
• The “//” denotes an in-line comment. Everything else on
the line is ignored by the compiler.
Summer 2007
CISC121 - Prof. McLeod
19
A Simple Java Program – Cont.
• The compiler ignores any “white space” in your
source code – returns, line feeds, tabs, extra
spaces and comments.
• Here’s our little program without white space
(imagine this all on one line):
public class HelloProg{public static void main(String[]
args){System.out.println("Hello there!");}}
• This does still run, but it is hard to read…
Summer 2007
CISC121 - Prof. McLeod
20
Running a Java Program
• What happens when a program is run?
• Remember that Java code is platform
independent.
• Compilation of Java source code (HelloProg.java)
is done by a compiler (javac.exe) that creates a
“byte code” file (HelloProg.class) that is still
platform independent.
• This byte code file cannot be viewed or edited and
is very compact.
Summer 2007
CISC121 - Prof. McLeod
21
Running a Java Program – Cont.
• Each platform capable of running Java programs
has its own “JVM” or Java Virtual Machine – also
called a “byte code interpreter”.
• This program (java.exe on a Wintel machine) runs
the byte code file to perform on a specific
platform.
Summer 2007
CISC121 - Prof. McLeod
22
Eclipse Demo
• Let “us” check out Eclipse and how it runs a
program:
– Create a project.
– Create an empty program.
– Edit / save / debug / run the program.
Summer 2007
CISC121 - Prof. McLeod
23
Running an Applet
• Helps to explain why Java programs run this way:
• An Applet is a small byte code file that is linked to
a web page.
• Compact is important in order to minimize
download times.
• The JVM is part of the browser, and browsers are
platform specific, but the applet is not.
• In the case of an applet, the JVM built into the
browser runs the applet.
Summer 2007
CISC121 - Prof. McLeod
24
A Simple Java Program – Cont.
• Back to our little program:
public class HelloProg
{
public static void main (String [] args)
{
System.out.println ("Hello there!");
} // end main method
} // end HelloProg class
Summer 2007
CISC121 - Prof. McLeod
25
A Simple Java Program – Cont.
• A Class is an “Object” in Java. All Objects in Java
are Classes…
• A Class is a container – it holds attributes or fields
(data) and methods (code that does something).
• Our class is called “HelloProg”. Our class must
be defined in a file called “HelloProg.java”.
• The code “public class HelloProg” is used
to declare the class.
• The contents of the class are contained in a set of
curly brackets: “{ }”.
Summer 2007
CISC121 - Prof. McLeod
26
A Simple Java Program – Cont.
• Our little class does not contain any attributes
(data) and only has one method called “main”.
• The main method is declared using the code:
public static void main (String [] args)
• As before the code is contained within: “{ }”.
Summer 2007
CISC121 - Prof. McLeod
27
The main Method
• For the JVM to run a program, it must know where
to start.
• By design, the starting point is always the
execution of the main method.
• The JVM expects the main method to be
declared exactly as shown – the only thing you
can change is the name of the String array, called
“args” in this little program.
Summer 2007
CISC121 - Prof. McLeod
28
A Simple Java Program – Cont.
• Our main method contains only one line of code:
System.out.println ("Hello there!");
• It prints out “Hello there!” to the screen (or
“console”). We’ll talk more about I/O
(“Input/Output”) later.
• Note the “;” at the end of the line of code. Since
the Java compiler ignores white space, it must
use these characters to determine when a line
finishes.
Summer 2007
CISC121 - Prof. McLeod
29
Object Oriented Programming in Java
• An Object is simply a container with a defined
interface to the rest of the world.
• Examples: Tape Deck, Automobile, etc.
• An Object in Java is a class.
• A class contains members.
• Members can be attributes or fields (data) and
methods.
• Attributes are held by instance variables defined
inside the class.
Summer 2007
CISC121 - Prof. McLeod
30
OOP in Java - Cont.
• A class consists of instance variables and/or methods.
• By convention, instance variables are all declared before
the methods:
public class ShowStructure {
// instance variables or “attributes” here
// methods here
} // end class ShowStructure
Summer 2007
CISC121 - Prof. McLeod
31
Program Template
• Class structure:
public class HelloProg {
public static void main (String [] args){
System.out.println ("Hello
there!");
Method
Class
} // end main method
} // end HelloProg class
Summer 2007
CISC121 - Prof. McLeod
32
OOP in Java – Cont.
• In Java, a class is an Object, and an Object is a
class (rather Zen is it not!)
• Code and attributes cannot be defined outside of
a class.
• The only code that can exist outside a method are
attributes.
Summer 2007
CISC121 - Prof. McLeod
33
Attributes
• Also called “class variables” or “instance
variables” or “fields”.
• Declared within a class at the same level as the
method declarations.
• These variables are known to all methods within a
class.
• We will discuss them in more detail later…
Summer 2007
CISC121 - Prof. McLeod
34
OOP in Java - Cont.
• When referencing members of a class, the period
operator, “.” is used to separate member names
from the class name.
• If members of a class are “public” in scope,
then they can be used by other classes.
• If members of a class are “private” in scope
they are only available inside the class, not
outside.
• If the member is a method, then the method name
is always followed by “()”, even if they are empty.
Summer 2007
CISC121 - Prof. McLeod
35
Modular Programs
• For a very short time, we will discuss programs
that only have a main method.
• Initially we will concentrate on procedural code.
• Pretty soon, our main method will get too big, and
it will be time to break our programs into pieces.
Summer 2007
CISC121 - Prof. McLeod
36
Primitive Types
• Unfortunately not everything in Java is an Object.
• Primitive Types are used to declare variables
that themselves will not be Objects either.
• This is done for convenience and more efficient
use of memory.
• Primitive Type variables fall into the categories of
integer types, real types, characters and
booleans.
Summer 2007
CISC121 - Prof. McLeod
37
Integer Primitive Types
• byte, short, int, long
• For byte, from -128 to 127, inclusive (1 byte).
• For short, from -32768 to 32767, inclusive (2
bytes).
• For int, from -2147483648 to 2147483647,
inclusive (4 bytes).
• For long, from -9223372036854775808 to
9223372036854775807, inclusive (8 bytes).
• A “byte” is 8 bits, where a “bit” is either 1 or 0.
Summer 2007
CISC121 - Prof. McLeod
38
Aside - Number Ranges
• Where do these min and max numbers come
from?
• Memory limitations and the system used by Java
(two’s complement) to store numbers determines
the actual numbers.
• The Wrapper classes can be used to provide the
values - for example:
Integer.MAX_VALUE // returns the value 2147483647
• More on these topics later!
Summer 2007
CISC121 - Prof. McLeod
39
Real Primitive Types
• Also called “Floating Point” Types:
• float, double
• For float, (4 bytes) roughly ±1.4 x 10-38 to ±3.4
x 1038 to 7 significant digits.
• For double, (8 bytes) roughly ±4.9 x 10-308 to
±1.7 x 10308 to 15 significant digits.
Summer 2007
CISC121 - Prof. McLeod
40
Character Primitive Type
• char
• from '\u0000' to '\uffff' inclusive, that is,
from 0 to 65535 (base 10) or 0 to ffff (base 16, or
“hexadecimal”). A variable of the “char” type
represents a Unicode character. Can also be
represented as ‘a’ or ‘8’, etc.
Summer 2007
CISC121 - Prof. McLeod
41
Boolean Primitive Type
• boolean is either true or false.
Summer 2007
CISC121 - Prof. McLeod
42
Primitive Types, Cont.
• Everything else in Java is an Object.
• The rest of the language consists of:
–
–
–
–
literal values
operators
keywords
“punctuation”
Summer 2007
CISC121 - Prof. McLeod
43
String Objects
• String’s are not primitive data types, but are
Objects.
• A String is declared in the same way as a
primitive type using the keyword: String.
Summer 2007
CISC121 - Prof. McLeod
44
Variable Declaration
• Java is a “declarative” language.
• In other words, variables must be declared before they
can be used.
• To declare a variable, use the Java “keyword” appropriate
for the type of variable you are declaring followed by a
variable name you have created, followed by a semicolon.
• Examples:
int aNum;
char aLetter;
double totalVolume;
String userPrompt;
Summer 2007
CISC121 - Prof. McLeod
45
Legal Variable Names
• Java names may contain any number of letters,
numbers and underscore (“_”) characters, but
they must begin with a letter.
• Standard Java Naming Convention:
– Names beginning with lowercase letters are variables
or methods.
– Names beginning with uppercase letters are class
names.
– Successive words within a name are capitalized
(“camel case”).
– Names in all capital letters are constants.
• (We’ll get to “constants” shortly).
Summer 2007
CISC121 - Prof. McLeod
46
Literal Values
• Integers, for example:
12
-142
0
333444891
• If you write these kinds of numbers into your
program, Java will assume them to be of type
“int”, and store them accordingly.
• If you want them to be of type “long”, then you
must append a “L” to the number:
43L
Summer 2007
9999983475L
CISC121 - Prof. McLeod
-22233487L
47
Literal Values - Cont.
• Real or “Floating Point” numbers, for example:
4.5
-1.0
3.457E-10
-3.4E45
• These literals will be assumed to be of the
“double” type.
• If you want them to be stored as “float” types,
append an “F”:
3.456F
Summer 2007
5.678E-10F
CISC121 - Prof. McLeod
-321.0F
48
Literal Values - Cont.
• char literals:
‘A’
‘5’
‘\u0032’
• boolean literals:
true
false
• String literals:
“Hello there!”
Summer 2007
“456.7”
CISC121 - Prof. McLeod
“West of North”
49
Variable Declaration - Cont.
• int and double variables initially are given a
value of zero unless they are initialized to a value.
• Java may prevent you from using variables that
are not initialized.
• So, it is sometimes good practice to initialize your
variables before use, for example:
int numDaysInYear = 365;
double avgNumDaysInYear = 365.25;
String greetingLine = “Hello there!”;
long counter = 0;
Summer 2007
CISC121 - Prof. McLeod
50
Variable Declaration - Cont.
• All these statements could be carried out in two
lines, for example:
int numDaysInWeek = 7;
Is the same as:
int numDaysInWeek;
numDaysInWeek = 7;
Summer 2007
CISC121 - Prof. McLeod
51
Constants
• The Java keyword, “final” can be used to make
sure a variable value is no longer “variable”.
• It becomes a constant, because Java will not
allow your program to change its value once it has
been declared:
final int NUM_DAYS_IN_YEAR = 365;
final double MM_PER_INCH = 25.4;
Summer 2007
CISC121 - Prof. McLeod
52
Type Casting
• When a value of one type is stored into a variable
of another type.
• Casting in one direction is automatic, you do not
have to deliberately or “explicitly” cast:
• A value to the left can be assigned to a variable to
the right without explicit casting:
byte > short > int > long > float > double
Summer 2007
CISC121 - Prof. McLeod
53
Type Casting - Cont.
• For example in the statement:
double myVar = 3;
the number 3 is automatically cast to a double (3.0) before
it is stored in the variable “myVar”.
• However, if you tried the following:
int anotherVar = 345.892;
the compiler would protest loudly because a double
cannot be stored in an int variable without loss of
precision. Wrong direction!
Summer 2007
CISC121 - Prof. McLeod
54
Type Casting - Cont.
• If you really want to cast in the other direction,
then you must make an explicit cast. For
example:
int anotherVar = (int)345.892;
is legal. The “(int)” part of the statement casts
the double to an int. The variable
anotherVar would hold the value 345
• Note how numbers are truncated, not rounded
when casting!
Summer 2007
CISC121 - Prof. McLeod
55
Arithmetic Operators
• The standard binary arithmetic operators in Java are:
– Addition (+)
– Subtraction (-)
– Multiplication (*)
– Division (/)
– Modulus or Remainder (%) (ie. 12 % 5 yields 2)
• All of these operations apply to all numeric primitive data
types.
• All require values on both sides of the operator (why they
are called “binary operators”).
Summer 2007
CISC121 - Prof. McLeod
56
Integer Arithmetic
• Arithmetic operations between integers produce
integer results by truncating the answer —
fractional parts are discarded
• Examples:
3 / 4 stores as 0
4 / 4 stores as 1
5 / 4 stores as 1
• Integer arithmetic is unsuitable for calculations
involving real-world continuous quantities
Summer 2007
CISC121 - Prof. McLeod
57
Real or Floating Point Arithmetic
• Floating-point arithmetic is used with float and
double values. It produces the expected results:
4.0 / 3.0 = 1.3333333333333
• However, these numbers have range and
precision limits:
Type
float
double
Summer 2007
Range
±1038
±10308
Precision
6-7 decimal digits
15-16 decimal digits
CISC121 - Prof. McLeod
58
Mixed Type Arithmetic Expressions
• Suppose you have a “mixed type” expression involving an
arithmetic operator.
• To evaluate the expression, Java will cast one side to
match the other.
• For example if one side is an int and the other side is a
double, the int will be automatically cast to a double
before the operation takes place.
• For example:
9 /
9 /
4 *
4.0
Summer 2007
2 stores as 4
2.0 stores as 4.5
12 stores as 48
* 12 stores as 48.0
CISC121 - Prof. McLeod
59
Strings and the “+” Operator
• Not only can “+” operate on numeric values, but it
can also handle String’s on either or both sides.
• If one side is not a String, it will be changed to
one, and then it will be concatenated to the
String on the other side:
4 + “you” stores as “4you”
“apples” + “oranges” + 9 + 9 stores as
“applesoranges99”
3 + 7 + “little piggies” stores as “10little piggies”
• Expressions are evaluated from left to right,
unless precedence rules apply.
Summer 2007
CISC121 - Prof. McLeod
60
Unary Arithmetic Operators
• Unary operators include “+” and “-”, where “-aNum”
negates the value produced by aNum, for example.
• They also include the increment (++) and decrement (--)
operators which increase or decrease an integer value by
1.
• Preincrement and predecrement operators appear
before a variable. They increment or decrement the value
of the variable before it is used in the expression.
• Example:
int i = 4, j = 2, k;
k = ++i - j;
// i = 5, j = 2, k = 3
Summer 2007
CISC121 - Prof. McLeod
61
Unary Arithmetic Operators - Cont.
• Postincrement and postdecrement operators
appear after a variable. They increment or
decrement the value of the variable after it is used
in the expression.
• Example:
int i = 4, j = 2, k;
k = i++ - j;
// i = 5, j = 2, k = 2
• Keep expressions involving increment and
decrement operators simple!
Summer 2007
CISC121 - Prof. McLeod
62
Assignment Operators
=
*=
/=
-=
+=
Summer 2007
set equal to
multiply and set equal to
divide and set equal to
subtract and set equal to
add and set equal to
CISC121 - Prof. McLeod
63
Assignment Operators - Cont.
• An assignment statement in Java has the form
variableName = expression;
• The expression is evaluated, and the result of the
expression is stored in the specified variable.
• Assignment statements and arithmetic operations can be
combined in a single symbol. For example,
variableName += expression;
is equivalent to
variableName = variableName + expression;
Summer 2007
CISC121 - Prof. McLeod
64
Logical Binary Operators
• Return either true or false.
==
!=
>
<
>=
<=
equals to
not equals to
greater than
less than
greater than or equal to
less than or equal to
&, &&
|, ||
logical “And”
logical “Or”
Summer 2007
CISC121 - Prof. McLeod
65
Aside – “|” or “||”?
• What’s the difference?
• A single “|” or “&” always evaluates both sides of the
expression, whether it is necessary or not.
• “&&” stops if the left side is false, “||” stops if the left side
is true.
• When would this make a difference?
• For example:
int x = 0, y = 4;
boolean test = x != 0 & y / x > 1;
– Gives an error, using “&&” would not. Why?
Summer 2007
CISC121 - Prof. McLeod
66
Logical Operators - Cont.
• The one “unary” logical operator is “!”.
• Called the “Not” operator.
• It reverses the logical value of a boolean.
• For example:
!(5 > 3) evaluates to false
Summer 2007
CISC121 - Prof. McLeod
67
Logical Operators - Cont.
• “Truth” tables for the “And” and “Or” operators:
&&
||
testa
testa
testb true
false
testb true
false
true
false
true
true
true
false false false
Summer 2007
true
false true
CISC121 - Prof. McLeod
false
68
Precedence Rules
• Operator precedence rules determine which operations
take place in what order:
–
–
–
–
–
–
–
Unary operations including casting, are done first.
Then *, /, %
Then +, Then <, >, <=, >=
Then ==, !=
Then &, &&, |, ||
Then =, *=, +=, -=, /=
• Use “( )” to control order of operations, as the expression
inside “( )” will be evaluated before stuff outside of “( )”.
Summer 2007
CISC121 - Prof. McLeod
69
Expressions
• Expressions are combinations of variables, literal
values, and operators.
• For example:
int aNum = 4 + 3 * 7; // aNum
int aNum = (4 + 3) * 7;
//
(4 > 7) || (10 > -1)
//
(5.5 >= 5) && (4 != 1.0)
//
double circ = 3.14 * 2 * r;
…
Summer 2007
CISC121 - Prof. McLeod
is 25
aNum is 49
yields true
yields true
70