Apjava
Apjava
Apjava
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
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:
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
6
Introduction to Programming with Karel
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 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.
move();
putBall();
takeBall();
turnLeft();
7
Introduction to Programming with Karel
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.
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 .
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.
move();
move();
putBall();
move();
move();
9
More Basic Karel
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
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.
14
More Basic Karel
Here is the solution. The comments explain which direction Karel ends up facing after each
turnLeft(); command.
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
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.
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.
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
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.
When we run this program, Karel will simply move forward one spot.
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
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.
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:
We write all of our commands within the method body; this is the area between the opening
and closing curly brackets ( {} ).
20
Karel Can't Turn Right
While this solution works, we aren't using a turnRight() method. Let's fix that.
21
Karel Can't Turn Right
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
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.
Naming is crucial
Here is another example:
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: 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.
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
Now that we have defined our method, we can call it in the run() method.
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
There are a few basic principles to follow to know when to create a new method:
This leads us to the next discussion - what does it mean to have a specific task or a smaller
problem?
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
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.
See how each method is reusable? We will need to use the first method 3 times and the
second method 2 times.
30
Top Down Design and Decomposition in Karel
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
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 ______.
*/
32
Commenting Your Code
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.
/*
* 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();
}
}
/* 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();
}
34
Commenting Your Code
Full Example:
/*
* 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 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!
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
Example Two
This time, we want to have Karel move, put down a ball, and move again.
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.
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(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:
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();
}
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
Given these changing conditions, there are many questions that would be useful for Karel to
ask. For example:
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:
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.
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:
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/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:
49
If/Else Statements
Else statements have no conditions, i.e., there are no parentheses following the "else"
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();
}
*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
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.
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.
52
Control Structures Example
53
How To Indent Your Code
// 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.
57
Printing in Java
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
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; )
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 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
Char Type:
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:
Boolean Type:
In Java we declare a boolean using boolean before the variable name. Here are a couple of
examples:
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:
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 names, after the first character, can contain letters, numbers, or other
characters.
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.
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:
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
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:
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:
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
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)
Addition Operator
Subtraction Operator
65
Arithmetic Expressions
Multiplication Operator
Division Operator
66
Arithmetic Expressions
Modulus Operator
The modulus operator allows us to divide two numbers, and get the remainder.
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
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
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
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
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.
double x = 2;
int y = 5;
Arithmetic Shortcuts
There are shortcuts available when performing arithmetic expressions.
68
Arithmetic Expressions
69
Casting
Casting
Casting allows us to change a variable's type to better suit our needs.
To change a variable's type we just add the type in between parentheses to cast it.
70
Casting
We can get the correct answer by casting one of the variables to a double.
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.
We first want to declare the variable, loggedIn , and set it to true or false.
72
Booleans
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 :
73
Logical Operators
Logical 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 example below sets up a variable hungry as being true. Then it prints out NOT
hungry .
p !p
true false
false true
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.
p q p AND q
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.
75
Logical Operators
p q p OR q
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
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.
77
Comparison Operators
// 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;
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
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:
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.
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.
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
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.
Output:
82
For Loops
0
2
4
6
8
10
12
14
16
18
20
Output:
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:
84
While Loops
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:
System.out.println("Initiating countdown:");
while(i >= 0)
{
System.out.println(i + "...");
}
}
}
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.
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
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:
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
You can have as many else if statements as you want. There is no limit!
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
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.
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.
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.
92
If Statements
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?
while(true)
{
// code to execute
}
while(true)
{
// code to execute
if(condition)
{
// if the condition is true, stop looping
break;
}
}
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 :
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 .
Loop-and-a-Half:
95
Loop-and-a-Half
while(true)
{
int num = readInt("Enter an integer: ");
if(num == SENTINEL)
{
break;
}
System.out.println(num);
}
System.out.println("Done!");
}
}
Repeated code:
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:
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
After running the program, the concatenated String "McDonalds" gets printed to the screen.
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:
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
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:
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:
By removing the == and comparing the two Strings with the proper .equals() method, our
program now works as expected:
101
Strings
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
System.out.println("Tre flip");
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
System.out.println("Tre flip");
drawSkateboard();
System.out.println("180 no-comply");
drawSkateboard();
}
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
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.
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.
108
Methods and Parameters
addTen(5);
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:
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);
100
1635
86
109
Methods and Parameters
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:
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:
-------------
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
Keeping Results
Recall the addTen method from the previous chapter:
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.
112
Methods and Return Values
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.
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
We can now call the method and store its return values
114
Javadoc and More Methods
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:
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.
String Review
Let's review some key points about Strings:
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.
118
Strings Methods
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.
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
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?
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.
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
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
Always make sure to stay within a String's total index range to avoid these errors!
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
Output:
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.
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.
124
Strings Methods
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:
125
Strings and Characters
Strings characters
Type: String Type: char
Object primitive
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.
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!
128
Strings and Characters
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:
Looks good!
130
Strings and Characters
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
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:
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:
\\ backslash
So what is the reason for having these escape sequences? Their purpose is illustrated in the
example program below:
// 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);
}
}
134
Strings and Characters
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.
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
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
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.
if(Character.isUpperCase(ch))
{
System.out.println("It is uppercase!");
}
else
{
System.out.println("It is not uppercase");
}
}
}
137
Strings and Characters
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
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.
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:
We can use this as a guideline to write many different types of String processing methods.
Take this as an example:
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
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:
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
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.
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.
142
String Processing
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
}
/**
* 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
/**
* 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.
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
146
Introduction To Classes and 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
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
return rectInfo;
}
}
Animal Class
Here is another example of a class that lets us create new animal objects:
148
Introduction To Classes and Objects
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
Creating Objects
When creating a new object from a class you will use the following format:
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);
152
Introduction To Classes and Objects
153
Classes vs. Objects
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.
Examples
154
Classes vs. Objects
155
Using a Class as a Client
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.
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.
(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
(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
{
...
}
...
...
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:
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
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:
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:
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:
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:
161
Writing Classes
Notice how the toString method returns a String . So to print out a Dog object, you
would go like this:
162
Writing Classes and Instance Methods
the area of our rectangle object. It is important to remember that instance methods belong
to the specific instance of your object.
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 parameters is the list of our parameters, or the information we give to the method.
163
Writing Classes and Instance Methods
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).
164
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
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:
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
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:
166
Class Methods and Class Variables
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.
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:
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 Skater()
{
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.
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
171
Key Terms for Classes
What is an Object?
An object is something that contains both state and behavior. It is an instance of a class.
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.
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.
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:
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.
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
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.
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:
The values of objects, however, cannot be compared with the == . Instead, objects are
compared with a .equals method. For example:
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
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
It is important to know that the subclass inherits everything from the super class. This
includes: classes, methods, and fields.
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:
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.
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:
Subclass:
Test Class:
179
Inheritance
180
Class Design and Abstract Classes
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.
181
Class Design and Abstract Classes
In order to create an abstract class you must add the keyword: abstract to the class
declaration.
182
Class Design and Abstract Classes
{
private double gasTankCapacity;
private double milesPerTank;
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:
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.
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
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
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
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
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.
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.
Now, let's take a look at an example class which implements our interface:
192
Interfaces
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.
193
Interfaces
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?
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.
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).
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.
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
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.
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
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:
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:
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.
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
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;
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); .
201
Using Arrays
finalizeOrder(orangeOrders[4]);
finalizeOrder(orangeOrders[5]);
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.
We can also iterate over our array to determine how many oranges have been sold using:
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
Now we want to create a list of students in a classroom. We can use the ArrayList for this as
well:
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");
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:
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:
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:
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:
Finally, we can remove a specific item from our ArrayList using list.remove(index); . Here
is an example using our classGrades and students ArrayLists:
205
ArrayList Methods
We can use a regular for loop to iterate over our ArrayList like:
We also have the option of using a For Each loop to iterate over our ArrayList like:
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.
How we retrieve the size or length of an Array or ArrayList varies between the two.
To set the value of a given index with an ArrayList we use list.set(i, x); .
207
Arrays vs ArrayLists
Only ArrayLists have extra helper methods. These helper methods include: remove, add at
index, clear, and isEmpty.
Types:
ArrayLists can only hold Objects, and handles autoboxing and unboxing.
208
2D Arrays (Matrices or Grids)
Creating 2D Arrays
To create a 2D Array, we would use: type[][] name = new type[rows][columns];
209
2D Arrays (Matrices or Grids)
row/col 0 1 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.
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:
gameBoard[0][0] = 2;
gameBoard[0][1] = 2;
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.
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.
Key Value
Wezley Sherman 85
Wade Adams 95
Julio Rodriguez 84
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:
Adding Items:
Retrieving Items:
Let's say we wanted to access Trevor Forry's and Ada Lovelace's grades. To do so we
would use:
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
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:
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:
average = 15 + average - 15 + 10 - 5 - 3 - 2;
return average;
}
System.out.println(findAverageA(3, 4));
System.out.println(findAverageB(3, 4));
System.out.println(findAverageC(3, 4));
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.
repeat 10 times:
put ball
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.
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.
220
Linear Search
/**
* 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
222
Binary Search
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
224
Selection Sort
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.
226
Insertion Sort
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.
Source: https://prateekvjoshi.com/2013/10/05/understanding-recursion-part-i/
228
Advanced: Recursion
Source: https://en.wikipedia.org/wiki/Tower_of_Hanoi
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.
229
Advanced: Recursion
While this solution definitely works, we can simply it using recursion. Looking at the formula
for factorials: n * (n-1) * (n-2) * (n-3)...
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:
230
Advanced: Recursion
Given this formula, and looking at the sequence we can conclude that F(0) = 1 and F(1) =
1
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:
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.
Mergesort in Java
Here is what mergesort looks like in Java:
import java.util.Arrays;
233
Mergesort
mergeSort(array1);
mergeSort(array2);
mergeSort(listOne);
mergeSort(listTwo);
int resultPos = 0;
234
Mergesort
Extra Notes
235
Mergesort
It is important to know that if you utilize mergesort you will need to have extra space for
temporary storage.
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