What is computer science?

WELCOME TO CSE 142!  computers?  science?  programming?  late lonely nights in front of the computer?

ALGORITHMIC THINKING

host: benson limketkai al·go·rithm: a step-by-step procedure for solving a problem or accomplishing some end especially by a computer University of Washington, Summer 2007  How does that relate to programming?

1 2

Just like Legos…

3

How to do well in this course

 Keep up with the assignments

 The course material is cumulative

 From a former student: “Procrastination will eventually come around to bite you in the ass!”

 If you don’t understand something, ask questions (especially “WHY?”).

 “There’s no such thing as a dumb question.”

6

1 Your first Java program!

Basic Java programs  Java is a programming language . public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } Readings: 1.1 – 1.3 }

 What does this code output (print to the user) when you run (execute) it?

7 8

Running a program Program execution

 Before you run a program, you must compile it.  The output is printed to the console .  compiler: Translates a computer program  Some editors pop up the console as another written in one language (i.e., Java) to another window. language (i.e., code) compile execute source code byte code output (Hello.java ) (Hello.class )

9 10

Another Java program Writing your own Java programs

public class Hello2 { public class { public static void main(String[] args) { 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"); ; } } } }

 Every executable Java program consists of a class  that contains a method called main

 that contains the statements (commands) to be executed

11 12

2 Syntax Syntax Errors

 syntax: The set of legal structures and  syntax error: A problem in the structure of a commands that can be used. program.

1 public class Hello {  Examples: 2 pooblic static void main(String[] args) { 3 System.owt.println("Hello, world!")  Every basic statement ends with a semi-colon. 4 }  The contents of a class occur between curly 5 } compiler output: braces. 2 errors found: File: Hello.java [line: 2] Error: Hello.java:2: expected File: Hello.java [line: 3] Error: Hello.java:3: ';' expected 13 14

Finding syntax errors First lesson in computer science

