Chapter 0

Introduction

0.1 How to use this book

Welcome to ProgramLive! Or, rather, welcome to this paper companion to the livetext ProgramLive. This companion will help you in learning to program, although you will spend most of your time working with the livetext itself. ProgramLive contains the bulk of the teaching material: over 250 lectures with synchronized narration and animation, along with an index, a glossary that is unmatched in any other programming text, exercises and projects.

Why this supplementary text?

1. ProgramLive is nonlinear, and you can successfully learn to program by following its Activities in many different orders. This companion suggests an ordering and guides you through it. We have divided this business of learning to program into ten units which should take roughly 10 days each, and we include all the topics that are usually part of an introductory course. (Some topics, such as recursion, are taught only occasionally in a first course.)

2. You may need a place to keep track of your progress. We have included charts to fill in, places to write definitions, and areas to take notes. This companion also contains summaries and short explanations. Therefore, this companion gives you a good paper version to use for review when you are away from your computer. Also, the first appendix contains a checklist of all the Activities and suggested homework, so you can keep track of what you have done.

3. The appendices provide reference material. All of this material can be found in one form or another on ProgramLive or on the web, but in some cases it is easier to use reference material that appears on paper.

How to study

There are two absolutely necessary tasks that you must do when learning to program. They are:

• Take notes as you listen. When listening to an Activity in Program-Live, pause it often, relisten to it where necessary, and take notes. This companion will help you with that. When you are done with the livetext, most pages of this supplementary book should be covered with your handwriting. Use the margins as well as the outlined areas; write as much as you need to remember the material. ProgramLive is the only place where you can have the lecturer repeat something as often as you like!

• Write programs! As soon and as often as you can, write a program and run it. Just as you can’t learn to write poetry just by reading the works of Robert Frost, you can’t learn to program just by reading our programs. This companion provides many exercises for you to cement what you’ve just learned.

Beginning a whole new area of study almost always calls for learning new phrases and terms, and the area of programming is no different. We encourage you to use whatever means necessary to master the new terminology immediately, because it will be used over and over again in later work. If you don’t understand the terminology, you will not understand later material.

When a new term is defined, write it down in a list, or put it on a flashcard along with its definition, or rehearse saying the term and its precise meaning —do whatever it takes to make the term part of your working vocabulary. This means studying, and not just reading and listening. Reading and listening do little good if they are not followed by real study and practice. When you see a term that you don’t understand, look it up in the glossary and learn what it means. Don’t put off looking up a word; do it immediately.

All this requires more work on your part, but you will find that you will learn the material far more effectively, and in less time, than if you just read and listen.

0.2 Diving in

If you’re like the younger Gries, you don’t want to do the entire first chapter of the livetext in order to learn all its features. Here is the absolute minimum you should know about the livetext and how to use it:

• Tools

• Web

• Homework

• Labs 0.3. IDE 3

• Navigation You may use the

0.3 IDE

The IDE you use 4 CHAPTER 0. INTRODUCTION

Unit One: Basic Concepts

1.1 Unit One Activities

Activities in the first chapter (How to use ProgramLive) Activities on Lesson page 2-1 (Hardware and software) Activities on Lesson page 2-2 (Some simple Java programs) Activities on Lesson page 2-3 (Components of a Java program) Activities on Lesson page 2-4 (Three Statements: assignment, conditional, block)

1.2 Overview

In this first unit on programming, you will encounter some basic terminology of computing and programming, look at a few Java programs, and study the basic components of Java programs.

There are fewer activities in this unit compared to all the other units. This is intentional: we expect you to spend roughly 12-15 hours per unit, and most new programmers spend several hours learning how to compile and run programs. You should also spend about half an hour in the first chapter of ProgramLive, learning about all the features of the livetext. In addition to the activities, we provide a plethora of instructional tools such as the glossary, index, exercises and labs.

1.3 Lesson Page 2-1: Basics

