Download 01-intro

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSE 142 Lecture Notes
Introduction
These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or
modified without Marty Stepp's expressed written permission. All rights reserved.
1
Lecture outline

Introduce instructor, TAs

Discuss course syllabus and resources



Examine some simple programs to learn about
the Java programming language
How to use the TextPad editor
Decomposing problems and eliminating
redundancy using static methods
2
Computer programs

program: A set of instructions that are to be
carried out by a computer.

program execution: The act of carrying out
the instructions contained in a program.


programming language: A systematic set of
rules used to describe computations, generally
in a format that is editable by humans.
Java: One of many modern programming
languages; created by Sun Microsystems.
The language we will use in this course!
3
A simple Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

code, source code: The sequence of instructions in a
particular program.

The code in this program instructs the computer to print a
message of Hello, world! on the screen.

output: The messages printed to the user by a
program.

console: The black box onto
which output is printed.
4
Compiling, running a program



compiler: A program that translates
a computer program written in one
language into an equivalent program
in another language (often, but not
always, translating into machine
language).
interpreter: A program that
dynamically executes programs
written in a particular programming
language.
Java Virtual Machine: A
theoretical computer whose machine
language is the set of Java byte
codes.
source code
(Hello.java)
compile
byte code
(Hello.class)
execute
output
5
TextPad
To run a Java program in TextPad:
 Open a .java file (or type in your own)
 Click Tools, Compile Java, or press Ctrl-1


(the window should go white and
then return after a pause, while
the program is compiling)
Click Tools, Run Java, or press Ctrl-2