 Error messages do not always help us  Computers are stupid. understand what is wrong:  Computers can’t read minds.

File: Hello.java [line: 2]  Computers don’t make mistakes. Error: Hello.java:2: expected  If the computer is not doing what you want, poo blic static void main(String[] args) { it’s because YOU made a mistake.

 Why can’t the computer just say “ You misspelled ‘public’ ”?

15 16

More on syntax errors System.out.println

 Java is case-sensitive  System.out.println : A statement to print a line  Hello and hello are not the same of output to the console.  pronounced “ print-linn ” 1 Public class Hello { 2 public static void main(String[] args) {  Two ways to use System.out.println : 3 System.out.println("Hello, world!"); System.out.println(" "); 4 }  Prints the given message as a line of text to the console. 5 } compiler output: 1 error found: System.out.println(); File: Hello.java [line: 1] Error: Hello.java:1: class, , or enum  Prints a blank line to the console. expected 17 18

3 Strings Details about strings

 string: A sequence of text characters.  A string may not span across multiple lines. "This is not  Start and end with quotation mark characters a legal string."

 Examples:  A string may not contain a “ .

"hello"  The ‘ character is okay. "This is a string" "This is not a "legal" string either." "This, too, is a string. It can be very long!" "This is 'okay' though."

 This begs the question… 19 20

Escape sequences Questions

 A string can represent certain special characters by preceding them  What is the output of each of the following println statements? with a backslash \ (this is called an escape sequence ).  \t tab character System.out.println("\ta\tb\tc");  \n newline character  \" quotation mark character System.out.println("\\\\"); System.out.println("'");  Example: System.out.println("\"\"\""); System.out.println("Hello!\nHow are \"you\"?"); System.out.println("C:\nin\the downward spiral");

 Output: Hello!  Write a println statement to produce the following line of How are "you"? output:

 This begs another question… / \ // \\ /// \\\

21 22

Questions

 What println statements will generate the following output? This program prints a Procedural decomposition quote from the Gettysburg Address.

"Four score and seven years ago, using static methods our 'fore fathers' brought forth on this continent a new nation."

 What println statements will generate the following output?

A "quoted" String is Readings: 1.4 – 1.5 '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 "

23 24

4 Algorithms The “Bake sugar cookies” algorithm

 Recall: An algorithm is a list of steps for  Mix the dry ingredients. solving a problem.  Cream the butter and sugar.  Beat in the eggs.  Stir in the dry ingredients.  Set the oven for the appropriate temperature. What is the algorithm to bake sugar cookies?  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.

25 26

Structured algorithm How do we bake a double batch?

1. Make the cookie batter.  Observation : Structured Unstructured: Structured:  Mix the dry ingredients. algorithms are easier to  Mix the dry ingredients.  1. Make the cookie batter.  Cream the butter and sugar.  Cream the butter and sugar.  2a. Bake the first batch of cookies.  Beat in the eggs. understand.  Beat in the eggs.  2b. Bake the second batch of  Stir in the dry ingredients. cookies.  Stir in the dry ingredients.  3. Add frosting and sprinkles. 2. Bake cookies.  Set the oven …  Set the oven for the appropriate  Set the timer. temperature.  Place the cookies into the oven.  Observation : Structured  Set the timer.  Allow the cookies to bake.  Place the cookies into the oven. algorithms eliminate  Set the oven …  Allow the cookies to bake. redundancy.  Set the timer. 3. Add frosting and sprinkles.  Place the cookies into the oven.  Mix the ingredients for the frosting.  Allow the cookies to bake.  Spread frosting and sprinkles onto the cookies.  Mix the ingredients for the frosting.  Spread frosting and sprinkles onto the cookies.

27 28

Redundancy in programs How do we structure the program? public class FraggleRock { public static void main(String[] args) {  static method : A group of statements given System.out.println("Dance your cares away,"); a name. System.out.println("Worry's for another day."); System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock."); System.out.println();  To use a static method: System.out.println("Dance your cares away,"); System.out.println("Worry's for another day."); 1. declare it (write down the recipe) System.out.println("Let the music play,"); System.out.println("Down at Fraggle Rock.");  Write a group of statements and give it a name. } 2. call it (cook using the recipe) }  Tell our program to execute the method.

29 30

5 Declaring a static method Calling a static method

 The syntax for declaring a static method (writing  The syntax for calling a static method down the recipe): (cooking using the recipe): public class { ... (); public static void () { ; ; … ; } }

31 32

Static method example Worry’s for another day!

 Declaring a static method public class FraggleRock { public static void printAffirmation() { public static void main(String[] args) { System.out.println("I am good enough!"); singChorus(); System.out.println("I am smart enough!"); System.out.println(); System.out.println("People like me!"); singChorus(); } }  Calling a static method (possibly multiple times) printAffirmation(); public static void singChorus() { printAffirmation(); System.out.println("Dance your cares away,");  Output System.out.println("Worry's for another day."); I am good enough! System.out.println("Let the music play,"); I am smart enough! System.out.println("Down at Fraggle Rock."); People like me! } I am good enough! } I am smart enough! People like me!

33 34

Methods calling methods of methods

 One static method can call another: Output: public class MethodsExample {  When a method is called, the execution public static void main(String[] args) { This is message1. message1(); This is message2.  "jumps" into that method message2(); This is message1. Done with message2.  executes all of the method’s statements System.out.println("Done with main."); Done with main. }  "jumps" back to the statement after the method call public static void message1() { System.out.println("This is message1."); }

public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } }

35 36

6 Output: Control flow of methods This is message1. Summary: To use or not to use… This is message2. This is message1. Done with message2. public class MethodsExample { Done with main. public static void main(String[] args) {  Yes message1();  Statements that are related to each other ( structure ).  Statements that are repeated ( redundancy ). public static void message1() { message2(); System.out.println("This is message1."); }  No public static void message2() { ... System.out.println("This is message2");  Individual statements occurring only once and not related } message1(); to other statements } System.out.println("Done with message2.");  Unrelated or weakly-related statements }  Consider splitting the method into two smaller methods.  Blank lines public static void message1() { System.out.println("This is message1.");  Blank println statements can go in the main method. }

37 38

Example: Figure drawing Version 1: Unstructured

______ Write a program to print the figures. Use static  Create an empty program with a skeletal header / \ methods to capture structure and and eliminate / \ main / \ / \ and method. \/ redundancy. \/ \______/ \______/  Copy the expected output into it, surrounding \/ \/ each line with System.out.println syntax. \______/ \______/ +------+ +------+  Run and verify that it produces the correct ______output. / \ / \ / \ / \ | STOP | | STOP | \/ \/ \______/ \______/

______/ \ / \ / \ / \ +------+ +------+

39 40

Version 1: Unstructured Version 2: Structured with redundancy

// Suzy Student, CSE 142, Autumn 2047 ______ Identify the overall structure of the output, and // This program prints several assorted figures. / \ // divide the main method into several static public class Figures1 { / \ public static void main(String[] args) { \/ methods based on this structure. System.out.println(" ______"); \______/ System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); \/ System.out.println(" \\______/"); \______/ System.out.println(); +------+ System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println("+------+"); ______System.out.println(); / \ System.out.println(" ______"); / \ System.out.println(" / \\"); System.out.println("/ \\"); | STOP | System.out.println("| STOP |"); \/ System.out.println("\\ /"); \______/ System.out.println(" \\______/"); System.out.println(); System.out.println(" ______"); ______System.out.println(" / \\"); / \ System.out.println("/ \\"); / \ System.out.println("+------+"); } +------+ } 41 42

7 Version 2: Structured with redundancy Version 2: Structured with redundancy

______// Suzy Student, CSE 142, Autumn 2047  Identify the overall structure of the output, and / \ // Prints several assorted figures, with methods for structure. divide the main method into several static // / \ public class Figures2 { \/ methods based on this structure. public static void main(String[] args) { \______/ drawEgg(); drawTeaCup(); drawStopSign(); \/ The structure of the output: drawHat(); \______/  initial "egg" figure } +------+  // Draws a figure that vaguely resembles an egg. second "teacup" figure public static void drawEgg() { ______ third "stop sign" figure System.out.println(" ______"); / \ System.out.println(" / \\"); / \  fourth "hat" figure System.out.println("/ \\"); System.out.println("\\ /"); | STOP | System.out.println(" \\______/"); \/ System.out.println(); \______/ This structure can be represented by methods: }  drawEgg // Draws a figure that vaguely resembles a teacup. ______public static void drawTeaCup() { / \  drawTeaCup System.out.println("\\ /"); / \ System.out.println(" \\______/");  drawStopSign System.out.println("+------+"); +------+  System.out.println(); drawHat } 43 44

Version 2: Structured with redundancy Version 3: Structured without redundancy

// Draws a figure that vaguely resembles a stop sign. ______ Further divide the program to eliminate all public static void drawStopSign() { / \ System.out.println(" ______"); redundancy. System.out.println(" / \\"); / \ System.out.println("/ \\"); \/ System.out.println("| STOP |"); \______/ System.out.println("\\ /"); System.out.println(" \\______/"); System.out.println(); \/ } \______/ +------+ // Draws a figure that vaguely resembles a hat. public static void drawHat() { System.out.println(" ______"); ______System.out.println(" / \\"); / \ System.out.println("/ \\"); / \ System.out.println("+------+"); } | STOP | } \/ \______/

______/ \ / \ +------+

45 46

Version 3: Structured without redundancy Version 3: Structured without redundancy

______// Suzy Student, CSE 142, Autumn 2047  Further divide the program to eliminate all / \ // Prints several figures, with methods for structure and redundancy. / \ redundancy. public class Figures3 { \/ public static void main(String[] args) { \______/ drawEgg(); The redundancy: drawTeaCup(); drawStopSign(); \/  top half of egg (purple) drawHat(); \______/ }  bottom half of egg (green) +------+ // draws redundant part that looks like the top of an egg  divider line (yellow) public static void drawEggTop () { ______System.out.println(" ______"); / \ System.out.println(" / \\"); System.out.println("/ \\"); / \ This redundancy can be fixed by methods: } | STOP |  drawEggTop \/ // draws redundant part that looks like the bottom of an egg public static void drawEggBottom () { \______/  drawEggBottom System.out.println("\\ /"); System.out.println(" \\______/");  drawLine ______} / \ / \ +------+

47 48

8 Version 3: Structured without redundancy Exercise

// Draws a figure that vaguely resembles an egg. public static void drawEgg() {  Write a program that prints the following output to the console. Use drawEggTop(); drawEggBottom(); static methods as appropriate. System.out.println(); I do not like my email spam, } I do not like them, Sam I am! // Draws a figure that vaguely resembles a teacup. I do not like them on my screen, public static void drawTeaCup() { drawEggBottom(); I do not like them to be seen. System.out.println("+------+"); I do not like my email spam, System.out.println(); I do not like them, Sam I am! }

// Draws a figure that vaguely resembles a stop sign. public static void drawStopSign() {  Write a program that prints the following output to the console. Use drawEggTop(); System.out.println("| STOP |"); static methods as appropriate. drawEggBottom(); System.out.println(); Lollipop, lollipop } Oh, lolli lolli lolli

// Draws a figure that vaguely resembles a hat. public static void drawHat() { Lollipop, lollipop drawEggTop(); Oh, lolli lolli lolli System.out.println("+------+"); } } Call my baby lollipop 49 50

Exercise Identifiers: Say my name!

BBBBB B B  Write a program to print the block letters spelling  identifier : A name given to an entity in a program such as a class or BBBBB "banana". Use static methods to capture B B method. BBBBB structure and and eliminate redundancy. AAAA  Identifiers allow us to refer to the entities. A A AAAAAA A A

N N  Examples (in bold ): NNN N N NNN  public class Hello N N

AAAA  public static void main A A AAAAAA  public static void drawEgg A A

N N NNN N N NNN  N N Conventions for naming in Java (which we will follow):

AAAA  classes : capitalize each word ( ClassName ) A A AAAAAA  methodName A A methods : capitalize each word after the first ( )

51 52

Identifiers: Syntax Identifiers: Keywords

 First character must be a letter, underscore ( _) or $  keyword : An identifier that you cannot use, because it already has a  Following characters can be any of those or a number reserved meaning in the Java language.

 Complete list of Java keywords:  Examples: abstract default if private this boolean do implements protected throw  legal: susan second_place _myName break double import public throws TheCure ANSWER_IS_42 $variable byte else instanceof return transient method1 myMethod name2 case extends int short try catch interface static void char finally long strictfp volatile  illegal: me+u 49er question? class float native super while side-swipe hi there ph.d const for new switch continue goto package synchronized jim's 2%milk [email protected]  NB: Because Java is case-sensitive, you could technically use Class or cLaSs as identifiers, but this is very confusing and thus strongly discouraged.  Remember: Java is case-sensitive ( name is different from Name )

53 54

9 Comments Comments: Where do you go?

 comment : A note written in the source code to make the code easier to  … at the top of each file (also called a "comment header"), naming understand. the author and explaining what the program does  Comments are not executed when your program runs.  Most Java editors show your comments with a special color.  … at the start of every method, describing its behavior  Comment, general syntax: /* */ or,  … inside methods, to explain complex pieces of code //

 Examples: /* A comment goes here. */ /* It can even span multiple lines. */ // This is a one-line comment.

55 56

Comments: Why? Comments: Example

/* Suzy Student  Comments provide important documentation. CS 101, Fall 2019 This program prints lyrics from my favorite song! */ public class MyFavoriteSong {  Later programs will span hundreds or thousands of lines, split into /* Runs the overall program to print the song on the console. */ many classes and methods. public static void main(String[] args) { sing();

 Comments provide a simple description of what each class, method, // Separate the two verses with a blank line etc. is doing. System.out.println(); sing(); }  When multiple programmers work together, comments help one // Displays the first verse of the theme song. programmer understand the other's code. public static void sing() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); } }

57 58

Comments: How-to That thing called style…

 Do not describe the syntax/statements in detail.  What is style?  Instead, provide a short English description of the observed behavior when the method is run.  Indentation

 Example:  Capitalization // This method prints the lyrics to the first verse // of my favorite TV theme song.  Formatting / spacing // Blank lines separate the parts of the verse. public static void verse1() {  Structured code System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down");  No redundancy System.out.println(); System.out.println("And I'd like to take a minute,");  … System.out.println("just sit right there"); System.out.println("I'll tell you how I became the prince"); System.out.println("of a town called Bel-Air"); }  Why is it important? 59 60

10