The two Activities on this page use many phrases with which you are probably already familiar. The important ones to learn are:

hardware, software, program, CPU, I/O (input/output), memory, memory location, address of a memory location, byte, and bit.

It is useful to know that the bits in a memory location can be used to represent many things, like integers, characters, and computer instructions. Also, there are different representations of integers —e.g. decimal, binary, and octal. You don’t have to master these ideas right now —you can learn a lot about programming without them— but they are fundamental concepts that every programmer knows.

1.4 Lesson Page 2-2: Simple Java programs

Lesson page 2-2 gives you an overview of Java programs and their execution. The details will be explained in later Lessons, so don’t expect to or try to remember everything you see and hear about Java programs on this Lesson page. Pay attention to the filing cabinet metaphor, because we use it throughout ProgramLive.

Activity 2-2-1: A do-nothing Java program.

Definition of keyword:

Definition of method:

Execution of a program starts by calling:

Every program has a method called:

The is the basic building block in Java.

The body of every class begins with this symbol: and ends with this symbol: .

In programming, the terms instruction and statement mean the same thing.

       true         false

Programming exercise: W hat is wrong with the following Java program?

  // This program won't even compile.
  public class Garble (
      public static void start(String[] args) {
      }
  )

1. Type it in exactly as shown and see what happens when you compile it. You will get an error message, which indicates that the computer couldn’t understand something about your program while trying to compile. Read the error message carefully, review your notes from this section, and fix the two errors. When you try to compile again, it will work.

2. Now try to run it. You will get another error message; if you read it carefully it will seem to have something to do with method main being missing. And it is —the method in this program is called start, not main. Change the name, recompile, and run it again. This time, nothing will happen: 0 statements were executed. Nothing was printed, and so there is no output.

Activity 2-2-2: A program that prints.

What is the Java console?

What is the difference between print and println?

What happens when the following statement is executed?

       System.out.print(``Hello, everyone'');

Programming exercise: W rite a program that prints your name on the first line, then prints a blank line, and then prints your address. (Hint: use the following code to print a blank line: System.out.println(); )

8 CHAPTER 1. UNIT ONE: BASIC CONCEPTS Activity 2-2-3: A program that creates a window.

What does API stand for? What does GUI stand for? What is a package? Which package deals with input and output? Which package deals with graphical user interface components? What must you put at the top of a class to announce that you want to use the graphical user interface package? Which class deals with windows? Programming exercise: W rite a program that creates and shows three windows. (Hint: you’ll need three statements inside method main, instead of one.)

Activity 2-2-4: A program that draws.

Write down the two import statements that are shown in the code window: What is the name of the method that redraws the graphics window? When does method paint get called? Where is the origin (the (0,0) pixel) for drawing? What statement sets the drawing color? When talking about pixel (a,b), which coordinate comes first, the horizontal one or the vertical one?

Pixel (10,10) is closer to the bottom of the drawing window than pixel (40,10)).

  true         false

Pixel (10,10) is closer to the bottom of the drawing window than pixel (10,40)).

  true         false

What statement would you use to draw the String ``Wahoo!'' at pixel (40,60)?

Programming exercise: M ake a copy of the program from this activity. (Look on the lesson page for instructions on how to find it on the livetext, and be sure to get both of the files.) Modify method paint in class Draw1 to draw a face: add setColor, drawRect and drawOval statements to the end of method paint to draw an oval face with blue eyes, a red rectangular nose, and a red, wide and thin oval mouth.

You will find it very useful to sketch the face on paper first, in order to figure out roughly which pixel values to use for the various pieces of the face.

For now, don’t worry about drawing your face on top of the circles and rectangles that we drew: just get your face on the screen.

Activity 2-2-5: Exercises on simple programs.

The last Activity on Lesson page 2-2, an interactive exercise, will help you check whether you have digested the terminology that was introduced on this page. Be sure to take part in this Activity!

