Docsity

Methods - Computer Programming and Problem Solving - Research Paper | CS 111, Papers of Computer Science

Toggle sidebar
bg1
Chapter 3
Methods
3.1 Debugging
There are two stages of debugging: getting the program to compile and run, and
getting the program to do the right thing. The first stage is mostly a problem
with syntax, and the hardest part is usually figuring out what the error messages
mean. The second stage is a problem with semantics; the program you wrote
does not mean what you wanted it to mean.
At this point, the first step is to figure out what the program is doing. A
useful command for that is System.out.println. As debugging tools go, it’s a
little clumsy, but it can be a big help.
In the simplest form, the print statement looks like this:
System.out.println ("Hello");
Actually, calling it a print statement is misleading, since it doesn’t print any-
thing on paper. What it does, in most environments, is pop up a window, called
aconsole, where it displays whatever you tell it to display. In this case, we
told it to display the word Hello.
The quotation marks are necessary to indicate that this is a String, which
is yet another Java type. If you leave out the quotes, Java thinks Hello is the
name of a variable, and it complains if there isn’t a variable by that name.
On the other hand, if a variable does exist, println displays its current
value:
int x = 5;
System.out.println (x);
The output of this code is 5.
While you are debugging your code, you can add print statements almost
anywhere. When you are done, you might want to remove them, to avoid clutter.
If you think you might need them later, you can comment them out.
23
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Methods - Computer Programming and Problem Solving - Research Paper | CS 111 and more Papers Computer Science in PDF only on Docsity!

Chapter 3

Methods

3.1 Debugging

There are two stages of debugging: getting the program to compile and run, and getting the program to do the right thing. The first stage is mostly a problem with syntax, and the hardest part is usually figuring out what the error messages mean. The second stage is a problem with semantics; the program you wrote does not mean what you wanted it to mean. At this point, the first step is to figure out what the program is doing. A useful command for that is System.out.println. As debugging tools go, it’s a little clumsy, but it can be a big help. In the simplest form, the print statement looks like this:

System.out.println ("Hello");

Actually, calling it a print statement is misleading, since it doesn’t print any- thing on paper. What it does, in most environments, is pop up a window, called a console, where it displays whatever you tell it to display. In this case, we told it to display the word Hello. The quotation marks are necessary to indicate that this is a String, which is yet another Java type. If you leave out the quotes, Java thinks Hello is the name of a variable, and it complains if there isn’t a variable by that name. On the other hand, if a variable does exist, println displays its current value:

int x = 5; System.out.println (x);

The output of this code is 5. While you are debugging your code, you can add print statements almost anywhere. When you are done, you might want to remove them, to avoid clutter. If you think you might need them later, you can comment them out.

24 CHAPTER 3. METHODS

int x = 5; //System.out.println (x);

The phrases that appear in quotation marks are called strings, because they are made up of a sequence (string) of letters. Actually, strings can con- tain any combination of letters, numbers, punctuation marks, and other special characters. println is short for “print line,” because after each line it adds a special character, called a newline, that causes the cursor to move to the next line of the console. The next time println is invoked, the new text appears on the next line. Often it is useful to display the output from multiple print statements all on one line. You can do this with the print command:

System.out.print ("Goodbye, "); System.out.println ("cruel world!");

In this case the output appears on a single line as Goodbye, cruel world!. Notice that there is a space between the word “Goodbye” and the second quo- tation mark. This space appears in the output, so it affects the behavior of the program.

3.2 Concatenation

Earlier I said that the mathematical operators only work with numbers, but that is not completely true. The + operator works with Strings, although it does not do exactly what you might expect. For Strings, the + operator represents concatenation, which means joining up the two operands by linking them end-to-end. So "Hello, " + "world." yields the string "Hello, world." and fred + "ism" adds the suffix ism to the end of whatever fred is, which is often handy for naming new forms of bigotry. Concatenation is handy for combining Strings and other values inside a print statement:

int bananas = 17; System.out.println ("Yes, the number of bananas is " + bananas);

You might wonder how Java deals with an expression like "Yes, the number of bananas is " + bananas, since one of the operands is a String and the other is a int. Well, in this case Java is smart on our behalf; it automatically converts the int to a String before it concatenates. This kind of feature is an example of a common problem in designing a programming language, which is that there is a conflict between formalism, which is the requirement that formal languages should have simple rules with few exceptions, and convenience, which is the requirement that programming languages be easy to use in practice.

