Week 1 - Friday
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 - - 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;
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; case value2: statements 2; … case valuen: statements n; default: default statements; }
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 }
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
- 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
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 }
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
- 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
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
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
while( condition ) { statement1; statement2; … statementn; }
A whole bunch of statements
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;
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++; }
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
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
Way to Progress Ending Point Starting Point
for( init; condition; inc ) { statement1; statement2; … statementn; }
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;
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++; }
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); }
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
do { statement1; statement2; … statementn; } while( condition );
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
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
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;
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];
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]);
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
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
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);
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
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
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
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];
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
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
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
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
Given two integers, find the smaller:
public static int min(int a, int b) { if( a < b ) return a; else return b; }
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
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);
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!"); }
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
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
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);
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; }
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
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
- 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