1.5 Components of a Java program

Lesson page 2-3 begins a detailed explanation of Java. This is the time to begin learning terminology in earnest. When you finish this page, check to make sure that you understand fully the terms that are discussed below.

Activity 2-3-1: Comments and whitespace.

Describe the purpose of comments.

The form of comment that can span several lines begins with this: and ends with this: .

Write an example of a one-line comment:

Describe the five forms of whitespace:

1.

2.

3.

4.

5.

Comments are not a form of whitespace.

  true         false

Where can whitespace appear?

Where can’t whitespace appear?

Programming exercise: G o back to the face exercise from Activity 2-2-4 and “comment out” the lines of code that produce the rectangle and oval and the two Strings. Add comments above the lines of code you added to describe what the code you added does. Use both types of commenting syntax. Compile and run the code to make sure that your face is still being drawn correctly.

Activity 2-3-3: Keywords and indentifiers. Definition of keyword:

Write the six keywords used in this activity:

Definition of identifier:

Write the rules for forming an identifier:

1.

2.

3.

4. What are the two non-alphanumeric characters (characters that are not letters or numbers) that can appear in identifiers?

The identifiers Dingbat and dingbat are really the same, because Java ignores capitalization.

  true         false

Write the two conflicting guidelines for identifiers:

1.

2.

Activity 2-3-5: Variables and types.

You don’t have to memorize every little aspect of each type that you run across, because references are just a few mouse clicks away. Visit the glossary on the livetext when you see a word you don’t understand. Definition of variable:

Any keywords can be used as the name of a variable.

  true         false

Definition of type:

Definition of variable declaration:

Describe the three parts of a variable declaration:

1.

2.

3. The range of an int variable is to inclusive. The range of a byte variable is to inclusive. You don’t have to memorize the previous two items, but you should recognize that an int can hold a much, much wider range of values than a

byte.

How is type String different from char, int, and byte?

Activity 2-3-6: Expressions. What is weird about division when both operands are of type int?

Figure out the results of the following when calculated as part of a Java program. Assume all numbers are of type int:

1. 5 + 2 * 3 =

2. 5 + (2 * 3) =

3. (5 + 2) * 3 =

4. 5 / 2 =

5. 7 / 2 * 4 =

6. 7 / (3 * - 2) = Write a program that prints the value of each of these to verify your answers. Given x= 5; y= 2; z= 3; what is the value of z after execution of each line of code? (Assume z= 3; at the start of each line.)

  1. z= 4;
  2. z= y;
  3. z= 22 / x;
  4. z= x + z;
  5. z= x + (z * y);
  6. z= y + z * x;
  7. z= (3 * (- (z)));

Write a program that prints the value of each of these to verify your answers.

1.6 Three statements: assignment, condition, block

Activity 2-4-1: The assignment statement.

Write the form of an assignment:^{1}

Write the form of a variable declaration:

Write the steps to executing an assignment statement:

1.

2.

A variable may only be assigned a value once during execution of a program.

  true         false

Programming exercise: T he statement

                    int numberOfFeet= 2;

stores the value 2 in variable numberOfFeet, and the code

              System.out.println(numberOfFeet);

prints the value stored in numberOfFeet.

You should all recognize the pythagorean formula a^{2} + b^{2} = c^{2} for calculating the length of a hypotenuse of a right triangle. Write a program that declares an int variable called cSquared. Variable cSquared should store the square of the length of the hypotenuse of a triangle with side a of length 3 and side b of length 5. The last statement of the program should print the value of cSquared.

Activity 2-4-2: Example: swapping the values of two variables.

Programming exercise: W rite a program that first declares three variables, a, b and c. Next, assign a the value 1, b the value 2, and c the value 3.

Now write a sequence of statements to rotate those values, so that afterward a has the value that b had, b has the value that c had, and c has the value that a had.

