Download as pdf or txt
Download as pdf or txt
You are on page 1of 236

Table

of Contents
Introduction 1.1
Introduction to Programming in Java with Karel the Dog 1.2
Introduction to Programming with Karel 1.2.1
More Basic Karel 1.2.2
Java Programs and the Run Method 1.2.3
Karel Can't Turn Right 1.2.4
Methods in Karel 1.2.5
Top Down Design and Decomposition in Karel 1.2.6
Commenting Your Code 1.2.7
SuperKarel 1.2.8
For Loops 1.2.9
While Loops in Karel 1.2.10
If Statements 1.2.11
If/Else Statements 1.2.12
Control Structures Example 1.2.13
How To Indent Your Code 1.2.14
Basic Java 1.3
Printing in Java 1.3.1
Variables and Types 1.3.2
User Input 1.3.3
Arithmetic Expressions 1.3.4
Casting 1.3.5
Booleans 1.3.6
Logical Operators 1.3.7
Comparison Operators 1.3.8
For Loops 1.3.9
While Loops 1.3.10
If Statements 1.3.11
Loop-and-a-Half 1.3.12
Short-Circuit Evaluation 1.3.13

1
De Morgan's Laws 1.3.14
Strings 1.3.15
Methods 1.4
Java Methods 1.4.1
Methods and Parameters 1.4.2
Methods and Return Values 1.4.3
Javadoc and More Methods 1.4.4
Strings Methods 1.4.5
Strings and Characters 1.4.6
Exceptions 1.4.7
String Processing 1.4.8
Classes and Object-Oriented Programming 1.5
Introduction To Classes and Objects 1.5.1
Classes vs. Objects 1.5.2
Using a Class as a Client 1.5.3
Writing Classes 1.5.4
Writing Classes and Instance Methods 1.5.5
Getter and Setter Methods 1.5.6
Class Methods and Class Variables 1.5.7
Method Overloading 1.5.8
Local Variables and Scope 1.5.9
Key Terms for Classes 1.5.10
Objects vs Primitives 1.5.11
Inheritance 1.5.12
Class Design and Abstract Classes 1.5.13
Polymorphism 1.5.14
Interfaces 1.5.15
Data Structures 1.6
What Are Data Structures? 1.6.1
Introduction to Arrays 1.6.2
Using Arrays 1.6.3
ArrayList Methods 1.6.4
Arrays vs ArrayLists 1.6.5
2D Arrays (Matrices or Grids) 1.6.6

2
Hashmaps 1.6.7
Algorithms and Recursion 1.7
What is an Algorithm? 1.7.1
Pseudocode 1.7.2
Linear Search 1.7.3
Binary Search 1.7.4
Selection Sort 1.7.5
Insertion Sort 1.7.6
Advanced: Recursion 1.7.7
Mergesort 1.7.8

3
Introduction

AP Computer Science in Java

Learn computer science and prepare for the AP exam with CodeHS. Check out the course
at CodeHS and read the book online at GitBook!

The CodeHS AP Java course is a year-long course designed to help students master the
basics of Java and equip them to successfully pass the College Board AP Computer
Science A Exam at the end of the school year. All learning materials and resources teachers
and students need for a successful year-long AP Java course can be found on the CodeHS
website.

Contributors
We'd like to thank all those who have helped write this book:

Karel the Dog (@karelthedog, http://karelthedog.com/)

Michael Goheen

Neil Shankar

4
Introduction

Kurt Hepler

Vincent Xie

Sachi Williamson

Wezley Sherman

Kathryn Rodgers

5
Introduction to Programming in Java with Karel the Dog

Introduction to Programming in Java with


Karel the Dog
This chapter introduces basic Java programming and computer science topics with Karel the
Dog.

6
Introduction to Programming with Karel

Introduction to Programming with Karel


the Dog
Computers play an integral role in the modern world. From playing games to banking online,
we interact with computers directly and indrectly every day. Understanding how computers
work and how to work with them is an important skill. Computer programming is the process
of giving commands to a computer. Sequences of commands can be combined into
programs that perform specific tasks.

Programming with Karel


Giving instructions to a computer is much like giving commands to a dog. In this course, we
will learn the basics of programming with Karel the Dog.

Karel's world is a simple one: Karel can move around the world and put down and pick up
tennis balls. Though Karel only knows a few commands, these commands can be combined
into interesting programs to solve many different problems and explore the basics of
computer science.

Karel's Grid World


Karel's world is actually a grid. Each point on the grid is marked by a dot. Karel can move
from point to point and travel around the world. The horizontal rows are called streets in
Karel's world, and the vertical columns are referred to as avenues. In each spot, Karel can
face four directions: north, south, east, or west.

Karel's commands
In order to have Karel perform an action, you need to give Karel a command. A command is
an instruction that tells Karel what to do.

Karel only knows four commands:

move();
putBall();
takeBall();
turnLeft();

7
Introduction to Programming with Karel

What does each command do?


The move() command has Karel move one spot in the direction that Karel is facing.

The putBall() command puts down one tennis ball in the spot where Karel is standing.

The takeBall() command removes one tennis ball from the spot where Karel is standing.

The turnLeft() command turns Karel 90 degrees to the left.

The parts of a command


Notice that Karel's commands look a little different from plain English words. This is because
Karel's commands are written as computer code. These simple spelling rules are called the
syntax of Karel's language. There are a few things to keep in mind when writing commands
for Karel:

You need to write the command exactly as it appears in the list above.

You need to match the exact capitalization. For example, turnleft(); is incorrect. It
should be written as turnLeft(); with an uppercase L .

Make sure to end every command with a ();

Each command goes on its own line.

Our First Karel Program

8
Introduction to Programming with Karel

Imagine you have Karel starting in the world on the left: in the bottom left corner, facing east.
You want to get Karel to the world on the right. What would be the code that you write?

Remember, Karel has four commands, and we can use those commands to write this
program. Below you can find the program.

Here's a program we could write to have Karel complete the task:

move();
move();
putBall();
move();
move();

9
More Basic Karel

More Basic Karel


Karel can navigate a world by moving and turning left within it. Karel can also take balls and
put balls down. Recall that these are the only four commands Karel knows:

move();
putBall();
takeBall();
turnLeft();

Karel resides in a boxed-in world. Let's review the basic components of Karel's world.

Karel's World
Karel's world is a grid composed of walls, streets, and avenues.

Walls:
Walls block Karel's movement. Walls include the borders of a world as well as any lines
running through the world.

Karel cannot move through walls! If Karel attempts a move(); command while directly in
front of a wall, Karel will crash into it.

10
More Basic Karel

Streets:
A street is a row in the grid.

The 5th row, or 5th street, is highlighted in the example world above.

Avenues:
An avenue is a column in the grid.

11
More Basic Karel

The 8th column, or 8th avenue, is highlighted in the example world above.

Karel's Direction
Karel can face one of four directions at any given time - north, east, south, or west. The
direction Karel is facing determines which direction Karel will move. If Karel is facing north, a
move(); command will make Karel move up. If Karel is facing east, a move(); command

will make Karel move to the right. The same is true for the south and west directions.

12
More Basic Karel

Karel can always go right, left, or forward from any position.

13
More Basic Karel

For example, if Karel is initially facing east, a turnLeft(); command will result in Karel
facing north.

Similarly, if Karel is initially facing north, a turnLeft(); command will result in Karel facing
west.

Our Second Karel Program


Using our knowledge of direction, let's have Karel make a square out of balls.

14
More Basic Karel

Here is the solution. The comments explain which direction Karel ends up facing after each
turnLeft(); command.

/* Tennis Ball Square


* This program has karel place a square of tennis balls
* and return to his starting point.
*/

//Karel begins facing east


putBall();
move();
turnLeft(); //Karel is now facing north

putBall();
move();
turnLeft(); //Karel is now facing west

putBall();
move();
turnLeft(); //Karel is now facing south

putBall();
move();
turnLeft(); //Karel finishes facing east.

15
Java Programs and the Run Method

Java Programs and the Run Method


So far, we have been writing our Java programs as a series of commands. However, a truly
proper Java program requires a few additional parts. From now on, we will be writing our
commands inside of a Karel class and a run method.

Writing a Java Class


The general format for writing a Java class is:

public class ClassName extends SomeOtherClass


{

Let's break this down a little further by looking at each of these parts individually:

public - The visibility of the class. For right now, all of our classes will be public.

class - This simply tells Java that we are writing a class.

ClassName - The name of the class. You can name your class anything, but the name

should make sense and describe your program appropriately. Class names are written
in UpperCamelCase, where each word starts with a capital letter.
extends SomeOtherClass - Extending SomeOtherClass allows us to use properties and

methods from that class. This is known as inheritance. You will learn more about
inheritance as well as the extends keyword in future chapters.
{ } - Classes start with an opening curly bracket ( { ) and end with a closing curly

bracket ( } ). The rest of our program goes in between these two brackets.

Let's look at an example using the Karel class:

public class SquareKarel extends Karel


{

In this example, SquareKarel is the name of our class. Our SquareKarel class extends the
Karel class. This allows us to write a Karel program. You will learn more about this later, but
for right now, you will only need to extend the Karel class.

16
Java Programs and the Run Method

Adding The Run Method


A class contains methods. Before we begin writing our code, we need to add a run method
to our class. The run method is where our program starts its execution.

public class SquareKarel extends Karel


{
public void run()
{
// Our code here
}
}

The run method is indented inside of the opening and closing curly brackets ( {} ) of the
class body. The run method has its own set of curly brackets ( {} ). We write our Karel
commands within the run method's curly brackets.

Let's look at an example:

public class MoveKarel extends Karel


{
public void run()
{
move();
}
}

When we run this program, Karel will simply move forward one spot.

Square Karel as a Full Java Program


Let's rewrite our second Karel program, SquareKarel , as a full and proper Java program.
What would it look like?

17
Java Programs and the Run Method

We simply encapsulate our code from before inside of the run method. The run method is
inside of our SquareKarel class.

/* SquareKarel
* This program has karel place a square of tennis balls
* and return to his starting point.
*/
public class SquareKarel extends Karel
{
public void run()
{
//Karel begins facing east
putBall();
move();
turnLeft(); //Karel is now facing north

putBall();
move();
turnLeft(); //Karel is now facing west

putBall();
move();
turnLeft(); //Karel is now facing south

putBall();
move();
turnLeft(); //Karel finishes facing east.
}
}

18
Java Programs and the Run Method

19
Karel Can't Turn Right

Karel Can't Turn Right


You may have noticed that Karel can not turn right. Karel can only turn left. To get Karel to
turn right, you have to write out three consecutive turnLeft(); commands like so:

// Turning left three times is the same as turning right once.


turnLeft();
turnLeft();
turnLeft();

Wouldn't it be easier if we had a turnRight(); command that did the same thing?

Methods
In the previous chapter, we introduced the run method. This method is where our program
starts executing our commands.

public void run()


{
// Our code begins here
}

We can create additional methods using a similar syntax. A method is how we teach Karel
new commands. By using the power of methods, we can teach Karel how to turnRight(); .
Here is the turnRight() method:

private void turnRight()


{
turnLeft();
turnLeft();
turnLeft();
}

We write all of our commands within the method body; this is the area between the opening
and closing curly brackets ( {} ).

Tower and Turn Right


Let's have Karel build a tower and then turnRight(); using methods.

20
Karel Can't Turn Right

public class TowerKarel extends Karel


{

public void run()


{
move();
putBall();
turnLeft();
move();
putBall();
move();
putBall();
move();
turnLeft();
turnLeft();
turnLeft();
}
}

While this solution works, we aren't using a turnRight() method. Let's fix that.

21
Karel Can't Turn Right

public class TowerKarel extends Karel


{
public void run()
{
move();
putBall();
turnLeft();
move();
putBall();
move();
putBall();
move();
turnRight();
}
}

We replaced our three turnLeft(); commands with one turnRight(); command, but the
program still does not work. Why is that?

When we run the program, we get an error message telling us that Karel does not know how
to turn right. We still need to teach Karel how to turnRight(); by writing a turnRight()
method.

22
Karel Can't Turn Right

public class TowerKarel extends Karel


{
public void run()
{
move();
putBall();
turnLeft();
move();
putBall();
move();
putBall();
move();
turnRight();
}

private void turnRight()


{
turnLeft();
turnLeft();
turnLeft();
}
}

By writing a turnRight() method, we have taught Karel a new command and completed
the program.

23
Methods in Karel

Methods in Karel
In the last chapter, we briefly introduced using a method to turn Karel right. But what is a
method? And why would we want to use them?

The Basics
A method is a way to teach Karel a new word, or a new command. Methods allow us to
break our program down into smaller parts and make it easier to understand. A program with
many smaller methods is easier to read and fix than a program with one very large method.

The format of a method looks like:

private void myMethod()


{
/* code goes here */
}

Naming is crucial
Here is another example:

private void buildPyramid()


{
/* code goes here */
}

From the name of our method, buildPyramid() , it is very clear what the method does. There
are a few rules for how you name your methods:

Method name should start with a letter, and cannot have any spaces.
Every new word in the name starts with an uppercase letter.
The name should describe what this function does.
The name should start with an action verb, and sound like a command.

Good! The method name describes what it does, is in Camel Case, and does not have any
illegal characters.--> Bad! The method name is not an action/command.--> Bad! The method
name should not have spaces between words. --> Bad! The method name should not start
with a number. --> Good! The method name describes what it does, is in Camel Case, and

24
Methods in Karel

does not have any illegal characters.--> Bad! The method name is not descriptive.-->

Defining a method vs. calling a method


When we want to create and use new methods, there are two parts: Defining a method and
calling our method after we have defined it.

Defining a method: Teaching Karel the new command. In other words, writing out the
instructions for this new action.

Calling a method for Karel: Actually getting Karel to do the command. Actually causing the
action to happen.

For Karel to know how to do the command, we will first need to teach Karel the command.

Example
Defining turnRight() : Karel, when you want to turn right, the instructions are to turn left
three times.

Calling turnRight() : Karel, turn right.

Example: Defining turnAround()


Let's teach Karel how to turn around. Here is our class in a code editor:

public class TurnAroundKarel extends Karel{

public void run()


{
move();
}

If we try and call turnAround() before we define the method, there will be an error:
Uncaught ReferenceError: turnAround is not defined .

25
Methods in Karel

public class TurnAroundKarel extends Karel{

public void run()


{
move();
turnAround(); // Won't work
}

Instead, we need to define turnAround() in another method.

public class TurnAroundKarel extends Karel{

public void run()


{
move();
}

//defining our method


private void turnAround()
{
turnLeft();
turnLeft();
}

Now that we have defined our method, we can call it in the run() method.

public class TurnAroundKarel extends Karel{

public void run()


{
move();
turnAround(); //calling our method after it has been defined
}

private void turnAround()


{
turnLeft();
turnLeft();
}

And that's it! You should now be able to define and call methods properly to make your code
cleaner and easier to understand.

26
Methods in Karel

27
Top Down Design and Decomposition in Karel

Top Down Design and Decomposition in


Karel
Now that we have most of the tools we need, let's focus on the structure of building a
program. Recall that we have commands and methods as the building blocks of our
program. Commands go inside of methods, and methods can be combined to build a
program. So how do we effectively build programs?

When to use a Method?


Recall that methods are used to break down a problem into smaller parts. Grouping a series
of commands into named methods also makes the program much easier to read.

There are a few basic principles to follow to know when to create a new method:

1. The group of commands accomplishes a specific task


2. The specific task is used more than once
3. The specific task solves a smaller problem, but helps solve the bigger problem. If this is
the case, it is ok if the method is only used once.

This leads us to the next discussion - what does it mean to have a specific task or a smaller
problem?

Top-down Design and Decomposition


Each program has the goal of solving a problem. Most of the time, this problem is rather
large and complex, or at least can be broken down into several parts.

When you write your program, you first want to consider the big picture - what is your overall
goal? Then you want to break down the problem into smaller chunks. What is the first step?
The second step? Once you have your steps, can you break down the steps even further?
Keep breaking down each subproblem until you have defined definite tasks that need to be
accomplished. These tasks don't need to be so small they are accomplished in a single
command, but they should be small enough that you could describe them in a short, single
sentence.

Making a Movie

28
Top Down Design and Decomposition in Karel

As an analogy, think about making a movie. The biggest problem that needs to be solved is
that we want a feature length movie that will have the biggest names in Hollywood with
awesome special effects and will entertain everyone who sees it. You can see that this is a
very large problem. So let's break it down, as shown in the picture below.

The big problem is shown at the top. Then it is broken down into 4 subproblems. We need to
entertain everyone, so we need a good script. We want the biggest names in Hollywood, so
we need to solve the cast and crew problem. Then we want awesome sound effects, so we
need to edit the movie. We actually need to have footage, so we need to film the movie.

Then you can see that each one of these problems needs to be broken down into more
managable problems. Here, we only show that Film the Movie gets broken down into filming
each scene.

You can see how each little problem is combined with the solutions to the other little
problems to make up the solution to the overall problem.

Hurdle Karel
Now, say we have a problem where we want Karel to go down the street and jump over all of
the hurdles. The beginning world would look like this:

29
Top Down Design and Decomposition in Karel

And the ending world looks like this:

Let's think about how to solve this. What is the big goal? We want Karel to go down the
street, jump over every hurdle, and stop at the end.

What are the next smaller goals?

1. Karel needs to go down the street until the end


2. When Karel meets a hurdle, Karel needs to jump over it
3. After the last hurdle, Karel needs to go to the end of the street

What tasks should be accomplished in methods?

1. Karel should go to the next hurdle


2. Karel should jump over the hurdle
3. Karel should stop at the wall at the end of the street

See how each method is reusable? We will need to use the first method 3 times and the
second method 2 times.

Finally, we can outline the code we need to write.

30
Top Down Design and Decomposition in Karel

public class HurdleJumpingKarel extends Karel


{

public void run()


{
runToHurdle();
jumpHurdle();
runToHurdle();
jumpHurdle();
runToFinish();
}

private void jumpHurdle()


{
// Make Karel jump over a hurdle
}

private void runToHurdle()


{
// make Karel go to the next hurdle
}

private void runToFinish()


{
// make Karel go to the end of the street
}
}

For the sake of space, not all of the methods have been fully implemented. However, notice
how the use of methods makes the program's goal obvious. You can read through the run
method like it is telling a story. Each helper method accomplishes a specific, small part of the
problem.

Summary
Programs are made up of methods, which are made up of commands. We need to build our
program using methods to make our code readable and to break down the problem into
smaller, more manageable tasks. The program's problem, or goal, should be broken down
into single sentence goals. Each of these small goals gets its own method.

31
Commenting Your Code

Commenting Your Code


There are two parts to writing a program: One part is getting it to work (the functionality). The
other part is the style: How did you write the program? Did you break it down into parts? Is it
clear to read?

This is where comments come into play!

Introducing comments
Comments are a way for you to leave notes about what your code is doing in plain English
so that other people can understand it.

Why comment?
Even though code is run by computers, it is read by other people. Comments help others
understand your code. If you read your code ten years from now, would you be able to
understand what it does?

The computer that runs your program knows not to ignore comments if they are written as
multi-line or single line comments.

Multi-line comments
Use multi-line comments to leave a comment so a reader understands what your program or
method is doing. The start of a multi-line comment uses /* , each line following with a
single * , and ending the multi-line comment with */ .

/*
* This program does ______.
*/

Single line comments


Use single line comments to leave a comment for a single line in your code. For each single
line comment, put two backslashes ( // ) before the comment.

//This line does ______.

32
Commenting Your Code

Preconditions and postconditions


Another important part of commenting is using preconditions and postconditions. We can
leave notes at the top of our methods about assumptions that we make.

Preconditions: What assumptions we make and what must be true before the method is
called.

Postconditions: What should be true after the method has been called.

This helps us think about the problem and make sure our methods line up.

Example: Hurdle Karel with comments


Let's add comments to our Hurdle Karel program. First, we want to add a multi-line comment
to describe what the program does at the top.

/*
* This program has Karel run a race
* by jumping two hurdles.
*/
public class HurdleKarel extends Karel
{
...
}

Next, let's add another multi-line comment to describe what our method, run() , does.

33
Commenting Your Code

/*
* This program has Karel run a race
* by jumping two hurdles.
*/
public class HurdleKarel extends Karel
{
/*
* This method is our main entry point for the program.
* Karel runs to the hurdle and jumps it twice, before
* finishing the race.
* Precondition: Karel should be in the bottom left
* corner, facing east.
* Postcondition: Karel should be at the end of the race.
*/
public void run()
{
runToHurdle();
jumpToHurdle();
runToHurdle();
jumpToHurdle();
finish();
}
}

Let's also add a multi-line comment for another method, runToFinish() .

/* This method has Karel move four times to finish the race.
* Precondition: Karel has finished jumping the last hurdle.
* Postcondition: Karel is at the end of the race.
*/
private void runToFinish()
{
move();
move();
move();
move();
}

In the runToFinish() method, we can add a single line comment.

private void runToFinish()


{
// This method has Karel move four times to finish the race.
move();
move();
move();
move();
}

34
Commenting Your Code

Full Example:

* This program has Karel run a race by jumping


* two hurdles.
*/
public class HurdleKarel extends Karel
{

/*
* This method is our main entry point for the program.
* Karel runs to the hurdle and jumps it twice, before
* finishing the race.
* Precondition: Karel should be in the bottom left
* corner, facing east.
* Postcondition: Karel should be at the end of the race.
*/
public void run()
{
runToHurdle();
jumpHurdle();
runToHurdle();
jumpHurdle();
runToFinish();
}

/* This method has Karel move four times to finish the race.
* Precondition: Karel has finished jumping the last hurdle.
* Postcondition: Karel is at the end of the race.
*/
private void runToFinish()
{
// This method has Karel move four times to finish the race.
move();
move();
move();
move();
}

/*
* This method has Karel run to a hurdle that is three spots
* away.
* Precondition: Karel is three spaces away from a hurdle,
* facing east.
* Postconding: Karel is right next to a hurdle, ready to jump
* over it.
*/
private void runToHurdle()
{
move();
move();
move();
}

35
Commenting Your Code

/*
* This method has Karel jump over a hurdle that
* is one row tall.
* Precondtion: Karel is right next to a hurdle, facing east.
* Postcondition: Karel has jumped over the hurdle and is on
* the other side, facing east.
*/
private void jumpHurdle()
{
turnLeft();
move();
turnRight();
move();
turnRight();
move();
turnLeft();
}

/*
* This method has Karel turn right.
* Precondition: None, Karel can be facing any direction.
* Postcondition: Karel will have turned right by 90 degrees.
*/
private void turnRight()
{
turnLeft();
turnLeft();
turnLeft();
}
}

36
SuperKarel

SuperKarel
Karel the Dog only knows a few basic commands. For example, in order to have Karel turn
right, you first must create a new method to teach Karel how to turn right. Wouldn't it be nice
if Karel already knew some of these commands?

Introducing SuperKarel
Now that you've had some practice writing methods like turnRight(); , you are ready to
meet SuperKarel. SuperKarel already knows turnRight() and turnAround() , so you don't
need to create your own methods for those two commands anymore!

Using SuperKarel
To write a Karel class, you extended Karel . To use SuperKarel, you will extend
SuperKarel instead.

// Regular Karel
public class HurdleKarel extends Karel

// SuperKarel
public class HurdleKarel extends SuperKarel

A SuperKarel Example
Using SuperKarel allows us to write fewer methods, since Karel already knows how to turn
right and turn around. Below is an example of the HurdleKarel program using SuperKarel.
Notice how the jumpHurdle method calls turnRight(); even though this method is not
defined in the program?

/*
* This program has Karel run a race by jumping
* two hurdles. This is a SuperKarel program which
* means turnRight() is built in.
*/
public class HurdleKarel extends SuperKarel
{

/*

37
SuperKarel

* This method is our main entry point for the program.


* Karel runs to the hurdle and jumps it twice, before
* finishing the race.
* Precondition: Karel should be in the bottom left
* corner, facing east.
* Postcondition: Karel should be at the end of the race.
*/
public void run()
{
runToHurdle();
jumpHurdle();
runToHurdle();
jumpHurdle();
runToFinish();
}

/*
* This method has Karel jump over a hurdle that
* is one row tall.
* Precondtion: Karel is right next to a hurdle, facing east.
* Postcondition: Karel has jumped over the hurdle and is on
* the other side, facing east.
*/
private void jumpHurdle()
{
turnLeft();
move();
turnRight();
move();
turnRight();
move();
turnLeft();
}

/* This method has Karel move four times to finish the race.
* Precondition: Karel has finished jumping the last hurdle.
* Postcondition: Karel is at the end of the race.
*/
private void runToFinish()
{
// This method has Karel move four times to finish the race.
move();
move();
move();
move();
}

/*
* This method has Karel run to a hurdle that is three spots
* away.
* Precondition: Karel is three spaces away from a hurdle,
* facing east.
* Postconding: Karel is right next to a hurdle, ready to jump

38
SuperKarel

* over it.
*/
private void runToHurdle()
{
move();
move();
move();
}

39
For Loops

For Loops
We've seen how to give Karel instructions, but so far we've given each command one at a
time. But what if we want Karel to move 40 times? Or what if we want Karel to put down 135
balls in one spot? Do we really have to type putBall() 135 times? The good news is, no
we don't!

Why For Loops?


For loops let us type a series of commands only once, then let the program tell Karel to do it
multiple times. It is important to note that for loops are used when we want a fixed number of
repetitions. For example, we could use a for loop if we want to move 10 spaces or put down
150 balls. In both of these cases, we have a fixed number of times we want to execute a
specific set of instructions to.

Using For Loops


The syntax of a for loop is as follows:

for(int i = 0; i < count; i++)


{
//code you want repeated
}

A for loop consists of three parts: the header, the curly braces, and the code inside of the
curly braces. The curly braces are there to designate what code you want repeated. All of
the code between the curly braces will be repeated. You can put any commands you want
Karel to do to inside of the for loop.

The header is made up of three parts: initialization, the conditional, and update. You must
separate each of these parts with a semicolon, but be careful to not put a semicolon after
the closing parenthesis! The initialization part simply declares and initializes your loop
variable -- int i = 0; . The conditional part is how you specify how many times you want
the loop to execute -- i < count . This works by only letting i reach a particular value. The
update part lets you choose how i should be incremented after each time the loop
executes -- i++ . In the example above, we've specified that i should have one added to
the value each time.

The flow chart below shows the flow of execution in a for loop.

40
For Loops

Be Careful!
There are several things that you want to make sure to watch out for when using for loops.

1. Don't put a semicolon after the closing parenthesis of the header. This will cause the for
loop to not repeat the code in the body of the loop.
2. Put spaces around the operators in the header. The equals sign and less than symbol
should have spaces around them.
3. Put spaces between each part of the header. You should end the initialization and
conditional parts with a semicolon and space. None of this squished nonsense: for(int
i=0;i<0;i++)

4. Make sure all of the code you want to be in the body of the loop is between the curly
braces. Only code in the curly braces will be considered as part of the loop.

Examples

Example One
Let's make Karel put down 5 balls. In this case, we'll initialize i to 0, and count will be 5,
because we want something to happen 5 times. The code inside of the for loop will be
putBall() because that's what we want to happen 5 times. The for loop looks like this:

41
For Loops

for(int i = 0; i < 5; i++){


putBall();
}

Example Two
This time, we want to have Karel move, put down a ball, and move again.

Here is what the starting world looks like:

Here's what we want the ending world to look like:

How can we build a for loop to do this? Let's build the loop from the inside out. What do we
want Karel to do each iteration? Karel should 1) move, 2) put down a ball, and 3) move
again. The body of the for loop would look like this:

for( ){
move();
putBall();
move();
}

42
For Loops

Now, let's look at the world. It has 9 avenues. However, since we're telling Karel to move
twice, we can't use i < 9 because we'd make Karel crash into the wall! If we were only
moving once, then we would iterate 9 times. Since we're moving twice, we can only iterate
9/2 times. We'll round down and say that 9/2 = 4.5 and rounded is 4. We need the loop to
iterate four times! Why didn't we round up to five? Look at the picture of the ending world.
There is only room for four balls. If we had looped five times, Karel would have still crashed
into the wall.

Here's the final for loop

for(int i = 0; i < 4; i++){


move();
putBall();
move();
}

Summary
For loops are a convenient way to repeat chunks of code. We can use for loops when we
have a fixed number of iterations. A for loop is made of three parts: the header, the body,
and the curly braces. The header has the initialization, condition, and update information.
THe opening curly brace comes before the body. The body is made up of the statements
that should be repeated. The closing curly brace finishes up the for loop and tells the
program that we're done with the code we want repeated.

43
While Loops in Karel

While Loops in Karel


Lets say Karel is standing on one side of the world, and we want to move to the next side.
Up to this point, the best way would be to write a for loop that repeats the move();
command a set number of times. What if we don't know the size of Karel's world? In this
case we would use a while loop, which will execute a command while a condition is true.

Basics of While Loops


While loops, unlike for loops, execute the target statement as long as the given condition is
true.

A while loop is usually formatted like:

while(condition)
{
// code to execute
}

It is important to know that a while loop will only repeat the target statement until the
condition is no longer true. Consider the following diagram:

Examples of While Loops


Consider the following situation:

While a vehicle's engine is on, it will use gas.


When the vehicle's engine is off, it will no longer use gas.

44
While Loops in Karel

In this case the vehicle's engine represents the condition of our while loop. The use of gas
represents our target statement that will only execute when the condition is met. Your code
for this situation should look like:

while(engineOn())
{
useGas();
}

Here is another example of a while loop, as seen in Karel's world:

While a ball is present in Karel's current position, move one space.


When Karel lands on a position that does not contain a ball, don't move.

In this situation Karel will only move when a ball is in Karel's current position. As soon as
Karel lands in a position that does not contain a ball the loop will exit, and Karel will stop
moving. The code for this situation should look like:

while(ballsPresent())
{
move();
}

45
If Statements

If Statements and Conditionals


Now that Karel can understand and learn new commands, it is time to write programs that
have Karel adapt to different situations. Like methods, these new additions to Karel's
language will allow us to write code that can be used in many different situations.

Asking Questions about Karel's World


Karel's world tends to change a lot. Sometimes it is large, other times it is small. It often has
walls, but not always. And though there are usually tennis balls scattered throughout the
world, the balls are rarely in the same place for each exercise.

Given these changing conditions, there are many questions that would be useful for Karel to
ask. For example:

Is there a ball where Karel is standing?


Is Karel facing north?
Is Karel hungry?

Introducing Conditions
These types of questions can be asked using conditions. Conditions are very simple
methods that look at the state of Karel's world and return a true or false answer. Here is a list
of the conditions that Karel can check:

. .
frontIsClear() frontIsBlocked()

leftIsClear() leftIsBlocked()
rightIsClear() rightIsBlocked()

facingNorth() notFacingNorth()
facingSouth() notFacingSouth()

facingEast() notFacingEast()

facingWest() notFacingWest()
ballsPresent() noBallsPresent()

Like Karel's other commands, it is important to include the parentheses () at the end.

46
If Statements

In the following world, the frontIsClear() condition returns true, as Karel's front is clear.
The ballsPresent() condition also returns true, because Karel is standing on a ball.
Similarly, the facingSouth() condition would return false, as Karel is not facing south.

Introducing If Statements
Checking conditions allows us to write programs that can respond to changes in Karel's
world. One important way to handle different conditions is by using if statements. If
statements let us check a condition before executing any code. We can use if statements to
help control the flow of the program. The basic format of an if statement is:

if(condition)
{
// code to run
}

An if statement will only execute if the condition is true. Such checks probably sound familiar
-- in fact, we use the same type of thinking in everyday life. Here are some examples of real-
world if statements:

if there is music, then I will dance


if I am tired, then I will sleep
if it is raining, then I will carry an umbrella

47
If Statements

Pay attention to the structure of these statements. The first part is used to check the
condition of the world (am I tired? is it raining?). The second part contains the "code" that will
execute if the check is true. Thus, if it is raining, I will take my umbrella. On the other hand, if
it is not raining, then I will not carry an umbrella.

Karel uses if statements and conditions in a similar way. For example, in the world above,
Karel can check if the front is clear before moving:

if(frontIsClear())
{
move();
}

Using an if statement to check the world before moving helps Karel avoid crashing into the
wall. Such a check would be important in a world like this one:

48
If/Else Statements

If/Else Statements
One of the driving forces behind writing conditionals is the need to vary the program's
behavior based on certain conditions. When writing comprehensive conditionals, you will
often want to have your program do something specifically when a particular if statement is
evaluated as false. This is when the else statement becomes useful.

Introducing If/Else Statements


Think of the else statement as the "otherwise" conditional. Consider the following
pseudocode for an alarm clock function:

If it is the weekend, go off at 10 AM.


Otherwise, go off at 7 AM.

The "otherwise" clause allows us to account for all possible scenarios. In this example, we
could have executed the same logic using two if statements, as follows:

If it is the weekend, go off at 10 AM.


If it is a weekday, go off at 7 AM.

However, when writing comprehensive programs, it may not be practical to account for every
possible scenario. Suppose we want the alarm to go off at 7 AM on Tuesday and Thursday,
and 8 AM on all other days. Using an "otherwise" clause, the logic is as follows:

If it is Tuesday or Thursday, go off at 7 AM.


Otherwise, go off at 8 AM.

Without using an "otherwise" clause, the logic follows:

If it is Tuesday or Thursday, go off at 7 AM.


If it is Sunday, Monday, Wednesday, Friday, or Saturday, go off at 8 AM.

It is clear that the former is more concise and pragmatic.

If/Else Example
Suppose we want Karel to move if he can, and turn left otherwise. Keep in mind the
following rules of thumb when writing if/else statements:

Every else statement must be preceded by an if statement


Not every if statement must have an else statement

49
If/Else Statements

Else statements have no conditions, i.e., there are no parentheses following the "else"

Your code should then look like this:

if (frontIsClear())
{
move();
} else
{
turnLeft();
}

Note that, stylistically, the else statement may begin on the same line as the if statement's
closing bracket, or on the following line. It is recommended that you stay consistent with
whichever method you prefer. The code above may also be written as:

if (frontIsClear())
{
move();
}
else
{
turnLeft();
}

If Statements vs. If/Else Statements


In general, else statements are not required.* You can usually achieve the effect of an else
statement using a series of if statements. While this is valid, it is preferred that you use else
statements for clarity and conciseness.

*You may later be faced with scenarios in which else statements are required when writing
helper functions with return values. More on this to come.

50
Control Structures Example

Control Structures Example


Control structures allow us to shape the flow of our programs and write code that can adapt
to the conditions of the world. Control structures can be combined to produce responsive
and powerful programs.

Control Structures
There are two main categories of control structures that we have learned so far. The first
group, if statements and if-else statements, ask questions about the world. The second
group, for loops and while loops, repeat patterns of code.

Ask Questions Repeat Code


If Statement For Loop
If/Else Statement While Loop

In the world above, Karel needs to put down five tennis balls in every empty spot. If a spot is
not empty, Karel should only put down one more tennis ball.

We will need to use several different control structures to solve this problem. First, we need
Karel to determine whether there is a ball present or not. If there is not a ball, Karel should
put down five tennis balls. Otherwise (if there is already a ball), Karel should just put down
one ball. This can be easily written using an if-else statement.

Counting out five tennis balls suggests the use of a loop. In this case, a for loop works well.

51
Control Structures Example

Finally, this process needs to occur across the entire world. A while loop can be used to
repeat the code as long as the front is clear.

A typical solution for this challenge may look like:

public class LayFiveTennisBalls extends Karel


{
public void run()
{
while(frontIsClear())
{
checkAndPutBalls();
move();
}
checkAndPutBalls();
}

private void checkAndPutBalls()


{
if(noBallsPresent())
{
for(int i = 0; i < 5; i++)
{
putBall();
}
}
else
{
putBall();
}
}
}

52
Control Structures Example

53
How To Indent Your Code

How to Indent Your Code


Indentations are responsible for making your code easy to read and understand. Indenting
your code is always best practice as it helps to show the overall structure of your code.

Indenting Your Code


A general rule for Java is to always place brackets on their own lines, and indent the code
within the brackets. Here is an example for you to reference:

// Notice how the brackets are on new lines and the code within is indented.
public void run()
{
move();
turnLeft();
move();
}

You apply the same rule for indentations when using nested control structures. Consider this
example:

// Notice how the brackets are on new lines and the code within is indented.
public void run()
{
while(ballsPresent())
{
if(frontIsClear())
{
move();
}
}
}

54
How To Indent Your Code

55
Basic Java

Basic Java
Learn the basics of the Java programming language. This unit covers printing, variables,
types, as well as how to use the basic control structures in the Java language.

56
Printing in Java

Printing in Java
Now that you're comfortable using basic Java commands with Karel the Dog, it's time to
move into the Java console environment.

Environment Set Up
Using the CodeHS editor makes writing Java programs simple and straightforward. The
Java console environment is similar to the Karel environment you've used already, with a
few key differences. Instead of showinga grid world where Karel will execute the program,
the Java environment presents a console area that will print the output of your program.
There is also a list of files for each program on the left side of the page. Many of the Java
programs you will write will make use of more than one file -- all of the files will be listed in
this section.

Writing Hello World


Writing a program that prints "Hello world" to the console requires a few lines of code:

public class HelloWorld extends ConsoleProgram


{
public void run()
{
System.out.println("Hello world");
}
}

57
Printing in Java

There are a few key parts to pay attention to here:

This program extends ConsoleProgram instead of Karel . This tells the program that it's
going to use the console instead of a Karel grid world.
The text is printed to the console with the System.out.println() command. This
command looks a bit long, but you can think of it as telling the console to print whatever
is inside the parentheses.

Now that you can print to the console, you'll be able to write programs that can display
information to the user!

58
Variables and Types

Variables and Types


Variables allow us to store information such as numbers, words, or true/false expressions. A
variable can be thought of as a box that stores information inside. In Java, variables are
composed of three things: a name, type, and value.

Primitive Types
In Java we must specify what type of information we want our variables to hold. You must
always give your variable a type before naming it, and specifying the value it holds. (Ex. int
myVariable = 10; )

Here are some of the primitive types found in Java:

Numeric Type:

As seen above, primitive numeric types in Java include both integers and doubles.

Integers are whole numbers, or counting numbers. (Ex. -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5)

In Java we declare an integer using int before the variable name. Here are a couple of
examples:

int itemsInStore = 10;

int numberOfMessages = 8;

doubles are like integers, but can have decimals. (Ex. -54.34, 90.21, 0.1223)

In Java we declare a double using double before the variable name. Here are a couple of
examples:

59
Variables and Types

double costOfApple = 1.24;

double milesToRun = 5.64;

Char Type:

Characters represent a single character.

In Java we declare a character using char before the variable name. We also use single
quotes to identify a character (Ex. 'A' ). Here are a couple of examples:

char currentGrade = 'A';

char favoriteLetter = 'W';

Boolean Type:

Booleans are variables that hold a true or a false value.

In Java we declare a boolean using boolean before the variable name. Here are a couple of
examples:

boolean passedCalculus = true;

boolean hasDog = false;

String Type:

Strings are variables that hold text. Strings are not a primitive type, so you must declare
them using String with a capital S. Unlike characters, we need to use double quotes when
assigning strings (Ex. "This is my string." ). Here are a couple of examples:

String fishName = "Dog";

String myUniversity = "Arizona State University";

60
Variables and Types

Naming Variables
Giving your variables meaningful names throughout your code is very important. Proper
variable names allow others to easily read and understand your code. A good way to name
your variables is to give them as descriptive of a name as possible, without making it too
long. For example, int numberOfApplesOnTheTree = 10; is a very long name, and can easily
be replaced with a name like int numApples = 10; .

Variable Naming Conventions:

Variable names must start with a letter, $ symbol, or _ symbol.

Variable names are case sensitive so myVariable is different than MyVariable

Variable names, after the first character, can contain letters, numbers, or other
characters.

Here are some examples of different variable names:

61
User Input

User Input
Being able to obtain user input creates new opportunities while coding. This allows us to
take in data from the user to make our programs work for them.

Getting User Input


In Java there are four ways we can obtain user input:

Input of Strings
To read the user's input as a string, we use readLine("String prompt") . This allows us to ask
the user for their name, favorite color, or any other text input from the user.

Here is an example of how we would ask the user for their favorite color, and then print it:

// Ask for the input, and store it in the 'favColor' string.


String favColor = readLine("Hello, what is your favorite color? ");
// Then print it.
System.out.println(favColor);

Input of Integers
To read the user's input in an integer format, we use readInt("String prompt") . This allows
us to ask the user for their age, favorite number, or any other whole number.

Here is an example of how we would ask the user for their age, and then print it:

62
User Input

// Ask for the input, and store it in the 'age' integer.


int age = readInt("Hello, how old are you? ");
// Then print it.
System.out.println(age);

Input of Doubles
To read the user's input as a double, we use readDouble("String prompt") . This allows us to
ask the user how many miles they have traveled, how much an item costs, or any other
numerical value that has a decimal.

Here is an example of how we would ask the user for how many miles they have traveled,
and then print the input:

// Ask for the input, and store it in the 'miles' double.


double miles = readDouble("How many miles have you traveled? ");
// Then print it.
System.out.println(miles);

Input of Booleans
To read the user's input as a boolean, we use readBoolean("String prompt") . This allows us
to ask the user any true or false question.

Here is an example of how we would ask the user if they are a astronaut, and then print their
answer:

// Ask for the input, and store it in the 'isAstronaut' boolean.


boolean isAstronaut = readBoolean("Hello, are you an astronaut? ");
// Then print it.
System.out.println(isAstronaut);

User Input Applications


Now that we have seen a some examples of how to get user input, lets look an application.

Lets say we are writing a piece of code in which we want to ask the user for their name, age,
and if they own a pet. In this case we will ask the user each question, one at a time, and
store the answers in their own variables. After we get the user input we will print the
variables. Here is what our code will look like:

63
User Input

public class UserInput extends ConsoleProgram


{
public void run()
{
String name = readLine("What is your name? ");
int age = readInt("How old are you? ");
boolean hasPet = readBoolean("Do you own a pet? ");

System.out.println("");
System.out.println("Your name is " + name);
System.out.println("You are " + age + " years old.");
System.out.println("You own a pet: " + hasPet);
}
}

Here is what the user prompts will look like, once the code executes:

64
Arithmetic Expressions

Arithmetic Expressions
Arithmetic Expressions allow us to perform mathematical operations within Java.

Such expressions can be used for basic math and even more complex algorithms.

Arithmetic Operators
Operator Description
+ Addition operator (Ex. 1 + 1 = 2)

- Subtraction operator (Ex. 2 - 1 = 1)


* Multiplication operator (Ex. 2 * 2 = 4)
/ Division operator (Ex. 6 / 2 = 3)
% Modulus operator (Ex. 10 % 3 = 1)

Addition Operator

The addition operator allows us to add values together.

Here is an example of the addition operator in Java:

public class AdditionOperator extends ConsoleProgram


{
public void run()
{
int firstVal = 5;
int secondVal = 2;

int firstPlusSecond = firstVal + secondVal;

// The output will be '7'


System.out.println(firstPlusSecond);
}
}

Subtraction Operator

The subtraction operator allows us to subtract values from one another.

Here is an example of the subtraction operator in Java:

65
Arithmetic Expressions

public class SubtractionOperator extends ConsoleProgram


{
public void run()
{
int firstVal = 4;
int secondVal = 2;

int firstMinusSecond = firstVal - secondVal;

// The output will be '2'


System.out.println(firstMinusSecond);
}
}

Multiplication Operator

The multiplication operator allows us to multiply values.

Here is an example of the multiplication operator in Java:

public class MultiplicationOperator extends ConsoleProgram


{
public void run()
{
int firstVal = 4;
int secondVal = 2;

int firstMultSecond = firstVal * secondVal;

// The output will be '8'


System.out.println(firstMultSecond);
}
}

Division Operator

The division operator allows us to divide values.

Here is an example of the division operator in Java:

66
Arithmetic Expressions

public class DivisionOperator extends ConsoleProgram


{
int firstVal = 6;
int secondVal = 3;

int firstDivSecond = firstVal / secondVal;

// The output will be '2'


System.out.println(firstDivSecond);
}

Modulus Operator

The modulus operator allows us to divide two numbers, and get the remainder.

Here is an example of the modulus operator in Java:

public class ModulusOperator extends ConsoleProgram


{
int firstVal = 17;
int secondVal = 5;

int firstModSecond = firstVal % secondVal;

// The output will be '2' since the remainder of 17 / 5 is 3.


System.out.println(firstModSecond);
}

Operation Precedence
It is important to remember that the order of operations still apply. In instances where you
have multiple operators with the same precedence the order will be, left to right.

Operator Precedence
( ) Parenthesis 1st

* / Multiplication and Division 2nd


+ - Addition and Subtraction 3rd

Types of Divison
There are multiple types of division that can be performed in Java. These forms include:
integer division, double division, and mixed division.

67
Arithmetic Expressions

Integer Division

If you divide two integers you will be returned an integer value.

So in this case, while 2 / 5 = 2.5 , in Java 2 / 5 = 2 . This always holds true, unless the
type is specified as a double. Whenever you divide two integers, the return value is always
truncated.

Double Division

Dividing doubles is different from dividing integers.

When you divide two doubles you will be returned a double. In this case, 2.0 / 5.0 = 2.5
will be your result.

Mixed Division

Mixed division is when you divide a double by an integer, or an integer by a double.

When you used mixed division in your program you will be returned a double. This is true,
unless the type is specifically defined as an integer.

Consider the following piece of code:

double x = 2;
int y = 5;

double outXY = x / y; // 0.4

double outYX = y / x; // 2.5

int outInt = (int)(y / x); // 2

Arithmetic Shortcuts
There are shortcuts available when performing arithmetic expressions.

Consider the following table:

68
Arithmetic Expressions

Original Shortcut Description


counter = counter + 1; counter++; Increment a variable by 1
counter = counter - 1; counter--; Subtract 1 from a variable
x = x + y x += y Adding values to a variable
x = x - y x -= y Subtracting values from a variable
x = x * y; x *= y Multiplying values to a variable
x = x / y; x /= y Dividing values from a variable

69
Casting

Casting
Casting allows us to change a variable's type to better suit our needs.

How Casting Works


Lets say we want to turn a double into an integer, or an integer into a double.

To change a variable's type we just add the type in between parentheses to cast it.

Consider the following:

int doubleToInt = (int)10.95;


// This will become '10'

Casting an Integer to a Double

To cast an integer value to a double we add (double) in front of the variable.

int intVal = 10;

// Our 'doubleVal' variable is now '10.0'


double doubleVal = (double)intVal;

Casting a Double to an Integer

To cast a double to an integer we add (int) in front of the variable. It is important to


remember our new integer value will truncate the decimal.

double doubleVal = 7.4;

// Our 'intVal' variable is now '7'


int intVal = (int)doubleVal;

Division with Casting


If we divide two integers, even if we are setting them to a double, we will always be returned
an integer.

70
Casting

int currResidents = 50;


int floorTotal = 56;

double average = floorTotal / currResidents;


// 'average' will return the value '1'

We can get the correct answer by casting one of the variables to a double.

int currResidents = 50;


int floorTotal = 56;

double average = (double)floorTotal / currResidents;


// We now have the value of '1.12'

71
Booleans

Booleans
How do we write code that tells us whether a user is logged in to our program? Booleans are
the solution to these questions.

What are Booleans?


A boolean refers to a value that is true or false. Those are the only values of a boolean
expression, and these are useful if we want to check if something is true or false.

Meet George Boole


Let's meet the fellow behind the name, "booleans," George Boole. Mr. Boole was an
English-born mathematician, philosopher, and logician. He introduced boolean algebra in
The Mathematical Analysis of Logic (1847) and Investigation of the Laws of Thought (1854).
Many consider him to be one of the founders of Computer Science.

Working with Booleans


How about an example? Let's create a variable and set it equal to true. Then, we'll print the
variable.

We first want to declare the variable, loggedIn , and set it to true or false.

boolean loggedIn = false;

72
Booleans

We can similarly set the variable to true instead:

boolean loggedIn = true;

You can imagine a boolean variable as a box that can hold only the values true or false. The
box below shows the current value of loggedIn :

Notice that we do not need to have quotations around true or false .

The full example looks like:

// In this program we declare a boolean


// value to represent whether the user
// is logged in, and then print it out.
public class LoggedIn extends ConsoleProgram
{
public void run()
{
boolean loggedIn = false;
System.out.println("User logged in?: " + loggedIn);
}
}

Remember, use booleans if you want to set a variable to true or false!

73
Logical Operators

Logical Operators

What Are Logical Operators?


Boolean variables can only take on one of two possible values, true or false. Logical
operators allow you to combine and connect booleans in useful ways.

There are three fundamental boolean operators:

NOT
OR
AND

These should look quite familiar; in fact, we use them in speech every day! The NOT
operator is used on a single boolean, wheres AND and OR are used across multiple boolean
values.

The NOT Operator


NOT is represented in JavaScript as ! . When placed in front of a boolean value, NOT
causes the boolean to take on its opposite value. For example "NOT true" gives the answer
"false." This is fairly intuitive -- if something is not true, then it must be false. Similarly, if
something is not false, then it must be true.

The example below sets up a variable hungry as being true. Then it prints out NOT
hungry .

boolean hungry = true;


System.out.println(!hungry); // prints "false"

For a variable p that can be true or false :

p !p
true false

false true

The AND Operator

74
Logical Operators

AND is represent in JavaScript as: &&. An expression using AND is true only when all its
component parts are true. If any of the boolean values are false, the whole expression
evaluates to false.

For example, if it is 6:30am AND it is a school day, you should wake up. You can test the
expression of "6:30am AND a school day." If both are true, then the whole expression
evaluates to true. If either or both are false, then the whole expression is false, and you
should stay in bed.

boolean sixThirty = true;


boolean schoolDay = false;
System.out.println(sixThirty && schoolDay); // because both values aren't true, it pr
ints "false"

For variables p and q that can be true or false :

p q p AND q

true true true


true false false
false true false
false false false

The OR Operator
OR is represented in JavaScript as || . An expression using OR is true when all or any of
its parts are true. It is only false when all of the boolean values are false.

Say that you are trying to decide whether to wear a coat today. You'll wear your coat if it is
raining right now or if it is cold outside. You can evaluate this expression based on the
answers to those two boolean values. If it's raining, cold, or raining and cold, then you will
wear your coat. The only case in which you would not wear your coat is if it's neither raining
nor cold.

boolean isRaining = true;


boolean isCold = false;
System.out.println(isRaining || isCold); // it's not cold, but it is raining, so it p
rints true

For variables p and q that can be true or false :

75
Logical Operators

p q p OR q

true true true


true false true
false true true

false false false

76
Comparison Operators

Comparison Operators
Comparison operators allow us to compare two values against one another. A comparison
returns a boolean result of either true or false. The table below lists each of the common
comparison operators and their usages:

Operator Usage
> Greater Than

< Less Than


>= Greater Than Or Equal To
<= Less Than Or Equal To
== Equal To
!= Not Equal To

A Basic Comparison
In the following example, we compare two variables x and y . We store the result of this
comparison in variable z .

int x = 10;
int y = 8;

boolean z = x > y;
System.out.println(z);

What will get printed to the screen? The above comparison, x > y, is evaluating if 10 is
greater than 8. Because 10 is indeed greater than 8, z is assigned a value of true. Thus,
true will get printed to the screen.

More Practice with Comparisons


Let's get a little more practice. Take a look at the following code segment below. Pay close
attention to each comparison and the operator being used.

77
Comparison Operators

// Declare some integer variables to use for practice comparisons below.


int a = 3;
int b = 5;
int c = 2;
int d = 3;

// We store the boolean results of each comparison into boolean variables t-z.
boolean t = a > 0;
boolean u = a == d;
boolean v = d >= b;
boolean w = b > c;
boolean x = a != d;
boolean y = d < = a;
boolean z = 4 < = c;

/* In addition to integers, it is possible to compare other data types too.


Here we are comparing some of the boolean values computed above (t-z).
We store the results into new boolean variables. */
boolean boolComparison1 = t == u;
boolean boolComparison2 = t == w;
boolean boolComparison3 = t != u;
boolean boolComparison4 = x != y;

// Print out all the integer comparison results


System.out.println("t = " + t);
System.out.println("u = " + u);
System.out.println("v = " + v);
System.out.println("w = " + w);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);

// Print out all the boolean comparison results


System.out.println("boolComparison1 = " + boolComparison1);
System.out.println("boolComparison2 = " + boolComparison2);
System.out.println("boolComparison3 = " + boolComparison3);
System.out.println("boolComparison4 = " + boolComparison4);

When we run this code, what boolean values (true or false) will get printed to the screen for
variables t through z? What boolean values (true or false) will get printed to the screen for
each of the boolComparison variables? See if you can figure it out on your own. The solution
is given below.

Solution:
Our program prints out:

78
Comparison Operators

t = true
u = true
v = false
w = true
x = false
y = true
z = false
boolComparison1 = true
boolComparison2 = true
boolComparison3 = false
boolComparison4 = true

Comparison Operators in a Program


Suppose we want to write a program which restricts people under a certain height from
riding on a roller coaster. For this particular roller coaster, people who are under 4 feet (48
inches) are not allowed on the ride. How would we do this?

int heightInInches = readInt("How tall are you (in inches)? ");


boolean isTallEnough = heightInInches >= 48;
System.out.println("Can ride on the roller coaster: " + isTallEnough);

After getting the potential rider's height in inches, we do a comparison to ensure that they
are over 48 inches. The result of this comparison is then printed out.

Pitfalls
A common mistake is using = when you actually want to use == . = is used for
assignment of variables whereas == is used for comparing the equality of two values.

For example, x = 5 stores the value 5 into the variable x . However, x == 5 tests to
see if the value 5 is equal to the variable x and then returns either true or false. They are
not the same thing!

79
For Loops

For Loops
For loops allow us to repeat code a fixed number of times. A basic for loop is structured like
this:

for (int i = 0; i < COUNT; i++)


{
// Code segment that is executed COUNT times.
}

Breaking Down the For Loop


A for loop can be divided into three major parts. The first part initializes the loop variable,
the second part tests some condition, and the third part increments or decrements the
loop variable. Each part of the for loop is separated by a semicolon ( ; ).

Let's break down the following example into its three major parts:

Part 1: Initialize
The first part of a for loop initializes some variable. In the example above, int i = 0 initially
sets the variable i equal to 0 .

Part 2: Condition
The second part of a for loop tests a condition. If the condition is true, the code within the for
loop executes. If the condition is false, the code within the for loop is skipped. In the example
above, i < 3 compares the current value of our variable i to determine if it is less than 3 .
Each time i is less than 3 , the value of i will be printed to the screen. This happens
three times.

Part 3: Increment/Decrement

80
For Loops

The third part of a for loop changes the variable after each time the loop runs. Remember,
i++ means 1 is added to i . It is incremented. Conversely, i-- means 1 is subtracted

from i . It is decremented.

Putting It All Together


What happens when we run the example for loop? What gets printed to the screen?

The first part of our for loop, int i = 0 , initializes our variable. It sets our loop variable i
equal to 0 Next, the condition part of the loop is evaluated. Is i < 3? Since i is currently
set to 0 , and 0 is indeed less than 3 , the condition i < 3 is true. Thus, the code within
the for loop is executed. 0 is printed to the screen. After this, i is incremented. i++
means we add 1 to i , so i is now set to 1 .

Since i is now set to 1 , the condition i < 3 is re-evaluated. It is still true. 1 is now
printed to the screen. i is incremented again and becomes set to 2 .

The condition i < 3 is re-evaluated. Since i is now set to 2 , our condition is still true. 2
is printed to the screen. i is incremented again and becomes set to 3 .

Finally, when the condition i < 3 is re-evaluated, our condition is false. 3 is not less than 3, so
the code within the for loop is skipped. Nothing else gets printed. The for loop is done.

Thus, our output would be:

0
1
2

More Examples
Countdown
In this countdown example, i is initially set to 5. We decrement (or subtract) 1 from i on
each iteration of the for loop. We print out each value of i until it reaches 0.

81
For Loops

public class Countdown extends ConsoleProgram


{
public void run()
{
System.out.println("Initiating countdown:");
for(int i = 5; i >= 0; i--)
{
System.out.println(i + "...");
}
}
}

Output:

Initiating countdown:
5...
4...
3...
2...
1...
0...

Count by Twos
Instead of incrementing or decrementing i by only 1, we will increment i by adding 2 in
this example instead. This allows us to count up by two each time.

public class CountByTwos extends ConsoleProgram


{
public void run()
{
for(int i = 0; i < 21; i += 2)
{
System.out.println(i);
}
}
}

Output:

82
For Loops

0
2
4
6
8
10
12
14
16
18
20

For Loop Sum Program


Here is a program which sums all the numbers from 1 to 100. The for loop adds the numbers
1+2+3+4+5+6+.....+98+99+100. Since this program uses global constants, we can easily
change the MIN and MAX values used in our sum without having to touch the for loop at all.

public class ForLoopSum extends ConsoleProgram


{
/* MIN and MAX are constants. Constants are variables that do not change.
We use them in our program below. You will learn more about constants and
their purposes later. */
private static final int MIN = 1;
private static final int MAX = 100;

// This program adds the numbers from 1 to 100.


public void run()
{
int sum = 0;
for(int i = MIN; i < = MAX; i++)
{
sum += i;
}
System.out.println("The sum was " + sum);
}
}

Output:

The sum was 5050

83
While Loops

While Loops
While loops are a way to repeat a block of code so long as some condition remains true.
The condition is written in the form of a boolean expression. The basic structure of a while
loop is shown below.

while(boolean expression)
{
// code block inside of while loop to execute if the boolean expression is true
}
// code outside of while loop to execute if the boolean expression is false

As long as the boolean expression remains true, code within the while loop will be executed.
The moment that the boolean expression becomes false, code outside of the while loop will
be executed; the loop is done. This behavior can be summarized in the following flowchart
below:

While Loop Countdown


In the previous chapter, we looked at a simple program which counts down from 5 using a
for loop. We can do the same thing using a while loop instead.

84
While Loops

public class WhileLoopCountDown extends ConsoleProgram


{
public void run()
{
int i = 5;

System.out.println("Initiating countdown:");
while(i >= 0)
{
System.out.println(i + "...");
i--;
}
}
}

We first declare a variable i and set it equal to 5. Before the while loop, we print out a
message letting the user know that the countdown is about to begin. Our while loop starts by
checking to see if the boolean expression, i >= 0, is true. The current value of i is 5. 5 >=
0 is true, so the code within the while loop gets executed. It prints out the number 5 and then
decrements it by subtracting 1.

i is now set to 4. Our while loop then checks to see if 4 >= 0. Since this condition is still

true, the code within the while loop gets executed again. This will continue until i gets
down to 0. After 0 gets printed to the screen, we decrement i so that it is now set to -1.
Our while loop tests to see if -1 >= 0. Since -1 is not greater than or equal to 0, the boolean
expression is false. The code within the while loop is skipped. The while loop has finished its
execution.

After we run the above program, this is what gets printed to the screen:

Initiating countdown:
5...
4...
3...
2...
1...
0...

Infinite Loops
You must exercise caution when using while loops to avoid the dreaded infinite loop. An
infinite loop is a loop that never terminates. It never finishes its execution. It will continue to
repeat until the end of time! Infinite loops will often cause a program to freeze and crash.

85
While Loops

We have rewritten our while loop countdown program below, but we have omitted an
essential line of code. This will cause an infinite loop:

public class InfiniteWhileLoopCountdown extends ConsoleProgram


{
public void run()
{
int i = 5;

System.out.println("Initiating countdown:");
while(i >= 0)
{
System.out.println(i + "...");
}
}
}

But why? Why does this cause an infinite loop?

With the omission of i-- , we are no longer changing our variable. i will forever be set to
5. Our while loop will repeatedly check to see if 5 >= 0. Since this condition is always true,
the code within the while loop body will execute forever. The while loop will never terminate.
Our program will just keep printing a value of 5 over and over again.

Thus, after running the program, our output will look something like this (assuming the
browser does not freeze and crash):

86
While Loops

Initiating countdown:
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
5...
[NOTE: This will continue printing "5..." forever!]

In the CodeHS editor, we can manually stop the program by clicking on the "STOP" button
next to the "RUN CODE" button. Otherwise, it will continue spamming the number 5 at us
until the end of time.

While Loop or For Loop?


How do you decide whether to use a while loop or a for loop? After all, they are both used to
repeat code segments.

For loops are for repeating code a fixed number of times. We use for loops when we know
exactly how many times we want to repeat a given segment of code. We use while loops
when we don't know how many times we will need to repeat some given code.

Consider the following program. In this program, the user attempts to guess a secret number
between 1 and 100, but they don't know what that number is. We give them an unlimited
number of guesses. If their guess is wrong, we have them guess again. If their guess is
right, we inform them that they found the secret number and the program ends.

87
While Loops

public class GuessTheSecretNumber extends ConsoleProgram


{
public void run()
{
// The secret number for the user to guess is 54. But they don't know that!
System.out.println("I am thinking of a secret number from 1 to 100. Can you gu
ess it? ");
int secretNumber = 54;

// Read an integer guess from the user


int guess = readInt("Type a number: ");
while (guess != secretNumber)
{
guess = readInt("Incorrect. Try a different number: ");
}
System.out.println("Correct! You got it!");
}
}

We don't know how many guesses it will take the user to find the secret number. It might
take them only one or two guesses. It might take them over twenty or even over fifty
guesses. We don't know! Thus, we must use a while loop here. A for loop won't do us any
good.

Here is just one possible example of many for what a user might do after running the
program:

I am thinking of a secret number from 1 to 100. Can you guess it?


Type a number: 5
Incorrect. Try a different number: 60
Incorrect. Try a different number: 44
Incorrect. Try a different number: 32
Incorrect. Try a different number: 11
Incorrect. Try a different number: 99
Incorrect. Try a different number: 52
Incorrect. Try a different number: 53
Incorrect. Try a different number: 54
Correct! You got it!

88
If Statements

If Statements
In the previous chapters, you learned all about logical operators and comparison operators.
These form the basis for writing boolean expressions in if statements.

We use if statements to run a segment of code only if some boolean expression first
evaluates to true. An if statement takes the following basic form:

if (boolean expression)
{
// Segment of code that will run if the boolean expression is true
}

If the boolean expression evaluates to false, nothing will happen. The code within the if
statement is ignored.

If/Else Statements
We can add the else keyword to our if statement. In this case, if the boolean expression in
our if statement evaluates to false, the code within the else segment will run. If the boolean
expression evaluates to true, the code within the if segment will run.

if (boolean expression)
{
// Segment of code that will run if the boolean expression is true
}
else
{
// Segment of code that will run if the boolean expression is false
}

If/Else/Else If Statements
We can add the else if keyword between our if/else statement. If boolean expression one
evaluates to false, then boolean expression two gets evaluated next. If boolean expression
two also turns out to be false, the code within the else segment will run.

89
If Statements

if (boolean expression one)


{
// Segment of code that will run if boolean expression one is true
}
else if (boolean expression two)
{
// Segment of code that will run if boolean expression two is true
}
else
{
// Segment of code that will run if boolean expression one and boolean expression
two are both false
}

You can have as many else if statements as you want. There is no limit!

Test for Negative Numbers


Using if statements, we can determine if a number is negative. If a number is less than 0, we
know it is a negative number.

public class TestForNegatives extends ConsoleProgram


{
public void run()
{
System.out.println("This program tests if a number is negative.");
int number = readInt("Enter a number: ");
if (number < 0)
{
System.out.println("You entered a negative number!");
}
}
}

Age Survey
Suppose we want to ask users for their age, but we want to restrict them from being able to
enter a negative number. After all, someone can not have a negative age. We can
accomplish this by doing the following:

90
If Statements

public class AgeSurvey extends ConsoleProgram


{
public void run()
{
int age = readInt("How old are you? ");
if (age < 0)
{
System.out.println("You can't have a negative age!");
}
else
{
System.out.println("Your age: " + age);
}
}
}

If the user enters a negative age (less than 0), our program informs them that is not allowed.
Otherwise, it prints their age back out to them.

Improved Age Survey


We can improve our age survey even further by restricting users from being able to enter
ages that are too large. We do this by adding in an else if statement.

public class ImprovedAgeSurvey extends ConsoleProgram


{
public void run()
{
int age = readInt("How old are you? ");
if (age < 0)
{
System.out.println("You can't have a negative age!");
}
else if (age > 123)
{
System.out.println("No one has ever lived to the age of " + age + "!");
}
else
{
System.out.println("Your age: " + age);
}
}
}

91
If Statements

With these restrictions, we have created a range of acceptable ages. Valid ages are
considered between 0 and 123 inclusive. If a user enters an age that is less than 0, we tell
them that is impossible. If a user enters an age over 123, we inform them that no one has
ever lived that long before. Otherwise, we simply print their age.

Even or Odd
We want to write a program that tests whether some given number is even or odd. Here is
how that can be done.

public class EvenOrOdd extends ConsoleProgram


{
public void run()
{
int num = readInt("Number: ");
if(num % 2 == 0)
{
System.out.println("Number is even.");
}
else
{
System.out.println("Number is odd.");
}
}
}

Recall that the modulus operator % returns the remainder after a division. For example,
let's say the user enters the number 5. 5%2 is equal to 1. Thus, the code within the else
segment will run. It rightly tells us that the number is odd.

Logical Operators in Boolean Expressions


In the previous examples, we have been using comparison operators in our boolean
expressions. We will now write a program which combines the usage of comparison
operators with logical operators. This program will determine a user's letter grade.

92
If Statements

public class DetermineLetterGrade extends ConsoleProgram


{
public void run()
{
int grade = readInt("What grade did you get? ");
if (grade > 89) // 90 or above is an A
{
System.out.println("You got an A! Great job!");
}
else if (grade > 79 && grade < 90) // 80 - 89 is a B
{
System.out.println("You got an B.");
}
else if (grade > 69 && grade < 80) // 70 - 79 is a C
{
System.out.println("You got a C.");
}
else if (grade > 59 && grade < 70) // 60 - 69 is a D
{
System.out.println("You got a D.");
}
else // Anything else is a F. B
elow 60.
{
System.out.println("Oh no! You failed.");
}
}
}

93
Loop-and-a-Half

Loop-and-a-Half
Recall that while loops execute as long as their condition is true. Repeating code while a
condition is true can be very useful; for example, the frontIsClear() condition can be used
to have Karel repeatedly move until the front is no longer clear. But what happens if the
condition is always true?

The Infinite Loop


Infinite loops can occur unintentionally if you are not careful with the conditions of a while
loop. In these cases, the infinite loop can cause the program to crash. However, infinite
loops can be a very useful tool in programming. If your program needs to repeat a block of
code an indefinite number of times, an infinite loop may be the correct approach.

Here's how to set up a basic infinite loop:

while(true)
{
// code to execute
}

Breaking out of a Loop


Repeating code is nice, but it's just as important to be able to stop the loop so that the rest of
the program can continue executing. Loops can be stopped using the break statement.
When the loop encounters a break statement, it quits running the loop and program flow
continues.

while(true)
{
// code to execute

if(condition)
{
// if the condition is true, stop looping
break;
}
}

Stopping with Sentinels

94
Loop-and-a-Half

Notice how in the previous example, the break statement occurs when a certain condition
is true. Checking for a condition like this is a useful way to have the while loop repeat as
many times as needed. This is especially true when getting input from the user. For
example, you may want to print out numbers from the user until the program encounters the
value -1 . Such a program may look like this:

while(true)
{
int num = readInt("Enter an integer: ");
if(num == -1)
{
break;
}
System.out.println(num);
}

We can clean up this code by using a variable instead of writing -1 in the body of the
program. This variable acts as a sentinel value that signals the end of the loop. As such,
we'll name the variable SENTINEL :

int SENTINEL = -1;

while(true)
{
int num = readInt("Enter an integer: ");
if(num == SENTINEL)
{
break;
}
System.out.println(num);
}

Using a sentinel value allows us to change the condition quickly and easily; for example, you
can change the sentinel from -1 to 0 and the loop will stop when the user enters 0 .

Why Use a Loop-and-a-Half?


It may seem dangerous or time-consuming to use an infinite loop, but when used
appropriately, the loop-and-a-half structure is efficient and effective. The loop-and-a-half
structure is preferred because it avoids repeating code outside and inside the loop.
Furthermore, it is often easier to reason through the logic behind a loop-and-a-half. For
example, with a simple program that prints numbers to the screen:

Loop-and-a-Half:

95
Loop-and-a-Half

public class PrintNumbersA extends ConsoleProgram


{
public void run()
{
int SENTINEL = -1;

while(true)
{
int num = readInt("Enter an integer: ");
if(num == SENTINEL)
{
break;
}
System.out.println(num);
}
System.out.println("Done!");
}
}

Repeated code:

public class PrintNumbersB extends ConsoleProgram


{
public void run()
{
int SENTINEL = -1;
int num = readInt("Enter an integer: ");

while(num != SENTINEL)
{
System.out.println(num);
num = readInt("Enter an integer: ");
}
System.out.println("Done!");
}
}

The second example PrintNumberB reads in user input both outside and inside the
loop. By using while(true) , the loop-and-a-half structure only reads in the variable
inside the loop. This cuts down on repeated code and avoids confusion.

96
Short-Circuit Evaluation

Short-Circuit Evaluation
Coming soon!

97
De Morgan's Laws

De Morgan's Laws
Coming soon!

98
Strings

Strings
As you have learned, a character is one of the primitive data types in Java. We use the
char keyword to declare it. A character is a single letter. 'A', 'a', 'D', and 'Z' are all examples

of characters.

It is great that we have an easy way to represent a single character, but what if we wanted to
represent words or sentences? How can we do this?

Introducing Strings
A String is a sequence of characters. We use Strings to represent full words and sentences.
For example, the famous "Hello World" is a String. Some more examples of Strings:

"I am a String. A sequence of characters strung together to form words and/or


sentences."
"CodeHS is the best coding website ever! Everyone loves CodeHS!"
"She sells sea shells by the sea shore."
"Strings!"
"abcdefghijklmnopqrstuvwxyz"

A String is not a primitive type like int , char , boolean , and double are. Primitive types
always start with lowercase letters, but a String starts with a capital letter. This makes it an
object. You will learn more about objects in future chapters, but for now, it is important to
just remember that a String is not a primitive type.

Concatenating Strings
Concatenate is a fancy word for joining or linking two things together. To concatenate two or
more Strings means that you are joining them together to form one String. We can do this in
Java by using the addition operator, + .

In this example, we concatenate two separate Strings, "Mc" and "Donalds", to form one
String, "McDonalds"

99
Strings

public class ConcatenateStrings extends ConsoleProgram


{
public void run()
{
String one = "Mc";
String two = "Donalds";
String concatenate = one + two;
System.out.println(cancatenate);
}
}

After running the program, the concatenated String "McDonalds" gets printed to the screen.

Concatenating Strings with Primitive Data Types:


We are not limited to concatenating Strings with other Strings. We can concatenate Strings
with other data types. Here we are concatenating a String and an integer together:

public class ConcatenateStringAndInt extends ConsoleProgram


{
public void run()
{
int number = 24;
System.out.println("This String is concatenated with an integer at the end: "
+ number);
}
}

Look familiar? We have been doing this all the time in previous programs when printing out
results to the screen! After running the program, we get:

This string is concatenated with an integer at the end: 24

You can also concatenate Strings with other primitive types like char , boolean , and
double .

Comparing Strings
In this program, we are comparing two Strings to determine if they are the same. We start by
asking the user what the best programming website is. Their answer gets stored into the
programmingWebsite String variable. We then attempt compare their answer with another

String, "CodeHS". If they match, we congratulate them for making the right choice. If they
don't match, we inform them that CodeHS is the best.

100
Strings

public class ComparingStrings extends ConsoleProgram


{
public void run()
{
String programmingWebsite = readLine("What is the best programming website eve
r? ");
if (programmingWebsite == "CodeHS")
{
System.out.println("Absolutely! Everyone loves CodeHS!");
}
else
{
System.out.println("No! CodeHS is the best!");
}
}
}

This should work as we expect, right? Not quite! There is a major bug in our program! If the
user types the correct answer to the question after running the program, this happens:

What is the best programming website ever? CodeHS


No! CodeHS is the best!

So what went wrong? We can not use == to compare Strings since they are not
primitive types! Instead, we must compare Strings using the .equals() method. This
change is shown below:

public class ComparingStrings extends ConsoleProgram


{
public void run()
{
String programmingWebsite = readLine("What is the best programming website eve
r? ");
if (programmingWebsite.equals("CodeHS"))
{
System.out.println("Absolutely! Everyone loves CodeHS!");
}
else
{
System.out.println("No! CodeHS is the best!");
}
}
}

By removing the == and comparing the two Strings with the proper .equals() method, our
program now works as expected:

101
Strings

What is the best programming website ever? CodeHS


Absolutely! Everyone loves CodeHS!

Hooray! The bug is now gone!

It is important to note that when we compare Strings, it is case-sensitive. Uppercase and


lowercase letters need to match exactly. Typing codeHS or Codehs as an answer will not
work because capitalization matters.

Thus, The General Format for Comparing Two Strings Is:

boolean result = stringOne.equals(stringTwo);

Comparing two Strings will always return a boolean result of either true or false. The Strings
either match or they don't.

102
Methods

Methods
Methods are segments of code that perform a specific task. This module teaches you how to
define methods in your programs and uses the autograder to test if your methods are
working correctly.

103
Java Methods

Java Methods
To teach Karel a new word, we had to create a method that contained instructions for Karel
to follow. Though we are no longer programming with Karel, we can still use methods to
organize our code in a similar way.

Methods in Java
Methods allow us to break our program down into smaller parts by grouping commands
together. Methods are useful because they help us avoid having to repeat the same
sequence of commands over and over. As you recall, to have Karel turn right, you could give
Karel three turnLeft(); commands. But it was much easier to create a turnRight method
to "teach" Karel how to turn right instead of writing out turnLeft(); three times over and
over.

Let's say we want to write a program that prints out your favorite skateboard tricks and
draws ASCII art of a skateboarder between every word. Your program might look like this:

104
Java Methods

public class SkateVocab extends ConsoleProgram


{
public void run()
{
System.out.println("Nollie big spin");
System.out.println(" | ");
System.out.println(" /o ");

System.out.println(" / ");
System.out.println(" _/o ");

System.out.println("Tre flip");
System.out.println(" | ");
System.out.println(" /o ");

System.out.println(" / ");
System.out.println(" _/o ");

System.out.println("A super clean kickflip");


System.out.println(" | ");
System.out.println(" /o ");

System.out.println(" / ");
System.out.println(" _/o ");

System.out.println("180 no-comply");
System.out.println(" | ");
System.out.println(" /o ");

System.out.println(" / ");
System.out.println(" _/o ");
}
}

Drawing out the skateboard so many times becomes quite tedious. Instead of writing out
four lines of System.out.println(), it would be much easier to create a "draw skateboard"
method.

105
Java Methods

public class SkateVocab extends ConsoleProgram


{
public void run()
{
System.out.println("Nollie big spin");
drawSkateboard();

System.out.println("Tre flip");
drawSkateboard();

System.out.println("A super clean kickflip");


drawSkateboard();

System.out.println("180 no-comply");
drawSkateboard();
}

private void drawSkateboard()


{
System.out.println(" | ");
System.out.println(" /o ");

System.out.println(" / ");
System.out.println(" _/o ");
}
}

Using a method makes the program easier to read and understand. Also, if you ever want to
change the ASCII art picture of the skateboard, you would only need to do it once in the
method instead of changing it througout the program.

106
Methods and Parameters

Methods and Parameters


Writing methods allows us to break our code into well-organized and reusable parts. But
sometimes we may want to reuse a method with a slight change.

Repetitive Actions
Take a look at the following code:

int x = 3;
int addTenToX = 10 + x;
System.out.println(addTenToX);

int y = 21;
int addTenToY = 10 + y;
System.out.println(addTenToY);

Notice that the code contains some repetition. The process of adding 10 to a variable is the
same whether we're adding 10 + 3 or 10 + 21 . In each case, we're adding 10.

Parameters
Recall that methods are like blocks of code that do a particular thing. We can write a method
that prints out "hello" when called, or a method that draws a circle. But what if we want to
create a method to add ten to a number? We can sketch out the method like so:

107
Methods and Parameters

We would expect an addTen method to add 10 to any number it is given. If we give it 3, the
method will give us 13. Were we to give it 32, it would give us 42. This pattern can be
generalized even more: if we give the method any number x , it will give us x + 10 in
return. The action that the addTen method takes is the same every time -- it adds 10 -- the
only thing that changes is the number we give to the method. The number that we pass to
the method is called a parameter.

Defining a method with Parameters


Let's write the addTen method in code:

public void addTen(int x)


{
int xPlusTen = x + 10;
System.out.println(xPlusTen);
}

Notice that there is an x that is being taken in and used by the method. This is the
parameter. Its value will be whatever the user decides to "pass" to the method. Also note
that the x parameter can be used like a regular variable in the body of the method.

Calling a Method with Parameters


Now that the addTen method is defined, it's time to call the method. Let's first add ten to the
number 5:

108
Methods and Parameters

addTen(5);

This will result in 15 being printed to the console.

This works with variables as well. We can create a variable y that stores a number, then
pass y to the addTen method:

int y = 115;
addTen(y);

The variable 115 is passed as an argument to the addTen method. The method accepts
115 as the parameter, adds 10 to it, and then prints 125 to the console.

Multiple Parameters
It's often helpful to write methods that can take in more than one parameter. For example, if
we were to write a generic add method, we would want to be able to input two numbers. To
include more than one parameter, you can simply write more than one parameter, separated
by a comma. The code below takes in two numbers, represented by x and y , and adds
them:

public void add(int x, int y)


{
int sum = x + y;
System.out.println(sum);
}

We call the method in a similar manner. If we give the function the following calls:

add(10, 90);
add(635, 1000);
int first = 72;
int second = 14;
add(first, second);

then the program will print the following to the console:

100
1635
86

109
Methods and Parameters

Why Use Parameters?


Using parameters allows us to write code that is flexible and reusable. Writing a method is
like telling the program to do something (add two numbers or draw a rectangle on the
canvas). Parameters are like giving that method specific instructions ("I want to add 3 and 7"
or "I want my greeting message to say their name and my name").

Functions can also take in multiple parameters. If you wanted to print several greetings,
you'd likely want them to contain different text depending on the person receiving the
greeting. If each of these pieces of information was hard-coded into the method, you would
need a separate method for each greeting!

Using parameters allows you to write one printMessage method that can be used to send
many greeting messages:

public void printMessage(String to, String from, String salutation, String message)
{
System.out.println("-------------");
System.out.println(salutation + " " + to + ",");
System.out.println(message);
System.out.println("Best regards,");
System.out.println(from);
System.out.println("-------------");
}

If Karel wants to send a birthday message to Bill Gates and a Halloween card to Steve
Wozniak, Karel could write:

printMessage("Bill Gates", "Karel", "Howdy", "Wishing you a happy birthday!");

String halloweenMessage = "Hope you have a spooky Halloween!";


printMessage("Steve Wozniak", "Karel", "Hi", halloweenMessage);

This would print two letters to the console:

110
Methods and Parameters

-------------
Howdy Bill Gates,
Wishing you a happy birthday!
Best regards,
Karel
-------------
-------------
Hi Steve Wozniak,
Hope you have a spooky Halloween!
Best regards,
Karel
-------------

An Important Note!
It's very important to pass arguments to methods in the proper order. Using the
printMessage example above, you may know that Karel is the name of the person sending

the message and that you want it to start with "Howdy", but the computer does not know this
information. The way that the computer finds out which argument goes to which parameter is
by the order in which your code passes the arguments into the method. For example, if you
wrote:

printGreeting("Howdy", "Karel", "Wishing you a happy birthday!", "Bill Gates");

you would end up with a mixed-up message:

-------------
Wishing you a happy birthday! Howdy,
Bill Gates
Best regards,
Karel
-------------

As you can see, order matters when you are using parameters.

111
Methods and Return Values

Methods and Return Values


Similar to how methods can take in values as parameters, methods can also return values.

Keeping Results
Recall the addTen method from the previous chapter:

public void addTen(int x)


{
int xPlusTen = x + 10;
System.out.println(xPlusTen);
}

This method takes in a parameter, x , and adds 10 to it. Lastly, the program prints the value
to the console.

But what if we wanted to store the value of x + 10 ? In the method above, x + 10 is stored
into a local variable called xPlusTen . However, this variable is lost when the method is
finished -- it cannot be accessed outside of the method.

Using a return statement will allow us to pass a value back out of the method. That return
value can be stored into a variable for later use.

Here's how to rewrite addTen to return a value instead of printing:

112
Methods and Return Values

public int addTen(int x)


{
int xPlusTen = x + 10;
return xPlusTen;
}

There are a few differences here. First, take a look at the first line of the method: public int
addTen(int x) . Instead of void , we now use int . This tells the program that the addTen

method will return a value that is an int. This is called the return type of the method. Up to
this point, we've only used the void return type, which indicates that the method does not
return anything. Because the addTen method will return an integer, we set the return type to
int .

Note also that the return keyword does not require parentheses. Also, returning a value
does not print that value to the console, similar to how passing in a value as a parameter
does not print the value to the console.

Calling a Method With a Return Value


A return value by itself would not be very useful, given that it does not print to the console.
Fortunately, we can store a method's return value into a variable. Take a look at the following
code:

int num = 7;
int tenAdded = addTen(7);

First, we create a variable named num and initialize it to 7. Then, we create another
variable called tenAdded . Notice that tenAdded is not given a normal value. Instead, we are
setting it equal to addTen(7) . This means that the tenAdded variable will hold the result of
whatever the function call addTen(7) returns. We know that addTen(7) will return 17, so
tenAdded will be 17 .

113
Methods and Return Values

Multiple Parameters With a Return Value


Return values work in many situations. For example, we can rewrite the add method from
the previous section to return the sum instead of print it to the screen:

public int add(int x, int y)


{
int sum = x + y;
return sum;
}

We can now call the method and store its return values

int sum = add(10, 90);


System.out.println(sum);

which would print 100 to the console.

114
Javadoc and More Methods

Javadocs and More Methods


Javadoc is all about commenting your code correctly. Javadoc is both a tool and the style of
commenting your Java programs. Commenting is important as it provides notes in our code
to help others understand it.

Javadoc Rules
Javadoc comments are similar to multiline comments, but contain an extra * . Here is an
example of a Javadoc comment and its structure:

/**
* Description of method
*
* @param paramName1 description
* @param paramName2 description
* return Description of return value
*/

More Examples
Here are some examples of proper Javadoc comments:

115
Javadoc and More Methods

/**
* This method returns the product of two integers.
*
* @param numOne The first integer
* @param numTwo The second integer
* @return The product of the two integers
*/
private int product(int numOne, int numTwo)
{
return numOne * numTwo;
}

/**
* This method returns an array with each word from a string in it.
*
* @param input The string we want to split.
* @return The new string array.
*/
private String[] split(string input)
{
return input.split("\\s+");
}

116
Strings Methods

Strings Methods
You will remember that Strings are a sequence of characters. Let's look at this example
String below:

String str = "Hello World"

Here is a way to think about this String as a sequence of individual characters:

0 1 2 3 4 5 6 7 8 9 10

H e l l o W o r l d

Each character in this string has a position from 0 to 10. For example, the first character, 'H',
is at position 0. The second character, 'e', is at position 1. The last character, 'd', is at
position 10. You will note that the space between the two words, ' ', is also a character and is
located at position 5.

A character's particular position in a string is formally known as its index.

String Review
Let's review some key points about Strings:

Strings are objects.


Strings are not primitive types (like char , int , boolean , double , etc.).
A String starts with a capital letter whereas primitive types are all lowercase.
Since Strings are objects, we must use the .equals() method to determine if two
Strings are exactly the same. Using == to compare two Strings will result in buggy
programs.
string1.equals(string2) is the correct way to compare two Strings. string1 ==

string2 is NOT the correct way to compare two Strings.

Notes About The Java Documentation


The Java Documentation is the reference for how to use different methods and
classes.
The full Java documentation for all methods and classes is located here.
In this chapter, we will be focusing specifically on the documentation for Strings (located

117
Strings Methods

on this page).
Tip: you can find a specific page in the documentation using a search engine like
Google. When searching for a specific method or class, search using the keywords
"Java [method or class]".
For example, here is a Google search for the Java String Documentation.
This is often easier than navigating through the full Java Documentation website.

String Methods
If you go to the String documentation page, you will notice that there are a lot of different
methods we can use on Strings. In this section, we will be focusing on some of the key
methods from that page which are listed in the table below:

The left-most column in the table shows us the return type of the method. The middle
column in the table shows us the method signature. The method signature includes the
name of the method and its parameters. The middle column also tells us what the method
does. The right-most column gives an example of using the method.

The equals Method versus the equalsIgnoreCase Method


You have already learned about using the .equals() method in the previous Strings
chapter. The .equalsIgnoreCase() method does the same thing, but it ignores differences in
case between the two strings. Essentially, this means that we ignore differences in
capitalization. For example, the three Strings "Hello world", "Hello World", and "HELLO
WORLD" are all equal when we ignore case.

118
Strings Methods

Using the indexOf Method


The indexOf() method tells us the starting position, or the index, of a String within another
String. For example, here we are finding the index of the String "Hello" within the String
"Hello World!":

public class IndexOfExample extends ConsoleProgram


{
public void run()
{
String str = "Hello World!";
int index = str.indexOf("Hello");
System.out.println("The index is " + index);
}
}

Let's take a quick look back at our chart above:

0 1 2 3 4 5 6 7 8 9 10
H e l l o W o r l d

Remember, a character's particular position in a string is formally known as its index. The
top row gives us the index of each character on the corresponding bottom row.

You will notice that "Hello" begins at index 0. When we run our program, it prints out The
index is 0 as we expect.

Consider another example:

public class IndexOfExample2 extends ConsoleProgram


{
public void run()
{
String str = "Hello World!";
int index = str.indexOf("World");
System.out.println("The index is " + index);
}
}

Here we are finding the index of the String "World". From out chart above, we see that this
String begins at index 6. Does our program agree? After running the program, it prints The
index is 6 . Hooray! Our program matches with what we expect!

But what if we look for the index of a String that does not exist?

119
Strings Methods

public class IndexOfExample3 extends ConsoleProgram


{
public void run()
{
String str = "Hello World!";
int index = str.indexOf("banana");
System.out.println("The index is " + index);
}
}

Here we are looking for the index of the String "banana" inside of the String "Hello world!".
No such index exists! So what happens when we run the program?

Output: The index is -1

When a String has no index within another String, it returns a value of -1. Since an
index can not be negative, getting a return value of -1 tells us the index was not found.

Using the charAt Method


The charAt() method returns the character at a specified index. Let's break apart another
String into its individual indexes:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
S t r i n g s a r e f u n !

Let's get the first, fourth, ninth, eleventh, and fifteenth character in this String using the
charAt() method:

120
Strings Methods

public class CharAtExamples extends ConsoleProgram


{
public void run()
{
String str = "Strings are fun!";

// Get the first character (index 0)


char first = str.charAt(0);
System.out.println("The first character at index 0 is " + first);

//Get another character at index 4


char fourth = str.charAt(4);
System.out.println("The character at index 4 is " + fourth);

//Get another character at index 9


System.out.println("The character at index 9 is " + str.charAt(9));

//Get another character at index 11


char eleventh = str.charAt(11);
System.out.println("The character at index 11 is " + eleventh);

//Get another character at index 15


char fifteenth = str.charAt(15);
System.out.println("The character at index 15 is " + fifteenth);
}
}

Does the output of our program match the table above?:

The first character at index 0 is S


The character at index 4 is n
The character at index 9 is r
The character at index 11 is
The character at index 15 is !

Our program works!

What happens if we try to look at an index that exceeds the String's length? Like trying
to get a character at index 16 when there are only 15 total indexes:

121
Strings Methods

public class CharAtOutOfBounds extends ConsoleProgram


{
public void run()
{
String str = "Strings are fun!";
char sixteenth = str.charAt(16); //Index 16 does not exist!
System.out.println("The character at index 16 is " + sixteenth);
}
}

We get an error; our program throws a IndexOutOfBoundsException exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out


of range: 16
at java.lang.String.charAt(String.java:658)
at CharAtOutOfBounds.run(CharAtOutOfBounds.java:6)
at ConsoleProgram.main(ConsoleProgram.java:21)

Always make sure to stay within a String's total index range to avoid these errors!

Using the substring Method


The substring(int beginIndex, int endIndex) method returns a String given a starting index
and an ending index. If you give no ending index, substring(int beginIndex) , it returns the
entire remaining string starting from the beginning index.

Consider our example String from before:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
S t r i n g s a r e f u n !

What if we wanted to get each individual word out of the sentence? How would we do this?
We can use substrings!

122
Strings Methods

public class GettingSubstrings extends ConsoleProgram


{
public void run()
{
String stringsAreFun = "Strings are fun!";

// Get the first word in the String


String firstWord = stringsAreFun.substring(0, 7);
System.out.println("The first word is: " + firstWord);

// Get the second word in the String


String secondWord = stringsAreFun.substring(8, 11);
System.out.println("The second word is: " + secondWord);

// Get the third word in the String


String thirdWord = stringsAreFun.substring(12, 16);
System.out.println("The third word is: " + thirdWord);
}
}

Output:

The first word is: Strings


The second word is: are
The third word is: fun!

Inclusive versus Exclusive Indexes:


Important! The beginning index is inclusive! The ending index is exclusive! For example:

When we get the first word using the substring method, we give a starting index of 0 and an
ending index of 7. The 0 is inclusive, meaning 0 is included in the range. However, the 7 is
exclusive, meaning 7 is not included in the range.

In short, we are actually returning the substring from indexes 0 - 6. Index 7 is not included!

123
Strings Methods

This is how we can have an ending index of 16 when getting the third word. The 16th index
is not included in the substring, so the program won't throw an IndexOutOfBoundsException
error.

Strings are Immutable:


Strings are immutable! This means that they can not be changed or modified in anyway.
When you use substring or any similar String method, you are actually getting an entirely
new String.

Looping Over a String


Looping through the contents of a String is something that is essential to know. The general
for loop for doing just that is given below:

for(int i = 0; i < str.length(); i++)


{
char cur = str.charAt(i);
System.out.println(cur);
}

Our for loop looks at each individual character in the String. We use the variable i to keep
track of the current index. The loop starts by getting the first character at index 0 using the
charAt() method. It stores this character into the variable, cur , and then prints it out. Our

loop continues to give us the characters at each consecutive index until we reach the last
character in the String. We know how long our string is by using the length() method.

Here is a program that loops through the "Hello World!" String:

124
Strings Methods

public class LoopingOverString extends ConsoleProgram


{
public void run()
{
String str = "Hello World!";

int length = str.length();


System.out.println("Character length of String: " + length);

for(int i = 0; i < str.length(); i++)


{
char cur = str.charAt(i);
System.out.println("Index" + i + ": " + cur);
}
}
}

First, we print out the length of the string by calling the length() method on it. Our String is
12 characters long. Next, we loop through the String. We print out each individual character
along with its corresponding index number. Our output looks like:

Character length of String: 12


Index0: H
Index1: e
Index2: l
Index3: l
Index4: o
Index5:
Index6: W
Index7: o
Index8: r
Index9: l
Index10: d
Index11: !

125
Strings and Characters

Strings and Characters


Let's review some key differences between Strings and characters:

Strings characters
Type: String Type: char
Object primitive

Compare using the .equals() method Compare using ==


Surrounded by double quotes (Example: Surrounded by single quotes (Example:
"hello") 'a')

Sequence of characters (Example: "hello") A single character (Example: 'a')

Here is an example of declaring a String in Java:

String website = "CodeHS";

And here is an example of declaring a character in Java:

char letter = 'b';

Let's break apart these two examples into their individual components:

Highlighted in blue is the type. On the left, we have the type for Strings, String . On the
right, we have the type for characters, char . Highlighted in orange is the name of our
variables. We can name them whatever we want, but our names should follow proper
naming conventions and make sense. Highlighted in red is the value. This is the actual
String and character we are assigning to our variable.

Characters are Numbers!

126
Strings and Characters

Computers prefer working with numbers rather than letters. Thus, every character is actually
a unique number behind the scenes. The table below lists each character's assigned
number. This table is known as the ASCII (American Standard Code for Information
Interchange) table:

The table has three columns. The first column, Hex , gives us each character as a
hexadecimal number. Hexadecimal numbers are just another way for us to represent each
character, but for now, we will ignore this column. It isn't important to us right now. The
second column, Dec , gives us each character as a decimal number. Decimal numbers are
the standard numbers that we are all used to working with (0, 1, 2, 3, 4, etc.). The third
column, Char , lists each of the corresponding characters.

It is important to remember that lowercase and capital letters are assigned different
numbers. For example, the capitalized character 'A' is the number 65 whereas the lowercase
character 'a' is the number 97.

127
Strings and Characters

You will also notice that there are a lot of special characters like "NULL" (number 0), "TAB"
(number 9), and "CAN" (number 24). Most of these special characters are abbreviated, so
they are spelled out more clearly to the right. For example, "CAN" stands for "Cancel". Even
things like spaces (number 32), exclamation points (number 33), dollar signs (number 36),
and semicolons (number 59) are considered characters!

Characters as Numbers in a Program


Here is a program that prints out different characters as numbers:

128
Strings and Characters

public class CharsAreNumbers extends ConsoleProgram


{
// If you want to see more about the ints behind every
// char take a full look at the ASCII table
// You can also find the ASCII table at http://www.asciitable.com/
public void run()
{
// 'a' has the ASCII value 97
System.out.println("Testing if 'a' has the ASCII value 97:");
char lowercaseA = 'a';
System.out.println("'a' as a letter: " + lowercaseA);
System.out.println("'a' as a number: " + (int)lowercaseA);

// 'A' has the ASCII value 65


System.out.println();
System.out.println("Testing if 'A' has the ASCII value 65:");
char uppercaseA = 'A';
System.out.println("'A' as a letter: " + uppercaseA);
System.out.println("'A' as a number: " + (int)uppercaseA);

// 'j' has the ASCII value 106


System.out.println();
System.out.println("Testing if 'j' has the ASCII value 106:");
char lowercaseJ = 'j';
System.out.println("'j' as a letter: " + lowercaseJ);
System.out.println("'j' as a number: " + (int)lowercaseJ);

// 'J' has the ASCII value 74


System.out.println();
System.out.println("Testing if 'J' has the ASCII value 74:");
char uppercaseJ = 'J';
System.out.println("'J' as a letter: " + uppercaseJ);
System.out.println("'J' as a number: " + (int)uppercaseJ);

// '!' has the ASCII value 33


System.out.println();
System.out.println("Testing if '!' has the ASCII value 33:");
char exclamationPoint = '!';
System.out.println("'!' as a character: " + exclamationPoint);
System.out.println("'!' as a number: " + (int)exclamationPoint);

// '$' has the ASCII value 36


System.out.println();
System.out.println("Testing if '$' has the ASCII value 36:");
char dollarSign = '$';
System.out.println("'$' as a character: " + dollarSign);
System.out.println("'$' as a number: " + (int)dollarSign);
}
}

129
Strings and Characters

Here we are testing to make sure that each of these characters correspond correctly to their
ASCII table numbers. First, we test lowercase and capital letters 'a' and 'A' as well as 'j' and
'J'. Then we test a couple of non-letter characters, the exclamation point ('!') and dollar
symbol ('$'). Does it work? Does our output match with the ASCII table above? Let's run the
program to check:

Testing if 'a' has the ASCII value 97:


'a' as a letter: a
'a' as a number: 97

Testing if 'A' has the ASCII value 65:


'A' as a letter: A
'A' as a number: 65

Testing if 'j' has the ASCII value 106:


'j' as a letter: j
'j' as a number: 106

Testing if 'J' has the ASCII value 74:


'J' as a letter: J
'J' as a number: 74

Testing if '!' has the ASCII value 33:


'!' as a character: !
'!' as a number: 33

Testing if '$' has the ASCII value 36:


'$' as a character: $
'$' as a number: 36

Looks good!

Adding and Subtracting Characters


Yes! You heard that right. Because characters are numbers, we can add and subtract them.
How does this work? Take a look at the example program below:

130
Strings and Characters

public class CharsAreNumbers extends ConsoleProgram


{
// If you want to see more about the ints behind every
// char take a full look at the ASCII table
// You can also find the ASCII table at http://www.asciitable.com/
public void run()
{
// 'C' is 2 characters after 'A'
System.out.println("SUBTRACTING EXAMPLE:");
System.out.println("'C' as a number: " + (int)'C');
System.out.println("'A' as a number: " + (int)'A');
System.out.println("Thus, 'C' is 2 characters after 'A'");
int difference = 'C' - 'A';
System.out.println("'C' - 'A' = " + difference);

// 'K' is 10 characters after 'A'


System.out.println();
System.out.println("ADDING EXAMPLE:");
System.out.println("'K' is 10 characters after 'A'");

char tenAfter = (char)('A' + 10);


System.out.println("'A' + 10 = " + tenAfter);

System.out.println("How does that work?");

char capitalA = 'A';


System.out.println(capitalA);
System.out.println(".... has the int value ...");

int capitalAInt = (int)capitalA;


System.out.println(capitalAInt);

System.out.println(".... add 10 and you get ...");


int capitalAPlusTen = capitalAInt + 10;
System.out.println(capitalAPlusTen);

System.out.println("... cast that back to a char and you get...");

char backToChar = (char)capitalAPlusTen;


System.out.println(backToChar);
}
}

After we run the program, we get a better idea of what is happening:

131
Strings and Characters

SUBTRACTING EXAMPLE:
'C' as a number: 67
'A' as a number: 65
Thus, 'C' is 2 characters after 'A'
'C' - 'A' = 2

ADDING EXAMPLE:
'K' is 10 characters after 'A'
'A' + 10 = K
How does that work?
A
.... has the int value ...
65
.... add 10 and you get ...
75
... cast that back to a char and you get...
K

First, we print out 'C' and 'A' as numbers. 'C' is the number 67 and 'A' is the number 65, so
we know that 'C' must be 2 characters after 'A'. When we subtract the two characters, 'C' -
'A', we confirm that their difference is 2.

Then, we add the number 10 to the character 'A'. We can do this because 'A' is a number!
We get a character result of 'K'. But why? Well, 'A' is the number 65, so when we add 10 to it
we get a number of 75. What character corresponds to the number 75? 'K' does! 'K' is also
the number 75.

Converting Cases
If you look at the ASCII table, you might notice that capital letters and their equivalent
lowercase letters are exactly 32 numbers away. We can use this to manually convert
between lowercase and capital letters!

132
Strings and Characters

public class ConvertCharsToUppercase extends ConsoleProgram


{
// This program manually converts each character in a String to uppercase
public void run()
{
// Read a string
System.out.println("Manually convert each character in a String to uppercase:"
);
String str = readLine("Enter any String: ");

// Loop over the String


for(int i = 0; i < str.length(); i++)
{
// Get each individual character from the String
char cur = str.charAt(i);
// Convert that character to uppercase
if (cur >= 97 && cur <= 122)
{
System.out.print((char)(cur - 32));
}
else
{
System.out.print(cur);
}
}
}
}

First, we read a String from the user. Then, we loop over the String as was taught in the
previous Strings Methods chapter. Within the loop, we get each individual character in the
String. From the ASCII table, we can see that all lowercase letters fall within the range
between 97 and 122, inclusive. Thus, we have an if statement to ensure that only lowercase
letters are converted to uppercase. If the current character is not within the acceptable
lowercase letter range, our else statement ensures that we simply print back the character
without changing it at all.

For example, the letter 'a' is the number 97 and the letter 'x' is the number 120. Both fall in
this acceptable range, so they will be properly converted to uppercase. Punctuation marks,
uppercase letters, and everything else does not get converted as none of those characters
fall in the acceptable lowercase letter range.

Here is an example of running this program. Many other possiblilties exist as the user is free
to enter any String they want:

Manually convert each character in a String to uppercase:


Enter any String: This String will be converted to all uppercase letters!!!
THIS STRING WILL BE CONVERTED TO ALL UPPERCASE LETTERS!!!

133
Strings and Characters

It works! The String we inputted was successfully converted to all uppercase. Notice how the
exclamation points still show up properly in our converted String. This is because '!' has the
number 33, so it didn't fall within our acceptable lowercase letter range. We didn't need to
subtract anything from it.

Escape Sequences
Escape sequences are characters with special meaning. While it might look like they
consist of multiple characters, they are actually treated as if they are a single character.
They always start with a backslash ( \ ). The table below gives some examples of common
escape sequences:

Escape Sequence Description


\t tab
\n new line
\' single quote
\" double quote

\\ backslash

So what is the reason for having these escape sequences? Their purpose is illustrated in the
example program below:

public class EscapeSequences extends ConsoleProgram


{
public void run()
{
// We can quote what someone has said
String quote = "John says, \"Hello!\"";
System.out.println(quote);

// We can use the \n to add a new line!


String manyLines = "First Line\nSecond Line\nThird Line";
System.out.println(manyLines);

// Two backslashes (\\) let's us actually use the backslash itself in a String
String backslashInString = "\\n is an escape sequence that adds a newline.";
System.out.println(backslashInString);
}
}

When we run this program, we get the following output:

134
Strings and Characters

John says, "Hello!"


First Line
Second Line
Third Line
\n is an escape sequence that adds a newline.

If we didn't have these escape sequences, our program would not work properly! The double
quotes in our first String will confuse Java if they are not escaped properly. Without the
backlash in front of the double quotes, the String would get broken apart right in the middle.
This would cause an error when we run the program!

In our second String, it is much simpler to use \n to create new lines. Otherwise, we would
have to write a series of empty println statements to get the same effect.

In our third String, we want to print out a backslash, so we need to use the two backslashes.
If we only had a single backslash, we would accidentally create a new line instead.

The Character Class


Just like how there is a String class that lets us use a variety of different methods on Strings,
there is also a Character class. The Character class lets us use a variety of different
methods on characters.

Important: Character is different than char . Character is a class while char is a


primitive type. You can not use methods on the primitive type, char . You will learn more
about these differences and why they exist in future chapters.

Useful Methods in the Character Class


There are many useful methods you will want to know about in the Character class. Some of
the most useful methods are given in the table below:

135
Strings and Characters

For a full list of all the methods in the Character class, you can visit the relevant page in the
Java documentation here. But for now, we will just be focusing on the methods in the table
above.

These methods are all static methods. This means you call these methods on the
Character class rather than an instance of the Character class. Take this as an example:

136
Strings and Characters

public class CharacterMethods extends ConsoleProgram


{
public void run()
{
String str = "abc4";
char lastChar = str.charAt(3);
if (Character.isDigit(lastChar))
{
System.out.println("Yep! The last character in str is a digit.");
}
}
}

Notice how we call the String charAt() method on our variable name str . This means we
are calling this method on an instance of the String class. However, we call the Character
isDigit() method on the Character class itself rather than an instance of the Character

class. This is the major difference between the two.

This may still be a little confusing to you right now, but you will learn more about static
methods in future chapters. For now, just remember that you call Character methods on the
Character class itself.

Character Methods in a Program


Let's look at an example of using a Character class method in the example program below:

public class CharacterMethods extends ConsoleProgram


{
public void run()
{
char ch = 'f';

if(Character.isUpperCase(ch))
{
System.out.println("It is uppercase!");
}
else
{
System.out.println("It is not uppercase");
}

}
}

137
Strings and Characters

We declare a character ch with a value of a lowercase f . We call the isUpperCase()


method on the Character class and pass in our primitive char as an argument. Remember,
we can not call this method on our ch variable since it is a static method!

If the character is uppercase, we print that out informing the user. Otherwise, we inform the
user that it is not uppercase. When we run this program, our program prints out: It is not
uppercase . If we were to change that lowercase f to an uppercase F , our program prints

out: It is uppercase! instead.

138
Exceptions

Exceptions
Coming soon!

139
String Processing

String Processing
In this chapter, we will combine everything we have learned about Strings and characters so
far. You will become more familiar with the underlying patterns involved in processing
Strings. By using these patterns, you will learn how to do more advanced forms of String
processing.

String Processing Pseudocode


Pseudocode is a step-by-step description of what you want a program to do in plain
English. Before writing any actual code, it is always recommended you write pseudocode
first. This helps us figure out how to structure more complex programs without getting
bogged down in specifics.

By now, you should be familiar with how to loop over Strings. Looping over Strings is the
most common form of String processing. You will consistently find yourself having to write
methods which do something to each of the characters in a String. This follows a pattern,
and that pattern can be expressed in the pseudocode given below:

Create a result String


For every character in the String
Do something with the current character
Return your result

We can use this as a guideline to write many different types of String processing methods.
Take this as an example:

private String processAStringExample(String str){


String resultingString = ""; // Create a result String
for(int i = 0; i < str.length(); i++) // For every character in the String
{
resultingString += str.charAt(i); // Do something with the current character
}
return resultingString; // Return your result
}

The relevant pseudocode for each line of actual code is given on the right. Let's test our
method to make sure it works:

140
String Processing

public class Palindromes extends ConsoleProgram


{
/**
* This program lets the user input some text and
* prints out whether or not that text is a palindrome.
*/
public void run()
{
String str = readLine("Enter a String for processing: ");
System.out.println("You typed: " + processAStringExample(str));
}

private String processAStringExample(String str){


String resultingString = ""; // Create a result String
for(int i = 0; i < str.length(); i++) // For every character in the String
{
resultingString += str.charAt(i); // Do something with the current charact
er
}
return resultingString; // Return your result
}
}

We have added a run method to test String input from the user. Here is an example of what
a user might type as a test String after running the program:

Enter a String for processing: Process this String!


You typed: Process this String!

You are not limited to simply storing each character into a new resulting String. You can do
anything to each of the characters. You could change the case, change the ordering, or even
change each of the characters into a different character entirely. The possibilities are
endless with how you choose to process the String!

Finding Palindromes
Let's look at a more advanced example of String processing. In this example, we will write a
program which checks to see if a given String is a palindrome. A palindrome is a word or
sentence that is the same forwards and backwards. Here are a some examples of
palindromes:

racecar
mom
A man, a plan, a canal - Panama!

141
String Processing

Writing an isPalindrome Method


Let's use top-down design and pseudocode to help us solve this problem. In order for a
String to be a palindrome, we know that it must:

Be the same forwards and backwards.


Be equal to the reversed version of the String.

Let's write a method in pseudocode which checks for this:

isPalindrome(String text)
reversed = get reversed text
if text is equal to reversed
return true
return false

First, we want to reverse the String, so we will have to write another method to do that.
Then, if the original String is equal to the reversed String, we know that it must be a
palindrome. Our method will return true. If the original String is not equal to the reversed
String, we know that it is not a palindrome. Our method returns false instead.

Writing a reverse Method


Now that we know we need a reverse method, we can write the pseudocode for that:

reverse(String text)
result = "";
for every character starting from the end
add it to result
return result

Does this look familiar? It should! We are using the same general pattern for processing a
String that was given at the start of this chapter!

First, we need to create a result String. We then take a look at each character starting from
the end of the String. We add each of these characters into the result String. We finish by
returning the resulting reversed String.

Putting It All Together


With both methods written in pseudocode, we have a good outline for our program:

142
String Processing

public class Palindromes extends ConsoleProgram


{
// Let's write a program that determines if a word is a palindrome.
public void run()
{

isPalindrome(String text)
reversed = get reversed text
if text is equal to reversed
return true
return false

reverse(String text)
result = "";
for every character starting from the end
add it to result
return result
}

We just need to fill in the details!

public class Palindromes extends ConsoleProgram


{
/**
* This program lets the user input some text and
* prints out whether or not that text is a palindrome.
*/
public void run()
{
String text = readLine("Type in your text: ");
if(isPalindrome(text))
{
System.out.println("Your word is a palindrome!");
}
else
{
System.out.println("Not a palindrome :(");
}
}

/**
* This method determines if a String is a palindrome,
* which means it is the same forwards and backwards.
*
* @param text The text we want to determine if it is a palindrome.
* @return A boolean of whether or not it was a palindrome.
*/
private boolean isPalindrome(String text)
{

143
String Processing

String reversed = reverse(text);


if(text.equals(reversed))
{
return true;
}
else
{
return false;
}
}

/**
* This method reverses a String.
*
* @param text The string to reverse.
* @return The new reversed String.
*/
private String reverse(String text)
{
String result = "";
for(int i = text.length() - 1; i >= 0; i--)
{
char cur = text.charAt(i);
result += cur;
}
return result;
}
}

In our run method, we get a String from the user. We then check to see if it is a palindrome
by calling the isPalindrome method. Since we have the pseudocode already written for this
method, we just need to convert it into actual code. Once we have that method finished, we
can do the same for the reverse method.

Let's test it with a palindrome!:

Type in your text: racecar


Your word is a palindrome!

Now let's test it with a word that is not a palindrome:

Type in your text: CodeHS


Not a palindrome :(

By using good top-down design principles and writing out pseudocode for each of our
methods, we have created a very advanced String processing program.

144
String Processing

145
Classes and Object-Oriented Programming

Classes and OOP


This unit teaches students the basics of Object-Oriented Programming in Java, which is a
powerful programming paradigm. Students will learn how objects store data and interact with
each other in Java programs. Students will design and implement classes and extend
classes using inheritance.

146
Introduction To Classes and Objects

Introduction to Classes and Objects


Classes and Objects are utilized in Java as part of the object-oriented programming model.
This model focuses on objects and the data and actions associated with the objects.

Objects
Objects are structures that contain a state and behavior. Every day objects we commonly
use have states and behaviors. For example, a car is an object with both a state and a
behavior.

State

The state contains the information about the specific object.

Thinking back to the car in this case. An example of a state, with the car, would be how
much fuel it has.

Behavior

The behavior is the actions that can be performed on the specific object.

A behavior of the car may be to get the mileage from the remaining fuel.

Classes
Classes are the templates we use for creating objects.

Rectangle Class

Here is an example of a class that lets us create a rectangle, and get its area:

147
Introduction To Classes and Objects

public class Rectangle


{
private double width;
private double height;

public Rectangle(double rectWidth, double rectHeight)


{
width = rectWidth;
height = rectHeight;
}

public int getWidth()


{
return width;
}

public int getHeight()


{
return height;
}

public int getArea()


{
return width * height;
}

public String toString()


{
String rectInfo = "Rectangle with width: " + width + " and height: " + height
+
" and area: " + getArea();

return rectInfo;
}
}

Animal Class

Here is another example of a class that lets us create new animal objects:

148
Introduction To Classes and Objects

public class Animal


{
private String name;
private boolean isPet;
private int age;

public Animal(String animalName, boolean isAnimalPet, int animalAge)


{
name = animalName;
isPet = isAnimalPet;
age = animalAge;
}

public String getName()


{
return name;
}

public boolean getPetStatus()


{
return isPet;
}

public int getAge()


{
return age;
}

public String toString()


{
String aInfo = "This animal's name is: " + name + " they are currently a pet: "
+
isPet + ". The animal is " + age + " years old.";

return aInfo;
}
}

Vehicle Class

Here is another example of a class that takes in a vehicle type, its age, and how many miles
it has:

149
Introduction To Classes and Objects

public class Vehicle


{
private String vehicleType;
private int vehicleAge;
private double vehicleMiles;

public Vehicle(String vType, int vAge, double vMiles)


{
vehicleType = vType;
vehicleAge = vAge;
vehicleMiles = vMiles;
}

public String getType()


{
return vehicleType;
}

public int getAge()


{
return vehicleAge;
}

public double getMiles()


{
return vehicleMiles;
}

public double estimateMilesPerYear()


{
return vehicleMiles / vehicleAge;
}
}

Creating Objects
When creating a new object from a class you will use the following format:

[Class Name] [Object Name] = new [Class Name] (params);

// Here are some examples using the classes we created earlier

Rectangle rect = new Rectangle(20, 8);

Animal pet = new Animal("Cujo", true, 7);

Vehicle myTruck = new Vehicle("Truck", 10, 173600.4);

150
Introduction To Classes and Objects

Using Objects
Here are some examples on how to create objects with our previous defined classes, and
use them.

151
Introduction To Classes and Objects

// Rectangle Class
public class StateBehavior_Rectangle
{
// Here we will create a new rectangle, and then print its information.
public void run()
{
// Create the rectangle
Rectangle rect = new Rectangle(20, 8);
// This will print "Rectangle with width: 20 and height: 8 and area: 160"
System.out.println(rect);
}
}

// Animal Class
public class StateBehavior_Animal
{
// Here we will create a new animal, and then print its information.
public void run()
{
// Create the animal and assign its attributes
Animal myPet = new Animal("Cujo", true, 7);
// Print out the animal info
System.out.println(myPet);

// This will print: "This animal's name is: Cujo they are currently a pet: tru
e.
// The animal is 5 years old."
}
}

// Vehicle Class
public class StateBehavior_Vehicle
{
// Here we will create a new vehicle, and then calculate how many miles/year it ha
s.
public void run()
{
// Create the vehicle and assign its attributes
Vehicle myTruck = new Vehicle("Truck", 15, 173600.4);

// Now we will use the `estimateMilesPerYear()` method to determine how many m


iles
// per year, it has been driven.
System.out.println("Your yearly mileage is: " + myTruck.estimateMilesPerYear()
);
}
}

152
Introduction To Classes and Objects

153
Classes vs. Objects

Classes vs. Objects


It is important to remember that classes are just templates for creating new objects. Objects
contain both a state and behavior, and is an instance of a class.

Instances
An instance is a specific version of an object that can differ in numerous ways.

Going back to the previous chapter, Rectangle, Animal, and Vehicle are all classes. These
classes, as is, are considered a type, unless you create a specific version of the class.

In essence, if we create two different vehicles they would be specific instances of the
Vehicle class.

Remember, An object is an instance of a class.

Examples

public class ExampleClass extends ConsoleProgram


{
public void run()
{
// `Animal` is our class.

// `myDog` and `myCat` are objects, because


// they are specific instances of our `Animal` class.
Animal myDog = new Animal("Cujo", true, 7);
Animal myCat = new Animal("Kerby", true, 2);
}
}

public class ExampleClass extends ConsoleProgram


{
public void run()
{
// `Rectangle` is our class.

//`mySquare` and `myRectangle` are objects, because


// they are specific instances of our `Rectangle` class.
Rectangle mySquare = new Rectangle(20, 20);
Rextangle myRectangle = new Rectangle(5, 10);
}
}

154
Classes vs. Objects

155
Using a Class as a Client

Using a Class as a Client


In Java, you can think of everything as a class. If you want to write a program to act as a
grade book, GradeBook is a class. The same can be thought of with any program you code
in Java.

Since you can think of everything as a class in Java, you can bundle these classes and their
functionality. You can even use classes that are written by other people without knowing
exactly how they work.

Whenever you use a class, it is class a client of the class.

Reading Documentation
Documentation is a great resource to use to see how a class works. As long as you can read
the documentation, you don't need to know how the class works.

Here is an example of the documentation for the String Class:

(http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)

The documentation for a class tells us how to use the class constructor, and various
methods that the class provides.

156
Using a Class as a Client

Here is another example of documentation:

(https://codehs.com/editor/slides/75977/97708/277/53)

This documentation is for the Rectangle Class that you may have worked with in previous
exercises.

157
Writing Classes

Writing Classes
Now that we have learned about what classes are... but wouldn't it be great if we could write
our own classes? Well, it turns out that we can! In this section, we will go over the different
parts that make up a typical class in Java, parts that you will have to write yourself in order
to make your class.

As a reminder, a class is a general blueprint for a certain type of object. For example, we
could have a class named Dog that serves as a general blueprint for objects of the type
Dog .

//Pretend that we have a class named Dog. This defines what an object with the type D
og would be like.
public class Dog
{
...
}
...
...

//These are objects that have the type Dog!


Dog karel = new Dog();
Dog scoobyDoo = new Dog();

What Goes Inside a Class?


Usually, most classes will include the following features:

1. Instance variables
2. Constructors
3. Methods

Instance Variables
Hopefully, by now, you know what a variable is. As a reminder, a variable is something that
stores information. An instance variable (sometimes also named field is a kind of variable
that stores a certain piece information about an object created from a class. It essentially
represents a kind of information that is shared among other objects of the same class. The
kinds of instance variables a class contains will depend on what pieces of information you

158
Writing Classes

would want the class's objects to store! A class will declare what kinds of instance variables
it would like its objects to have, and each object will have its own copy (also known as
instance) of each instance variable declared in the class.

So let's use our Dog class example from before... What kind of instance variables would we
want to put into a Dog class? Well, let's first think about what kinds of information that
different Dog objects would share. All dogs (we are not considering wild ones here) seem to
have names. That's one instance variable! What else other kinds of things are similar in
dogs? Age seems to be another property that all dogs have. That's another instance
variable! These instance variables (as well as other instance variables) can be declared in
the Dog class like this:

public class Dog


{
private String name;
private int age;
private double weight;
private boolean isAlive;

//This part will be continued below


...
}

Constructors
Constructors are essentially object creators. We use constructors to create new objects
using a class. When we create new objects using constructors, we also set any initial values
of instance variables if necessary. These initial values of instance variables can be set either
with or without the use of parameters.

Here is the continuation of the above example showing how you would write a constructor:

159
Writing Classes

public class Dog


{
private String name;
private int age;
private double weight;
private boolean isAlive;

public Dog(String theName, int theAge, double theWeight, boolean isThisAlive)


{
name = theName;
age = theAge;
weight = theWeight;
isAlive = isThisAlive;
}
}

In the above example, the variables in the parenthesis are the parameters that are passed in
when you create a new Dog object. This is how you would create a Dog object using the
Dog class from above:

Dog exampleDog = new Dog("Johnny", 17, 110.5, true);

That will create a new Dog named Johnny that has an age of 17, a weight of 110.5, and is
alive.

It is good to know that you you are not forced to always have a parameter corresponding to
an instance variable. You are also allowed to set an instance variable for all objects to the
same value, like this:

public class Dog


{
private String name;
private int age;
private double weight;
private boolean isAlive;

public Dog(String theName, int theAge)


{
name = theName;
age = theAge;
weight = 122.5;
isAlive = true;
}
}

160
Writing Classes

In the above example, there are only two parameters (the parameters theName and
theAge ), but we decided to set the weight of ALL dogs to 122.5 and make ALL dogs alive.

So if you wanted to create a new dog using this constructor, you would only need to write
this:

Dog exampleDog = new Dog("Johnny", 17);

This example will create will create a new Dog named Johnny that has an age of 17, a
weight of 122.5, and is alive.

Methods
In the Karel Java exercises, we said that methods were like ways of teaching Karel new
words/commands. Here in non-Karel Java, methods are still essentially the same: they teach
the program new commands.

We will go into more detail about methods in later sections. For now, you should know about
a specific kind of method that you can write into your classes: the toString method. The
toString just "converts" a class's object into something that you will be able to print out

using System.out.println .

So for example, you could add a toString method to the Dog class from above, like this:

public class Dog


{
private String name;
private int age;
private double weight;
private boolean isAlive;

public Dog(String theName, int theAge, double theWeight, boolean isThisAlive)


{
name = theName;
age = theAge;
weight = theWeight;
isAlive = isThisAlive;
}

public String toString()


{
return "This dog is named " + name;
}
}

161
Writing Classes

Notice how the toString method returns a String . So to print out a Dog object, you
would go like this:

Dog exampleDog = new Dog("Johnny", 17);


System.out.println(exampleDog.toString());

That above snippet would print out:

This dog is named Johnny.

What Comes Next?


In this section, we went over the basic elements that make up a class in Java. In the next
sections, we will explore the details of writing classes.

162
Writing Classes and Instance Methods

Writing Classes and Instance Methods

Instance methods allow us to define the behavior of an object.


Lets say you are wanting to get the area of a specific rectangle object you created using the
Rectangle class. To do this, you would need to define an instance method that will return

the area of our rectangle object. It is important to remember that instance methods belong
to the specific instance of your object.

Creating Instance Methods

The general form of an instance method is as follows:

[visability] [returnType] name(parameters)


public double getArea()
private int truncateArea()

The visibility of your method determines if it can be used outside your object's class. This is
usually public or private.

The returnType is the type of our return value. If there is no return value for the method we
use void.

The name is the name of our method.

The parameters is the list of our parameters, or the information we give to the method.

Here is what our Rectangle class looks like:

163
Writing Classes and Instance Methods

public class Rectangle


{
// Instance variables
private double width;
private double height;

public Rectangle(double rWidth, double rHeight)


{
width = rWidth;
height = rHeight;
}

// Our instance method


public double getArea()
{
return width * height;
}
}

Using Instance Methods

To call instance methods we use the following format: objectName.methodName(parameters);

The objectName is the name of the object we are calling the method on.
The methodName is the name of the instance method we are calling.
The parameters are the inputs we give the method (if any).

In practice, this looks like:

Rectangle rect = new Rectangle(7, 10);

// Get the area of our rectangle by calling instance method `area();`


double rectArea = rect.getArea();

164
Getter and Setter Methods

Getter and Setter Methods

Getter and setter methods allow us to get and set instance variables from the client class.

We use getter and setter methods for validation, to hide internal representation, expansion,
and security.

Getter Methods

Getter methods allow us to access specific instance variables of an object. Getter


methods are also known as accessor methods.

Creating Getter Methods:

When creating getter methods there is a common convention you should follow. When
naming your getter methods you should always use this format: get[Variable Name] for the
name. Some examples of this would be: getWidth(); , getHeight() , and getColor() .
Getter methods usually only return the variable we are trying to get. Here are some
examples of how this would look:

private int width = 10;


private int height = 3;
private Color rectCol = Color.blue;

public int getWidth()


{
return width;
}

public int getHeight()


{
return height;
}

public Color getColor()


{
return rectCol;
}

165
Getter and Setter Methods

Setter Methods

Setter methods allow us to set the values of an object's instance variables. Setter
methods are also known as modifier methods

Creating Setter Methods:

As with getter methods we use a common convention when creating setter methods.
When creating setter methods you should always use: set[Variable Name] . Some
common examples include: setWidth(int width) , setHeight(int height) , setColor(Color
color) . Here are some examples of how to create these setter methods:

private int width = 10;


private int height = 3;
private Color rectCol = Color.blue;

public void setWidth(int newWidth)


{
width = newWidth;
}

public void setHeight(int newHeight)


{
height = newHeight;
}

public void setColor(Color color)


{
rectCol = color;
}

166
Class Methods and Class Variables

Class Methods and Class Variables

Classes and Instances


Recall that an object is an instance of a class. The class is like the blueprint from which
instances can be built. Each instance can have its own state and behavior. An object's state
is stored in instance variables, and its behavior is carried out with instance methods. These
are called instance variables and instance methods because they belong to a single
instance of the class.

But what if you wanted to keep track of a single variable or have a shared behavior across
all the members of a class? Because each object has its own instance variabes and
methods, these won't work to store information for the entire class.

Class Methods and Class Variables


Sometimes it is useful to store information that is shared across all the objects of an entire
class. A class variable is a variable or attribute of a class that is common to all instances of
a class. A class method is a method of a class that is common to all instances of a class
and is not called on any specific object instance. These are sometimes referred to as static
variables and static methods.

A new static variable or method is defined by adding the keyword static to the variable or
method declaration. A method to return the total number of birds of the Bird class may look
like:

private static int getTotalBirds()


{
return totalBirds;
}

Skating and Coding


For example, if you ran your own indoor skatepark, you may want to keep track of the
skaters at the park. In order to use the park, a new skater would sign up and an new
instance of the Skater class would be created. What information would be useful to track

167
Class Methods and Class Variables

about each skater? You may want to know a skater's name, age, experience level, and a
history of times he or she arrived at and left the park. These are all unique to each skater
and could be stored as instance variables.

It would also be useful to know how many skaters have ever skated at the park. This is a
useful stat to know, but it is affected by all the skaters, not just one. Because this information
is shared across the whole class, it can be stored in a class variable. The Skater class
could be defined to include these:

public class Skater


{
private static int totalSkaters = 0;

public Skater()
{
totalSkaters++;
}

public static int getTotalSkaters()


{
return totalSkaters;
}
}

Whenever a new skater is added, the static variable totalSkaters is increased. The
totalSkaters variable is shared across all instances of the Skater class. Each object in

the class has the same value for this variable, and we can get the value of this variable with
the static getTotalSkaters method.

Using Static Methods and Variables


Because static methods and variables are available across an entire class, they don't need
to be called on a particular instance of the class. You do not need to create a new object just
to call a class method.

To find out how many skaters have been to the skatepark, you can write:

Skater.getTotalSkaters();

This will call the getTotalSkaters() method on the Skater class without requiring an
instance of the class to be created.

168
Class Methods and Class Variables

169
Method Overloading

Method Overloading
Coming soon!

170
Local Variables and Scope

Local Variables and Scope


Coming soon!

171
Key Terms for Classes

Key Terms for Classes


You've likely noticed that learning a programming language involves learning a lot of new
vocabulary terms. Let's review some of the key concepts and terms that we've learned so
far.

Objects and Classes


Not surprisingly, objects are a key part of object-oriented programming. Let's review some of
the important concepts of objects and classes.

What is an Object?
An object is something that contains both state and behavior. It is an instance of a class.

A class is a template for creating an object.

An instance is what you call a specific version of a class. Instances and objects generally
refer to the same thing.

For example, if you owned a factory that produced bikes, you would likely want blueprints or
plans for each type of bike. Mountain bikes would a blueprint, BMX bikes would have a
different blueprint, and road bikes would have their own blueprint. These blueprints are like
classes in programming. The plans for each class can produce a specific object. If you
were to follow the plans to build a road bike, the object you end up with could be called an
instance of the "RoadBike" class.

State and Behavior


Objects have state and behavior. An object's state is store in variables, while its behavior is
defined by methods. State and behavior can be specific to a single instance of a class (for
example, one specific road bike), or shared between all the members of a class.

An instance method is a method called on an instance of a class, or an object, that helps


define the behavior of the class.

An instance variable is a variable belonging to an instance of a class, or an object, that


helps define the state of the class.

172
Key Terms for Classes

An class method or static method is a method called on the class. It does not have an
object as the receiver. It is accessible to all instances of the class.

A class variable or static variable is a variable belonging to the class, not any object
instance. It is accessible to all instances of the class.

Packages
A benefit of using classes and objects is that they can potentially reduce the amount of code
that you need to rewrite. To create a new road bike, you don't need to rewrite all of the road
bike code. You can simply instantiate a new instance of the "RoadBike" class.

This same type of code reusability is present in other aspects of the Java programming
language as well. You may find yourself wanting to use and reuse related classes that you or
other programmers have already designed. Rather than rewriting classes each time, classes
can be bundled into packages and imported into your code.

You import classes from a package like: import packageName.*;

You import a single class like import packageName.ClassName;

Visibility
Some of the code you write should be accessible to everyone, but you may often want to
limit who or what can access certain parts of your code. You can help ensure that an object's
state and behavior can only be modified properly by setting the visibility of classes,
methods, and variables.

Public visibility means that the object, method, or variable is open for use by everyone. Most
of the classes we write in this course are public. Something is decalred public by using the
public keyword: public class RoadBike

Private visibility limits access. Most of the instance variables we write are private, which
prevents them from being changed by others. The private keyword is used to declare
something as private: private int costOfBike;

The levels of access each type of visibility provides can be summarized in a table:

visibility Class Package World (everyone)


public yes yes yes

private yes no no

173
Key Terms for Classes

What is This?
It can often be confusing to know whether a variable in a constructor is referring to an
instance variable or a variable that was passed in as an argument to the constructor. One
way around this is to use different variable names for the instance variables and parameters.

public class BMX


{
private String frameSize;
private int numPegs;

public BMX(String theFrameSize, int theNumPegs)


{
frameSize = theFrameSize;
numPegs = theNumPegs;
}
}

Notice that the constructor's parameters are theFrameSize and theNumPegs instead of
frameSize and numPegs .

Using different names can get a little confusing. Fortunately, Java has a way of specificying
when you are referring to the object itself: this.

this refers to the current object. The this keyword allows us to be very clear whether we

are referring to the object's instance variable or a parameter:

public class BMX


{
private String frameSize;
private int numPegs;

public BMX(String frameSize, int numPegs)


{
this.frameSize = frameSize;
this.numPegs = numPegs;
}
}

174
Objects vs Primitives

Objects vs Primitives
Not surprisingly, objects play a key role in object-oriented programming. But objects are not
the only way that you will interact with data in the Java programming languages. Up to this
point, you have built programs that include both objects and primitive data types.
Understanding the differences between objects and primitives will help you plan and write
programs.

What is a Primitive?
Primitive data types are the basic building blocks of the Java programming language. These
basic types cannot be broken down into other parts. Java includes several primitive types
that you have seen before:

Type Example
int int x = 42;
char char oneChar = 'a';
double double myNumber = 13.37;
boolean boolean likesCoding = true;

These primitive types can be combined and used to build more complex objects. Primitive
types are named with all lowercase letters.

Primitives and Objects


Primitive data types are used to make objects. For example, a Movie object may have a title,
director, whether it is a sequel, number of tickets sold, and runtime of the movie in minutes:

public class Movie


{
private String title;
private String director;
private boolean isSequel;
private int numTicketsSold;
private double runtime;
}

Strings are not Primitives

175
Objects vs Primitives

Note that Strings are not a primitive data type. Strings are sequences of characters. As
such, when creating a new string of text, be sure to capitalize the S in String: private String
nyName

Making Comparisons
Comparing primitive data types like integers is straightforward using == . For example, to
check if a user-entered number is 0:

int userNumber = readInt("Enter a number: ");


System.out.println(userNumber == 0);

The values of objects, however, cannot be compared with the == . Instead, objects are
compared with a .equals method. For example:

String textOne = new String("Hello world!");


String textTwo = new String("Hello world!");
System.out.println(textOne.equals(textTwo));

176
Inheritance

Inheritance
Inheritance is when we have two classes that share functionality. You use inheritance
when you want to create a new class, but utilize existing code from another class. In this
case, you derive your new class from the existing class. By doing this, you can utilize
methods from the existing class without having to rewrite code.

Class Hierarchy
Class hierarchy is the inheritance relationship between your classes. Class hierarchy is
also known as an inheritance tree. It is important to know that the root class in our hierarchy
is the Object Class. The Object Class contains many useful methods, such as: clone() ,
equals() , toString() , finalize() , and a few others. The further away from the root

class we go the more exclusive the class behavior is.

Here is an example of an inheritance tree:

As you can see, we start off with our root class, move to Vehicle Class and from there we
get more defined as we go down the tree. Whenever we pass a method through our class it
will travel up the inheritance tree until a suitable definition is found. Lets say we start in the
Truck class, and call toString() . The toString() message will be sent up the tree until it
gets to the Object Class. Once it gets to the Object Class a toString() method is found
and utilized.

177
Inheritance

Subclass and Superclass


The Subclass is the class the extends another class, or inherits from another class.

The Superclass is the class being utilized by the subclass.

It is important to know that the subclass inherits everything from the super class. This
includes: classes, methods, and fields.

Important Key Words


Extends

In order to show that a class relates to another, we use the extends keyword. Here is an
example of a class that extends the ConsoleProgram class:

public class Output extends ConsoleProgram


{
// code here
}

In this example Output is our subclass, and ConsoleProgram is the superclass.

Super

We can call the constructor of our superclass directly from our subclass by using the key
work super.

Here we have a class which extends our Rectangle class. We use super to call the
constructor of Rectangle to create a square.

public class Square extends Rectangle


{
public Square(int sideLength)
{
super(sideLength, sideLength);
}
}

Subclass Functionality
There are many things we can do from our subclass since it inherits the private and public
members of the parent class.

It is important to remember:

178
Inheritance

Subclasses inherit all of the public and protected instance methods of the parent class.
Subclasses inherit all of the public and protected instance and class variables.
Subclasses can have their own instance variables.
Subclasses can have their own static and instance methods.
Subclasses can override the parent class's methods.
Subclasses can contain constructors that directly invoke the parent class's constructor
using the super keyword.

Example of Inheritance
Here is an example of inheritance utilizing our Rectangle and Sqaure classes.

Superclass:

public class Rectangle


{
int width;
int height;

public Rectangle(int rwidth, int rheight)


{
width = rwidth;
height = rheight;
}

public int getArea()


{
return width * height;
}
}

Subclass:

public class Square extends Rectangle


{
// Class constructor
public Square(int sideLength)
{
// Call the class constructor for `Rectangle` using `super`
super(sideLength, sideLength);
}
}

Test Class:

179
Inheritance

public class SquareTest extends ConsoleProgram


{
public void run()
{
Square ourSquare = new Square(10);

/* `.getArea()` only exists in `Rectangle`, but we can use it


* Since it is the parent class of `Square`
*/
int squareArea = ourSquare.getArea();
}
}

180
Class Design and Abstract Classes

Class Design and Abstract Classes


One of the biggest challenges in Java is taking the time to actually write out relations
between classes, outside of the editor. It is incredibly important to understand how each
class relates to one another. It is also important to know the characteristics that define each
class.

Class Design
Let's take a look at the Vehicle Class from the previous chapter:

In this diagram we can see that both Car Class and Motor Cycle Class inherit from Vehicle
Class. While Truck, Sports Car, and S.U.V. extend Car Class. This diagram demonstrates
the relations between our subclass and superclass.

Abstract Classes
Unlike an ordinary class, abstract classes can't be instantiated. This means that you can
not create new instances of an abstract class, as you would an ordinary class. While you
can't instantiate an abstract class, it can still share properties or be related to the subclass.

Creating an Abstract Class

181
Class Design and Abstract Classes

In order to create an abstract class you must add the keyword: abstract to the class
declaration.

Here are a couple of examples of abstract classes in Java:

// Here is our Vehicle Class


public abstract class VehicleClass
{

// Here is an example of our Shape class


public abstract class Shape
{

Creating Abstract Methods


Abstract methods are methods that are declared within an abstract class, but lack
implementation. In most cases you would have to implement the method within the subclass.
This way you have more flexibility with subclasses that require different logic in the same
method.

Here is an example of abstract methods using our Vehicle Class

public abstract class VehicleClass


{
private String type;
private String vehicleName;

public VehicleClass(String vType, String vName)


{
type = vType;
vehicleName = vName;
}

/* This will need to be abstract, since


* we will need to implement different formulas
* depending on if the vehicle is electric or
* gas powered.
*/
public abstract double getMileage();
}

/* As you can see, in both classes, we have `getMileage` implemented


* with different formulas.
*/
public class Truck extends VehicleClass

182
Class Design and Abstract Classes

{
private double gasTankCapacity;
private double milesPerTank;

public Truck(double capacity, double miles)


{
gasTankCapacity = capacity;
milesPerTank = miles;
}

public double getMileage()


{
return milesPerTank/gasTankCapacity;
}
}

public class ElectricCar extends VehicleClass


{
private double maxCharge;
private double milesPerCharge;
private double maxEnergyUsage;

public ElectricCar(double charge, double maxEnergy, double milesCharge)


{
maxCharge = charge;
maxEnergyUsage = maxEnergy;
milesPerCharge = milesCharge;
}

public double getMileage()


{
return (maxCharge*milesPerCharge)/maxEnergyUsage;
}
}

183
Polymorphism

Polymorphism
Polymorphism is one of the most important concepts in Object Oriented Programming.
Polymorphism is the capability of a single object to take on multiple forms. Polymorphism
can also be explained as the ability to perform a single action, in many ways, across multiple
objects. This means we can use the same method across different objects, using different
implementations.

Concepts of Polymorphism
There are several concepts of polymorphism that are crucial to understand. These include:

Method Overriding: Allows us to call the correct implementation of a method across


multiple objects that share the same superclass.

Upcasting: Occurs when the reference variable of a superclass points to the object of
the subclass. This allows us to go from a low level class type to a higher level one.

ex: Animal fox = new Fox(); , Animal dog = new Dog();


Downcasting: Occurs when the reference variable of a subclass points to an object of
the superclass type. This will manually convert the object type to that of the subclass.

ex: Animal animal = new Fox(); Fox castedFox = (Fox) animal


Dynamic Binding: Is the concept where the proper method implementation is chosen
at run-time, and not compilation.

Static Binding: Is the concept where the proper method implementation is chosen at
compilation, and not run-time.

Method Overriding
Method Overriding allows us to use the same method across multiple objects, with differing
implementations. Let's take a look at an example of this concept:

184
Polymorphism

public abstract class Animal


{
public abstract String speak();
}

public class Dog extends Animal


{
public String speak()
{
return "The dog says woof!";
}
}

public class Fox extends Animal


{
public String speak()
{
return "What does the fox say?";
}
}

public class UpcastingExample extends ConsoleProgram


{
public void run()
{
Animal myFox = new Fox();
Animal myDog = new Dog();

/* Polymorphism here is seen as the correct implementaiton of `speak()`


* being chosen, regardless of the object type. */

System.out.println(myFox.speak()); // Will print `What does the fox say?`


System.out.println(myDog.speak()); // Will print `The dog says woof!`
}
}

Upcasting:
Upcasting refers to taking an object of a lower level class type and referencing it to a class
of a higher level. Lets look at an example of this:

185
Polymorphism

public abstract class Animal


{
public abstract String speak();
}

public class Dog extends Animal


{
public String speak()
{
return "The dog says woof!";
}
}

public class Fox extends Animal


{
public String speak()
{
return "What does the fox say?";
}
}

public class UpcastingExample extends ConsoleProgram


{
public void run()
{
Animal myDog = new Dog(); // Upcasting
Animal myFox = new Fox(); // Upcasting

System.out.println(myDog.speak()); // Will print `The dog says woof!`


System.out.println(myFox.speak()); // Will print `What does the fox say?`
}
}

Downcasting
Downcasting is conversion of a reference variable's type to that of the subclass. A
difference in downcasting, as compared to upcasting, is that you must manually downcast.
Lets look at an example of this:

186
Polymorphism

public abstract class Animal


{
public abstract String speak();
}

public class Dog extends Animal


{
public String speak()
{
return "The dog says woof!";
}
}

public class Fox extends Animal


{
public String speak()
{
return "What does the fox say?";
}
}

public class UpcastingExample extends ConsoleProgram


{
public void run()
{
// Upcasting is done automatically
Animal myDog = new Dog(); // Upcasting
Animal myFox = new Fox(); // Upcasting

// Downcasting must be done manually


Dog yourDog = (Dog) myDog; // Downcasting
Fox yourFox = (Fox) myFox; // Downcasting

System.out.println(yourDog.speak()); // Will print `The dog says woof!`


System.out.println(yourFox.speak()); // Will print `What does the fox say?`
}
}

Dynamic Binding
Dynamic Binding is an important concept to runtime polymorphism. It is the concept of
the proper method implementation being chosen at run-time. Lets look at an example:

187
Polymorphism

Static Binding

188
Polymorphism

Polymorphic Arrays
Polymorphic Arrays allow us to store an array of objects with differing types that share the
same superclass. Lets see this in action:

189
Polymorphism

public abstract class Animal


{
public abstract String speak();
}

public class Dog extends Animal


{
public String speak()
{
return "The dog says woof!";
}
}

public class Fox extends Animal


{
public String speak()
{
return "What does the fox say?";
}
}

public class Cow extends Animal


{
public String speak()
{
return "The cow goes moo!";
}
}

public class AnimalArrays extends ConsoleProgram


{
public void run()
{
// Create the array and set its size to `3`
Animal[] animalArray = new Animal[3];

// Set each object in the array


animalArray[0] = new Dog();
animalArray[1] = new Fox();
animalArray[2] = new Cow();

// Print out the array


for(int i = 0; i < animalArray.length; i++)
{
// Will print out the various `speak()` methods for each animal.
System.out.println(animalArray[i].speak());
}
}
}

190
Polymorphism

191
Interfaces

Interfaces
Interfaces in Java allow us to create a collection of methods to guarantee a class's
interaction. An interface does not contain method implementation, constructors, or instance
variables.

Interfaces are commonly used to help achieve polymorphism.

Implementing Interfaces
To implement an interface we use the implements keyword after our class name, like:
public class Dog implements Animal . In this case Dog is our class name, where Animal is

our interface.

Let's look at an interface for using a computer. We will call it UseComputer .

public interface UseComputer


{
/* Notice how we end our method signatures with semi-colons `;`
* and not curly brackets
*/
public void pressKey(Key keyPressed);
public void clickMouse(MouseEvent mouse);
public void shutDown();
public void startUp();
}

Now, let's take a look at an example class which implements our interface:

192
Interfaces

public class GeneralUser implements UseComputer


{
private boolean isShuttingDown = false;
private boolean isStartingUp = false;

public void pressKey(Key keyPressed)


{
return keyPressed;
}

public void clickMouse(MouseEvent mouse)


{
return mouse;
}

public void shutDown()


{
isShuttingDown = true;
isStartingUp = false;
}

public void startUp()


{
isShuttingDown = false;
isStartingUp = true;
}
}

As you can see, we store the method signatures in our UseComputer interface, and
implement them within our GeneralUser class.

Comparable Interface
Java is full of interfaces that you are free to utilize within your code. One interface you
should become familiar with is the Comparable interface. The Comparable interface can be
incredibly useful with sorting algorithms.

Here is what an implementation of the Comparable interface looks like:

// Marbles class, implements Comparable


public class Marbles implements Comparable<Marbles>
{
private String owner;
private int quantity;

public Marbles(String ownerName, int mQuantity)


{
owner = ownerName;
quantity = mQuantity;

193
Interfaces

public String getOwner()


{
return owner;
}

public int getQuantity()


{
return quantity;
}

public void setOwner(String newOwner)


{
owner = newOwner;
}

public void setQuantity(int newQuantity)


{
quantity = newQuantity;
}

public int compareTo(Marbles comMarbles)


{
int comQuantity = comMarbles.getQuantity();

return getQuantity() - comQuantity;


}
}

// Our main class


public class MarblesProgram extends ConsoleProgram
{
public void run()
{
Marbles marbles1 = new Marbles("Wezley", 10);
Marbles marbles2 = new Marbles("James", 20);
Marbles marbles3 = new Marbles("Kurt", 10);

System.out.println(marbles1.compareTo(marbles2));
System.out.println(marbles1.compareTo(marbles3));
}
}

194
Data Structures

Data Structures
Learn basic data structures in Java including arrays, ArrayLists, 2 dimensional arrays, and
HashMaps.

195
What Are Data Structures?

What Are Data Structures?


Data is the name for the symbols or quantities on which a program operates. There are
many types of data and many ways to use data in programs. For example, if you are
interested in weather patterns, you would want to collect temperature readings every day for
several years. Or if you are working on a book of knock-knock jokes, you'd need to find as
many knock-knock jokes as possible.

However, data isn't of much use on its own. Without programs to interpret them, data would
just be a pile of symbols, numbers, and other characters. Programmers write code that takes
in and processes data to make sense of the collected information. Because data is intended
for use in programs and analysis, it needs to be organized. Hearkening back to the
temperature collecting example, the data wouldn't be very useful if you wrote down a bunch
of scattered numbers on one page and wrote the dates and times in a different order spread
across other pages. Disorganized data is difficult for both computers and humans to
understand.

Introducing Data Structures


Data structures are particular ways of organizing data in programs. Just as there are many
different types of data, there are many different types of data structures. We will cover a few
of the most important data structures in this course: arrays, ArrayList, 2D arrays, and
HashMaps.

Array
For example, imagine that you need to buy exactly 10 items at the grocery store. Rather
than trying to remember every item to purchase, you find a piece of paper that is just big
enough to write down a list of these 10 items and bring that list with you to the store. This
type of data structure is called a list or array.

ArrayList
But what if your friend calls you on the way to the store and asks you to purchase a few
items for her? Recall that the array has a fixed size, since the piece of paper you used to
write it down on was only big enough for 10 items. In this case, you would want to use a list
that would let you add and remove items as you go. This kind of flexible list is called an
ArrayList.

196
What Are Data Structures?

2D Array
Say that after going grocery shopping, you and your friend decide to play a game of
checkers. A checkerboard is a grid of rows and columns, with each piece stored on its own
location in the grid. A grid is a type of data structure commonly referred to as a 2D array,
since it has two dimensions (rows and columns).

HashMap
Or perhaps you are going on vacation to an exciting place and you want to send postcards
to your friends while you are away. You could create an address book to take with you by
writing the name of each friend in one column and the corresponding mailing address in the
next column. This data is different from the list of grocery items because each entry actually
consists of two pieces of information: a key (the friend's name) and a value (the friend's
address). As such, you would use a different data structure called a map to store this type of
data (so called because it "maps" each name to an address).

In summary, the data types are:

Type Simple Definition Example


array List of fixed size 10-item grocery list
ArrayList List of changing size Flexible grocery list to add or remove items

2D array Table of grid Checkerboard


HashMap Association, key to value Address book to store friend's addresses

197
Introduction to Arrays

Introduction to Arrays
An array is a list of data. Arrays can store many different types of information. For example,
if you had a shopping list, you could store the shopping list as an array.

Organizing Information in an Array


The information stored in an array is kept in order. The items in an array are often referred to
as members or elements of the array.

Unless we make changes to the array, the first element in the array will always be the first
element, and the last item will always be last. It is important to note that in computer science,
we usually start counting from 0. So the first item in the array is actually at index position 0,
the second item in the array is at index position 1, and so on.

Let's say our grocery list contained these items, in this order: apples, dog food, donuts,
celery, and orange juice. If we were to draw out the array, it would look something like this:

index position: 0 1 2 3 4
list item: apples dog food donuts celery orange juice

We can see that dog food is at index 1 and celery is at index 3.

Creating Arrays
To create an array in Java, you must first know what type of data you want to store and how
many elements the array will hold. In the grocery list example above, we created an array of
Strings, but it's just as easy to create arrays of ints or any other data type.

The format for creating an array is:

type[] arrayName = new type[numberOfElements];

Let's take apart the array declaration:

type[] : This tells us what type of data is being stored in the array. For example, a list

of integers would be int[] . The brackets [] indicate that this is an array and not a
single int .
arrayName : The name by which the array will be known. It's best to pick a descriptive

198
Introduction to Arrays

name, like groceryList instead of just things .


new : The new keyword indicates that a new array is being created.

type[numberOfElements] : The type of elements is mentioned again, as well as the

number of items the array will store.

Getting and Setting Array Elements


Once an array is declared, it's ready to store information. Perhaps the easiest way of putting
data into an array is to initizalize the array with data when declaring it. To do so, simply
include the array elements between curly braces. Here's a list of 6 numbers:

int[] numberList = {10,20,30,40,50,60};

index position: 0 1 2 3 4 5
list item: 10 20 30 40 50 60

Setting Elements
It's also possible to declare a new empty array and add in the list items later. Elements in an
array can be accessed using the index position of the array. Let's create a new empty array
of numbers, then add in two numbers:

// Create an empty array that will store 6 integers


int[] newNumberList = new int[6];

// Add the number 11 to index position 0


newNumberList[0] = 11;

// Add the number 13 to index position 1


newNumberList[1] = 13;

The array now contains two integers:

index position: 0 1 2 3 4 5

list item: 11 13

The same syntax can be used to change elements in a list. Let's change 13 to 21:

newNumberList[1] = 21;

199
Introduction to Arrays

index position: 0 1 2 3 4 5

list item: 11 21

Getting Elements
Accessing elements in a list uses a similar syntax. We can get and store the number at
index 0 into a variable:

// This variable will contain the number 11


int firstNumber = newNumberList[0];

// Two ways to print out the number 11 to the console


System.out.println(firstNumber);
System.out.println(newNumberList[0]);

// Now print out the number at index position 1 to the console


System.out.println(newNumberList[1]);

The output from the code will be:

11
11
21

200
Using Arrays

Using Arrays
Arrays are utilized for many operations in various programs. Since arrays store data in order,
we can iterate through them to access this data. Let's say we are creating an online store
that sells oranges. We would want to store the customer orders in an array so we can honor
the first orders before the orders that come later.

Accessing the Array


There are many ways we can access the items within our array.

Let's say we have an array that stores the order data from our market. Here is the array:

Index: 0 1 2 3 4 5
10 3 6 4 5 1
Orders:
Oranges Oranges Oranges Oranges Oranges Orange

In Java our array will look like:

int[] orangeOrders = {10, 3, 6, 4, 5, 1};

Accessing a Single Element:

Our third order index 2 is for 6 oranges, but what if the customer made a mistake and only
wants 3 oranges?

In this case we would access the array, and change the value at index 2 to 6. To do this we
would use:

orangeOrders[2] = 3;

The value at index 2 in our array is set to 3.

Now, let's say orders at index 4 and index 5 paid for an express purchase. We need to
push these two items into our order queue before the rest of our orders. To do this we would
use orangeOrders[4] and orangeOrders[5] , and push them through our queue using
finalizeOrder(order); .

Our code will look like:

201
Using Arrays

finalizeOrder(orangeOrders[4]);
finalizeOrder(orangeOrders[5]);

Iterating Over The Array

It is the end of the day and our store has stopped accepting new orders. Now we need to
send the current array of orders to be finalized. We don't want to access each item in the
array one-by-one and rewrite code. So we will need to iterate over our array using a for loop.
Since we are using a for loop, how do we know how many iterations it should perform? We
use arr.length to see how many items are in our array.

Our code will look something like:

int[] orangeOrders = {10, 3, 6, 4, 5, 1};

for(int i = 0; i < orangeOrders.length; i++)


{
finalizeOrder(orangeOrders[i]);
}

We can also iterate over our array to determine how many oranges have been sold using:

int[] orangeOrders = {10, 3, 6, 4, 5, 1};


int sumOfOranges = 0;

for(var i = 0; i < orangeOrders.length; i++)


{
sumOfOranges += orangeOrders[i];
}

System.out.println("Total oranges sold: " + sumOfOranges);

202
ArrayList Methods

ArrayList Methods
Arrays are amazing tools! Unfortunately, they lack flexibility and useful methods. That's
where ArrayList comes into play. An ArrayList is similar to an Array, except it is resizable and
has more functionality.

ArrayLists
You can think of an ArrayList as a container that will resize as we add and remove objects
from it.

Creating ArrayLists
They way we create an ArrayList varies from the way we create an Array. To create an
ArrayList we use: ArrayList<type> variableName = new ArrayList<type>(); . It is also import
to know ArrayLists can't store primitive types, so we must use Integer for ints and Double
for doubles

Lets say we want to create an ArrayList that holds the grades for a class. Here is an
example of what that code will look like:

203
ArrayList Methods

// Import the ArrayList


import java.util.*;

public class ArrayListExample extends ConsoleProgram


{
public void run()
{
// Create the ArrayList named `classGrades` and set its type to `Integer`
ArrayList<Integer> classGrades = new ArrayList<Integer>();

// Add the grades to our ArrayList


classGrades.add(97);
classGrades.add(50);
classGrades.add(80);
classGrades.add(90);
}
}

Now we want to create a list of students in a classroom. We can use the ArrayList for this as
well:

// Import the ArrayList


import java.util.*;

public class ArrayListExample extends ConsoleProgram


{
public void run()
{
// Create the ArrayList named 'students' and set its type to 'String'
ArrayList<String> students = new ArrayList<String>();

// Add the students to our ArrayList


students.add("Stephen");
students.add("Wezley");
students.add("Wade");
}
}

ArrayList Methods
After creating and populating your ArrayList you can use multiple methods with it.

Adding to an ArrayList

To add a value to an ArrayList you use list.add(elem); . Here is an example using our
classGrades and students ArrayLists:

204
ArrayList Methods

classGrades.add(100);
students.add("Trevor");

Adding at a Specific Index

ArrayLists also allow us to add an item at a specific index using list.add(index, elem); .
Here is an example using our classGrades and students ArrayLists:

classGrades.add(1, 29); // Adds '29' to index 1, and shifts everything right


students.add(2, "Kyle"); // Adds 'Kyle' to index 2, and shifts everything right

Getting a Value

To get a value from your ArrayList you use list.get(index); . Here is an example using our
classGrades and students ArrayLists:

int grade = classGrades.get(2); // Will return `80`


String student = students.get(1); // Will return `Wezley`

Setting a Value

With ArrayLists we can set a specific index's value using list.set(index, value); . Here is
an example using our classGrades and students ArrayLists:

classGrades.set(1, 90); // Will change the value at index 1 to `90`


students.set(0, "Ryan"); // Will change the value at index 0 to `Ryan`

Getting Size of an ArrayList

We can also access the length or size of a specific ArrayList using list.size(); . Here is an
example using our classGrades and students ArrayLists:

int gradeSize = classGrades.size(); // Will return 4


int classSize = students.size(); // Will return 3

Removing From ArrayList

Finally, we can remove a specific item from our ArrayList using list.remove(index); . Here
is an example using our classGrades and students ArrayLists:

classGrades.remove(1); // Removes `50` from `classGrades`


students.remove(0); // Removes `Stephen` from `students`

205
ArrayList Methods

Iterating Over ArrayLists


As with traditional Arrays, we can iterate over ArrayLists.

We can use a regular for loop to iterate over our ArrayList like:

// Loops through `classGrades`


for(int i = 0; i < classGrades.size(); i++)
{
// Prints out our class grades
int grade = classGrades.get(i);
System.out.println(grade);
}

// Loops through `students`


for(int i = 0; i < students.size(); i++)
{
// Prints out our students
String name = students.get(i);
System.out.println(name);
}

We also have the option of using a For Each loop to iterate over our ArrayList like:

// Loops through `classGrades`


for(int grade: classGrades)
{
// Prints out the class grades.
System.out.println(grade);
}

// Loops through `students`


for(String name: students)
{
// Prints the name of our students
System.out.println(name);
}

206
Arrays vs ArrayLists

Arrays vs ArrayLists
Both Arrays and ArrayLists are incredibly useful to programmers, but how do we know when
to use them? While both Arrays and ArrayLists perform similar operations, they are used
differently.

Differences Between Arrays and ArrayLists


One the biggest differences between an Array and ArrayList is expandability. While the size
of an ArrayList can change, an Array is a set size. Other differences include handling types
and getting the size/length.

Getting the Size or Length:

How we retrieve the size or length of an Array or ArrayList varies between the two.

When dealing with an Array we use arr.length to access its length.

With ArrayLists we would use list.size() .

Setting Values at an Index:

Settings values at a given index varies as well.

To set the value of a given index with an Array we use arr[i] = x; .

To set the value of a given index with an ArrayList we use list.set(i, x); .

Getting Values at an Index:

To retrieve values at a given index is as follows:

To get a value at a given index with an Array we use int x = arr[i]; .

To get a value at a given index with an ArrayList we use int x = list.get(i); .

Creating New Instances:

To create new instances of an Array or ArrayList you use:

To create a new instance of an Array we use int[] arr = new int[5]; .

To create a new instance of an ArrayList we use

207
Arrays vs ArrayLists

ArrayList<Integer> list = new ArrayList<Integer>();

Extra Helper Methods:

Only ArrayLists have extra helper methods. These helper methods include: remove, add at
index, clear, and isEmpty.

Types:

Arrays can hold Primitives or Objects.

ArrayLists can only hold Objects, and handles autoboxing and unboxing.

208
2D Arrays (Matrices or Grids)

2D Arrays (Matrices or Grids)


Imagine a video game company contacts you to build Tic-Tac-Toe game. As part of the
game development process, you'd need to figure out a method of storing each player's turn.
How would we achieve this? Java has a two-dimensional array data structure that we can
use. 2D Arrays, also known as Matrices or Grids, can are essentially an "array of arrays."

Creating 2D Arrays
To create a 2D Array, we would use: type[][] name = new type[rows][columns];

Here are some examples:

// Create a 2x4 grid of doubles


double[][] doubleGrid = new double[2][4];

// Create a 5x6 grid of Strings


String[][] stringGrid = new String[5][6];

// Create a 6x10 grid of chars


char[][] charGrid = new char[6][10];

// Create a 3x3 grid of integers


int[][] intGrid = new int[3][3];

// Initializing our Tic-Tac-Toe Grid with X's (1's) as the winner.


int[][] gameBoard = {
{1, 0, 2},
{0, 1, 2},
{0, 0, 1}
};

What 2D Arrays Look Like


If you were to visualize a 2D Array, it would be easiest to think of it like a table of values:

Here is what a 3x3, 2D Array would look like:

209
2D Arrays (Matrices or Grids)

row/col 0 1 2

0 (0, 0) (1, 0) (2, 0)

1 (0, 1) (1, 1) (2, 1)

2 (0, 2) (1, 2) (2, 2)

Where the top and far left rows represent our X and Y indexes.

Utilizing 2D Arrays
Now that we understand what 2D Arrays look like, and how to create them, we can focus on
utilization.

Let's say we have a 3x3 grid, named gameBoard , with the value of our Tic-Tac-Toe game. In
this case, 0 represents a blank space, 1 represents a X, and 2 represents an O.

Here is what our grid looks like with X as the winner:

row/col 0 1 2
0 1 0 2

1 0 1 0
2 2 2 1

Getting an Element:

Let's say we want to access a specific element of our grid. For this, we use: int elem =
grid[row][col]; . With that said, we want to grab the element in the middle of the grid. So we

would use: int elem = gameBoard[1][1]; , which would give us a 1 . Now, we want to get
the element in the top right corner of the canvas. In this case, we use: int elem =
gameBoard[2][0]; and we get 2 .

Setting an Element:

In order to set an element of a grid we use: grid[row][col] = elem; . If we wanted to make


O the winner of our game we would have to set the elements at (0, 0) and (0, 1) to 2 .
In order to do this we would use:

gameBoard[0][0] = 2;
gameBoard[0][1] = 2;

Now our Grid looks like:

210
2D Arrays (Matrices or Grids)

row/col 0 1 2

0 2 0 2
1 2 1 0
2 2 2 1

Getting a Row:

Finally, to get a specific row of a grid, we use int[] row = grid[row]; . If were were to
access the values in the 2nd row of our board, we would use int[] 2ndRow = gameBoard[1]; .

211
Hashmaps

Hashmaps

Hashmaps are helpful tools that allow us to store a key and a value. Unlike Arrays and
Arraylists, Hashmaps allow us to easily look up a value if we know its key.

With that said, let's say you are creating a piece of software that stores student grades for a
class. We want to be able to look up a student's grade by their name, so we will need to use
a Hashmap.

What a Hashmap Looks Like

With Hashmaps we assign a key and a value associated with that key. If we are creating a
piece of software to store student grades, our keys are the students' names and the value is
the grade.

This would look like:

Key Value
Wezley Sherman 85
Wade Adams 95
Julio Rodriguez 84

Trevor Forrey 100


Ada Lovelace 96

Sally Pants 98

Sarah Abe 86

The Key is the element we use to look up a specific Value in the map.
The Value is the result we get when we look up a specific item with a Key.
The Key-Value Pair is the combination of the Key and the Value associated.

It is important to remember that each key can only have one value, and key-value pairs
are not ordered.

Utilizing Hashmaps

212
Hashmaps

Creating Hashmaps:

In order to create a Hashmap we use: Hashmap<key_type, value_type> name = new


Hashmap<key_type, value_type>(); .

If we were to create our grade book Hashmap we would use:

Hashmap<String, Integer> gradeBook = new Hashmap<String, Integer>();

Adding Items:

To add an item to a Hashmap we use: map.put(key, value);

If we were to add grades to our grade book Hashmap we would use:

gradeBook.put("Wezley Sherman", 85);


gradeBook.put("Wade Adams", 95);
gradeBook.put("Julio Rodriguez", 84);
...

Retrieving Items:

To retrieve an item from a Hashmap we use: map.get(key);

Let's say we wanted to access Trevor Forry's and Ada Lovelace's grades. To do so we
would use:

// `adaGrade` would contain `96`


int adaGrade = gradeBook.get("Ada Lovelace");
// `trevGrade` would tonain `100`
int trevGrade = gradeBook.get("Trevor Forrey");

Iterating Over a Hashmap:

Now, let's say we want to print out every grade in our grade book. In order to do this, we
would have to iterate over our Hashmap. Here is an example of what that would look like:

213
Hashmaps

System.out.println("Class Grades: ");

// For each `key` in gradeBook.keySet()


for(String key: in gradeBook.keySet)
{
int grade = gradeBook.get(key);
System.out.println(key + ": " + grade);
}

214
Algorithms and Recursion

Algorithms
Learn the fundamentals of searching and sorting algorithms including sequential search,
binary search, insertion sort, selection sort, and mergesort. Recursion is also introduced.

215
What is an Algorithm?

What is an Algorithm?
An algorithm is a set of steps to follow to solve a particular problem. Programs can perform
specific tasks by following the steps of an algorithm.

Following a Recipe
Algorithms are like recipes in cooking. By following the steps of the recipe, you can create
the desired food. Here's a sample recipe for chocoloate chip cookies, adapted from a
common cookie recipe:

1. Preheat the oven to 350 degrees Fahrenheit.


2. In a mixing bowl, mix the following ingredients together until smooth:
1 cup butter
1 cup white sugar
1 cup brown sugar
3. Beat in 2 eggs, one at a time.
4. Stir in 2 teaspoons vanilla extract.
5. Dissolve 1 teaspoon baking soda in hot water and add to mixture.
6. Stir in the following ingredients:
1/2 teaspoon salt
3 cups flour
2 cups chocolate chips
7. When mixed thoroughly, drop cookie dough onto baking sheet.
8. Bake at 350 degrees Fahrenheit for 10 minutes.

To make delicious cookies, you'll need to follow the steps in the correct order and with the
correct ingredients. What would happen if you used twice as much flour? Or if you put the
cookie dough onto the baking sheet before you mixed it together? Your cookies would most
likely not turn out very well. That's why it is important to follow the steps from start to finish.

Programs as Recipes
Computer programs, like recipes, are designed to accomplish specific tasks. Though a
program may not be baking cookies, it too must follow a specific set of instructions in order
to achieve the desired results.

216
What is an Algorithm?

Though the cookie recipe above is popular, it is certainly not the only chocoloate chip cookie
recipe available. Similarly, there are often many different ways to write a program to solve a
particular problem. Here is a very simplified example of writing a few different methods that
find the average of two numbers:

public double findAverageA(int a, int b)


{
return (double) (a + b) / 2;
}

public double findAverageB(int a, int b)


{
return (a + b) / 2.0;
}

public double findAverageC(int a, int b)


{
int sum = a + b;
int numerator = sum;
int denominator = 2;
double average = (double) numerator / (double) denominator;

average = 15 + average - 15 + 10 - 5 - 3 - 2;

return average;
}

Each of these programs returns the same result:

System.out.println(findAverageA(3, 4));
System.out.println(findAverageB(3, 4));
System.out.println(findAverageC(3, 4));

will print out:

3.5
3.5
3.5

Though the results are the same, there are some important differences. And take a look at
the findAverageC method. It finds the correct solution, but it's doing way more work than the
other algorithms! As the programs you write solve bigger and bigger problems, it becomes
more important to compare the speed and efficiency of different algorithms.

217
What is an Algorithm?

218
Pseudocode

Pseudocode
Pseudocode is a brief explanation of code in plain English.

Writing pseudocode is a good way to map out your ideas for a program before actually
writing the real code. It can help you think about the function decomposition, the top down
design, and the structure of a program.

Here are some examples of pseudocode:

Pseudocode to put down 10 tennis balls

repeat 10 times:
put ball

Pseudocode to draw a tower on every avenue in a Karel world.

while front is clear:


build tower
move
build last tower

Then, you can also pseudocode the build tower part like this:

build tower:
turn left
repeat 3 times:
put ball and move
turn around
move down
turn left

Writing out algorithms in pseudocode allows you to focus on the structure and important
ideas of the program without worrying about syntax. Once you have a good idea of the
program written in pseudocode, writing the actual program is simply a matter of turning the
pseudocode into Java code.

219
Linear Search

Linear Search
Searching for items in an array is an important and common task in computer science. For
example, a meterologist may want to konw the hottest day on record in a fiven month.
Teachers may want to find a particular student in a class roster. A skateboard shop may
want to check their inventory to see if they have a certain deck in stock. Storing data in a
computer allows information like this to be easily searched and retrieved.

Introducing Linear Search


One way to search through a list of items is to start at the beginning of the list and continue
through the list until the desired item is found. If the desired item is not found, then that
means it is not in the list.

Suppose that you are given a set of raffle tickets at a school raffle. Each ticket has its own
number on it. Your tickets may look like this:

Ticket 0 1 2 3 4 5
Number 44 53 12 51 64 15

The 0th ticket has number 144, and the ticket at index 4 has raffle number 64. The school
will randomly select a number between 1 and 100. If you have the ticket with that number,
you win!

What if the school picks 51 as the winning number? As a human, it's easy to look over the
whole list and see that you have the ticket with 51 on it. But computers can't look over a
whole list the way a human can. Computers need a more programmatic approach to looking
through the list.

Implementing Linear Search


Linear search isn't too difficult to implement. To programmatically searching our list of raffle
ticket numbers, we just need to iterate through the list one number at a time. At each new
number, if the number matches the desired number, we know that the desirred number is in
the list, so we can stop searching and return the index position of the number. If we make it
all the way to the end of the list and haven't spotted our desired number, then that means it's
not in the list.

220
Linear Search

Here's what it looks like in pseudocode:

for every index in the list:


get the current number at that index position
if the current number matches our target number:
return the index
return not found

We can then turn that pseudocode into real Java code:

/**
* This method takes an array called array and a
* key to search for, and returns the index of
* key if it is in the array or -1 if it is not
* found.
*/
public int linearSearch(int[] array, int key)
{
for(int i = 0; i < array.length; i++)
{
int element = array[i];
if(element == key)
{
return i;
}
}
return -1;
}

221
Binary Search

Binary Search
Linear search is a fantastic implementation of a search algorithm, but it assumes the list is
not sorted. Using a binary search algorithm, we can skip half of the list and return what we
are looking for much faster.

How it Works

Using binary search, we will choose high and low indexes. The algorithm will then grab the
element in the middle index and compare it to what we are searching for. If the element is
smaller than our key, we discard the half that is larger, and vice versa. Finally, we search
through the remaining half of our list until we come across the key.

How it Looks

Here is an example of a binary search algorithm:

222
Binary Search

public class BinarySearch extends ConsoleProgram


{
public void run()
{
// Create our array of numbers
int[] listNums = {1, 2, 3, 4, 5, 10, 20};

// Designate a key to search for


int numKey = 10;

// Assign our high and low indexes


int low = 0;
int high = listNums.length-1;

// Start iterating over the array to search for our key


while(low <= high)
{
int mid = (low + high)/2;

if(listNums[mid] == numKey)
{
return mid;
}
else if(listNums[mid] < number)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
}
}

223
Selection Sort

Selection Sort
Let's say we are working on a statistics package that returns the median value of an array.
The problem we run into is that the numbers in the array aren't sorted. First we must sort the
numbers in the array from smallest to largest. Using Selection Sort is one way to sort the
numbers in this array.

How it works

Selection Sort will sort the numbers in our array using loops to iterate over the arrays as we
sort one number at a time. Each time the loop iterates we look for the smallest value left in
the unsorted chunk and sort it.

How it looks

Here is an example of what a Selection Sort algorithm looks like:

224
Selection Sort

/* This is a Selection Sort example with an array of


* integers. This will iterate over our array, and
* look for the smallest values. It will rearrange
* our values from smallest to largest
*/
public class SelectionSort extends ConsoleProgram
{
public void run()
{
// Create our array of numbers
int[] intsToOrder = {10, 3, 6, 4, 5, 1};

// Create minimum index, and temporary value variables


int minIndex = 0;
int tmpValue = 0;

// Loop through the number array and set minIndex to i


for(int i = 0; i < intsToOrder.length - 1; i++)
{
minIndex = i;
// Loop through the array again, and compare each value to
// the value at `minIndex`. Set `minIndex` to `j` if it's smaller.
for(int j = i + 1; j < intsToOrder.length; j++)
{
if(intsToOrder[j] < intsToOrder[minIndex])
{
minIndex = j;
}
}

// Swap the value in spot `i` with the value in


// `minIndex`
tmpValue = intsToOrder[minIndex];
intsToOrder[minIndex] = intsToOrder[i];
intsToOrder[i] = tmpValue;
}
}
}

225
Insertion Sort

Insertion Sort
Insertion Sort is another sorting algorithm that we can use to sort arrays. Going back to the
statistics package example discussed in the previous chapter, we can use Insertion Sort to
sort our array of integers so that we can find the median value.

How it works

As with Selection Sort, Insertion Sort uses loops to iterate over the array. However, there is
an important difference: while Selection Sort searches for the smallest element on each
iteration, Insertion Sort immediately puts each element into its designated position as it
iterates over the array.

What it looks like

Here is an example of what an Insertion Sort algorithm looks like:

226
Insertion Sort

// Note: In some cases the list may be sorted in reverse order.

public class InsertionSort extends ConsoleProgram


{
public void run()
{
// Create our array of integers to sort
int[] intsToSort = {1, 5, 6, 3};

// We start at `1` instead of `0`


// because first value is already sorted
for(int i = 1; i < intsToSort.length; i++)
{
int currNum = intsToSort[i];

// Shift element into designated position


int currIndex = i-1;
while(currIndex > -1 && intsToSort[currIndex] > currNum)
{
intsToSort[currIndex+1] = intsToSort[currIndex];
currIndex--;
}
intsToSort[currIndex+1] = currNum;
}
}
}

227
Advanced: Recursion

Advanced: Recursion
Recursion is when you break down a given problem into smaller problems of the same
instance. The goal is to break down the problems into smaller forms so that they become
easier to solve.

In computer science, recursion is when a method calls itself to solve a given problem.

What Recursion Looks Like

Source: https://prateekvjoshi.com/2013/10/05/understanding-recursion-part-i/

228
Advanced: Recursion

Source: https://en.wikipedia.org/wiki/Tower_of_Hanoi

Recursion is an important part of Computer Science, because it allows us to condense our


code into a simple, easy to read, form.

Parts of a Recursive Method


Base Case:
The Base Case is the terminating case in a recursive problem. This case does not use
recursion, because it is the simplest form of the problem. The Base Case causes the
method to terminate. If we don't have a Base Case the recursive method would continue
indefinitely.

Recursive Case:
The Recursive Case is the step, or set of steps, that reduces all the other cases as the
Recursive Algorithm gets closer to the Base Case.

Recursive Algorithm:
The Recursive Algorithm is a finite set of steps that calls itself with simpler inputs, as the
algorithm approaches the Base Case.

Examples of Recursion
Some common examples of recursive solutions include Factorials and the Fibonacci
Sequence. Other examples of recursive solutions include: Tower of Hanoi, Golden Ratio,
Catalan Numbers, and Computer Compound Interest.

Factorials and Recursion:


One common way to solve for factorials use to use a for loop. Here is one example:

229
Advanced: Recursion

private int factorial(int n)


{
int res = 1;
for(int i = n; i > 0; i--)
{
res *= i;
}
return res;
}

While this solution definitely works, we can simply it using recursion. Looking at the formula
for factorials: n * (n-1) * (n-2) * (n-3)...

we can see a recurrence relation of:

n!: 1 for n = 0,
(n-1)! * n for n > 0

Looking at this from a programming point of view, this means: factorial(0); = 1 , and
factorial(n); = factorial(n-1) * n;

Base Case:

Since factorial(0); is the simplest form we can achieve, it is our base case. This means
we want to keep calling our factorial(); method until the input is equal to 0 .

Recursive Case:

Given that factorial(0); is our Base Case we can conclude that factorial(n) =
factorial(n - 1) * n; is our Recursive Case.

Now that we have our Base Case and Recursive Case we can construct our recursive
method:

private int factorial(int n)


{
// Our Base Case
if(n == 0)
{
return 1;
}

// Our Recursive Case


return factorial(n - 1) * n;
}

230
Advanced: Recursion

Fibonacci Sequence and Recursion:


The Fibonacci Sequence is achieved by adding up the two previous numbers to get the next
number. The sequence looks like: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...

The recurrence relation for the Fibonacci Sequence is:

F(n) = F(n - 1) + F(n - 2)

Given this formula, and looking at the sequence we can conclude that F(0) = 1 and F(1) =
1

From a programming point of view, this means fibonacci(0) = 1 , fibonacci(1) = 1 , and


fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)

Base Case:

Since fibonacci(0) = 1 and fibonacci(1) = 1 are the simplest forms we can achieve,
these are our Base Cases.

Recursive Case:

Now that we know our Base Cases, we are left with fibonacci(n) = fibonacci(n-1) +
fibonacci(n-2) . This is our Recursive Case.

Now that we have our Base Cases and Recursive Case we can construct our recursive
method:

private int fibonacci(int num)


{
// Our Base Cases
if(num == 0 || num == 1)
{
return 1;
}

// Our Recursive Case


return fibonacci(num-1) + fibonacci(num-2);
}

The Humor of Recursion


Sometimes recursion is used as the subject of humor for mathematicians and computer
scientists. One of the most famed examples of humorous recursion can be seen by going to
Google and searching: "recursion."

231
Advanced: Recursion

232
Mergesort

Mergesort
Mergesort is an extremely efficient sorting algorithm, compared to selection and insertion.
Mergesort utilizes recursion to achieve efficient sorting of lists.

How it works
Mergesort uses what is known as a "Divide and Conquer" strategy. This means mergesort
divides the problem into smaller parts until the array length is equal to one. Then it merges
together adjacent arrays and sorts them until the whole list is sorted.

Lets see this in action:

Here is another example:

Mergesort in Java
Here is what mergesort looks like in Java:

import java.util.Arrays;

233
Mergesort

public class MyProgram extends ConsoleProgram


{
public void run()
{
int[] array1 = {7, 9, 10, 11, 20, 50, 10, 5, 3, 1, 2};
int[] array2 = {8, 9, 4, 2, 4, 5, 1};

System.out.print("First array: ");


System.out.println(Arrays.toString(array1));
System.out.print("Second array: ");
System.out.println(Arrays.toString(array2));
System.out.println();

mergeSort(array1);
mergeSort(array2);

System.out.println("After mergesort: ");


System.out.print("First array sorted: ");
System.out.println(Arrays.toString(array1));
System.out.print("Second array sorted: ");
System.out.println(Arrays.toString(array2));
}

public int[] mergeSort(int[] list)


{
if(list.length > 1)
{
int firstHalf = list.length/2;
int secondHalf = list.length - firstHalf;
int[] listOne = new int[firstHalf];
int[] listTwo = new int[secondHalf];

System.arraycopy(list, 0, listOne, 0, firstHalf);


System.arraycopy(list, firstHalf, listTwo, 0, secondHalf);

mergeSort(listOne);
mergeSort(listTwo);

merge(listOne, listTwo, list);


}
return list;
}

public void merge(int[] listOne, int[] listTwo, int[]finalList)


{
int indexOne = 0;
int indexTwo = 0;

int resultPos = 0;

while(indexOne < listOne.length && indexTwo < listTwo.length)


{

234
Mergesort

if(listOne[indexOne] < listTwo[indexTwo])


{
finalList[resultPos] = listOne[indexOne];
indexOne++;
}
else
{
finalList[resultPos] = listTwo[indexTwo];
indexTwo++;
}
resultPos++;
}
System.arraycopy(listOne, indexOne, finalList, resultPos, listOne.length - ind
exOne);
System.arraycopy(listTwo, indexTwo, finalList, resultPos, listTwo.length - ind
exTwo);
}
}

Here is what this looks like in the editor:

Extra Notes

235
Mergesort

It is important to know that if you utilize mergesort you will need to have extra space for
temporary storage.

Mergesort is also recursive, meaning it calls upon itself.

In a more advanced setting we can observe that the runtime complexity of mergesort is
O(nlogn) . This means that mergesort is a linear (n), and the operation occurs in log(n)

steps.

236

You might also like