Week 1 - Friday What did we talk about last time? Java: Types if - - PowerPoint PPT Presentation

week 1 friday what did we talk about last time java
SMART_READER_LITE
LIVE PREVIEW

Week 1 - Friday What did we talk about last time? Java: Types if - - PowerPoint PPT Presentation

Week 1 - Friday What did we talk about last time? Java: Types if statements But there's sometimes a cleaner way to express a list of possibilities Enter: the switch statement switch( data ) { case value1: statements 1;


slide-1
SLIDE 1

Week 1 - Friday

slide-2
SLIDE 2

 What did we talk about last time?  Java:

  • Types
  • if statements
slide-3
SLIDE 3
slide-4
SLIDE 4
slide-5
SLIDE 5

 But there's sometimes a cleaner way to express a list of

possibilities

 Enter: the switch statement

slide-6
SLIDE 6

switch( data ) { case value1: statements 1; case value2: statements 2; … case valuen: statements n; default: default statements; }

slide-7
SLIDE 7

switch( base ) { case 'A': System.out.println("Adenine"); break; case 'C': System.out.println("Cytosine"); break; case 'G': System.out.println("Guanine"); break; case 'T': System.out.println("Thymine"); break; default: System.out.println("Your base" + "doesn't belong to us"); break; // unnecessary }

slide-8
SLIDE 8

int data = 3; switch( data ) { case 3: System.out.println("Three"); case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); }

Both "Three" and "Four" are printed The break is

  • ptional

The default is optional too

slide-9
SLIDE 9
  • 1. The data that you are performing your switch on must be

an int, a char, or a String

  • 2. The value for each case must be a literal
  • 3. Execution will jump to the case that matches
  • 4. If no case matches, it will go to default
  • 5. If there is no default, it will skip the whole switch block
  • 6. Execution will continue until it hits a break
slide-10
SLIDE 10