Hint: you will need to use a temporary variable.

Activity 2-4-3: The if-statement.

Write the form of an if-statement:

1Look in the Glossary.

14 CHAPTER 1. UNIT ONE: BASIC CONCEPTS What are the possible values that a boolean expression can evaluate to? What happens if the boolean expression evaluates to true? What happens if the boolean expression evaluates to false? Programming exercise: C omplete the following program: Make up something that declares some variables and needs and if-statement.

Activity 2-4-4: The if-else-statement. Write the form of an if-else-statement: What happens if the boolean expression evaluates to true? What happens if the boolean expression evaluates to false? Programming exercise: Make up something that declares some variables and needs and if-else-statement.

Activity 2-4-5: Boolean expressions. List all the elements in the set of boolean values: Definition of boolean expression: Definition of proposition: List six mathematical expressions that produce a boolean value. List three boolean operators. Programming exercise: W rite a program that prints the values of the following expressions. (Make sure you understand the output!)

    true && false
    true || false
    false || false
    false && false

false && true
false || true
false && !true
!false
!true

Activity 2-4-6: Blocks.

Write the form of a block:

Because all of the statements in a block get executed, it doesn’t matter what order they are in.

true         false

Write the indentation rule:

Programming exercise: T here are errors (both with the uses of blocks and with indentation) in this program. Fix them.

public class ErrorRiddled {
    public static void main(String[] args) {
    }
}

Activity 2-4-7: Assignment, conditional and block statements.

Programming exercise:

16 CHAPTER 1. UNIT ONE: BASIC CONCEPTS

Unit Two

2.1 Unit One Activities

Activities on Lesson page 2-5 Activities on Lesson page 2-6 Activities on Lesson page 3-1 Activities on Lesson page 3-2 Activities on Lesson page 3-3 Activities on Lesson page 3-4 Activities on Lesson page 3-5 Activities on Lesson page 6-1 Activities on Lesson page 2-7

2.2 Overview

In this first unit on programming, you will encounter some basic terminology of computing and programming, look at a few Java programs, and study the basic components of Java programs.

2.3 Basic output and input

Activity 2-5-1: Using the Java Console for output.

Activity 2-5-2: Using the Java Console for input.

Definition of prompt:

Programming exercise:

Type the following code into a file named “Test.java”:

    public class Test {
        public static void main(String[] args) {
            System.out.println(``Hi'' + ``Phred.'');
        }
    }

Compile and run this program. Notice how the output looks a bit funny? Fix it so it becomes readable.

Now try using the + operator with ints, longs, and Strings. For example, what is the output if you substitute in the following lines of code?

     System.out.println(``high '' + 5);
     System.out.println(``3'' + 20 * 2);
     System.out.println(3.4 + 1.6 + `` is five'');
     System.out.println(``Is five '' + 3.4 + 1.6);

Activity 2-5-3: A GUI: JLiveWindow.

Programming exercise: C hange method buttonPressed in class MyJLiveWindow so that it reads from int field 0 and puts twice that amount in int field

1. What happens if you type a letter into the int field?

Activity 2-5-4: The Java Console and GUIs.

Programming exercise: D raw the Olympic rings.

Need a picture here

Activity 2-5-5: Graphics windows.

Activity 2-5-6: Using a graphics window.

Activity 2-5-7: Exercises on graphics windows.

What is the type of the result, when you “add” the following:

A String and an int produces a result of type \underline{String}.

A String and a String produces a result of type .

An int and an int produces a result of type .

An int and a String produces a result of type .

A String and an int and then another int produces a result of type .

An int and a long produces a result of type .

Match the outputs with the print statements. If there is a mistake in the print statement, don’t match it with anything.

System.out.println(“fred”); System.out.println(23);

System.out.print(fred);  fred

System.out.print(23);

System.out.print(“23”);  23

System.out.print(“fr” + ed); System.out.print(“1” + 20 + 2);