26 CHAPTER 3. METHODS

3.4 The Java Execution Model

The Java Execution Model (JEM) is a way to visualize what is going on when a piece of code executes. It is useful for debugging and it provides a visual aid to otherwise abstract concepts. If you are ever in doubt about what a piece of code does, take out a piece of paper and draw out the JEM.

The JEM is divided into two regions: Object Land, where objects live, and Execution Land, where the code is executed.

3.5 Execution Land

Execution Land displays the evolution of a piece of code as it executes. It is inhabited by execution frames, one for each method that is currently running.

Every execution frame has two parts, the set of variables used in the method, and the sequence of statements that make up the body of the method.

The following figure shows a JEM with a single execution frame. The name of the method, run, is outside the frame. Inside the frame are variables named this and becky. The code is the body of run.

position

heading

brushDown true

color

x 4

y 2

this becky Buggle becky = new Buggle (); becky.setPosition (new Point (4, 2));

run

Execution Land

unknown instance variables

unknowninstance variables

unknown instance variables

Object Land Buggle Point

Direction

Color

MyBuggleWorld

The variable named this is a special variable that is created by Java; you don’t have to declare it. When you send a message to an object, the object uses this to refer to itself. In this example, this refers to the MyBuggleWorld that received the run message.

3.6. OBJECT LAND 27

3.6 Object Land

In Object Land, each object is represented as a group of instance variables that describe the object at a specific point in time. This JEM shows five objects: a MyBuggleWorld object, a Buggle, a Point, a Color and a Direction. Each is labelled with its type. For some objects we know what the instance variables are and we can show them in the JEM. For other objects the internal state is opaque. There are two kinds of value a variable might hold, primitive values and object references. Integers are primitive types, and so are the truth values true and false. When a variable contains a primitive value, we write the value inside a box and write the name of the variable outside. The instance variables brushDown, x and y are examples. Object references are, um, references to objects. In the JEM they are rep- resented by a dot and an arrow pointing to an object.

3.7 Writing your own methods

Take a look at the following code and figure out what it does. As an exercise, draw a picture of what BuggleWorld looks like after the program runs.