switch( base ) { case 'A': case 'a': System.out.println("Adenine"); break; case 'C': case 'c': System.out.println("Cytosine"); break; case 'G': case 'g': System.out.println("Guanine"); break; case 'T': case 't': System.out.println("Thymine"); break; default: System.out.println("Your base doesn't belong to us"); break; // unnecessary }

slide-11
SLIDE 11

 Using if-statements is usually safer  if-statements are generally clearer and more flexible  switch statements are only for long lists of specific cases  Be careful about inconsistent use of break

slide-12
SLIDE 12
slide-13
SLIDE 13
  • 1. while loops
  • Used when you don’t know how many times you are going to need

to repeat

  • 2. for loops
  • Used when you do know how many times you are going to repeat
  • 3. do-while loops
  • Used never
  • Oh, okay, they are used whenever you need to be guaranteed the

loop runs at least once

slide-14
SLIDE 14

 Any problem that uses loops can use any kind of loop  The choice is supposed to make things easier on the

programmer

 Some loops are more convenient for certain kinds of problems

slide-15
SLIDE 15
slide-16
SLIDE 16

 The simplest loop in Java is the while loop  It looks similar to an if statement  The difference is that, when you get to the end of the while

loop, it jumps back to the top

 If the condition in the while loop is still true, it executes

the body of the loop again

slide-17
SLIDE 17

while( condition ) { statement1; statement2; … statementn; }

A whole bunch of statements

slide-18
SLIDE 18

 A while loop will usually have multiple statements in its

body

 However, it is possible to make a while loop with only a

single statement

 Then, like an if-statement, the braces are optional

while( condition ) statement;

slide-19
SLIDE 19

 Let's print the numbers from 1 to 100  We could do this with lots of cut/paste, or:

int i = 1; while( i <= 100 ) { System.out.println(i); i++; }

slide-20
SLIDE 20

 The while loop executes each statement one by one  When execution gets to the bottom, it jumps to the top  If the condition is still true

(i.e., i <= 100), it repeats the loop

slide-21
SLIDE 21
slide-22
SLIDE 22

 for loops are great when you know how many times a loop

will run

 They are the most commonly used of all loops  They are perfect for any task that needs to run, say, 100 times  A for loop has 3 parts in its header: 1.

Initialization

  • 2. Condition

3.

Increment

slide-23
SLIDE 23

Way to Progress Ending Point Starting Point

for( init; condition; inc ) { statement1; statement2; … statementn; }

slide-24
SLIDE 24

 A for loop will usually have multiple statements in its body  However, it is possible to make a for loop with only a single

statement

 Then, like if-statements and while-loops, the braces are

  • ptional

for( init; condition; inc ) statement;

slide-25
SLIDE 25

 Let's print the numbers from 1 to 100 (again)  Remember how this was done with while:

int i = 1; while( i <= 100 ) { System.out.println(i); i++; }

slide-26
SLIDE 26

 A for loop is specifically designed for this sort of thing:  The initialization and the increment are built-in

for( int i = 1; i <= 100; i++ ) { System.out.println(i); }

slide-27
SLIDE 27
slide-28
SLIDE 28

 They work just like while loops  The only difference is that they are guaranteed to execute at

least once

 Unlike a while loop, the condition isn’t checked the first time

you go into the loop

 Sometimes this is especially useful for getting input from the

user

 The syntax is a little bit different

slide-29
SLIDE 29

do { statement1; statement2; … statementn; } while( condition );

slide-30
SLIDE 30
slide-31
SLIDE 31

 Loops are great  But, without a way to talk about a list of variables, we can’t

get the full potential out of a loop

 Enter: the array

slide-32
SLIDE 32

 An array is a homogeneous, static data structure  Homogeneous means that everything in the array is the same

type: int, double, String, etc.

 Static (in this case) means that the size of the array is fixed

when you create it

slide-33
SLIDE 33
slide-34
SLIDE 34

 To declare an array of a specified type with a given name:  Example with a list of type int:  Just like any variable declaration, but with []

type[] name; int[] list;

slide-35
SLIDE 35

 When you declare an array, you are only creating a variable

that can hold an array

 At first, it holds nothing, also know as null  To use it, you have to create an array, supplying a specific size:  This code creates an array of 100 ints

int[] list; list = new int[100];

slide-36
SLIDE 36

 You can access an element of an array by indexing into it, using

square brackets and a number

 Once you have indexed into an array, that variable behaves

exactly like any other variable of that type

 You can read values from it and store values into it  Indexing starts at 0 and stops at 1 less than the length

list[9] = 142; System.out.println(list[9]);

slide-37
SLIDE 37

 When you instantiate an array, you specify the length  Sometimes (like in the case of args) you are given an array of

unknown length

 You can use its length member to find out

int[] list = new int[42]; int size = list.length; System.out.println("List has " + size + " elements"); //prints 42

slide-38
SLIDE 38

 When you create an int, double, char, or boolean array,

the array is automatically filled with certain values

 For other types, including Strings, each index in the array

must be filled explicitly

Type Value int double 0.0 char '\0' boolean false

slide-39
SLIDE 39

 Explicit initialization can be done with a list:  Or, a loop could be used to set all the values:

String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; String[] numbers = new String[100]; for(int i = 0; i < numbers.length; i++) numbers[i] = "" + (i + 1);

slide-40
SLIDE 40
slide-41
SLIDE 41

 An array takes up the size of each element times the length of

the array

 Each array starts at some point in computer memory  The index used for the array is actually an offset from that

starting point

 That’s why the first element is at index 0

slide-42
SLIDE 42

 We can imagine that we have an array of type int of length

10

 Java decides what address in memory is going to be used, but

let’s say it starts at 524

12 43

  • 9

6 789

  • 23

23 10 6

0 1 2 3 4 5 6 7 8 9

524 528 532 536 540 544 548 552 556 560

Addresses Indexes

slide-43
SLIDE 43
slide-44
SLIDE 44

 Arrays are a fixed size list of a single kind of data  A for loop is ideal for iterating over every item and

performing some operation

 for loops and arrays will crop up again and again  Of course, a while loop can be used with an array, but it

rarely is

slide-45
SLIDE 45

 Imagine that we have an array of ints called list  Let's use a for loop to sum up those ints  We don’t even need to know how big the array is ahead of

time

int sum = 0; for( int i = 0; i < list.length; i++ ) sum += list[i];

slide-46
SLIDE 46
slide-47
SLIDE 47

 So far, our code has been inside of the main() method  What about a big program?  The main() method is going to get really long and hard to

read

 Sometimes you need to do similar things several times:

  • Read some input and check that it falls within certain values
  • Draw a green hexagon at several different locations
  • Find the square root of several different numbers
slide-48
SLIDE 48

 Methods allow you to package up some code to run over and

  • ver

 Methods usually take some input (like numbers or Strings)

so that they can be customized

 Methods often give back an answer (like the square root of a

number)

 Also called functions in some other languages

slide-49
SLIDE 49

 More modular programming

  • Break a program into separate tasks
  • Each task could be assigned to a different programmer

 Code reusability

  • Use code over and over
  • Even from other programs (like Math.sqrt())
  • Less code duplication

 Improved readability

  • Each method can do a few, clear tasks
slide-50
SLIDE 50
slide-51
SLIDE 51

public static type name(type arg1,…,type argn) { statement1; statement2; … statementm; } Required syntax Type of answer Name of last argument Name of 1st argument Name of method Type of 1st argument Type of last argument Code done by method

slide-52
SLIDE 52

 Given two integers, find the smaller:

public static int min(int a, int b) { if( a < b ) return a; else return b; }

slide-53
SLIDE 53

 static methods are methods that are not connected to a

particular object

 They are just supposed to perform some simple task  We are going to focus on static methods until next week  For now, just taken it as a given that the definition of every

method will include the static keyword

slide-54
SLIDE 54

 It is possible to divide methods into two types:

  • Value returning methods
  • Void methods

 Value returning methods give an answer:

int small = min(x, y);

slide-55
SLIDE 55

 Void methods are declared with void as their return type  Void methods just do something  If you try to save the value they give back, there will be a compiler

error

public static void help(int times) { for( int i = 0; i < times; i++ ) System.out.println("Help!"); }

slide-56
SLIDE 56

 Like most code in Java, the code inside of a method executes

line by line

 Of course, you are allowed to put if statements and loops

inside methods

 You can also put in return statements  A method will stop executing and jump back to wherever it

was called from when it hits a return

 The return statement is where you put the value that will be

given back to the caller

slide-57
SLIDE 57
slide-58
SLIDE 58

 Defining a method is only half the game  You have to call methods to use them  Calling a method means giving a method the parameters (or

arguments) it needs and then waiting for its answer

 You have already done some method calls

  • System.out.println()
  • Math.sqrt()

 You can call your own methods the same way

slide-59
SLIDE 59

 Proper syntax for calling a static method gives first the name

  • f the class that the method is in, a dot, the name of the

method, then the arguments

 If the method is in the same class as the code calling it, you

can leave off the Class. part

 If it is a value returning method, you can store that value into

a variable of the right type

Class.name(arg1, arg2, arg3);

slide-60
SLIDE 60

 Variables from outside of the method don’t exist unless they

have been passed in as parameters

 No matter how complex a program is, inside this method,

  • nly x, y, and z variables exist

public static int add(int x, int y){ int z = x + y; return z; }

slide-61
SLIDE 61

 A magical process called binding happens which copies the

values from the calling code into the parameters of the method

 The calling code can use variables with the same names, with

different names, or even just literals

 The method does not change the values of the variables in the

  • riginal code

 Remember, it only has copies of the values

slide-62
SLIDE 62

 No connection between the two different x’s

and y’s

public static int add(int x, int y){ int z = x + y; //5 + 10 return z; } int a = 10; int x = 3;

int y = add( 5, a ); //y contains 15 now

slide-63
SLIDE 63
  • 1. Start a method with the keywords public static
  • 2. Next comes the return type
  • 3. Then the name of the method
  • 4. Then, in parentheses, the arguments you want to give to the

method

  • 5. Inside braces, put the body of the method
  • 6. Include a return statement that gives back a value if

needed

slide-64
SLIDE 64
slide-65
SLIDE 65

 Finish methods  File I/O  Objects

slide-66
SLIDE 66

 Keep reading 1.1 of Algorithms  Consider reading Chapters 8, 9, and 20 from https://start-

concurrent.github.io/