Given the value stored in a is 20 and the value stored in b in 3, write the output of the following print statement:

System.out.println("Compost composed...  /nThe result of a + b:
"
+ a + b + "/n" + 33 + ", 44, 55");  .5in

Notice how difficult it is to read when written as one statement? Using the same variables, a and b, re-write the print statement as three seperate print statements. Hint: each line of output should be a seperate line of code. You may use “println” instead of “/n”.

Assuming you have included the file JLiveRead.java in your project, what line of code will read an integer typed by the user, and store it in some integer variable x?

What do the following lines of code do? System.out.print(``Enter

number of young goats:  ``);int numKids= JLiveRead.readInt();

What would you expect the following code to do? (It is not code you can

execute, so don’t bother trying!) int phredID= ExampleClass.readIntID();

Programming exercise: C reate a project in your IDE using the two

files JLiveWindow.java and MyJLiveWindow.java. Compile and run the

project, to check that you’ve set it up correctly. Given that the line of code:

int sum= getIntField(0) + getIntField(1);

reads the integer in field 0, adds it to the integer read from field 1 and stores the result in sum whenever the button is pressed, what do each of the following lines of code do? Add them to method buttonPressed, and create a line of code to set different int fields to the results. Then run the program to check your results.

int mult= getIntField(0) * getIntField(1);
int other= getIntField(0) - getIntField(1);
int divResult= getIntField(0) / getIntField(1);

What happens if you type 4 in field 0 and 3 in field 1? Where did the decimal place go?

2.4 Assertions in programs

2-6

Activity 2-6-1: Relations about variables and values.

Definition of relation:

Activity 2-6-2: Simplifying a particular kind of relation.

dogs can mean feet.^{1}

  true         false

What is wrong with the following relation?

If it is raining, wp is true.

Rewrite the relation to completely specify wp.

Activity 2-6-3: Assertions.

1It’s in the footnote to this activity.

2.5 Methods

Activity 3-1-1: Methods are recipes.

Computers are not intelligent. They will follow the instructions they are given without any extrapolation or imagination. If you want to write a program to “Add two numbers together”, you need to tell the computer which two numbers, and where to store the result. Someone else already told the computer how to add.

Write a set of instructions for wrapping a present. Assume the person following the instructions knows what the present is, as well as what paper, sicissors, string, tape, pen and label are. Try to follow your instructions using real materials, and you may find your instructions aren’t as detailed as you think.

When you look at a box of instant cake mix (or a box of pasta, or soup mix, or some other pre-processed food), you find a set of instructions. Write a set of instructions for boiling pasta. Can you make them general enough that you can substitute “rice” for “pasta” and only have to change the cooking time? How about for boiling potatoes?

Activity 3-1-2: The black-box view of a method. Definition of method:

Definition of procedure:

Definition of specification:

Write the form of a method header:

Definition of body:

Definition of parameter:

Write the form of a parameter declaration:

int is a type.

  true         false

A parameter is a variable.

  true         false

What does keyword public indicate?

Write a method header for a method called myFirstHeader that is public, has return type void, and has two parameters, a variable called i and a variable called j, both of type int.

Activity 3-1-4: Understanding procedure calls. What do you need to do in order to figure out what execution of a procedure call does?

