Upload
alfred-gardner
View
215
Download
1
Tags:
Embed Size (px)
Citation preview
John HurleySummer 2012Cal State LA
CS 201 Lecture 7:
Midterm
The midterm exam will be administered in class on Wednesday of week 6.
The exam will have many short answer questions, one one-paragraph writing question, and a programming problem.
On Monday I will administer a sample midterm which will be very similar to the actual midterm in number and type of questions and topic coverage. One of the short-answer questions will be repeated on the actual exam.
IMPORTANT NOTICE RE MIDTERM
You will need to use a lab computer, *not your own laptop* on the exam
Make sure *today* that you can log on to the network and familiarize yourself with the version of Eclipse that is installed in the lab.
Documentation From Oracle
Java was originally developed by Sun Microsystems and was closed-source but free for many years
Java is now open-sourceAnyone is free to use it or to write compilers, virtual machines, etc. that implement it
Oracle bought Sun a couple of years ago and now is the champion of Java
Documentation From Oracle
When you need to use something like Scanner, look it up in Oracle’s excellent online documentation
Example: Google +Java +ScannerFollow the link to
http://doc.java.sun.com/DocWeb/api/java.util.Scanner
Some Ugly Codepublic class UglyMess {
public static void main(String[] args){
int firstRadius = 2;
double firstCircumference = firstRadius * 2 * 3.1416;
System.out.printf("a circle with radius %d has circumference of %7.4f\n", firstRadius, firstCircumference);
int secondRadius = 6;
double secondCircumference = secondRadius * 2 * 3.14159;
System.out.printf("a circle with radius %d has circumference of %7f\n", secondRadius, secondCircumference);
int thirdRadius = 11;
double thirdCircumference = thirdCircumference = thirdRadius * 2 * 3.142;
System.out.printf("a circle with r = %d has circumference of %7.4f\n", thirdRadius, (thirdRadius * 2 * 3.142));
double fourthCircumference = 11 * 2 * 3.14;
System.out.printf(" circle with radius 11 has circumference of %7.4f\n", fourthCircumference);
}
}
What We Already KnowWe can already spot some problems with the code above:The second line of output shows 6 digits past the decimal point while the others show 4. Unless there is some reason to do otherwise, we should make this uniform.The last two lines of output show different values for the circumference of a circle with radius 11. We have several variables that are only used once each and represent the same kinds of values (radii and circumferences.)Different lines of output have slightly different label textThis code is hard for humans to understand because it does the same thing repeatedly in inconsistent ways.
Version 1.1public class LessUglyMess {
public static void main(String[] args){
final double PI = 3.14159;
int radius;
double circumference;
radius = 2;
circumference = radius * 2 * PI;
System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);
radius = 6;
circumference = radius * 2 * PI;
System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);
radius = 11;
circumference = radius * 2 * PI;
System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);
radius = 11;
circumference = radius * 2 * PI;
System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);
}
}
Version 1.1
New version is easier to understand, more consistent, and does not use unnecessary variables
But we are still doing the same thing several timesSeveral opportunities to make each possible
mistakeHard to change Hard for human beings to read the code
Which mistakes are we likely to make?
Modularity
As the state of the art of programming has progressed, we have found ways to make programs more modular
Modular = constructed from standardized components
Your house contains thousands of nails. They were not each custom-machined-they are multiple copies of the same basic form.
Ford was able to make Model Ts cheaply because, since they were all the same, they could be made cheaply on assembly lines from interchangeable parts
If you made a car from custom-machined parts, it would be expensive to make and hard to repair
Modularity
How far can we take this analogy to physical products when we are talking about software engineering?
You will spend a lot of time in the near future learning ways to make your software more modular; using methods is just the first step
Version 2.0This is BASIC, but this technique was used in other languages ca. 1950s-1960s
10 LET P = 3.1416
20 LET r = 2
30 LET x = 50
40 GOTO 140
50 LET r = 6
60 LET x = 80
70 GOTO 140
80 LET r = 11
90 LET x = 110
100 GOTO 140
110 LET x = 130
120 GOTO 140
130 end
140 LET c = r * 2 * P
150 print "circumference of circle with radius "; r; " is "; c
160 GOTO x
Version 2.0: Pros
Achieves consistency in calculating circumference
If the calculation was more complex than this one, it would also reduce redundant code
We can use the same calculation code whenever we need to by using if statements
If you like this kind of stuff, check out http://www.quitebasic.com/ or find a download of Microsoft QBasic
Version 2.0: Cons
Even harder to understand than v. 1.1!Still many opportunities for errors, including
ones that would be harder to diagnose than the ones we might make with version 1.0
Note the global scope of x, r, and c. They are available anywhere in the program and might be changed anywhere. This is a common source of errors.
Methods
Solution: design and use a methodAlso called subroutines, functions, or procedures in other languages
Separate some coherent piece of functionality into a separate unit of code
MethodsBenefit of using methods: Modularity
Code a method once, use it as often as you need to
If the method is sufficiently modular, you can even copy it into another class when you need similar functionality
Make code easier to understandMake it easier to change the code; only need to change the method once
Mt. Fuji Principle
A wise man climbs Mt. Fuji once. A fool does it twice.-Japanese proverb
MethodsYou have already used the main(String[] args)
method in all your assignments so far.main(String[] args) is just a special method that the JVM will find and run when just given a class
You have also used methods from classes distributed with Java, like JOptionPane.showMessageDialog(null, message)
System.out.print()
Defining Methods
19
A method is a collection of statements that are grouped together to perform an operation.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Method Signature
20
Method signature is the combination of the method name and the parameter list.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Formal Parameters
21
The variables defined in the method header are known as formal parameters.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Actual Parameters
22
When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Return Value Type
23
A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.
public static int max(int num1, int num2) {
int result; if (num1 > num2) result = num1; else result = num2; return result;
}
modifier return value
type method name
formal parameters
return value
method body
method header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters (arguments)
method signature
Parameter Order
A method that takes multiple parameters will assign the values passed to its parameters in the order in which they appear in the method signature. This will seem completely obvious when you see the
next slide.If the values received don’t match the data
types in the method signature, an error exists.A good IDE will catch many errors of this kind
Parameter Orderpublic class ParameterOrderDemo{
public static final double PI = 3.1416;
public static void main(String[] args){
double radius = 1.0;
double height = 2.0;
double cylVol = calcCylinderVolume(radius, height);
System.out.println("radius: " + radius + "; height: " + height + "; cylinder volume: " + cylVol);
}
public static double calcCylinderVolume(double r, double h){
return radius * radius * PI * height;
}
}
Parameters and Return Values
Neither parameters nor a return value is required to meet the definition of a method
We might have any of the following combinations:
No parameters, no return valueParameters but no return valueReturn value but no parametersParameters and return value
No Parameters, No Return Value
Some methods don’t take any parameters or return anything, just do something:
public static void main(String[] args) {boolean brat = false;// some other logic might result in brat == trueif (brat == true)
countToTen();// do other stuff
}
public static void countToTen() {System.out.println("Alright, I’m going to count to ten, and if
you don’t stop by then, you are in big trouble");for (int counter = 1; counter <= 10; counter++) {
System.out.println("that’s" + counter);}
}}
Parameters, No Return ValueDo something that can be adjusted according to the value of parameters, but don’t return anything:
public class Brat{public static void main(String[] args){
boolean brat = true;int limit = 1;String crime = “breaking dishes";if(brat == true) countToTen(limit, crime);
}
public static void countToTen(int max, String offense){System.out.println("Alright, I'm going to count to " + max + ",
and if you don't stop " + offense + " by the time I'm done, you are in big trouble!");
for(int counter = 1; counter <= max; counter++){System.out.println("that's " + counter);
}}
}
Parameters, No Return ValueNotice that, in this case, max and limit
have different namesWhat is the scope of max?What is the scope of limit?What would happen if we tried to print the
value of limit in countToTen()?What would happen if we tried to print the
value of max in main()?
Return Value, No ParametersA method may get a value of some kind without needing any parameters:
import javax.swing.JOptionPane;
public class Choice{
public static void main(String[] args){
int choice = getChoice();
System.out.println("you say you are " + choice);
}
public static int getChoice(){
int choice = 0;
String choiceString = null;
while(choice < 1 || choice > 100){
choiceString = JOptionPane.showInputDialog(null, "Please enter your age");
choice = Integer.parseInt(choiceString);
}
return choice;}
}
Return Value and ParametersA method may get and return some type of value, based on parameters sent in:
public class MethodDemo {
final static double PI = 3.14159;
public static void main(String[] args){
int radius;
double circumference;
radius = 2;
circumference = calcCircumference(radius);
printCircumference(radius, circumference);
radius = 6;
circumference = calcCircumference(radius);
printCircumference(radius, circumference);
//etc.
}
public static double calcCircumference(int r){
double circ = r * 2 * PI;
return circ;
}
public static void printCircumference(int r, double c){
System.out.printf("a circle with radius %d has circumference of %7.4f\n", r, c);
}
}
32
Blocks
A pair of braces in a program forms a block
that groups components of a program.
public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
Class block
Method block
ScopeVariables and finals are visible at different
places in your program depending on where you declare them
Scope determines where each variable/final is visible
The modifiers public, protected, and private control which values are visible outside the class; we will cover this towards the end of the term
Variables/finals are only visible in the block in which they are declared and blocks that are inside it
Variables or finals are *not* visible in blocks outside the one in which they are declared, even ones that enclose it
ScopeIf a variable is declared in an outer block but has
a value assigned to it in an inner block, it still has the new value when control returns to the outer block
This is convenient but can be a source of logic errors
Scope and Parameters
Why can we use PI in the calcCircumference(int r) method?
Why couldn’t we use radius in calcCircumference?
Why couldn’t we use circumference in main?
Scope and Parameters
public static double calcCircumference(int r){double circ = r * 2 * PI;return circ;
}
r is available in this version of calcCircumference() because it is declared and given a value in the method signature
Scope and Methodspublic class ScopeDemo{
static String classString = "This string is visible everywhere in this class";
public static void main(String[] args){String mainString = "This string is visible only in the main method";
for(int counter = 0; counter < 1; counter++){String loopString = "This string is visible only inside the loop";
System.out.println("main method output: \n" + classString + "\n" + mainString +"\n" + loopString);
}otherMethod();
// trying to print loopString or otherMethodString here would cause an error because they are not in scope
// System.out.println(loopString);// System.out.println(otherMethodString);}
public static void otherMethod(){String otherMethodString = "This string is visible only in otherMethod()";System.out.println("\notherMethod output: \n" + classString + "\n" +
otherMethodString);// trying to print mainString or loopString here would cause an error
because they are not in scope// System.out.println(MainString);// System.out.println(MainString);
}}
Scopepublic class ScopeDemo2{
static String classString = new String();
public static void main(String[] args){String mainString = new String();
for(int counter = 0; counter < 1; counter++){String loopString = new String();System.out.println("loop output: \n" + classString + "\n" + mainString +"\n" + loopString);
}
otherMethod();if(1+1 == 2){
classString = "class string";mainString = "main string";System.out.println("if output: \n" + classString + "\n" + mainString);// printing or assigning a value to loopString here would cause an error// loopString = "loopString";
}
System.out.println("output from main after end of if block:\n" + mainString);otherMethod();System.out.println("output from main after returning from otherMethod: \n" + classString);
}
public static void otherMethod(){System.out.println("\notherMethod output: \n" + classString);// using mainString here would cause an error because it is out of scope
classString = "new value of class string";}
Scope and Parameters
Consider MethodDemo againEven if circumference in main() and circ in
calcCircumference() both had the same name, they would still be two separate variables. We would still have to pass circ as a return value.
We could declare circumference with class scope and avoid passing a return value
We could also declare radius with class scope and avoid passing any parameters
Why is this a bad idea?
Scope and ParametersConsider this class:public class MethodScopeDemo{
static int myInt;
public static void main(String[] args){
myInt = 1;
System.out.println(myInt);
otherMethod();
System.out.println(myInt);
}
public static void otherMethod(){
myInt = 2;
}
}
myInt is not passed as a parameter. Why is it in scope in otherMethod()?
What will the output be?
41
CAUTIONA return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value.
To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.
public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }
(a)
Should be
(b)
public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return –1; }
Value and ReferenceSo far, parameters are passed by value
The called method sets up a variable, assigns the parameter value to it, and, presumably, uses it.
If the parameter was a variable, its value in the calling method does not change
If you want to change the value of the variable in the calling method, you can return the correct data type from the called method and assign the return value to the variable:x = getNewX();
Value and Reference
If you want to change the value of the variable in the calling method, you can return the correct data type from the called method and assign the return value to the variable:x = getNewX();
Note the difference between this and the situation with myInt in MethodScopeDemo above!
Value and Reference
Even if you use the value of a class scope variable as a parameter and give the formal parameter in the called method the same name, Java will create a new variable with method scope that “hides” the class scope variable:
public class HidingDemo{
static int x = 1;
public static void main(String[] args){
int y = otherMethod(x);
System.out.println(x);
System.out.println(y);
}
public static int otherMethod(int x){
x = 2;
return x; // this x “hides” the global x
}
}
Output of the above is:12
Value and ReferenceSounds pretty simple so far, right? Not any more!
The demos above all use primitive types like int and double
It’s more complicated when you pass an object, such as a String
There will certainly be problems on the midterm and final that require you to understand this.
Value and Reference All parameters are passed by value as described above
BUT objects are not passed. Instead, we pass variables that contain references to objects
A reference is a description of where to look in memory for the object In this code:
StringBuilder sb = “Hi, Mom”; sb is a reference to the StringBuilder, not a copy of
the StringBuilder itself. We need to “dereference” the reference to get the actual StringBuilder.
This is transparent most of the time, but you need to understand it.
Value and Reference
Other languages (eg Visual Basic) use the concept “pass by reference”
Some languages, like C, allow the programmer to choose whether to pass by value or by reference
In Java, objects can’t be passedIn Java we conventionally say we are passing
the reference variable by value
Value and Reference
If the called method changes the object, we will see the changes from anywhere where the object is in scope
No need to return the new valueRemember that this is how we pass objects.
Primitive types are passed in a much simpler way, as described above.
Value and Referencepublic class NoPassByReferenceDemo{
public static void main(String[] args){StringBuilder tagLine = new StringBuilder("Ah,
Satan sees Natasha");System.out.println(tagLine);otherMethod(tagLine);System.out.println(tagLine);
}
public static void otherMethod(StringBuilder myString){myString.reverse();
}}
Value and Reference
In the code above,We passed the reference variable to otherMethod()Then we used it to find the object and changed the object,
but not the reference variableAfter that, the value of the reference is still the same – it
shows where to find the object. But, the object has changedWe see the new state of the object when we access it from
wherever it is in scope
This point is difficult but very important! If you don’t understand it after this lecture, study the last few slides carefully. If you still don’t understand it, come to my office hours.
Value and Reference
Next week’s lab will require you to track the largest value returned from multiple calls to a method.
The easiest way to do this is as follows:use an instance variable (one that has scope everywhere in the class) initialized to the lowest possible value; in the lab, that will be 0
Each time the other method is called, compare the return value to the value in the variable. If the new value is higher, reset the variable to that value; otherwise, do nothing.
Pass By ValueFor some reason,this image helps many students pay attention to the concept that passing by value is like making a copy of the value and handing it to the called method
Pass A Reference
Passing a reference to an object is like telling the called method where to find the object
Stacks
A stack is a way of ordering data so that the last value you add to the stack is the first one you use from it.Like a stack of plates in a cafeteria
Last In, First Out (LIFO)
Stacks
Stacks have many uses in programming
The one that concerns us in this class is that this is how the JVM keeps track of method calls
56
Call Stacks
(a) The main method is invoked.
Space required for the main method k: j: 2 i: 5
(b) The max method is invoked.
Space required for the max method num2: 2 num1: 5
(d) The max method is finished and the return value is sent to k.
(e) The main method is finished.
Stack is empty
Space required for the main method k: j: 2 i: 5
Space required for the main method k: 5 j: 2 i: 5
(c) The max method is being executed.
Space required for the max method result: 5 num2: 2 num1: 5
Space required for the main method k: j: 2 i: 5
57
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
i is declared and initialized
The main method is invoked.
i: 5
animation
58
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
j is declared and initialized
The main method is invoked.
j: 2 i: 5
animation
59
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Declare k
The main method is invoked.
Space required for the main method
k: j: 2 i: 5
animation
60
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Invoke max(i, j)
The main method is invoked.
Space required for the main method
k: j: 2 i: 5
animation
61
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
pass the values of i and j to num1 and num2
The max method is invoked.
num2: 2 num1: 5
Space required for the main method
k: j: 2 i: 5
animation
62
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
pass the values of i and j to num1 and num2
The max method is invoked.
result:
num2: 2 num1: 5
Space required for the main method
k: j: 2 i: 5
animation
63
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
(num1 > num2) is true
The max method is invoked.
result:
num2: 2 num1: 5
Space required for the main method
k: j: 2 i: 5
animation
64
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Assign num1 to result
The max method is invoked.
Space required for the max method result: 5
num2: 2 num1: 5
Space required for the main method
k: j: 2 i: 5
animation
65
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Return result and assign it to k
The max method is invoked.
Space required for the max method result: 5
num2: 2 num1: 5
Space required for the main method k:5
j: 2 i: 5
animation
66
Trace Call Stack
public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Execute print statement
The main method is invoked.
Space required for the main method k:5
j: 2 i: 5
animation
Method Overloading
Scary-sounding term for a very simple concept
You can’t have two methods in the same class with the same name and same method signature
But you can have two methods with the same name and different signatures
Method Overloading
Scary term for a very simple conceptYou can’t have two methods in the same class with the same name and same method signature
But you can have two methods with the same name and different signatures
import javax.swing.JOptionPane;
public class Overload{
public static void main(String[] args){
int x = 0;
x = getInt();
JOptionPane.showMessageDialog(null, "You chose " + x);
int min = 2;
int max = 10;
x = getInt(min, max);
JOptionPane.showMessageDialog(null, "You chose " + x);
}
public static int getInt(){
int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer"));
return x;
}
public static int getInt(int low, int high){
int val = low -1;
do{
val = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer between " + low + " and " + high));
} while(val < low || val > high);
return val;
}
}
Write and Test Your Code Incrementally
70
You should be able to explain in one sentence how any method you write works. If you can’t, break it down into two or more methods.
The Stevie Wonder principle:"When you believe in things that you don't understand, then you suffer."