Practice with Functions and Strings
> Click or hit Control-Enter to run the code above
Algorithmic Thinking and Problem Solving
But First: More About Functions
Java Method Overloading
I told you that functions couldn’t have the same name.
I lied.
> Click or hit Control-Enter to run the code above
Java Method Overloading
Java uses both the function name and the the list of arguments and types to determine which function to call.
Together they are called the function signature.
-
Does the function have the right name?
-
Does the function take the right arguments in the right order?
-
Java will also try to convert types to find a match as long as no loss of precision occurs
> Click or hit Control-Enter to run the code above
Function Input Validation
A common function design pattern is to check your inputs at the top.
Think about all the bad inputs you could possibly get from the caller.
int sum(int[] numbers) {
// check numbers to make sure it's sane
}
> Click or hit Control-Enter to run the code above
null
Arrays
What is the value of array declared below?
int[] output = null;
System.out.println(output);
-
Java has a special value that can be used to indicate that an object has not been initialized:
null
. -
null
is not a valid object: it has no properties or methods that you can use. -
Attempts to use
null
will result in an error
> Click or hit Control-Enter to run the code above
Defensive Programming 101
Always check objects for null
.
Let’s Solve Some Problems!
Consecutive Identical Values
Given a string, write a function to find all cases where consecutive characters are the same.
First, what is our algorithm?
-
Examine each character in the array
-
Compare it with the next character—but how do we get at that?
-
Print it out if they are the same
> Click or hit Control-Enter to run the code above
Testing
Test cases are an indispensable part of modern software development.
-
To perform a simple test, pick a input that you know the answer to and check that your function returns the expected value.
-
Try to pick cases that are hard and where you might not get the right answer—we call these corner cases.
Announcements
-
Quiz 2 starts today in the CBTF. It covers arrays, functions, and strings.
-
The fifth set of Turing’s Craft exercises (TC 5) will be out shortly and due Sunday by midnight.
-
MP1 is due today! Office hours until 5PM today.
-
MP2 will be out today and due next week—it’s another new challenge.