What does the method call drawRect(22, 30, 40, 10 do?

Activity 3-1-5: The general form of a procedure call.

What are the parts of a procedure call?

1.

2.

3.

Write the rules for the number and types of arguments:

1.

2.

3.

drawLine(0, 10, (3+30)/11, 4); is a valid procedure call.
  true         false

Programming exercise: Think of something.

2.6 Method bodies and method calls

Activity 3-2-1: The method body.

Write the steps for executing a procedure call:

2.

3.

4.

5.

Perform the first four steps for executing the following method call:

print3(8*4, (14-6)/2);

Perform the first four steps for executing the following method call, where

x=12:
doIt(8*4, (14-6)/2, x);

Here is the code for method doIt: // Draw something public static void doIt(int )

Activity 3-2-2: Example of method-call execution. Definition of frame:

It is so important that you memorize the steps to executing a procedure call that you should now, from memory, try to write those steps:

1.

2.

3.

4.

5. If you could do it, congratulations! If not, keep trying –this is one of the most important steps to learning how to program.

Perform the first four steps for executing the following method call, where

x=12:
doIt(8*4, (14-6)/2, x);

Here is the code for method doIt: // Draw something public static void doIt(int )

Activity 3-2-3: Executing inner calls.

From memory, write the steps to executing a procedure call:

1.

2.

3.

4.

5.

What happened to the frame for method paint while method drawTriangle was being executed?

When method drawTriangle finished executing, we re-started execution

of paint.
  true         false

Activity 3-2-5: Writing procedure calls.

Definition of debug:

2.7 Two components of method bodies

Activity 3-3-1: Local variables.

Definition of local variable:

Write the form of a local variable declaration:

What do you have to do to a local variable before you use it?

Definition of scope:

What is the scope of a local variable?

Circle the scope of variable aVar. public void foo() System.out.println(); int bVar; bVar= 3; int aVar; System.out.println(); aVar= bVar * 2;

Activity 3-3-2: Combining declaration and initialization. Write the form of an initialized variable declaration:

What should you do at the same time as you declare a local variable?

Activity 3-3-4: The return statement.

What happens when a return statement is executed?

2.8 Functions

Activity 3-4-1: Form of a function.

Write the two major differences between a procedure and a function:

• •

How can you tell the difference between a procedure and a function?

Activity 3-4-2: The function call.

Procedures and functions are mechanisms.

A procedure call is a

A function call is an

Describe the difference between the purposes of a function specification and a function body:

Here is a function specification and header, and a call on that function. What is the result?

Think up a function call.

Activity 3-4-3: Executing a function call.

Write the steps for executing a function call:

1.

2.

3.

4.

5.

Which two steps differ from the steps for executing a procedure call, and how are they different?

2.9 Top-down programming

Activity 3-5-1: Top-down design, or stepwise refinement.

Definition of top-down programming:

Definition of statement-comment:

Activity 3-5-2: The Raven.

How many lines did Poe decide The Raven should be?

What was the topic?

What was the tone?

What would have to be sonorous and susceptible to protracted emphasis?

Activity 3-5-3: Example 1: anglicizing integers.

In method tensName, why is n’s range 2 <= n <= 9? That is, why isn’t 1 included?

Activity 3-5-4: Example 2: anglicizing integers a different way.

In method anglicize, why didn’t we use if-else statements? What bug would happen if we had? Find an example of a method call that would evaluation to the wrong result if we had used if-else statements.

Programming exercise: Write a function that has a String parameter, which contains one of the single-digit words like ``zero'', ``one'' or ``nine'', and returns the int version of it. For example, if your function is called with argument ``seven'', it should evaluate to 7.

2.10 Classes

Activity 6-1-1: The class as a file drawer of methods.

Write the form of a class definition.

In the filing cabinet metaphor, where are static methods kept?

Definition of public:

On the Lesson page is a description of naming conventions for files. What should you name the file containing class Foo?

Activity 6-1-2: Referencing static methods.

Write the two rules for referring to a static method in a method call: 1. 2.

Activity 6-1-3: Examples of referencing static methods: temperature conversion. It is vital that you think about efficiency as you develop a program.

  true         false

What trick did we use to avoid having to work out formulas for the second set of temperature conversion methods?

Activity 6-1-4: Overloading method names.

Definition of overloading:

2.11 Footnote: exit, break and switch

Activity 2-7-: .

Unit Three

3.1 Unit Three Activities

Activities on Lesson page 4-2 (double and float) Activities on Lesson page 4-5 (Type char) Activities on Lesson page 4-6 (boolean and its weird-looking operators) Activities on Lesson page 6-2 (Class Math and a review of triginometric functions)

3.2 Overview

When you are finished this unit, you will be able to use decimal values in a program, understand the boolean (the “true-or-false”) logic of type boolean, and know how to use the built-in mathematical abilities of class Math.

3.3 Lesson Page 4-2: Integral types and casting basics

Integral constants (a.k.a. literals), operations on variables of type int and long, and how to convert from one type to another.

Activity 4-2-1: Integral constants (literals)

Given the line of code:

                  int buttons= 33 + 2 * 22;

Circle the integral constants (the literals).

Activity 4-2-2: Expressions of type int The following mathematical statement is true if you follow the conventions Java uses when doing the calculation. Why?

3 + (4 + 2 * (7 / 2)) / 4 = 5

What is the value of x?

                       int x= 3 - - 1;

The largest int value is 2,147,483,647, so if you tried to add 2,000,000,000 with 200,000,000 and store it in an int variable, your program might produce incorrect results.

  true         false

If you try to store the value 3,000,000,000 in an int variable, you will cause an because the value is too large to store in an

int.

Activity 4-2-3: Promoting values to a wider type What does it mean to say one type is wider than another?

Type int is wider than type long.

  true         false

The types most commonly used to contain numbers are int and long because types byte and short have a limited range.

  true         false

Types int and short take up less space than types byte and long.

  true         false

You can store the value 99.3 in a variable of type long.

  true         false

If you wanted to keep track of the number of people at a party, you would use a variable of type .

If you wanted to count the number of trees in one acre of forest, you would use a variable of type .

If you wanted to keep track of the percentage of people who wear hats, you would use a variable of type .

3.3. LESSON PAGE 4-2: INTEGRAL TYPES AND CASTING BASICS 31

Write the form of a variable declaration:

Write the steps to executing an assignment statement:

1.

2. Given x= 5; y= 2; z= 3; what is the value of z after execution of each line of code? (Assume z= 3; at the start of each line.)

  1. z= 4;
  2. z= y;
  3. z= 22 / x;
  4. z= x + z;
  5. z= x + (z * y);
  6. z= y + z * x;
  7. z= (3 * (- (z)));

Write a program that prints the value of each of these to verify your answers. Programming exercise: T he statement

                    int numberOfFeet= 2;

stores the value 2 in variable numberOfFeet, and the code

              System.out.println(numberOfFeet);

prints the value stored in numberOfFeet. You should all recognize the pythagorean formula a^{2} + b^{2} = c^{2} for calculating the length of a hypotenuse of a right triangle. Write a program that declares an int variable called cSquared. Variable cSquared should store the square of the length of the hypotenuse of a triangle with side a of length 3 and side b of length 5. The last statement of the program should print the value of cSquared. A variable may only be assigned a value once during execution of a program.

  true         false

Activity x-x-x: ActivityTitle Activity x-x-x: ActivityTitle Activity x-x-x: ActivityTitle 32 CHAPTER 3. UNIT THREE

3.4 double and float

3.5 Type char 3.6 boolean and some weird-looking operators 3.7 Class Math 3.8 Review of triginometric functions

Unit Four

4.1 Classes and objects 4.2 Creating and initializing objects 4.3 Scope 4.4 Constructors 4.5 Non-static methods 4.6 Style 4.7 Comments

34 CHAPTER 4. UNIT FOUR

Unit Five

5.1 Method toString 5.2 Numerical wrapper classes 5.3 Non-numerical wrapper classes

5.4 Strings
5.5 Vector

36 CHAPTER 5. UNIT FIVE

Unit Six

6.1 Introduction to iteration 6.2 Examples of loops 6.3 The for loop 6.4 Making progress and stopping 6.5 Loop roundup

38 CHAPTER 6. UNIT SIX

Unit Seven

7.1 Introduction to arrays 7.2 Array segments 7.3 Examples of array use 7.4 Arrays and classes 7.5 Basic array algorithms 7.6 Selection sort and insertion sort

40 CHAPTER 7. UNIT SEVEN

Unit Eight

8.1 Multidimensional arrays 8.2 Some programs that use 2-D arrays 8.3 Ragged arrays 8.4 Examples of ragged arrays

42 CHAPTER 8. UNIT EIGHT

Unit Nine

9.1 Subclasses 9.2 Constructors and inherited methods 9.3 Casting references

44 CHAPTER 9. UNIT NINE

Unit Ten

10.1 Unit Three Activities

Activities on Lesson page 4-2 (double and float) Activities on Lesson page 4-5 (Type char) Activities on Lesson page 4-6 (boolean and its weird-looking operators) Activities on Lesson page 6-2 (Class Math and a review of triginometric functions)

10.2 Overview

When you are finished this unit, you will be able to use decimal values in a program, understand the boolean (the “true-or-false”) logic of type boolean, and know how to use the built-in mathematical abilities of class Math.

10.3 Lesson Page 4-2: Integral types and casting basics

Integral constants (a.k.a. literals), operations on variables of type int and long, and how to convert from one type to another.

Activity 4-2-1: Integral constants (literals)

Given the line of code:

                  int buttons= 33 + 2 * 22;

Circle the integral constants (the literals).

Activity 4-2-2: Expressions of type int The following mathematical statement is true if you follow the conventions Java uses when doing the calculation. Why?

3 + (4 + 2 * (7 / 2)) / 4 = 5

What is the value of x?

                       int x= 3 - - 1;

The largest int value is 2,147,483,647, so if you tried to add 2,000,000,000 with 200,000,000 and store it in an int variable, your program might produce incorrect results.

  true         false

If you try to store the value 3,000,000,000 in an int variable, you will cause an because the value is too large to store in an

int.

Activity 4-2-3: Promoting values to a wider type What does it mean to say one type is wider than another?

Type int is wider than type long.

  true         false

The types most commonly used to contain numbers are int and long because types byte and short have a limited range.

  true         false

Types int and short take up less space than types byte and long.

  true         false

You can store the value 99.3 in a variable of type long.

  true         false

If you wanted to keep track of the number of people at a party, you would use a variable of type .

If you wanted to count the number of trees in one acre of forest, you would use a variable of type .

If you wanted to keep track of the percentage of people who wear hats, you would use a variable of type .

Write the form of a variable declaration:

Write the steps to executing an assignment statement:

1.

2. Given x= 5; y= 2; z= 3; what is the value of z after execution of each line of code? (Assume z= 3; at the start of each line.)

  1. z= 4;
  2. z= y;
  3. z= 22 / x;
  4. z= x + z;
  5. z= x + (z * y);
  6. z= y + z * x;
  7. z= (3 * (- (z)));

Write a program that prints the value of each of these to verify your answers. Programming exercise: T he statement

                    int numberOfFeet= 2;

stores the value 2 in variable numberOfFeet, and the code

              System.out.println(numberOfFeet);

prints the value stored in numberOfFeet. You should all recognize the pythagorean formula a^{2} + b^{2} = c^{2} for calculating the length of a hypotenuse of a right triangle. Write a program that declares an int variable called cSquared. Variable cSquared should store the square of the length of the hypotenuse of a triangle with side a of length 3 and side b of length 5. The last statement of the program should print the value of cSquared. A variable may only be assigned a value once during execution of a program.

  true         false

Activity x-x-x: ActivityTitle Activity x-x-x: ActivityTitle Activity x-x-x: ActivityTitle 48 CHAPTER 10. UNIT TEN

10.4 double and float

10.5 Type char 10.6 boolean and some weird-looking operators 10.7 Class Math 10.8 Review of triginometric functions