Title: CS1: Introduction to Computation
1CS1Introduction to Computation
- Day 20 December 5, 2007
- Java
2The Hitchhiker's Guide to the Galaxy (1981)
3Computer languages...
- Are like a Tower of Babel
- Many mutually-incomprehensible dialects
- Our goal CS 1 should be a kind of "Babel fish"
enabling you to rapidly absorb new languages as
needed - We test this theory today
4Reminisce
- On day 1
- we saw that we already knew many of the forms
and concepts needed to write Scheme code - We simply needed to
- pick out the ones to use
- be a bit more precise about how to specify a few
things
5Throughout the term
- Do arithmetic
- Work with types
- numbers, booleans, pairs, procedures
- Perform conditional operations
- if, cond
- Write functions
- Build compound data types
- cons
- Change values
- set!, set-car!, set-cdr!
- Reason about the meaning of programs
- Build generic data types
- Message passing
- Manage program complexity
- abstraction
6Claim
- Now that you know all these things
- you know most of the concepts which arise in all
computer languages - ? Largely a matter of concept-mapping and
transliteration to understand the others - Today transliteration to Java
7Java
- Language syntax roots in "C", "C"
- We'll learn a bit of C, too.
- Language features similar to Scheme
- Mostly a subset!
- Map analogies between features
- A couple of new concepts
- static typing
- explicit framework for message-passing objects
8Jumping Right In
9Summing integers
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
Java
10Summing integers
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
Scheme
11Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
12Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
Variables are explicitly typed in Java
13Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
Different symbols used for certain operators
14Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
infix instead of prefix notation for many
operations
15Recall
- prefix operator comes before operands
- infix operator comes between operands
- for some special two-operand functions
- e.g. - / etc.
infix instead of prefix notation for many
operations
16Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
still use prefix notation (with parentheses in
new place) for function calls
17Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
return statement(s)
18Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
access modifier
19Differences
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
curly braces ( ) and semicolons ( ) instead
of parentheses
20Summing integers
- public int sum (int n)
- if (n 0)
- return(0)
- else
- return(n sum(n - 1))
- (define (sum-integers n)
- (if ( n 0)
- 0
- ( n (sum-integers (- n 1)))))
The differences here are largely superficial!
21Expressions in Java
- Infix notation
- Parentheses are often optional
- ? when omitted, language follows a defined set of
precedence rules. - Examples in Java and Scheme
- 2 3 ( 2 3)
- axx bx c ( ( a x x) ( b x) c)
- (ax b)x c ( ( ( ( a x) b) x) c)
- ((a0) (a a 0) (
22Static Typing
- In Java, we must always explicitly declare types
of values - of procedure return value
- of procedure arguments
- of local variables
- Types have to match for code to execute
- true in Scheme, too, but not enforced until
program actually runs - in Java, "type mismatches" are detected at
compile time - what's "compile time"?
23Java code life cycle
- Write code in text editor
- Save to text file e.g. somefile.java
- Compile at command line
- javac somefile.java
- some kinds of errors detected reported here
- Successful compilation produces "machine-level"
code in somefile.class - Compiled files can be executed at command-line
- java somefile
24Primitive types in Java
- int
- finite-value, 32-bit storage
- 1 bit used for sign
- so max magnitude 231
- long
- just like int, but 64 bits
25Primitive types in Java
- float
- IEEE floating-point number, 32 bits
- 1 bit for sign 8 bits for exponent 23 bits
for "fraction" part (AKA "mantissa") - e.g. 6.02E23
- double
- IEEE "double-precision" float, 64 bits
- 1 sign bit 11 bits for exponent 52 mantissa
bits - e.g. 6.02E1332
26Primitive types in Java
- boolean
- similar to Scheme
- t in Scheme ? true in Java
- f in Scheme ? false in Java
- char
- "character"
- 16 bits, no sign bit
- (lots of international characters!)
27- In Java, mutation is the norm
- int x 2
- ? (define x 2)
- x 5
- ? (set! x 5)
- x 2 x
- ? (set! x ( 2 x))
- int y 4 foo(x)
- ? (define y ( 4 (foo x)))
28- is not a comparison operator!
- Since is "taken" for assignment operation, what
to use for comparison? -
- e.g. boolean b (x y)
- Common source of confusion
29Java Statements
- In addition to infix operations, Java has
"statements," many of which exist entirely for
their side effects - any return value intentionally tossed aside and
ignored - All statements end with a semi-colon
- a b c (set! a ( b
c)) - d sum(n) (set! d (sum
n)) - return (n sum(n - 1)) ( n (sum (- n 1))
30Procedure definitions
- Procedure in Scheme
- (define (foo arg1 arg2) ...)
- Procedure in Java
- foo( arg1, arg2)
- ...
- ? comma-delimited arguments inside parens
- types of arguments included in list
- procedure name outside and in front of parens
- return type before procedure name
31Procedures in Java
- Can be used in expressions
- f (x bar(q r s)) z
- compare (set! f ( ( x (bar ( q ( r s)))) z))
- Can be used as statements for their side-effects
- bar(43)
- compare (bar 43)
32Procedure Definition (in detail)
- return-type procname(type1 arg1,
- type2 arg2,
.) - type var initial-value
- type var2 initial-value // etc.
-
- statement1
- statement2 // etc.
33Sample Procedure Definition
- int aquad(int a, int b, int c, int x)
- int res 0
- res resc
- res resbx
- res resaxx
- return(res)
-
(define (aquad a b c x) (let ((res 0))
(set! res ( res c)) (set! res ( res ( b
x))) (set! res ( res ( a x x)))
res)))
34Comments, 1
- Two ways to make comments.
- / this is a Java comment /
- / comments can span
- multiple lines /
- Open with /
- Close with /
- Can be almost anywhere
- a b / will you date me? / c
- Often called "block comments"
35Comments, 2
- Another comment style similar to Scheme
- Open with //
- Comment extends to the end of the line
- // this is a comment
- a b c // sure, why not?
36Statement if
- if is a built-in statement in Java
- not an expression like in Scheme!
- Does not return/evaluate to a value
- So, anything interesting better happen via
side-effects - assign to (mutate) a value
- print something to the screen
- write to a file
- else is an explicit keyword
37Statement if
- Form
- if (test-expression)
- if-clause
- else
- else-clause
- else part is optional
38if Example
- int max (int a, int b)
- int res
- if (a b)
- res a
- else
- res b
- return (res)
(define (max a b) (let ((res 0)) (if
( a b) (set! res a)
(set! res b)) res) )
39if Example
- int max (int a, int b)
- int res
- if (a b)
- res a
- else
- res b
- return (res)
(define (max a b) (let ((res 0)) (if
( a b) (set! res a)
(set! res b)) res) )
40Block statements
- In Java, anywhere you can put a single statement,
you may put a block statement instead - Block statement an arbitrary number of
statements inside a pair of curly braces -
- variable declarations
- statement1
- statement2
-
- Similar to Scheme begin expression
41Block example
-
- int tmp1 max(a, b)
- int tmp2 min(a, b)
- c c - tmp2
- d d - tmp2
- e c / (tmp1 - tmp2)
- f d / (tmp1 - tmp2)
-
- (let ((tmp1 (max a b))
- (tmp2 (min a b)))
- (set! c (- c tmp2))
- (set! d (- d tmp2))
- (set! e (/ c (- tmp1 tmp2)))
- (set! f (/ d (- tmp1 tmp2))))
42Blocks often convenient with if
- if (a b)
- max a
- min b
- else
- max b
- min a
(if ( a b) (begin (set! max a)
(set! min b)) (begin (set! max
b) (set! min a)))
43return Statement
- return can occur anywhere in a procedure
- Explicit mechanism for exiting a procedure
immediately - Since procedures have a defined return type, the
value passed to return must have that type
44Example
- int scalebc(int a, int b, int c)
- int LARGE 1000000000 // for instance...
- if (b0) return(LARGE) // avoid division
by 0 - if (c0) return(LARGE) // similarly
- return (a / (b c)) // return an int
45Iteration for loop
- Vaguely similar to Scheme do loop
- Has a "continue-test" instead of an exit-test
- for ( )
-
- look familiar? ?
46for example
- Start with i set to 0,
- while i
- execute res res i
- execute i i 1
- go back to 2.
- int sum(n)
- int res 0
- int i
- for (i 0 i
- res res i
- return(res)
47for with block statement
- int sum 0
- int zeros 0
- for (int i0 ii i 1
- sum f(i) // shortcut for sum sum f(n)
- if (f(i) 0)
- zeros
48Interlude
49Useful reference
50(ok, not really)
51Admin Interlude
52Admin
- Course Feedback Questionnaires
- Pick up, fill out, turn in now.
- More thoughts? Email!
- Lectures, interludes
- Ideas?
- Final Ombuds lunch tomorrow noon
- mmmmm... foood...
53Labs
- No rework on lab9
- and no min grading
- Solutions for all labs posted on weekend
- (Don't consult if reworking, obviously)
54Final
- Final exam cover sheet available online soon.
- Read it in advance.
- cs1man submit final final.txt
- turn in hard copy of diagrams to box in lab
- Thursday/Friday recitations ? open QA
- Final out Saturday, due Friday 4am
- We'll grade Friday afternoon, so don't be late!
55Final review
- Final review
- Thursday (tomorrow) 9pm JRG 074
- go over exam-related material
- can ask questions, work through examples, etc.
56Final Content
- List Processing
- Tagged Data and Message-Passing
- Side-effects and Mutation
- Environment model
- Draw environment diagrams
- Reason about sameness/equality
- Remember stuff from first half
- Recursion, lambda, complexity, evaluation, .
- Read/understand code
- Decompose/design operations
57Movie clip
- Futurama math lecture
- Play Spot-the-nerdTM
58(No Transcript)
59(No Transcript)
60return
61Message-passing
- We called message-passing "the root of
Object-Oriented (OO) programming." - Java is an OO language.
- Contains explicit, built-in constructs for
designing, building, implementing "objects"
i.e. amalgamations of code and data
62Classes
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
63Classes
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
data members
64Classes
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
procedures
65Classes
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
access modifiers
66Classes
Usage Complex foo new Complex(1, 3) int wow
foo.getReal() int yay foo.getImag()
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
67Classes
Usage Complex foo new Complex(1, 3) int wow
foo.getReal() int yay foo.getImag() foo.realVa
l // compile error!
- class Complex
- private int realVal 0
- private int imagVal 0
- public Complex(int real, int imag)
- realVal real
- imagVal imag
-
- public int getReal()
- return(realVal)
-
- public int getImag()
- return(imagVal)
-
68Objects
- Classes act as definition of "message-passing"
object. - Messages ? regular procedures!
- We call those procedures "methods" in OO-speak
- Methods are executed on an instance of a class
using dot (.) operator - foo.someMethod()
- foo.someOtherMethod(55.2334, true)
69Objects
- "Access modifier"
- in front of each data member
- in front of each method
- public
- accessible to outside user
- private
- inaccessible to outsiders
- accessible to internal code within object
- Very similar to Scheme
- except enforced by keyword(s) and Java compiler
- rather than by a more implicit set of
environment rules
70Complex
- Defining class Complex creates a new type in
Java. - Objects of type Complex can now be manipulated
just like int, float, char - Complex a new Complex(1, 3)
- Complex b new Complex(15, -2)
- Complex result someFunction(a)
71Complex addition
- Could now write standalone add
- public Complex add(Complex a, Complex b)
- return (new Complex(a.getReal() b.getReal(),
- a.getImag() b.getImag()))
72Complex addition
- Usage
- Complex a new Complex(1, 3)
- Complex b new Complex(15, -2)
- Complex c add(a, b)
73Complex addition
- Alternative
- add add as a "method" (message) instead?
- Put inside class definition block...
74add method
- public Complex add(Complex other)
- return(new Complex
- (realVal other.getReal()),
- (imagVal other.getImag()))
-
75add method
- Usage
- Complex a new Complex(1, 4)
- Complex b new Complex(-5, 25)
- Complex c a.add(b)
76Whats Missing?
- Java does not have lambda
- Procedures can't be passed in as arguments
- Procedures do not have their own persistent
environments (their own state) - Procedures cannot return new procedures
77What did we miss?
- Java brings us arrays
- Contiguous blobs of homogeneous data
- Very fast look-up
- Expensive to resize
- Note Scheme has a kind of array called a
"vector" too - not homogeneous (can contain arbitrary types of
data)
78What did we miss?
- Around objects, Java adds
- a system to create hierarchies of objects
- additional access modifiers to baffle the mind
and - occasionally control inter-object access
privileges in useful ways
79What did we miss?
- Java's compiled "machine-level" code is actually
an intermediate "bytecode" - Any architecture for which a suitable interpreter
of that bytecode exists can execute the exact
same compiled program - Available for Linux, Windows, OS/X, etc.
- Some Schemes work like this too
80What did we miss?
- Java provides built-in support for multithreaded
computation - Two or more pieces of code executing
simultaneously/concurrently - "Multitasking"
- Very useful
- Can get very complex
- (DrScheme also provides this)
81What did we miss?
- Java provides an enormous library of pre-written
objects. - Graphics
- Sound
- Networking
- High performance file I/O
- Text Parsing/Searching
- Arbitrary-precision numbers (like Scheme)
- Containers (trees, vectors, hashmaps)
- 2,800 classes in Java 1.5 alone
- dozens of Java extensions with thousands more
82Big Ideas
- Most of what you know can be transliterated to
other languages - Will have to learn
- new syntax
- new rules
- But you know how to think about the rules and
constructs
83Where to Go Now?
84Future Directions
- CS 2!
- 9 units
- Required for some majors
- Learn
- Java
- more data structures
- Write larger programs (1,000 lines)
85Future Directions
- CS 11
- Language-specific focus
- Taught by yours truly ?
- (and Donnie)
- 3 paltry units of credit ?
- Available every term in
- C, C, Java, Python
86Future Directions
- CS 11
- Available some terms in
- advanced C/C, advanced Java,
- Ocaml, Haskell
- ACM programming competition
- projects
- ?? you tell us ??
- Little time for theory very hands-on
- Like those "Teach Yourself" books
- but much better and more expensive ?
87Also...
- If you've enjoyed this course...
- If you've done pretty well...
- If you like money, fame, and glory...
88I want YOU
to be a CS 1 TA!
89CS 1 TAs
- If you're interested, email me
- No rush, but no later than Spring term
- Lots of work
- but good money (28/hour currently)
- good teaching experience
- Probably 3-4 open slots at least
90Finally...
- Thanks for letting me teach you!
- I hope you learned a lot
- and had fun
- I hope you take more CS courses
- and I especially hope this isn't the end of your
programming career - One final clip...
91This is Spinal Tap (1984)