(a black console window
should appear with the
program's output)
6
Another Java program
public class Hello2 {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}

The code in this program instructs the
computer to print four messages on the screen.
7
Structure of Java programs
public class <Class name> {
public static void main(String[] args) {
<statements>;
}
}

Every executable Java program consists of a
class...

that contains a method named main...


that contains the statements to be executed
The previous program is a class named Hello,
whose main method executes one statement
named System.out.println
8
Java terminology


class:
(a) A module that can contain executable code.
(b) A category or type of object. (seen later)
statement: An executable piece of code that
represents a complete command to the
computer.


every basic Java statement ends with a semicolon ;
method: A named sequence of statements
that can be executed together to perform a
particular action or computation.
9
Syntax and syntax errors

syntax: The set of legal structures and commands that
can be used in a particular programming language.

syntax error or compiler error: A problem in the
structure of a program that causes the compiler to fail.

If you type your Java program incorrectly, you may violate
Java's syntax and see a syntax error.
public class Hello {
pooblic static void main(String[] args) {
System.owt.println("Hello, world!")_
compiler output:
}
H:\summer\Hello.java:2: <identifier> expected
}
pooblic static void main(String[] args) {
^
H:\summer\Hello.java:5: ';' expected
}
^
2 errors
Tool completed with exit code 1
10
Fixing syntax errors

Notice how the error messages are cryptic and do not
always help us understand what is wrong:
H:\summer\Hello.java:2: <identifier> expected
pooblic static void main(String[] args) {
^


The compiler does tell us the line number on which it
found the error, which helps us find the place to fix the
code.



We'd have preferred a friendly message such as,
"You misspelled 'public'"
Jump to the line by double-clicking the error in TextPad
Java has a fairly rigid syntax.
Several languages are friendlier than Java, but we must
pay this price in order to learn an industrial-strength
language that is used in real jobs
11
Common TextPad pitfalls

In TextPad, it is easy to accidentally save your Java
program with a .txt extension


Text files are the default;
hence the name, "TextPad"
If you make this mistake, you'll see a strange error
message like this:
javac: invalid flag: H:\summer\Hello.java.txt
Usage: javac <options> <source files>
where possible options include:
-g
Generate all debugging info
-g:none
Generate no debugging info
...
12
Fixing TextPad issues


to avoid saving as .txt: in TextPad click Configure,
Preferences..., File Name Filters, then move the
Java (*.java) item to the top
Windows Explorer doesn't show files' real extensions,
which makes it harder to find this problem

to change this setting, in Windows Explorer (My Computer),
click Tools, Options..., View, then uncheck the Hide
extensions for known file types box
13
System.out.println

Java programs use a statement called
System.out.println to instruct the computer
to print a line of output on the console


pronounced "print-linn"; sometimes called a println
statement for short
Two ways to use System.out.println :

1. System.out.println("Message");


Prints the given message as a line of text on the console.
2. System.out.println();

Prints a blank line on the console.
14
Strings and string literals


string: A sequence of text characters that can
be printed or manipulated in a program.
literal: a representation of a value of a
particular type

String literals in Java start and end with quotation
mark characters
"This is a string"
15
Details about Strings



A string may not span across multiple lines.
"This is not
a legal String."
A string may not contain a " character. ' is OK
"This is not a "legal" String either."
"This is 'okay' though."
A string can represent certain special characters by
preceding them with a backslash \ (this is called an
escape sequence).




\t
\n
\"
\\
tab character
new line character
quotation mark character
backslash character
16
Questions

What sequence of println statements will generate the
following output?
This program prints a
quote from the Gettysburg Address.
"Four score and seven years ago,
our 'fore fathers' brought forth on this continent
a new nation."

What sequence of println statements will generate the
following output?
A "quoted" String is
'much' better if you learn
the rules of "escape sequences."
Also, "" represents an empty String.
Don't forget to use \" instead of " !
'' is not the same as "
17
Another example question

What sequence of println statements will generate the following
output?
/
\
/
_____
/
\
\
/
\_____/
_____
/
\
\
|
|
|
|
|
|
\
/
\_____/
_____
/
\
/
\
+-------+
_____
/
\
/
\

What observations can we make about the
output that is generated?


It has a noticeable structure.
(draw first figure, draw second figure,
draw third figure, ...)
The output contains redundancy.
18
Structured algorithms

How does one bake sugar cookies?












Mix the dry ingredients.
Cream the butter and sugar.
Beat in the eggs.
Stir in the dry ingredients.
Set the oven for the appropriate temperature.
Set the timer.
Place the cookies into the oven.
Allow the cookies to bake.
Mix the ingredients for the frosting.
Spread frosting and sprinkles onto the cookies.
...
Can we express this process in a more structured way?
19
A structured algorithm


structured algorithm: A list of steps for solving a
problem, which is broken down into cohesive tasks.
A structured algorithm for baking sugar cookies:

1. Make the cookie batter.





2. Bake the cookies.





Set the oven for the appropriate temperature.
Set the timer.
Place the cookies into the oven.
Allow the cookies to bake.
3. Add frosting and sprinkles.



Mix the dry ingredients.
Cream the butter and sugar.
Beat in the eggs.
Stir in the dry ingredients.
...
Mix the ingredients for the frosting.
Spread frosting and sprinkles onto the cookies.
20
Redundancy in algorithms

How would we express the steps to bake a
double batch of sugar cookies?
Unstructured:













Mix the dry ingredients.
Cream the butter and sugar.
Beat in the eggs.
Stir in the dry ingredients.
Set the oven ...
Set the timer.
Place the first batch of cookies
into the oven.
Allow the cookies to bake.
Set the oven ...
Set the timer.
Place the second batch of
cookies into the oven.
Allow the cookies to bake.
Mix the ingredients for the
frosting.
Structured:





1. Make the cookie batter.
2a. Bake the first batch of
cookies.
2b. Bake the second batch of
cookies.
3. Add frosting and sprinkles.
Observation: A structured
algorithm not only presents the
problem in a hierarchical way
that is easier to understand, but
it also provides higher-level
operations which help eliminate
redundancy in the algorithm.
21
Static methods

static method: A group of statements that is
given a name so that it can be executed in our
program.


Breaking down a problem into static methods is also
called "procedural decomposition."
Static methods are useful for:


denoting the structure of a larger program in
smaller, more understandable pieces
eliminating redundancy through reuse
22
Static method syntax

The structure of a static method:
Inside your program's class:
public class <Class Name> {
public static void <Method name> () {
<statements>;
}
}

Example:
public static void printWarning() {
System.out.println("This product is known to cause");
System.out.println("cancer in lab rats and humans.");
}
23
Static methods example
public class TwoMessages {
public static void main(String[] args) {
displayMessage();
System.out.println();
displayMessage();
}
public static void displayMessage() {
System.out.println("Now this is the story all about how");
System.out.println("My life got flipped turned upside-down");
}
}
Program's output:
Now this is the story all about how
My life got flipped turned upside-down
Now this is the story all about how
My life got flipped turned upside-down
24
Identifiers

identifier: A name that we give to a piece of data or part of a
program.



The name you give a static method is an example of an identifier.
(What is another example identifier we've seen?)
Java identifier names:



Identifiers are useful because they allow us to refer to that data or
code later in the program.
first character must a letter or _ or $
following characters can be any of those characters or a number
Example Java identifiers:


legal:
illegal:
susan
me+u
second_place
49er
TheCure
side-swipe
ANSWER_IS_42
hi there
25
Keywords


keyword: An identifier that you cannot use because it
already has a reserved meaning in the language.
Complete list of Java keywords:
abstract
boolean
break
byte
case
catch
char
class
const
continue

default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
You may not name a method or a class char or while
or this ; Java uses those words to mean other things.
26
Comments

comment: A note written in the source code
by the programmer, to help make the program
easier to understand.



Comments are not executed when your program
runs.
TextPad and other editors turn your comments a
special color to make it easier to identify them.
Comment syntax:



/* A comment goes here. */
/* It can even span
multiple lines. */
// This is a one-line comment.
27
Using comments



In this course, it is considered proper
programming style to put a "comment header"
at the top of each program we write, explaining
what the program does.
We will also place a comment at the start of
every static method, describing the method's
behavior.
Lastly, we can use comments inside methods to
explain particular pieces of code.
28
Comments example
/*
Suzy Student
CSE 142 Summer 2005
This program prints lyrics from my favorite song!
*/
public class TwoMessages {
/* Runs the overall program to print the song. */
public static void main(String[] args) {
displayMessage();
// Separate the two verses with a blank line
System.out.println();
displayMessage();
}
/* Displays the first verse of the theme song. */
public static void displayMessage() {
System.out.println("Now this is the story all about how");
System.out.println("My life got flipped turned upside-down");
}
}
29
Suggested reading / tasks

Chapter 1
Simple programs with println statements:
 read 1.1 - 1.7 (skip 1.7.1), 1.7.2 - 1.8, 1.10
 self-checks 5-7, 12
Static methods, comments, identifiers:
 read 1.7.1, 1.8 - 1.9
 self-checks 1-4, 8-11, 13 - 15


Make sure that you can log in to the school's labs using
your UW NetID.
Also, try compiling and executing a simple Java
program (such as Hello) for next time.
30
Working from home



Download and install Java 2 Software
Development Kit ("J2SE SDK") from:
http://java.sun.com/j2se/1.4.2/download.html
Download and install TextPad from:
http://www.textpad.com/
(be sure to install it after installing Java)
Download (Save to Disk) or type in a sample
program to test, such as:
http://www.cs.washington.edu/education/
courses/cse142/05su/Hello.java
31
Working from home, cont'd
To test that your home setup works:
 Open your Test.java program in TextPad
 Click Tools, Compile Java, or press Ctrl-1


(the window should go white and
then return after a pause, while
the program is compiling)
Click Tools, Run Java, or press Ctrl-2

(a black console window
should appear that says,
"Hello, world!")
32