public class MyBuggleWorld extends BuggleWorld{

public void run() { Buggle becky = new Buggle (); becky.setPosition (new Point (4,2)); Buggle bobby = new Buggle (); bobby.setColor (Color.blue);

// becky draws a box 3 steps on each side becky.forward (2); becky.left (); becky.forward (2); becky.left (); becky.forward (2); becky.left (); becky.forward (2); becky.left ();

// bobby draws a box 3 steps on each side bobby.forward (2); bobby.left (); bobby.forward (2); bobby.left (); bobby.forward (2); bobby.left ();

3.8. WRITING METHODS WITH PARAMETERS 29

unknown

state variables

this becky

position heading

brushDown true

color

Box2Buggle position heading

brushDown true

color

Box2Buggle

Object Land

Execution Land run

Box2BuggleWorld

this.forward (2); this.left();this.forward (2); this.left();this.forward (2); this.forwardthis.left();this.left(); (2);

box

Box2Buggle becky = new Box2Buggle (); becky.setPositionBox2Buggle bobby =(new new PointBox2Buggle (4, 2)); (); bobby.setColor (Color.blue); becky.box();bobby.box();

bobby this

For the object references inside the Buggle objects, I just drew dots and omitted the objects they refer to. Notice that there are now two execution frames, one for run and one for box. Inside run I added a dot that shows which line of the program is currently excecuting. In this JEM, we are in the middle of executing box. The arrow points from the method invocation to the execution frame of the method. Inside box, there is only one variable, this. As always, this refers to the object that received the message, which is becky. This is the first case we have seen where two variables refer to the same object. This situation is called aliasing because becky is going by an alias. Inside run, she is known as becky, but inside box she goes by the nickname this. Of course, anything we do to this is going to affect becky. This example demonstrates one of the benefits of methods. By writing a box() method, we avoided writing the same code twice. Imagine how much code we would save if there were 10 Buggles making boxes! Methods also make code more readable, less error prone, and easier to reuse.

3.8 Writing methods with parameters

In the previous example we wrote a method, box, that made a Box2Buggle draw a box 3 units on a side. But, what if we wanted the Buggle to draw a box with some other size, say 6? Would we have to write a whole new method? Not if we use parameters. Parameters are variables that store the arguments you provide when you invoke a method. Here is a version of box that can take the size of the box as a parameter.

class Box2Buggle extends Buggle {

30 CHAPTER 3. METHODS

public void box (int n) { forward(n-1); left(); forward(n-1); left(); forward(n-1); left(); forward(n-1); left(); } }

The first thing you might notice about this version of box is that I left out this. When you invoke one method inside another, Java understands that you want to invoke it on the current object.

The next thing you should have noticed is the variable declaration int n, which is the parameter list. It says that this version of box expects a single argument with type int.

If we try to invoke box with a non-integer expression as an argument, or more than one argument, we get a compile-time error. As usual, you should try it out so you see what the error message looks like.

Now when we invoke box we have the option of including an argument:

public class Box2World extends BuggleWorld {

public void run () { Box2Buggle becky = new Box2Buggle (); becky.setPosition(new Point(4,2)); Box2Buggle bobby = new Box2Buggle(); bobby.setColor(Color.blue);

becky.box(5); bobby.box(3); } }

As an exercise, draw a picture of what BuggleWorld will look like after this code runs.

Here is what the JEM looks like while bobby is executing box:

32 CHAPTER 3. METHODS

Within each statement, expressions are evaluated according to the rules of precedence. We have already talked about the order of evaluation for arithmetic expressions, and we have seen nested method invocations like

bobby.setColor (bobby.getColor().darker());

Expressions involving method invocations are evaluated from the innermost parentheses out, and from left to right. When you invoke one of the built-in methods, you don’t (and probably shouldn’t) think about how the method does what it does. But when you are invoking one of your own methods, it is tempting to think about the flow of execution. A method invocation is like a detour in the flow of execution. When the method is invoked, Java creates a new execution frame and starts executing the new method. At the same time it remembers where it is in the original frame. Again, the statements in the new method are executed one at a time, from top to bottom. When the method completes, the flow of execution returns to the original frame and picks up where it left off.

3.11 Picture objects

The Picture class defines a new type called Picture and a set of methods you can invoke on Picture objects. The Picture contract is in the Appendix. Most of the methods that operate on Pictures are fruitful. For example, clockwise90 takes a Picture as a parameter and returns a new Picture that is similar to the original, but rotated 90 degrees clockwise. Assume that we have a Picture object named original. We can create a new object named rotated:

Picture rotated = clockwise90 (original);

Other methods flip pictures and juxtapose pictures in various ways, but it is worth empasizing that none of these methods modifies an existing picture in any way. They only create new Pictures.

3.12 Writing fruitful methods

Just as we extended Buggle and BuggleWorld to add new methods, we can extend Picture. The difference is that the Picture methods will be fruitful. The following method takes four Pictures as parameters and returns a new Picture that contains all four pictures in a two-by-two grid.

public Picture fourPics (Picture p1, Picture p2, Picture p3, Picture p4){ Picture row1 = beside (p1, p2); Picture row2 = beside (p3, p4); Picture grid = above (row1, row2);

3.13. GLOSSARY 33

return grid; }

The first line assembles the first two pictures into a row. The second line does the same with the last two pictures. The next line combines the rows into a grid. The last line is a return statement. When return is executed, the method ends immediately and the flow of execution returns to the previous frame. For fruitful methods, the return statement has to include an expression. This expression gets evaluated and the result becomes the return value of the method. Whoever invokes this method will get the object that grid refers to as a return value. We can make this method more concise by eliminating the temporary variables.

public Picture fourPics (Picture p1, Picture p2, Picture p3, Picture p4){ return above (beside (p1, p2), beside (p3, p4)); }

The expression after the return statement is more complicated, but the effect is the same. Java evaluates the expression and returns the result. When you declare a fruitful method, you have to declare the return type (in this case Picture). The expression in the return statement has to be the same type, otherwise Java reports a compile-time error. Try it out so you know what the error message looks like. As an exercise, write a method called fourSame that takes a Picture as a parameter and that returns a new Picture with the original picture in all four quadrants of a grid.

3.13 Glossary

print statement: An invocation of System.out.println or System.out.print to display a value in the console window.

concatenate: To join two operands end-to-end.

console: A window that contains the text output of a program.

extend: Define a new class based on an existing class.

override: Write a new method for an extended class that replaces an existing method from the original class.

Java Execution Model (JEM): A visual language for representing the state of an executing Java program.

Object Land: The section of the JEM that represents objects.

Execution Land: The section of the JEM that represents methods as they execute and their local variables.