1 cse 142 lecture notes introduction these lecture notes are copyright (c) marty stepp 2005. may not...

32
1 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.

Upload: chastity-louise-turner

Post on 04-Jan-2016

222 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

1

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.

Page 2: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

2

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

Page 3: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

3

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!

Page 4: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

4

A simple Java programpublic 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.

Page 5: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

5

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

Page 6: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

6

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 andthen return after a pause, while the program is compiling)

Click Tools, Run Java, or press Ctrl-2 (a black console window

should appear with theprogram's output)

Page 7: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

7

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.

Page 8: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

8

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

Page 9: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

9

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.

Page 10: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

10

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!")_ }}

H:\summer\Hello.java:2: <identifier> expected pooblic static void main(String[] args) { ^H:\summer\Hello.java:5: ';' expected}^2 errorsTool completed with exit code 1

compiler output:

Page 11: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

11

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) { ^

We'd have preferred a friendly message such as,"You misspelled 'public'"

The compiler does tell us the line number on which it found the error, which helps us find the place to fix the code.

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

Page 12: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

12

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

...

Common TextPad pitfalls

Page 13: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

13

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

Page 14: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

14

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.

Page 15: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

15

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"

Page 16: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

16

Details about Strings A string may not span across multiple lines."This is nota 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 tab character \n new line character \" quotation mark character \\ backslash character

Page 17: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

17

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 "

Page 18: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

18

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.

Page 19: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

19

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?

Page 20: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

20

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. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients.

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 ingredients for the frosting. Spread frosting and sprinkles onto the cookies.

...

Page 21: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

21

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.

Page 22: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

22

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

Page 23: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

23

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.");}

Page 24: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

24

Static methods examplepublic 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 howMy life got flipped turned upside-down

Now this is the story all about howMy life got flipped turned upside-down

Page 25: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

25

Identifiers identifier: A name that we give to a piece of data or part of a

program. Identifiers are useful because they allow us to refer to that data or

code later in the 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: first character must a letter or _ or $ following characters can be any of those characters or a number

Example Java identifiers: legal: susan second_place TheCure ANSWER_IS_42 illegal: me+u 49er side-swipe hi there

Page 26: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

26

Keywords keyword: An identifier that you cannot use because it

already has a reserved meaning in the language.

Complete list of Java keywords: abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

You may not name a method or a class char or while or this ; Java uses those words to mean other things.

Page 27: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

27

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.

Page 28: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

28

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.

Page 29: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

29

Comments example/*Suzy StudentCSE 142 Summer 2005This 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"); }}

Page 30: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

30

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.

Page 31: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

31

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

Page 32: 1 CSE 142 Lecture Notes Introduction These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty

32

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 andthen 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!")