100% found this document useful (1 vote)
1K views

Introduction To Java

- Java is a popular programming language released in 1995 by Sun Microsystems. It is known for being simple, portable, secure, and robust. - The Java Virtual Machine allows Java code to run on different operating systems and platforms. Programmers write Java code once and it can run anywhere. - Comments are included in Java code to provide explanations for human readers, not the computer. They are prefixed with // for single-line comments and /* */ for multi-line comments.

Uploaded by

veronica1071985
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Introduction To Java

- Java is a popular programming language released in 1995 by Sun Microsystems. It is known for being simple, portable, secure, and robust. - The Java Virtual Machine allows Java code to run on different operating systems and platforms. Programmers write Java code once and it can run anywhere. - Comments are included in Java code to provide explanations for human readers, not the computer. They are prefixed with // for single-line comments and /* */ for multi-line comments.

Uploaded by

veronica1071985
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 150

Introduction to Java

Welcome to the world of Java programming!

Programming languages enable humans to write instructions that a computer can perform. With precise
instructions, computers coordinate applications and systems that run the modern world.

Sun Microsystems released the Java programming language in 1995. Java is known for being simple,
portable, secure, and robust. Though it was released over twenty years ago, Java remains one of the
most popular programming languages today.

One reason people love Java is the Java Virtual Machine, which ensures the same Java code can be run
on different operating systems and platforms. Sun Microsystems’ slogan for Java was “write once, run
everywhere”.
Programming languages are composed of syntax, the specific instructions which Java understands. We
write syntax in files to create programs, which are executed by the computer to perform the desired
task.

Let’s start with the universal greeting for a programming language. We’ll explore the syntax in the next
exercise.

Instructions

1.

You’re looking at a computer program written in Java.

Run the code in the text editor to see what is printed to the screen.
Hello Java File!
Java runs on different platforms, but programmers write it the same way. Let’s
explore some rules for writing Java.

In the last exercise, we saw the file HelloWorld.java. Java files have


a .java extension. Some programs are one file, others are hundreds of files!

Inside HelloWorld.java, we had a class:

public class HelloWorld {

}
We’ll talk about classes more in the future, but for now think of them as
a single concept.

The HelloWorld concept is: Hello World Printer. Other class concepts could be:
Bicycle, or: Savings Account.

We marked the domain of this concept using curly braces: {}. Syntax inside
the curly braces is part of the class.

Each file has one primary class named after the file. Our class
name: HelloWorld and our file name: HelloWorld. Every word is capitalized.

Inside the class we had a main() method which lists our program tasks:


public static void main(String[] args) {

}
Like classes, we used curly braces to mark the beginning and end of a method.

public, static,and void are syntax we’ll learn about in future lessons. String[]


args is a placeholder for information we want to pass into our program. This
syntax is necessary for the program to run but more advanced than we need
to explore at the moment.

Our program also displayed the text "Hello World" on the screen. This was
accomplished using a print statement:

System.out.println("Hello World");
We’ll learn more about print statements in the next exercise!

Instructions

1.
The text editor has a file, HelloYou.java, that contains a HelloYou class with
a main() method.

Inside main(), add a statement which prints Hello someName!, with your name


replacing someName. Make sure to end the statement with a semicolon.

For example, if your name were “Maria,” the program would print Hello Maria!.

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

Print Statements
Let’s take a closer look at this instruction from our previous program:
System.out.println("Hello World");
Print statements output information to the screen (also referred to as the
output terminal). Let’s break this line of code down a little more. Don’t worry if
some of the terms here are new to you. We’ll dive into what all of these are in
much more detail later on!

 System is a built-in Java class that contains useful tools for our programs.
 out is short for “output”.
 println is short for “print line”.

We can use System.out.println() whenever we want the program to create a


new line on the screen after outputting a value:

System.out.println("Hello World");
System.out.println("Today is a great day to code!");
After "Hello World" is printed, the output terminal creates a new line for the
next statement to be outputted. This program will print each statement on a
new line like so:

Hello World
Today is a great day to code!
We also can output information using System.out.print(). Notice that we’re
using print(), not println(). Unlike System.out.println(), this type of print
statement outputs everything on the same line. For example:

System.out.print("Hello ");
System.out.print("World");
The above code will have the following output:

Hello World
In this example, if you were to use print() or println() again, the new text will
print immediately after World on the same line. It’s important to remember
where you left your program’s “cursor”. If you use println() the cursor is
moved to the next line. If you use print() the cursor stays on the same line.

Note: Going forward, all exercises will use System.out.println() to output


values.
Instructions

1.
Inside main() and underneath the print statement System.out.println("Let's
play hide and seek.");, output the following two statements
using System.out.print():

 "Three..."
 "Two..."

Stuck? Get a hint


2.
Underneath your previous statements, output the following two text values
using System.out.println():

 "One..."
 "Ready or not, here I come!"

Commenting Code
Writing code is an exciting process of instructing the computer to complete
fantastic tasks.

Code is also read by people, and we want our intentions to be clear to humans
just like we want our instructions to be clear to the computer.

Fortunately, we’re not limited to writing syntax that performs a task. We can
also write comments, notes to human readers of our code. These comments
are not executed, so there’s no need for valid syntax within a comment.

When comments are short we use the single-line syntax: //.

// calculate customer satisfaction rating


When comments are long we use the multi-line syntax: /* and */.

/*
We chose to store information across multiple databases to
minimize the possibility of data loss. We'll need to be careful
to make sure it does not go out of sync!
*/
Another type of commenting option is the Javadoc comment which is
represented by /** and */. Javadoc comments are used to create
documentation for APIs (Application Programming Interfaces). When writing
Javadoc comments, remember that they will eventually be used in the
documentation that your users might read, so make sure to be especially
thoughtful when writing these comments.

Javadoc comments are typically written before the declaration of fields,


methods, and classes (which we’ll cover later in this course):

/**
* The following class accomplishes the following task...
*/
Here’s how a comment would look in a complete program:

/**
* The following class shows what a comment would look like in
a program.
*/
public class CommentExample {
  // I'm a comment inside the class
  public static void main(String[] args) {
    // I'm a comment inside a method
    System.out.println("This program has comments!");
  }
}
Comments are different from printing to the screen, when we
use System.out.println(). These comments won’t show up in our terminal,
they’re only for people who read our code in the text editor.

Instructions

1.
The file Timeline.java has plain text information about Java.

Plain text facts aren’t valid syntax. We’ll use comments to avoid breaking the
program.
Use the single-line comment syntax for the first fact.

Change this line into a comment:

Sun Microsystems announced the release of Java in 1995


Stuck? Get a hint
2.
Our program is still broken!

Use the multi-line syntax to make these lines into a single comment:

    James Gosling is a Canadian engineer who created Java while


    working at Sun Microsystems. His favorite number is the
    square root of 2!
You should still see You are a fun language! printed!

Timeline.java

public class Timeline {
  public static void main(String[] args) {
    System.out.println("Hello Java!");
    
    System.out.println("You were born in 1995");

    Sun Microsystems announced the release of Java in 1995
    
    System.out.println("You were created by James Gosling");
    
    James Gosling is a Canadian engineer who 
    created Java while working at Sun Microsystems. 
    His favorite number is the square root of 2!
    
    System.out.println("You are a fun language!");
  }

Semicolons and Whitespace


As we saw with comments, reading code is just as important as writing code.

We should write code that is easy for other people to read. Those people can
be co-workers, friends, or even yourself!

Java does not interpret whitespace, the areas of the code without syntax, but
humans use whitespace to read code without difficulty.

Functionally, these two code samples are identical:

System.out.println("Java");System.out.println("Lava");System.o
ut.println("Guava");
System.out.println("Java");

System.out.println("Lava");

System.out.println("Guava");
They will print the same text to the screen, but which would you prefer to
read? Imagine if it was hundreds of instructions! Whitespace would be
essential.

Java does interpret semicolons. Semicolons are used to mark the end of


a statement, one line of code that performs a single task.

The only statements we’ve seen so far are System.out.println("My message!");.

Let’s contrast statements with the curly brace, {}. Curly braces mark the scope
of our classes and methods. There are no semicolons at the end of a curly
brace.

Instructions

1.
The LanguageFacts.java file prints information about Java to the screen.

Unfortunately, the writer of the file has avoided using whitespace.

Make the file easier to read by adding a newline after each statement!
Stuck? Get a hint
2.
Inside main(), add a new statement printing how you feel about coding.

Start the message with: “Programming is… “.

Remember to place a semicolon at the end of the statement!

LanguageFacts.java

public class LanguageFacts {
  public static void main(String[] args) {
    // Press enter or return on your keyboard after each semicolon!
    
    System.out.println("Java is a class-based language.
");System.out.println("Java classes have a 'main' method.");System.out.println("
Java statements end with a semicolon.");
  }
}

Compilation: Catching Errors


Java is a compiled programming language, meaning the code we write in
a .java file is transformed into byte code by a compiler before it is executed by
the Java Virtual Machine on your computer.

A compiler is a program that translates human-friendly programming


languages into other programming languages that computers can execute.

Previous exercises have automatically compiled and run the files for you. Off-
platform development environments can also compile and run files for you,
but it’s important to understand this aspect of Java development so we’ll do it
ourselves.

The compiling process catches mistakes before the computer runs our code.

The Java compiler runs a series of checks while it transforms the code. Code
that does not pass these checks will not be compiled.

This exercise will use an interactive terminal. Codecademy has a lesson on the
command line if you’d like to learn more.

For example, with a file called Plankton.java, we could compile it with the


terminal command:

javac Plankton.java
A successful compilation produces a .class file: Plankton.class, that we
execute with the terminal command:

java Plankton
An unsuccessful compilation produces a list of errors. No .class file is made
until the errors are corrected and the compile command is run again.

Instructions

1.
Let’s practice compiling and executing a file by entering commands in the
terminal!

Our text editor contains a broken program so we can see how compilers help
us catch mistakes. Don’t make any corrections!

In the terminal, type this command: javac Compiling.java and


press  enter  or  return .

Then click the Check Work button to check your work and move on to the
next checkpoint.
Stuck? Get a hint
2.
Do you see the error?

The compiler is telling us one of the print statements is missing a semicolon.

In the terminal, type ls and press  return  or  enter.

ls is short for "list" and this command lists all the available files.

There is only one file: Compiling.java, we did not successfully compile the file
because of the error.

Click the Check Work button to move on to the next checkpoint.


Stuck? Get a hint
3.
Add the missing semicolon in the text editor, then click the Check
Work button.

We’ll compile and execute this file in the next exercise!

Compiling.java

ublic class Compiling {
  public static void main(String[] args) {
    
    System.out.println("Java is a class-based language.");
    System.out.println("Java classes have a 'main' method.");
    System.out.println("Java statements end with a semicolon.")

    System.out.println("Programming is... fun!");
    
  }
}

Compilation: Creating Executables


Compilation helped us catch an error. Now that we’ve corrected the file, let’s
walk through a successful compilation.
As a reminder, we can compile a .java file from the terminal with the
command:

javac Whales.java
If the file compiles successfully, this command produces
an executable class: FileName.class. Executable means we can run this
program from the terminal.

We run the executable with the command:

java Whales
Note that we leave off the .class part of the filename.

Here’s a full compilation cycle as an example:

// within the file: Welcome.java


public class Welcome {
  public static void main(String[] args) {
    System.out.println("Welcome to Codecademy's Java course!");
  }
}
We have one file: Welcome.java. We compile with the command:

javac Welcome.java
The terminal shows no errors, which indicates a successful compilation.

We now have two files:

1. Welcome.java, our original file with Java syntax.


2. Welcome.class, our compiled file with Java bytecode, ready to be
executed by the Java Virtual Machine.

We can execute the compiled class with the command:

java Welcome
The following is printed to the screen:

Welcome to Codecademy's Java course!

Instructions
1.
Let’s compile and execute our program!

Run the ls command in the terminal to see the uncompiled .java file.


Stuck? Get a hint
2.
Compile the file from the terminal!
Stuck? Get a hint
3.
Enter ls again to see the new .class file.

Run the executable file from the terminal!

Java Review: Putting It All Together


In this lesson, we’ve started writing our first programs in Java.

We’ve also learned rules and guidelines for how to write Java programs:

 Java programs have at least one class and one main() method.


o Each class represents one real-world idea.
o The main() method runs the tasks of the program.
 Java comments add helpful context to human readers.
 Java has whitespace, curly braces, and semicolons.
o Whitespace is for humans to read code easily.
o Curly braces mark the scope of a class and method.
o Semicolons mark the end of a statement.
 Java is a compiled language.
o Compiling catches mistakes in our code.
o Compilers transform code into an executable class.

Instructions

1.
The text editor holds an empty file named Review.java. Fill it in!

Define a public class named Review.


Use opening and closing curly braces for the scope of the class.

Remember, no semicolons for classes or methods!


Hint
We define a class in Java like so:

public class MyClass {


  // class code goes here
}
2.
This code produces an error because Java programs need a main() method.

Define the main() method within the curly braces of the Review class.


Hint
Every Java program has one main() method with the following signature:

public static void main(String[] args) {


  // method code goes here
}
3.
Inside of the curly braces for the main() method, write The main method executes
the tasks of the class as a single-line comment.
Hint
We create a single-line comment like so:

// Just a brief comment


4.
Below the comment, write a statement that prints the following: My first Java
program from scratch!.
Hint
We can print a statement with the following syntax:

System.out.println("Blah blah blah");

Java programs have a specific structure in how the code is written. There
are key elements that all Java programs share.
The Program
We have the text of a program inside the file called HelloWorld.java.

// This program outputs the message "Hello World!" to the


monitor

public class HelloWorld {


  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}
This program writes Hello World! to your terminal when run.

Case-Sensitivity

Java is a case-sensitive language. Case sensitivity means that syntax, the


words our computer understands, must match the case. For example, the
Java command for outputting text to the screen is System.out.println(). If
you were to type system.out.println() or System.Out.println(), the
compiler would not know that your intention was to use System or out.

Let’s go over this HelloWorld.java program line by line:

Comments

// This program outputs the message "Hello World!" to the


monitor
This is a single-line comment that documents the code. The compiler will
ignore everything after // to the end of the line. Comments provide
information outside the syntax of the language.

Classes

public class HelloWorld { 


  // class code
}
This is the class of the file. All Java programs are made of at least one
class. The class name must match the file: our file
is HelloWorld.java and our class is HelloWorld. We capitalize every word,
a style known as pascal case. Java variables and methods are named in a
similar style called camel case where every word after the first is
capitalized.

The curly braces, { and }, mark the scope of the class. Everything inside


the curly braces is part of the class.

Methods

  public static void main(String[] args) {


   // Statements
  }
Every Java program must have a method called main(). A method is a
sequence of tasks for the computer to execute. This main() method holds
all of the instructions for our program.

Statements

System.out.println("Hello World!");
This code uses the method println() to send the text “Hello World!” to
the terminal as output. println() comes from an object called out, which
is responsible for various types of output. Objects are packages of state
and behavior, and they’re often modeled on real-world things.

out is
located within System, which is another object responsible for
representing our computer within the program! We can access parts of
an object with a ., which is known as dot notation.

This line of code is a statement, because it performs a single task.


Statements always conclude with a semicolon.

Whitespace
Java programs allow judicious use of whitespace (tabs, spaces, newlines)
to create code that is easier to read. The compiler ignores whitespace,
but humans need it! Use whitespace to indent and separate lines of
code. Whitespace increases the readability of your code.

Practice

The structure of a Java program will feel familiar the more you work with
this language. Continue learning at Codecademy and you’ll be a Java pro
in no time!

What is an IDE?
An IDE, or Integrated Development Environment, enables programmers
to consolidate the different aspects of writing a computer program.

IDEs increase programmer productivity by combining common activities


of writing software into a single application: editing source code,
building executables, and debugging.

Editing Source Code

Writing code is an important part of programming. We start with a blank


file, write a few lines of code, and a program is born! IDEs facilitate this
process with features like syntax highlighting and autocomplete.

Syntax Highlighting

An IDE that knows the syntax of your language can provide visual cues.
Keywords, words that have special meaning like class in Java, are
highlighted with different colors.

Compare these two code samples:

// without syntax highlighting

public class NiceDay {


  public static void main(String[] args) {
    System.out.println("It's a nice day out!");
  }
}
// with syntax highlighting

public class NiceDay {


  public static void main(String[] args) {
    System.out.println("It's a nice day out!");
  }
}
Syntax highlighting makes code easier to read by visually clarifying
different elements of language syntax.

Autocomplete

When the IDE knows your programming language, it can anticipate what
you’re going to type next!

We’ve seen statements with System.out.println() quite a bit so far. In an


IDE, we might see System as an autocomplete option after only typing Sy.
This saves keystrokes so the programmer can focus on logic in their
code.
Building Executables

Java is a compiled language. Before programs run, the source code of


a .java file must be transformed into an executable .class by the
compiler. Once compiled, the program can be run from the terminal.

This compilation process is necessary for every program, so why not


have the IDE do it for us? IDEs provide automated build processes for
languages, so the act of compiling and executing code is abstracted
away, like in Codecademy lessons.

Debugging

No programmer avoids writing bugs and programs with errors.

When a program does not run correctly, IDEs provide debugging tools
that allow programmers to examine different variables and inspect their
code in a deliberate way.

IDEs also provide hints while coding to prevent


errors before compilation.
Coding On Your Computer
The biggest benefit to using an IDE is that it allows you to code and run
Java programs on your own computer. We recommend IntelliJ IDEA,
which you can download for macOS, Windows, or Linux.

You should download and install Java to your computer before using an


IDE.

Here are two videos that walk through how to set up an IDE and run Java
code.
Introduction
Let’s say we need a program that connects a user with new jobs. We need the
user’s name, their salary, and their employment status. All of these pieces of
information are stored in our program.

We store information in variables, named locations in memory.

Naming a piece of information allows us to use that name later, accessing the
information we stored.

Variables also give context and meaning to the data we’re storing. The
value 42 could be someone’s age, a weight in pounds, or the number of orders
placed. With a name, we know the value 42 is age, weightInPounds,
or numOrdersPlaced.

In Java, we specify the type of information we’re storing. Primitive


datatypes are types of data built-in to the Java system. The three main
primitive types we’ll cover are int, double, and boolean; this lesson will
introduce these built-in types and more.
We must declare a variable to reference it within our program. Declaring a
variable requires that we specify the type and name:

// datatype variableName
int age;
double salaryRequirement;
boolean isEmployed;
The names of the variables above are age, salaryRequirement, and isEmployed.

These variables don’t have any associated value. To assign a value to a


variable, we use the assignment operator =:

age = 85;
Now, age has a value of 85. When code is used to represent a fixed value,
like 85, it is referred to as a literal.

It’s also common to declare a variable and assign it a value in one line!

For example, to assign 2011 to a variable named yearCodecademyWasFounded of


type int, we write:

int yearCodecademyWasFounded = 2011;

Instructions

1.
In Creator.java, we have defined some variables related to James Gosling, the
creator of Java.

Inside main(), use System.out.println() to print out the variable name.


Hint
We do not use double quotes to print a variable because we want to print
what the variable references.

String cat = "Buffy";

System.out.println("cat");
// prints cat
System.out.println(cat);
// prints Buffy
2.
Use the same command to print out yearCreated.
Hint
We have to write print statements after declaring and initializing the variable:

System.out.println(cat);
String cat = "Buffy";
//this code will have an error, since cat is not defined yet!
String cat = "Buffy";
System.out.println(cat);
//this code will run, since cat is assigned the value of
"Buff"!

Creator.java

public class Creator {
  public static void main(String[] args) {
    String name = "James Gosling";
    int yearCreated = 1995;
  }
}

ints
The first type of data we will store is the whole number. Whole numbers are
very common in programming. You often see them used to store ages, or
maximum sizes, or the number of times some code has been run, among
many other uses.

In Java, whole numbers are stored in the int primitive data type.

ints hold positive numbers, negative numbers, and zero. They do not store
fractions or numbers with decimals in them.

The int data type allows values between -2,147,483,648 and 2,147,483,647,


inclusive.
To declare a variable of type int, we use the int keyword before the variable
name:

// int variable declaration


int yearJavaWasCreated;
// assignment
yearJavaWasCreated = 1996;
// declaration and assignment
int numberOfPrimitiveTypes = 8;

Instructions

1.
The file CountComment.java has a number of comments in it.

In your head, count the number of comments. Then, inside the main() method,


declare a variable called numComments that holds how many comments you
counted.
2.
Print out numComments.

CountComment.java

//This is the class declaration
public class CountComment {
  //This is the main method that runs when you compile
  public static void main(String[] args) {
    //This is where you will define your variable
    
    //This is where you will print your variable
    
  }
  
  //This is the end of the class
}

//This is outside the class
doubles
Whole numbers don’t accomplish what we need for every program. What if we
wanted to store the price of something? We need a decimal point. What if we
wanted to store the world’s population? That number would be larger than
the int type can hold.

The double primitive data type can help. double can hold decimals as well as


very large and very small numbers. The maximum value is
1.797,693,134,862,315,7 E+308, which is approximately 17 followed by 307
zeros. The minimum value is 4.9 E-324, which is 324 decimal places!

To declare a variable of type double, we use the double keyword in the


declaration:

// doubles can have decimal places:


double price = 8.99;
// doubles can have values bigger than what an int could hold:
double gdp = 12237700000;

Instructions

1.
As of 2016, Android has 81.7 percent of the market share for mobile operating
systems. Create a variable called androidShare that holds this percentage as a
double.
2.
Print out androidShare to the console.

MarketShare.java

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

booleans
Often our programs face questions that can only be answered with yes or no.

Is the oven on? Is the light green? Did I eat breakfast?

These questions are answered with a boolean, a type that references one of
two values: true or false.

We declare boolean variables by using the keyword boolean before the variable


name.

boolean javaIsACompiledLanguage = true;


boolean javaIsACupOfCoffee = false;
In future lessons, we’ll see how boolean values help navigate decisions in our
programs.

Instructions

1.
Create a variable called intsCanHoldDecimals. Set it to true if the int type can
hold a decimal number. Set it to false if the int type cannot do this.
2.
Print out your intsCanHoldDecimals variable.

Booleans.java

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

char
How do we answer questions like: What grade did you get on the test? What
letter does your name start with?

The char data type can hold any character, like a letter, space, or punctuation
mark.
It must be surrounded by single quotes, '.

For example:

char grade = 'A';


char firstLetter = 'p';
char punctuation = '!';

Instructions

1.
Create a variable called expectedGrade of type char.

Fill it with a single letter, representing the grade you think you would get in a
graded Java course where the grades A, B, C, D and F are possible.
2.
Print out your expectedGrade variable!

Char.java

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

  }
}

String
So far, we have learned primitive data types, which are the simplest types of
data with no built-in behavior. Our programs will also use Strings, which
are objects, instead of primitives. Objects have built-in behavior.

Strings hold sequences of characters. We’ve already seen instances of a String,


for example, when we printed out "Hello World". There are two ways to create
a String object: using a String literal or calling the String class to create a
new String object.
A String literal is any sequence of characters enclosed in double-quotes ( "").
Like primitive-type variables, we declare a String variable by specifying the
type first:

String greeting = "Hello World";


We could also create a new String object by calling the String class when
declaring a String like so:

String salutations = new String("Hello World");


There are subtle differences in behavior depending on whether you create
a String using a String literal or a new String object. We’ll dive into those later,
but for now, we’ll almost always be using String literals.

Keep Reading: AP Computer Science A Students

Certain symbols, known as escape sequences, have an alternative use in Java


print statements. Escape sequences are interpreted differently by the compiler
than other characters. Escape characters begin with the character \.

There are three escape sequences to be aware of for the AP exam.

The \" escape sequence allows us to add quotation marks " to a String value. :

System.out.println("\"Hello World\"");
// Prints: "Hello World"
If we didn’t use an escape sequence, then Java would think we’re using " to
end the String!

Using the \\ escape sequence allows us to place backslashes in our String text:

System.out.println("This is the backslash symbol: \\");


// Prints: This is the backslash symbol: \
This is similar to the last example - just like ", \ usually has a special meaning.
In this case, \ is used to start an escape sequence. Well, if we don’t want to
start an escape sequence and just want a \ in our String, then we’ll use \\ —
we’re using an escape sequence to say that we don’t want \ to be interpreted
as the start of an escape sequence. It’s a little mind-bending!
Finally, if we place a \n escape sequence in a String, the compiler will output a
new line of text:

System.out.println("Hello\nGoodbye");
/*
Prints:
Hello
Goodbye
*/
You can think of \n as the escape sequence for “newline”.

Instructions

1.
Create a variable called openingLyrics that holds "Yesterday, all my troubles
seemed so far away".
2.
Call System.out.println() to print out openingLyrics.
Song.java

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

  }
}

Static Checking
The Java programming language has static typing. Java programs will not
compile if a variable is assigned a value of an incorrect type. This is a bug,
specifically a type declaration bug.

Bugs are dangerous! They cause our code to crash, or produce incorrect
results. Static typing helps because bugs are caught during programming
rather than during execution of the code.

The program will not compile if the declared type of the variable does not
match the type of the assigned value:

int greeting = "Hello World";


The String "Hello World" cannot be held in a variable of type int.

For the example above, we see an error in the console at compilation:

error: incompatible types: String cannot be converted to int


    int greeting = "Hello World";
When bugs are not caught at compilation, they interrupt execution of the
code by causing runtime errors. The program will crash.

Java’s static typing helps programmers avoid runtime errors, and thus have
much safer code that is free from bugs.

Instructions

1.
In the Mess.java file, we have declared a bunch of variables with the wrong
type. Try to compile the file using the command:
javac Mess.java
2.
Change the types of the variables so that they correspond with the type of the
assignment values.

For example, year is assigned 2001, so it should be an int.


3.
Compile the file again. Look at how it compiles with no errors now!

Mess.java

public class Mess {
  public static void main(String[] args) {   
    String year = 2001;
    double title = "Shrek";
    int genre = 'C';
    boolean runtime = 1.58;
    char isPG = true;
  }
}

Naming
Let’s imagine we’re storing a user’s name for their profile. Which code
example do you think is better?

String data = "Delilah";


or

String nameOfUser = "Delilah";


While both of these will compile, the second example is way more easy to
understand. Readers of the code will know the purpose of the value: "Delilah".

Naming variables according to convention leads to clear, readable, and


maintainable code. When someone else, or our future self, reads the code,
there is no confusion about the purpose of a variable.
In Java, variable names are case-sensitive. myHeight is a different variable
from myheight. The length of a variable name is unlimited, but we should keep
it concise while keeping the meaning clear.

A variable starts with a valid letter, or a $, or a _. No other symbols or numbers
can begin a variable name. 1stPlace and *Gazer are not valid variable names.

Variable names of only one word are spelled in all lowercase letters. Variable
names of more than one word have the first letter lowercase while the
beginning letter of each subsequent word is capitalized. This style of
capitalization is called camelCase.

// good style
boolean isHuman;

// bad styles
// no capitalization for new word
boolean ishuman;
// first word should be lowercase
boolean IsHuman;
// underscores don't separate words
boolean is_human;

Instructions

1.
In the BadNames.java file, we declared variables with confusing names. Run
the file and look at the error messages you get when trying to compile.
2.
Some of these variable names are illegal! Change the ones that are preventing
the file from compiling.

BadNames.java

public class BadNames {
  public static void main(String[] args) {   
    String 1stName = "Samira";
    String blah = "Smith";
    String .com = "[email protected]";
    int salaryexpectation = 100000;
    int year_of_birth = 1955;
    
    System.out.println("The program runs!");
  }
}

Review
Creating and filling variables is a powerful concept that allows us to keep track
of all kinds of data in our program.

In this lesson, we learned how to create and print several different data types
in Java, which you’ll use as you create bigger and more complex programs.

We covered:

 int, which stores whole numbers.


 double, which stores bigger whole numbers and decimal numbers.
 boolean, which stores true and false.
 char, which stores single characters using single quotes.
 String, which stores multiple characters using double quotes.
 Static typing, which is one of the safety features of Java.
 Variable naming conventions.

Practice declaring variables and assigning values to make sure you have a
solid foundation for learning more complicated and exciting Java concepts!

Instructions

1.
The file MyProfile.java contains a class that represents your hiring profile as
presented to potential employers.

In the main() method, create a variable called name that holds your name, as a


sequence of characters.
Hint
If we were defining a variable called userID that would hold a string of letters,
we would use a line like this:

String userID = "myUsername";


You can use the same sort of declaration and initialization for
your name variable!
2.
Create a variable called age that holds your age as a whole number.
3.
Create a variable called desiredSalary that holds your desired salary per year to
a precision of two decimal points.
Hint
If we were defining a variable called gpa that would hold a decimal number, we
would use a line like this:

double gpa = 5.1;


You can use the same sort of declaration and initialization for
your desiredSalary variable!
4.
Create a variable called gender that holds a single
character, m (male), f (female), n (for none), or o (for other).
5.
Create a variable called lookingForJob that holds whether or not you are
currently open to job offers.
Hint
If we were defining a variable called isLightOn that would hold either true or
false, we would use a line like this:

boolean isLightOn = true;


You can use the same sort of declaration and initialization for
your lookingForJob variable!

MyProfile.java

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

Introduction
Let’s say we are writing a program that represents a user’s bank account. With
variables, we know how to store a balance! We’d use a double, the primitive
type that can hold big decimal numbers. But how would we deposit and
withdraw from the account?

Lucky for us, we have the ability to manipulate the value of our variables. We
can use expressions, arithmetic operators, and more in order to change our
variables’ values.

For example, Java has built-in arithmetic operations that perform calculations
on numeric values:

// declare initial balance


double balance = 20000.99;
// declare deposit amount
double depositAmount = 1000.00;
// store result of calculation in our original variable
balance = balance + depositAmount;
In the final line of the code above, we used the expression balance +
depositAmount to determine the new value of the balance variable. When an
expression is executed, it produces a single value.

The data type of a variable plays a large role in the operations we can use to
manipulate it. We can think of a data type as a combination of a set of values,
and a set of operations on those values. For example, the double data type is
comprised of values like 4.8 and operations like addition (+). For now, we’ll
mainly focus on the set of operations that can be used on numbers and
booleans.

The data type of an expression is determined by the resulting value. For


example, an expression that uses two int values will evaluate to an int value. If
an expression contains a double value, then the resulting value will also be
type double.

Throughout this lesson, we will learn how to manipulate variables of different


data types.

Instructions
1.
In the file GuessingGame.java, we have defined two
integers mystery1 and mystery2.

We will talk about these operators, among others, in the rest of the lesson.

Use System.out.println() to print the variable that holds a value of 2.

GuessinGame.java

public class GuessingGame {
  public static void main(String[] args) {   
    int mystery1 = 8 + 6;
    int mystery2 = 8 - 6;
  }
}

Addition and Subtraction


In our bank account example from the last exercise, we used the + operator to
add the values balance and depositAmount:

double balance = 20000.99;


double depositAmount = 1000.0;
balance = balance + depositAmount;
// balance now holds 21000.99
If we wanted to withdraw from the balance, we would use the - operator:

double withdrawAmount = 500;


balance = balance - withdrawAmount;
// balance now holds 19500.99
Addition and subtraction work with int type values as well! If we
had 60 pictures of cats on our phone, and we took 24 more, we could use the
following line of code to store 84 in numPicturesOfCats.

int numPicturesOfCats = 60 + 24;


What if we took one additional picture of our cat? We can reflect this change
using an increment operator ++. When we append ++ to a number-based
variable, it increases the value by 1. We also have the decrement operator, --,
which decreases the value by 1.

// Take a picture
numPicturesOfCats++ // Value is now 85

// Delete a picture
numPicturesOfCats-- // Value is now 84

Instructions

1.
Create an int variable called animalsInZoo that holds the amount of zebras plus
the amount of giraffes at the zoo.

Then, print your animalsInZoo variable.


2.
Two of the zebras have been traded to a neighboring rival zoo. Subtract 2
from the number of zebras and store the result in a variable
called numZebrasAfterTrade.

Then, print the numZebrasAfterTrade variable!

PlusAndMinus.java

public class PlusAndMinus {
  public static void main(String[] args) {   
    int zebrasInZoo = 8;
    int giraffesInZoo = 4;
  }
}

Multiplication and Division


Let’s say that our employer is calculating our paycheck and depositing it to
our bank account. We worked 40 hours last week, at a rate of $15.50 an hour.
Java can calculate this with the multiplication operator *:
double paycheckAmount = 40 * 15.50;
//paycheckAmount now holds 620.0
If we want to see how many hours our total balance represents, we use the
division operator /:

double balance = 20010.5;


double hourlyRate = 15.5;
double hoursWorked = balance / hourlyRate;
//hoursWorked now holds 1291.0
Division has different results with integers. The / operator does integer
division, which means that any remainder is lost.

int evenlyDivided = 10 / 5;
//evenlyDivided holds 2, because 10 divided by 5 is 2
int unevenlyDivided = 10 / 4;
//unevenlyDivided holds 2, because 10 divided by 4 is 2.5
evenlyDivided stores what you expect, but unevenlyDivided holds 2 because ints
cannot store decimals! It’s important to note that the int doesn’t round the
decimal, but floors it. Java removes the 0.5 to fit the result into an int type!

It’s important to note that if we try to divide any number by 0, we will get
an ArithmeticException error as a result.

Instructions

1.
In main(), there is a variable called subtotal, which represents the subtotal of
an amount to pay on a bill, and a variable called tax, which represents the
amount of tax added to the subtotal.

Create a double variable, total, that holds subtotal plus the product


of subtotal and tax.

Print the total variable!
2.
There were 4 people who bought this meal together and want to split the cost.

Create a double variable called perPerson that holds total divided by 4.


Print the perPerson variable!

MultAndDivide.java

public class MultAndDivide {
  public static void main(String[] args) {   
    double subtotal = 30;
    double tax = 0.0875;
  }
}

Modulo
If we baked 10 cookies and gave them out in batches of 3, how many would
we have leftover after giving out all the full batches we could?

The modulo operator %, gives us the remainder after two numbers are


divided.

int cookiesBaked = 10;


int cookiesLeftover = 10 % 3;
//cookiesLeftover holds 1
You have 1 cookie left after giving out all the batches of 3 you could!

Modulo can be a tricky concept, so let’s try another example.

Imagine we need to know whether a number is even or odd. An even number


is divisible by 2.

Modulo can help! Dividing an even number by 2 will have a remainder of 0.


Dividing an odd number by 2 will have a remainder of 1.

7 % 2
// 1, odd!
8 % 2
// 0, even!
9 % 2
// 1, odd!
Instructions

1.
You are trying to split up students into groups of 3. How many students will
be left out once the groups are made?

Create a variable called leftOut that holds the modulo of students and 3. Then,


print the variable!

Modulo.java

public class Modulo {
  public static void main(String[] args) {   
    int students = 26;
  }
}

Compound Assignment Operators


Sometimes, we need to adjust the value of a variable.

Imagine we’re working at a bake sale and want to keep track of how many
cupcakes we have by creating a variable called numCupcakes:

int numCupcakes = 12;


If we baked 8 more cupcakes, we know that we could update our variable
using the + operator:

numCupcakes = numCupcakes + 8; // Value is now 20


While this method works just fine, we had to write our
variable numCupcakes twice. We can shorten this syntax by using a compound
assignment operator.

Compound assignment operators perform an arithmetic operation on a


variable and then reassigns its value. Using the += compound assignment
operator, we can rewrite our previous code like so:

numCupcakes += 8; // Value is now 20


Now we only need to reference numCupcakes once.
We can use compound assignment operators for all of the arithmetic
operators we’ve covered:

 Addition (+=)
 Subtraction (-=)
 Multiplication (*=)
 Division (/=)
 Modulo (%=)

Instructions

1.
You are also in charge of keeping track of how many cookies there are at the
bake sale. This value is represented by the variable numCookies.

A customer comes and buys 3 cookies. Use the appropriate compound


assignment operator to reflect this change.
Stuck? Get a hint
2.
Another customer buys half of the remaining cookies.

Use the appropriate compound assignment operator to reflect this change.

BakeSale.java

public class BakeSale {
  public static void main(String[] args) {   
    int numCookies = 17;

    // Add your code above
    System.out.println(numCookies);
  }
}

Order of Operations
If we were to place multiple operators in a single expression, what operation
would the compiler evaluate first?

int num = 5 * (10 - 4) + 4 / 2;


The order of operations dictates the order in which an expression (like the one
above) is evaluated.

The order is as follows:

1. Parentheses
2. Multiplication
3. Division
4. Modulo
5. Addition
6. Subtraction

With this new information in mind, let’s dissect the expression from above so
that we can find the value of num:

5 * (10 - 4) + 4 / 2
10 - 4 would be evaluated first because it is wrapped in parentheses. This
value would become 6 making our expression look like this:

5 * 6 + 4 / 2 
Next, 5 * 6 will be evaluated because of the * operator. This value is 30. Our
expression now looks like this:

30 + 4 / 2
Following the order of operations, 4 / 2 will be evaluated next because the
division operator / has higher precedence than the addition operator +. Our
expression now resembles the following:

30 + 2
30 + 2 is 32. This means that the value of num is 32.

Instructions

Take a look at the expressions in Operations.java.


Solve for the value of each of the expressions on your own.

To find out if your calculations are right, uncomment the print statements and
run the code.

Operatins.java

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

    int expression1 = 5 % 2 - (4 * 2 - 1);
    // System.out.println(expression1);

    int expression2 = (3 + (2 * 2 - 5)) + 6 - 5;
    // System.out.println(expression2);

    int expression3 = 5 * 4 % 3 - 2 + 1;
    // System.out.println(expression3);

  }
}

Greater Than and Less Than


Now, we’re withdrawing money from our bank account program, and we want
to see if we’re withdrawing less money than what we have available.

Java has relational operators for numeric datatypes that


make boolean comparisons. These include less than (<) and greater than (>),
which help us solve our withdrawal problem.

double balance = 20000.01;


double amountToWithdraw = 5000.01;
System.out.print(amountToWithdraw < balance);
//this will print true, since amountToWithdraw is less than
balance
You can save the result of a comparison as a boolean, which you learned about
in the last lesson.
double myBalance = 200.05;
double costOfBuyingNewLaptop = 1000.05;
boolean canBuyLaptop = myBalance > costOfBuyingNewLaptop;
//canBuyLaptop is false, since 200.05 is not more than 1000.05

Instructions

1.
Print the expression that checks if the amount of credits you have
earned, creditsEarned, is greater than the number of credits you need to
graduate, creditsToGraduate.
2.
Create a variable called creditsAfterSeminar that holds the amount of credits
earned after taking a seminar, which is
worth creditsOfSeminar credits. creditsAfterSeminar should be the sum
of creditsEarned and creditsOfSeminar.

Print out whether creditsToGraduate is less than creditsAfterSeminar.

GreaterLessThan.java

public class GreaterLessThan {
  public static void main(String[] args) {   
    double creditsEarned = 176.5;
    double creditsOfSeminar = 8;
    double creditsToGraduate = 180;
  }
}

Equals and Not Equals


So how would we validate our paycheck to see if we got paid the right
amount?

We can use another relational operator to do this. == will tell us if two variables


are equal:

double paycheckAmount = 620;


double calculatedPaycheck = 15.50 * 40;
System.out.print(paycheckAmount == calculatedPaycheck);
// This will print true, since paycheckAmount equals
calculatedPaycheck
Notice that the equality check is two equal signs, instead of one. One equal
sign, =, is how we assign values to variables! It’s easy to mix these up, so make
sure to check your code for the right number of equal signs.

To check if two variables are not equal, we can use !=:

double balance = 20000.0;


double amountToDeposit = 620;
double updatedBalance = balance + amountToDeposit;

boolean balanceHasChanged = balance != updatedBalance;


// balanceHasChanged holds true, since balance does not equal
updatedBalance

Instructions

1.
You have unearthed two unlabeled albums, record A and record B.

To see if these are the same album, you’re going to compare the number of
songs on each one, and the total length of the albums.

First, create a variable called sameNumberOfSongs that stores whether the two


albums have the same number of songs.
Stuck? Get a hint
2.
Now, create a variable called differentLength that stores the result of checking
whether the two album lengths are not the same.

EqualNotEqual.java

public class EqualNotEqual {
  public static void main(String[] args) {   
    int songsA = 9;
    int songsB = 9;
    int albumLengthA = 41;
    int albumLengthB = 53;
  }
}

Greater/Less Than or Equal To


How could we make sure we got paid at least the amount we expected in our
paycheck? We could use greater than or equal to, >=, or less than or equal
to, <=!

double paycheckAmount = 620;


double calculatedPaycheck = 15.50 * 40;
System.out.println(paycheckAmount >= calculatedPaycheck);
//this will print true, since paycheckAmount equals
calculatedPaycheck

Instructions

1.
You have been trying to complete a 30 day challenge to drink enough water
per day.

Create a double variable called totalRecommendedAmount and set it to the product


of the recommended water intake (recommendedWaterIntake) and the amount of
days in the challenge (daysInChallenge).
2.
Create a boolean variable called isChallengeComplete and set it to the result of
checking if your intake, yourWaterIntake, is at least as much as
the totalRecommendedAmount.

Then, print the isChallengeComplete variable.

public class GreaterThanEqualTo {
    public static void main(String[] args){
      double recommendedWaterIntake = 8;
      double daysInChallenge = 30;
      double yourWaterIntake = 235.5;
    }       
}

.equals()
So far, we’ve only been using operations on primitive types. It doesn’t make
much sense to multiply Strings, or see if one String is less than the other. But
what if we had two users logging into a site, and we wanted to see if their
usernames were the same?

With objects, such as Strings, we can’t use the primitive equality operator. To
test equality with objects, we use a built-in method called .equals(). When
comparing objects, make sure to always use .equals(). == will work
occasionally, but the reason why it sometimes works has to do with how
objects are stored in memory.

For the purposes of this lesson (as well as good practice) remember to
use .equals() instead of == when comparing objects.

To use it, we call it on one String, by using ., and pass in the String to


compare against in parentheses:

String person1 = "Paul";


String person2 = "John";
String person3 = "Paul";

System.out.println(person1.equals(person2));
// Prints false, since "Paul" is not "John"

System.out.println(person1.equals(person3));
// Prints true, since "Paul" is "Paul"

Instructions

1.
We have three lines from a song in Song.java.
First, print out whether line1 and line2 are the same.
Stuck? Get a hint
2.
Now, print whether line2 and line3 are equal.

String Concatenation
We have covered a lot of built-in functionality in Java throughout this lesson.
We’ve seen +, -, <, ==, and many other operators. Most of these only work on
primitives, but some work on Strings too!

Let’s say we want to print out a variable, and we want to describe it as we print
it out. For our bank account example, imagine we want to tell the user:

Your username is: <username>


With the value of the variable username displayed.

The + operator, which we used for adding numbers together, can be used


to concatenate Strings. In other words, we can use it to join two Strings
together!

String username = "PrinceNelson";


System.out.println("Your username is: " + username);
This code will print:

Your username is: PrinceNelson


We can even use a primitive datatype as the second variable to concatenate,
and Java will intelligently make it a String first:

int balance = 10000;


String message = "Your balance is: " + balance;
System.out.println(message);
This code will print:

Your balance is: 10000

Instructions

1.
In our zoo, we have a certain number of animals, stored in animals, of a certain
species, stored in species.

Use + to make a new String variable called zooDescription. It should hold a


String that looks like:

Our zoo has <animals> <species>s!


For example, if we had 5 animals that were all of the species Masai Giraffe, the
String would say:

Our zoo has 5 Masai Giraffes!


Stuck? Get a hint
2.
Print out the variable zooDescription!

public class Zoo {
    public static void main(String[] args){
      int animals = 12;
      String species = "zebra";
    }       
}

final Keyword
Throughout this lesson, we’ve discussed the different ways we can manipulate
a variable; however, what do we do with a variable that should never change
its value?

For example, the year we were born will always stay the same. There’s no way
we can change that information. A value like this in our code should be
unchangeable.

To declare a variable with a value that cannot be manipulated, we need to use


the final keyword. To use the final keyword, prepend final to a variable
declaration like so:

final int yearBorn = 1968;


When we declare a variable using final, the value cannot be changed; any
attempts at doing so will cause an error to occur:

error: cannot assign a value to final variable yearBorn

Instructions

1.
Create an unchangeable double variable called pi and set its value to 3.14.

Print the value of pi.


Stuck? Get a hint
2.
On a new line, try to change the value of pi.

What happens when the program is run?


Stuck? Get a hint

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

Review
What’s the use of having variables if you can’t do anything with them? We’ve
now seen some ways you can operate on variables and compare them. The
possibilities are endless!

We covered:

 Addition and subtraction, using + and -


 Multiplication and division, using * and /
 The modulo operator for finding remainders, %
 Compound assignment operators +=, -=, *=, /=, and %=.
 The order of operations: parentheses -> multiplication -> division ->
modulo -> addition -> subtraction
 Greater than, >, and less than, <
 Equal to, ==, and not equal to, !=
 Greater than or equal to, >=, and less than or equal to, <=
 equals() for comparing Strings and other objects
 Using + to concatenate Strings
 The final keyword which makes variables unchangeable

Practice some of these concepts here, to make sure you have a solid
foundation for learning more complicated and exciting Java concepts!

Instructions

1.
To review, let’s try building some of the bank account functionality we talked
about throughout the lesson.

First, create a new double variable called updatedBalance, and


store balance with amountToWithdraw subtracted from it.
2.
Now, you’ve decided to split your balance evenly 3 ways and give it to your
three best friends.

Create a double variable called amountForEachFriend that holds your updated


balance divided by 3.
3.
Your friends each want to buy a concert ticket with the money you’ve given
them. The tickets cost 250!

Create a boolean called canPurchaseTicket and set it equal to whether or


not amountForEachFriend is at least enough to purchase a concert ticket.

Then, use System.out.println() to print canPurchaseTicket.


Hint
You can use >= to create this boolean:
boolean somethingIsAtLeast50 = something >= 50;
This will be true if something is at least 50, and false otherwise.
4.
How much money did you give your friends, anyway?

Use + and System.out.println() to print out:

I gave each friend <amountForEachFriend>...


with the value of amountForEachFriend where <amountForEachFriend> is.

public class BankAccount {
    public static void main(String[] args){
      double balance = 1000.75;
      double amountToWithdraw = 250;
    }       
}
Introduction to Classes
All programs require one or more classes that act as a model for the world.

For example, a program to track student test scores might


have Student, Course, and Grade classes. Our real-world concerns, students and
their grades, are inside the program as classes.

We represent each student as an instance, or object, of the Student class.

This is object-oriented programming because programs are built around


objects and their interactions. An object contains state and behavior.
Classes are a blueprint for objects. Blueprints detail the general structure. For
example, all students have an ID, all courses can enroll a student, etc.

An instance is the thing itself. This student has an ID of 42, this course


enrolled that student, etc.

Let’s review with another example, a savings account at a bank.

What should a savings account know?

 The balance of money available.

What should a savings account do?

 Deposit money.
 Withdraw money.
Imagine two people have accounts that are instances of
the SavingsAccount class. They share behavior (how they deposit and withdraw)
but have individual state (their balances), and even with the same balance
amount these accounts are separate entities.

Instructions

Our text editor contains a complete class definition that we’ll build up as we
progress through the lesson.

Run the code to see it in action.

public class Store {
  // instance fields
  String productType;
  int inventoryCount;
  double inventoryPrice;
  
  // constructor method
  public Store(String product, int count, double price) {
    productType = product;
    inventoryCount = count;
    inventoryPrice = price;
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("lemonade", 42, .99);
    Store cookieShop = new Store("cookies", 12, 3.75);
    
    System.out.println("Our first shop sells " + lemonadeStand.productType + " a
t " + lemonadeStand.inventoryPrice + " per unit.");
    
    System.out.println("Our second shop has " + cookieShop.inventoryCount + " un
its remaining.");
  }
}

Classes: Syntax
The fundamental concept of object-oriented programming is the class.

A class is the set of instructions that describe how an instance can behave and
what information it contains.

Java has pre-defined classes such as System, which we’ve used in logging text
to our screen, but we also need to write our own classes for the custom needs
of a program.

Here’s a definition of a Java class:

public class Car {


// scope of Car class starts after curly brace

  public static void main(String[] args) {


    // scope of main() starts after curly brace

    // program tasks


  }
  // scope of main() ends after curly brace

}
// scope of Car class ends after curly brace
This example defines a class named Car. public is an access level modifier that
allows other classes to interact with this class. For now, all classes will
be public.

This class has a main() method, which lists the tasks performed by the
program. main() runs when we execute the compiled Car.class file.

Instructions

1.
In the code editor, create a public Store class.
Hint
Refer to the example in the narrative if you need help.
2.
Your program will not compile without a main() method.

Define one within Store.

Classes: Constructors
In order to create an object (an instance of a class), we need a constructor
method. The constructor is defined within the class.

Let’s take a look at the Car class with a constructor. The constructor, Car(),


shares the same name as the class:

public class Car {


  // Constructor method
  public Car() {
    // instructions for creating a Car instance
  }  

  public static void main(String[] args) {


    // body of main method
  }
}
To create an instance, we need to call or invoke the constructor within main().
The following example assigns a Car instance to the variable ferrari:

public class Car {

  public Car() {
    // instructions for creating a Car instance
  }

  public static void main(String[] args) {


    // Invoke the constructor
    Car ferrari = new Car();
  }
}
In this example, instead of being declared with a primitive data type
like int or boolean, our variable ferrari is declared as a reference data type. This
means that the value of our variable is a reference to an instance’s memory
address. During its declaration, the class name is used as the variable’s type. In
this case, the type is Car.

After the assignment operator, (=), we invoke the constructor method: Car(),


and use the keyword new to indicate that we’re creating an
instance. Omitting new causes an error.

If we were to output the value of ferrari we would see its memory address:

Car@76ed5528
Keep Reading: AP Computer Science A Students

We can initialize a reference-type variable without assigning it a reference if


we utilize the special value null. Something that is null has no value; if we
were to assign null to an object, it would have a void reference.

For example, in the following code snippet, we’ll create an instance of Car,
assign it a reference, and then change its value to null:
Car thunderBird = new Car();
System.out.println(thunderBird); // Prints: Car@76ed5528

thunderBird = null; // change value to null


System.out.println(thunderBird); // Prints: null
It’s important to note that if we use a null reference to call a method or access
an instance variable, we will receive a NullPointerException error.

Instructions

1.
Let’s explore how code execution moves around the file with two methods.

Add a print statement inside our Store constructor with the message: I am


inside the constructor method.

We’ll see this message whenever we create an instance of Store by calling the
constructor.
Hint
We print messages using System.out.println(). Here’s an example printing the
message Making a shoe!

System.out.println("Making a shoe!");
Make sure you’re placing the print statement inside the curly braces of
the Store() constructor method!
2.
We did not see our constructor message printed because we haven’t run the
code inside the constructor.

Inside main(), create an instance of Store called lemonadeStand. Don’t forget


the new keyword!

We should see the constructor message.


Hint
We create instances of a class by using the new keyword and invoking the
constructor.

For example, say we had a Dog class.


public Dog {
  public Dog() {
    // body of Dog constructor method
  }
  public static void main(String[] args) {
    // declare variable type and name
    Dog fido;
    // assign a new instance of Dog to fido
    fido = new Dog();
  }
}
We’ll often consolidate declaration and assignment into a single line:

Dog fido = new Dog();


3.
Inside main(), print lemonadeStand to see how Java represents this instance.

Review the order of the printed messages:

1. Running the program invokes main()


2. We create an instance so we move from main() to Store()
3. The code inside Store() runs
4. When Store() finishes execution, we return to main()

Hint
When printing a variable, do not use double quotes.

Here’s how to print the variable fido:

System.out.println(fido);

public class Store {
  
  // new method: constructor!
  public Store() {
    System.out.println("I am inside the constructor method.");
  }
  
  // main method is where we create instances!
  public static void main(String[] args) {
    System.out.println("Start of the main method.");
    
    // create the instance below
    Store lemonadeStand = new Store();
    
    // print the instance below
    System.out.println(lemonadeStand);
  }
}

Classes: Instance Fields


Our last exercise ended with printing an instance of Store, which looked
something like Store@6bc7c054. The first part, Store, refers to the class, and the
second part @6bc7c054 refers to the instance’s location in the computer’s
memory.

We don’t care about memory location, but our instances have no other
characteristics! When an object is created, the constructor sets the initial state
of the object. The state is made up of associated data that represents the
characteristics of an object.

We’ll add data to an object by introducing instance variables, or instance fields.

We want Car instances of different colors, so we declare a String


color instance field. Often times, instance variables are described as a “has-a”
relationship with the object. For example, a Car “has-a” color. Another way to
think of this is that instance variables are the nouns and adjectives associated
with an object. What qualities other than color might a car have?

public class Car {


  /*
  declare fields inside the class
  by specifying the type and name
  */
  String color;
  public Car() {
    /*
    instance fields available in
    scope of constructor method
    */
  }

  public static void main(String[] args) {


    // body of main method
  }
}
The declaration is within the class and the instance variable will be available
for assignment inside the constructor.

Fields are a type of state each instance will possess. One instance may
have "red" as its color, another "blue", etc. It’s the job of the constructor to
give these instance fields initial value. We’ll learn how to this in the next
exercise.

Instructions

1.
Add some state to our Store class.

Declare a String instance field for productType.


Hint
Declare instance fields within the curly braces of the class, but outside any
method. For example, given the class Dog:

public Dog {
  // no instance fields

  public Dog() {
    // body of Dog constructor
  }
  public static void main(String[] args) {
    // just dog things...
  }
}
We can add the instance field breed of type String like so:

public Dog {
  // instance field
  String breed;

  public Dog() {
    // body of Dog constructor
  }
  public static void main(String[] args) {
    // just dog things...
  }
}

public class Store {
  // declare instance fields here!
  
  
  // constructor method
  public Store() {
    System.out.println("I am inside the constructor method.");
  }
  
  // main method
  public static void main(String[] args) {
    System.out.println("This code is inside the main method.");
    
    Store lemonadeStand = new Store();
    
    System.out.println(lemonadeStand);
  }
}

Classes: Constructor Parameters


To create objects with dynamic, individual states, we’ll use a combination of
the constructor method and instance fields.

In order to assign a value to an instance variable, we need to alter our


constructor method to include parameters so that it can access the data we
want to assign to an instance.

We’ve already seen a parameter in the main() method: String[] args, but this is


the first time we’re using the parameter value within a method body.

The Car constructor now has a parameter: String carColor:

public class Car {


  String color;
  // constructor method with a parameter
  public Car(String carColor) {
    // parameter value assigned to the field
    color = carColor;
  }
  public static void main(String[] args) {
    // program tasks
  }
}
When a String value gets passed into Car(), it is assigned to the
parameter carColor. Then, inside the constructor, carColor will be assigned as
the value to the instance variable color.

Our method also has a signature which defines the name and parameters of
the method. In the above example, the signature is Car(String carColor).

In the next exercise, we’ll learn how to pass values into a method!

Keep Reading: AP Computer Science A Students

There are two types of parameters: formal and actual. A formal


parameter specifies the type and name of data that can be passed into a
method. In our example above, String carColor is a formal
parameter; carColor will represent whatever String value is passed into the
constructor. We’ll learn about actual parameters in the next exercise.
In Java, because of constructor overloading, a class can have multiple
constructors as long as they have different parameter values. The signature is
useful in that it helps the compiler differentiate between the different
methods. For example:

public class Car {


  String color;
  int mpg;
  boolean isElectric;

  // constructor 1
  public Car(String carColor, int milesPerGallon) {
    color = carColor;
    mpg = milesPerGallon;
  }
  // constructor 2
  public Car(boolean electricCar, int milesPerGallon) {
    isElectric = electricCar;
    mpg = milesPerGallon;
  }
}
In the example above, there are two constructors. When we initialize an object,
the compiler will know which constructor to use because of the values we pass
into it. For example, Car myCar = new Car(true, 40) will be created by the
second constructor because the arguments match the type and order of the
second constructor’s signature.

If we do not define a constructor, the Java compiler will generate a default


constructor that contains no arguments and assigns the object default values.
Default values can be created by assigning values to the instance fields during
their declaration:

public class Car {


  String color = "red";
  boolean isElectric = false;
  int cupHolders = 4;

  public static void main(String[] args) {


    Car myCar = new Car();
    System.out.println(myCar.color); // Prints: red
  }
}

Instructions

1.
Add the String parameter product to the Store() constructor.
Hint
Parameters are located within the parentheses of the method. They list the
name and type of data which is available within the method body.

// method with no parameters


helloToYou() {
  System.out.println("Hello there!");
}

// adding one parameter


helloToYou(String person) {
  // data of type String available as 'person' variable
  System.out.println("Hello " + person);
}

2.
Inside of the constructor method, set the instance variable productType equal
to the product parameter.
Hint
Instance fields are available inside of any method.

Here’s how we can assign a value to an instance field inside of


the Dog() constructor.

public Dog {
  String breed;
  public Dog(String breedType) {
    // assign instance field of breed to equal breedType
parameter
    breed = breedType;
  }
}

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store() {
    
  }
  
  // main method
  public static void main(String[] args) {
    
    
  }
}

Classes: Assigning Values to Instance Fields


Now that our constructor has a parameter, we must pass values into the
method call. These values are referred to as arguments; once they are passed
in, they will be used to give the instance fields initial value.

Here we create an instance, ferrari, in the main() method with "red" as


its color field:

public class Car {


  String color;

  public Car(String carColor) {


    // assign parameter value to instance field
    color = carColor;
  }

  public static void main(String[] args) {


    // parameter value supplied when calling constructor
    Car ferrari = new Car("red");
  }
}
We pass the String value "red" to our constructor method call: new Car("red");.

The type of the value given to the invocation must match the type declared
by the parameter.

Inside the constructor, the parameter carColor refers to the value passed in


during the invocation: "red". This value is assigned to the instance field color.

color has
already been declared, so we don’t specify the type during
assignment.

The object, ferrari, holds the state of color as an instance field referencing the
value "red".

We access the value of this field with the dot operator (.):

/*
accessing a field:
objectName.fieldName
*/

ferrari.color;
// "red"
Keep Reading: AP Computer Science A Students

An actual parameter, or argument, refers to the value being passed during a


method call.

Call by value is the process of calling a method with an argument value. When
an argument is passed, the formal parameter is initialized with a copy of the
argument value. For example, when we declared the ferrari object,
the String value "red" is passed as an argument; then, the formal
parameter carColor is assigned a copy of that value.

Instructions
1.
Inside main(), create an instance of Store and assign it to the
variable lemonadeStand. Use "lemonade" as the parameter value.
Hint
Given the following Dog class:

public Dog {
  String breedType;

  public Dog(String breed) {


    breedType = breed;
  }

  public static void main(String[] args) {

  }
}
We can create an instance of Dog with a breedType of "retriever" like so:

Dog fido = new Dog("retriever");


2.
Print the instance field productType from lemonadeStand.
Hint
Access the field of an instance using dot notation.

For example, with an instance of Dog named fido containing the breed instance


field, we retrieve the value of that field using: fido.breed.

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // main method
  public static void main(String[] args) {
    
    
  }
}

Classes: Multiple Fields


Objects are not limited to a single instance field. We can declare as many
fields as are necessary for the requirements of our program.

Let’s change Car instances so they have multiple fields.

We’ll add a boolean isRunning, that indicates the car engine is on and an int
velocity, that indicates the speed at which the car is traveling.

public class Car {


  String color;
  // new fields!
  boolean isRunning;
  int velocity;

  // new parameters that correspond to the new fields


  public Car(String carColor, boolean carRunning, int
milesPerHour) {
    color = carColor;
    // assign new parameters to the new fields
    isRunning = carRunning;
    velocity = milesPerHour;
  }

  public static void main(String[] args) {


    // new values passed into the method call
    Car ferrari = new Car("red", true, 27);
    Car renault = new Car("blue", false, 70);

    System.out.println(renault.isRunning);
    // false
    System.out.println(ferrari.velocity);
    // 27
  }
}
The constructor now has multiple parameters to receive values for the new
fields. We still specify the type as well as the name for each parameter.

Ordering matters! We must pass values into the constructor invocation in the
same order that they’re listed in the parameters.

// values match types, no error


Car honda = new Car("green", false, 0);

// values do not match types, error!


Car junker = new Car(true, 42, "brown");

Instructions

1.
Add two new instance fields for Store.

inventoryCount of type int. inventoryPrice of type double.


Hint
Declare instance fields inside the class but outside of any method:

public class Dog {


  // declare instance fields here
  String breed;

  public Dog(String breedType) {


    // assign values to instance fields here
    breed = breedType;
  }
}
Each declaration must conclude with a semicolon.

  String breed;
  boolean isWagging;
  int age;
2.
Update the Store constructor method with the new parameters.

The parameters should be product, count, and price, in that order.

You must use that order and include the types for each parameter.

For example, product is of type String because that value is assigned to the


instance field String productType.
Hint
Here’s a Dog class constructor and instance fields:

public class Dog {


  String breed;
  boolean isWagging;
  int age;

  public Dog(String breedType, boolean wagging, int dogYears) {


    breed = breedType;
    isWagging = wagging;
    age = dogYears;
  }
}
3.
In the body of the Store constructor, assign the parameter values to the
appropriate instance fields.
Hint
Use product as an example:

// assigning product parameter to productType instance field


productType = product;
Do the same with count and price for their respective instance fields.
4.
Inside main(), create an instance of Store called cookieShop.

cookieShop has "cookies" as the product.

cookieShop has 12 cookies to sell and each cookie costs 3.75.


Hint
Creating an instance of Dog that has multiple fields:

public class Dog {


  String breed;
  boolean isWagging;
  int age;

  public Dog(String breedType, boolean wagging, int dogYears) {


    breed = breedType;
    isWagging = wagging;
    age = dogYears;
  }

  public static void main(String[] args) {


    // creating instance with multiple parameters
    Dog fido = new Dog("mutt", true, 7);
  }
}

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // main method
  public static void main(String[] args) {
    
  }
}

Classes: Review
Java is an object-oriented programming language where every program has at
least one class. Programs are often built from many classes and objects, which
are the instances of a class.

Classes define the state and behavior of their instances. Behavior comes from
methods defined in the class. State comes from instance fields declared inside
the class.

Classes are modeled on the real-world things we want to represent in our


program. Later we will explore how a program can be made from multiple
classes. For now, our programs are a single class.

public class Dog {


  // instance field
  String breed;
  // constructor method
  public Dog(String dogBreed) {
    /*
    value of parameter dogBreed
    assigned to instance field breed
    */
    breed = dogBreed;
  }
  public static void main(String[] args) {
    /*
    create instance:
    use 'new' operator and invoke constructor
    */
    Dog fido = new Dog("poodle");
    /*
    fields are accessed using:
    the instance name, `.` operator, and the field name.
    */
    fido.breed;
    // "poodle"
  }
}

Instructions
The text editor contains a Dog class. Play around with the code!

Try to add and remove instance fields. Create instances with different values.
Access and print different fields.

public class Dog {
  String breed;
  boolean hasOwner;
  int age;
  
  public Dog(String dogBreed, boolean dogOwned, int dogYears) {
    System.out.println("Constructor invoked!");
    breed = dogBreed;
    hasOwner = dogOwned;
    age = dogYears;
  }
  
  public static void main(String[] args) {
    System.out.println("Main method started");
    Dog fido = new Dog("poodle", false, 4);
    Dog nunzio = new Dog("shiba inu", true, 12);
    boolean isFidoOlder = fido.age > nunzio.age;
    int totalDogYears = nunzio.age + fido.age;
    System.out.println("Two dogs created: a " + fido.breed + " and a " + nunzio.
breed);
    System.out.println("The statement that fido is an older dog is: " + isFidoOl
der);
    System.out.println("The total age of the dogs is: " + totalDogYears);
    System.out.println("Main method finished");
  }
}
Introduction
In the last lesson, we learned that objects have state and behavior. We have
seen how to give objects state through instance fields. Now, we’re going to
learn how to create object behavior using methods. Remember our example of
a Savings Account.
The state tells us what a savings account should know:

 The balance of money available

The behavior tells us what tasks a savings account should be able to perform:

 Depositing - increasing the amount available


 Withdrawing - decreasing the amount available
 Checking the balance - displaying the amount available.

Methods are repeatable, modular blocks of code used to accomplish specific


tasks. We have the ability to define our own methods that will take input, do
something with it, and return the kind of output we want.

Looking at the example above, recreating a savings account is no easy task.


How can one program tackle such a large problem? This is where methods
and their ability to accomplish smaller, specific tasks comes in handy.
Through method decomposition, we can use methods to break down a large
problem into smaller, more manageable problems.

Methods are so reusable. Imagine we wrote a sandwich-making program that


used 20 lines of code to make a single sandwich. Our program would become
very long very quickly if we were making multiple sandwiches. By creating
a makeSandwich() method, we can make a sandwich anytime simply by calling it.

In this lesson, we’ll learn how to create and call our very own methods inside
of our programs.

Keep Reading: AP Computer Science A Students

If we were to share this sandwich-making program with another person, they


wouldn’t have to understand how makeSandwich() worked. If we wrote our
program well, all they would need to know is that if they called makeSandwich(),
they would receive a sandwich. This concept is known as procedural
abstraction: knowing what a method does, but not how it accomplishes it.

Instructions

1.
We have made a SavingsAccount class without using any methods
beyond main() and the constructor, SavingsAccount().

Run the code to see some account behavior happen.

Look at the main method! It’s so long! There is so much repeated code! Can
you imagine how messy it would look if you needed to make 10 deposits?
Throughout this lesson, we will learn how to make methods that would make
checking the balance, depositing, and withdrawing all behavior that would
take only one line of code.

public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Withdrawing:
    int afterWithdraw = savings.balance - 300;
    savings.balance = afterWithdraw;
    System.out.println("You just withdrew "+300);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Deposit:
    int afterDeposit = savings.balance + 600;
    savings.balance = afterDeposit;
    System.out.println("You just deposited "+600);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Deposit:
    int afterDeposit2 = savings.balance + 600;
    savings.balance = afterDeposit2;
    System.out.println("You just deposited "+600);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
  }       
}

Defining Methods
If we were to define a checkBalance() method for the Savings Account example
we talked about earlier, it would look like the following:

public void checkBalance(){


  System.out.println("Hello!");
  System.out.println("Your balance is " + balance);
}
The first line, public void checkBalance(), is the method declaration. It gives the
program some information about the method:

 public means that other classes can access this method. We will learn
more about that later in the course.
 The void keyword means that there is no specific output from the
method. We will see methods that are not void later in this lesson, but
for now, all of our methods will be void.
 checkBalance() is the name of the method.

Every method has its own unique method signature which is comprised of the


method’s name and its parameter type. In this example, the method signature
is checkBalance().
The two print statements are inside the body of the method, which is defined
by the curly braces: { and }.

Anything we can do in our main() method, we can do in other methods! All of


the Java tools you know, like the math and comparison operators, can be used
to make interesting and useful methods.

Keep Reading: AP Computer Science A Students

checkBalance() isconsidered a non-static method because its signature does


not include the keyword static like the main() method does. We’ll learn more
about non-static methods later in this course.

Instructions

1.
In between the constructor and the main() method, add a method
called advertise() to the Store class. It should be accessible by other classes,
and should have no output.

You can leave the body of the method empty.


Hint
If we wanted to write a method called bark() that is accessible by other classes
and produces no output, we would use syntax like:

public void bark(){

}
2.
Inside the advertise() method, type two print statements. They should result
in the printouts:

"Come spend some money!"


"Selling productType!"
where productType is replaced with the value in the variable productType.

However, we’re not going to see these Strings printed out yet! We’ll see in the
next exercise how we can make these printouts actually run.
Hint
If we wanted to print The name of this dog is dogName! with dogName replaced
by the value in the dogName variable, we would write:

System.out.println("The name of this dog is " + dogName +


"!");
Make sure to write your print statements within the curly braces of
the advertise() method!

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  
  // main method
  public static void main(String[] args) {
    
  }
}

Calling Methods
When we add a non-static method to a class, it becomes available to use on
an object of that class. In order to have our methods get executed, we
must call the method on the object we created.

Let’s add a non-static startEngine() method to our Car class from the previous


lesson. Inside the main() method, we’ll call startEngine() on
the myFastCar object:
class Car {

  String color;

  public Car(String carColor) {


    color = carColor;
  }

  public void startEngine() {


    System.out.println("Starting the car!");
    System.out.println("Vroom!");
  }

  public static void main(String[] args){


    Car myFastCar = new Car("red");
    // Call a method on an object
    myFastCar.startEngine();
    System.out.println("That was one fast car!");
  }
}
Let’s take a closer look at the method call:

myFastCar.startEngine();
First, we reference our object myFastCar. Then, we use the dot operator (.) to
call the method startEngine(). Note that we must include parentheses () after
our method name in order to call it.

If we run the above program, we will get the following output.

Starting the car!


Vroom!
That was one fast car!
Code generally runs in a top-down order where code execution starts at the
top of a program and ends at the bottom of a program; however, methods are
ignored by the compiler unless they are being called.

When a method is called, the compiler executes every statement contained


within the method. Once all method instructions are executed, the top-down
order of execution continues. This is why Starting the car! and Vroom! are
outputted before That was one fast car!.

Instructions

1.
Last exercise, we defined a new method, advertise(), but we didn’t actually see
it run.

We now have a Store class with advertise() defined.

Call the advertise() method on the lemonadeStand object in the main() method


and see what the output is!
2.
Now, call the advertise() method on the lemonadeStand object two more times.
It should be called in the main() method three times total.

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
    System.out.println("Selling " + productType + "!");
    System.out.println("Come spend some money!");
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade");
    
  }
}

Scope
A method is a task that an object of a class performs.

We mark the domain of this task using curly braces: {, and }. Everything inside
the curly braces is part of the task. This domain is called the scope of a
method.

We can’t access variables that are declared inside a method in code that is
outside the scope of that method.

Looking at the Car class again:

class Car {
  String color;
  int milesDriven;

  public Car(String carColor) {


    color = carColor;
    milesDriven = 0;         
  }

  public void drive() {


     String message = "Miles driven: " + milesDriven;
     System.out.println(message);
  }

  public static void main(String[] args){


     Car myFastCar = new Car("red");
     myFastCar.drive();
  }
}
The variable message, which is declared and initialized inside of drive, cannot be
used inside of main()! It only exists within the scope of the drive() method.
However, milesDriven, which is declared at the top of the class, can be used
inside all methods in the class, since it is in the scope of the whole class.

Instructions

1.
Inside of the advertise() method, change the productType variable to
the cookie variable, which is declared in the main() method. This should also
result in the printout:

Selling cookies!
Right?
Hint
Your advertise() method should now look like:

public void advertise() {


  String message = "Selling " + cookie + "!";
  System.out.println(message);
}
However, you’ll see that this code won’t work, since cookie is not defined in
the advertise() method. That’s okay! It’s helpful to see the error, so that you
can better understand how it looks when you call a variable outside of its
scope.
2.
No! We got an error! The cookie variable cannot be accessed inside of the
advertise method. The scope is wrong! Change it back to productType:

String message = "Selling " + productType + "!";


Hint
Your advertise() method should now look like it did at first:

public void advertise() {


  String message = "Selling " + productType + "!";
  System.out.println(message);
}
3.
Inside of the main() method, print the String message, which is declared in
the advertise() method. This should print:
Selling Cookies!
Right?
Hint
Your main() method should now look something like:

public static void main(String[] args) {


  String cookie = "Cookies";
  Store cookieShop = new Store(cookie);

  cookieShop.advertise();
  System.out.println(message);
}
However, you’ll see that this code won’t work, since message is not defined in
the main() method. That’s okay! It’s helpful to see the error, so that you can
better understand how it looks when you call a variable outside of its scope.
4.
Foiled again! The message variable only exists inside the scope of
the advertise() method!

Delete the faulty print statement from the main() method.


Hint
Your main() method should now look like it did on at first:

public static void main(String[] args) {


  String cookie = "Cookies";
  Store cookieShop = new Store(cookie);

  cookieShop.advertise();
}

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
    String message = "Selling " + productType + "!";
    System.out.println(message);
  }
  
  // main method
  public static void main(String[] args) {
    String cookie = "Cookies";
    Store cookieShop = new Store(cookie);
    
    cookieShop.advertise();
  }
}

Adding Parameters
We saw how a method’s scope prevents us from using variables declared in
one method in another method. What if we had some information in one
method that we needed to pass into another method?

Similar to how we added parameters to constructors, we can customize all


other methods to accept parameters. For example, in the following code, we
create a startRadio() method that accepts a Double parameter, stationNum, and
a String parameter called stationName:

class Car {

  String color;

  public Car(String carColor) {


    color = carColor;         
  }
  public void startRadio(double stationNum, String stationName)
{
    System.out.println("Turning on the radio to " + stationNum
+ ", " + station + "!");
    System.out.println("Enjoy!");
  }

  public static void main(String[] args){


    Car myCar = new Car("red");
    myCar.startRadio(103.7, "Meditation Station");
  }
}
Adding parameter values impacts our method’s signature. Like constructor
signatures, the method signature includes the method name as well as the
parameter types of the method. The signature of the above method
is startRadio(double, String).

In the main() method, we call the startRadio() method on the myCar object and


provide a double argument of 103.7 and String argument of "Meditation
Station", resulting in the following output:

Turning on the radio to 103.7, Meditation Station!


Enjoy!
Note that when we call on a method with multiple parameters, the arguments
given in the call must be placed in the same order as the parameters appear in
the signature. If the argument types do not match the parameter types, we’ll
receive an error.

Keep Reading: AP Computer Science A Students

Through method overloading, our Java programs can contain multiple


methods with the same name as long as each method’s parameter list is
unique. For example, we can recreate our above program to contain
two startRadio() methods:

// Method 1
public void startRadio(double stationNum, String stationName) {
  System.out.println("Turning on the radio to " + stationNum +
", " + station + "!");
  System.out.println("Enjoy!");
}

// Method 2
public void startRadio(double stationNum) {
  System.out.println("Turning on the radio to " + stationNum +
"!");
}

public static void main(String[] args){


  Car myCar = new Car("red");
  // Calls the first startRadio() method
  myCar.startRadio(103.7, "Meditation Station");

  // Calls the second startRadio() method


  myCar.startRadio(98.2);
}

Instructions

1.
Add a method to the Store class called greetCustomer(). It should be accessible
by other classes, and return no output. For now, have it take no parameters
and leave the body of the method empty.
Hint
If we wanted to write a method called bark() that is accessible by other classes
and produces no output, we would use syntax like:

public void bark(){

}
2.
Modify the greetCustomer() method so that it accepts a String parameter
called customer.
Hint
To add a parameter to a method signature, you put it in the parentheses:
public void methodWithIntParam(int myIntParam){

}
3.
Inside of the greetCustomer() method, add a print statement to print:

"Welcome to the store, " + customer + "!"


4.
Inside the main() method, call the greetCustomer() method on
the lemonadeStand object. Pass in a String argument of your choice!
Hint
If I were calling this method to greet myself, I would use the line:

lemonadeStand.greetCustomer("Laura");

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
    String message = "Selling " + productType + "!";
    System.out.println(message);
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade");
    
  }
}

Rez

public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
    String message = "Selling " + productType + "!";
    System.out.println(message);
  }
  
  public void greetCustomer(String customer){
    System.out.println("Welcome to the store, " + customer + "!");
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade");
    
    lemonadeStand.greetCustomer("Laura");
    
  }
}

Reassigning Instance Fields


Earlier, we thought about a Savings Account as a type of object we could
represent in Java.
Two of the methods we need are depositing and withdrawing:

public SavingsAccount{
  double balance;
  public SavingsAccount(double startingBalance){
    balance = startingBalance;
  }

  public void deposit(double amountToDeposit){


     //Add amountToDeposit to the balance
  }

  public void withdraw(double amountToWithdraw){


     //Subtract amountToWithdraw from the balance
  }

  public static void main(String[] args){

  }
}
These methods would change the value of the variable balance. We
can reassign balance to be a new value by using our assignment operator, =,
again.

public void deposit(double amountToDeposit){


  double updatedBalance = balance + amountToDeposit;
  balance = updatedBalance;
}
Now, when we call deposit(), it should change the value of the instance
field balance:

public static void main(String[] args){


  SavingsAccount myAccount = new SavingsAccount(2000);
  System.out.println(myAccount.balance);
  myAccount.deposit(100);
  System.out.println(myAccount.balance);
}
This code first prints 2000, the initial value of myAccount.balance, and then
prints 2100, which is the value of myAccount.balance after the deposit() method
has run.
Changing instance fields is how we change the state of an object and make
our objects more flexible and realistic.

Instructions

1.
We have added a price instance field to the Store class.

However, to combat inflation costs, we’ve found ourselves increasing the price
of our product over and over. We’ve added an empty increasePrice() method
to the Store class. It takes a double parameter priceToAdd.

Inside of the increasePrice() method, create a variable called newPrice. Declare


it to be a double, and set it equal to the price plus the priceToAdd.
2.
Inside of increasePrice(), set the instance field price to be newPrice!
3.
In the main() method, increase the price at the lemonade stand by 1.5. Then,
print the lemonadeStand.price to see how it has changed!

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    
  }
}

Rez

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    lemonadeStand.increasePrice(1.5);
    System.out.println(lemonadeStand.price);
  }
}
Returns
Remember, variables can only exist in the scope that they were declared in. We
can use a value outside of the method it was created in if we return it from the
method.

We return a value by using the keyword return:

public int numberOfTires() {


   int tires = 4;
   // return statement
   return tires;
}
This method, called numberOfTires(), returns 4. Once the return statement is
executed, the compiler exits the function. Any code that exists after the return
statement in a function is ignored.

In past exercises, when creating new methods, we used the keyword void.


Here, we are replacing void with int, to signify that the return type is an int.

The void keyword (which means “completely empty”) indicates that no value is
returned after calling that method.

A non-void method, like numberOfTires() returns a value when it is called. We


can use datatype keywords (such as int, char, etc.) to specify the type of value
the method should return. The return value’s type must match the return type
of the method. If the return expression is compatible with the return type, a
copy of that value gets returned in a process known as return by value.

Unlike void methods, non-void methods can be used as either a variable value
or as part of an expression like so:

public static void main(String[] args){


    Car myCar = new Car("red");
    int numTires = myCar.numberOfTires();
}
Within main(), we called the numberOfTires() method on myCar. Since the
method returns an int value of 4, we store the value in an integer variable
called numTires. If we printed numTires, we would see 4.
Keep Reading: AP Computer Science A Students

We learned how to return primitive values from a method, but what if we


wanted our method to return an object? Returning an object works a little
differently than returning a primitive value. When we return a primitive value,
a copy of the value is returned; however, when we return an object, we return
a reference to the object instead of a copy of it.

Let’s create a second class, carLot, that takes in a Car as a parameter and


contains a method which returns a Car object.

class CarLot {
    Car carInLot;
    public CarLot(Car givenCar) {
        carInLot = givenCar;
    }

    public Car returnACar() {


        // return Car object
        return carInLot;
    }

    public static void main(String[] args) {


        Car myCar = new Car("red", 70);
        System.out.println(myCar);
        CarLot myCarLot = new CarLot(myCar);
        System.out.println(myCarLot.returnACar());
    }
}
This code outputs the same memory address because myCar and carInLot have
the same reference value:

Car@2f333739
Car@2f333739

Instructions

1.
We want to have a method that returns the price plus tax.
Define a method called getPriceWithTax() that is intended to return the price
plus the tax. It should take in no parameters and return a double.

You can leave the body of the method empty for now. Note: the code will
have an error until we return the correct type from the method, which we will
do in the next step.
Hint
To create a method called getNumBarks() that returns an int, we would use the
syntax:

public int getNumBarks(){


}
2.
Inside the getPriceWithTax() method, create a double variable totalPrice that is
equal to price + price * 0.08. 0.08 is the tax applied to the price.

Then, return totalPrice.
Hint
You can also accomplish this by defining a variable called tax, and then
multiplying by tax instead:

double tax = 0.08;


double totalPrice = price + price*tax;
Make sure to return totalPrice at the end!
3.
Inside of main(), set a double variable lemonadePrice to the value returned
by lemonadeStand.getPriceWithTax().
4.
Now, print out lemonadePrice.

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method

  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);

  }
}

Rez

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method
  public double getPriceWithTax(){
    double tax = 0.08;
    double totalPrice = price + price*tax;
    return totalPrice;
  }

  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);

    double lemonadePrice = lemonadeStand.getPriceWithTax();
    
    System.out.println(lemonadePrice);
  }
}

The toString() Method


When we print out Objects, we often see a String that is not very helpful in
determining what the Object represents. In the last lesson, we saw that when
we printed our Store objects, we would see output like:

Store@6bc7c054
where Store is the name of the object and 6bc7c054 is its position in memory.

This doesn’t tell us anything about what the Store sells, the price, or the other
instance fields we’ve defined. We can add a method to our classes that makes
this printout more descriptive.

When we define a toString() method for a class, we can return a String that will


print when we print the object:
class Car {

    String color;

    public Car(String carColor) {


        color = carColor;
    }

    public static void main(String[] args){


        Car myCar = new Car("red");
        System.out.println(myCar);
    }

   public String toString(){


       return "This is a " + color + " car!";
   }
}
When this runs, the command System.out.println(myCar) will print This is a
red car!, which tells us about the Object myCar.

Instructions

1.
In the main() method, print the Objects lemonadeStand and cookieShop. Are these
printouts helpful in understanding these Objects?
2.
Create a toString() method for the Store class. The method signature should
say that it is public, and that it returns a String. It shouldn’t take in any
parameters. For now, have it return the String "Store".
3.
"Store" isn’t very helpful! What kind of Store is it?

Change the toString() to return a String that describes this Store object.

Your String should look like:

This store sells productType at a price of price.


where productType and price are the values in those instance fields. For
example, if it was a hat store where hats cost 8, the String would say:
This store sells hats at a price of 8.
4.
Look at the printouts again. Are they more helpful now?

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method
  public double getPriceWithTax(){
    double tax = 0.08;
    double totalPrice = price + price*tax;
    return totalPrice;
  }

  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    Store cookieShop = new Store("Cookies", 5);

  }
}

Rez

public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method
  public double getPriceWithTax(){
    double tax = 0.08;
    double totalPrice = price + price*tax;
    return totalPrice;
  }
  
  public String toString(){
    return "This store sells " + productType + " at a price of " + price + ".";
  }

  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    Store cookieShop = new Store("Cookies", 5);
    System.out.println(lemonadeStand);
    System.out.println(cookieShop);
  }
}

Review
Great work! Methods are a powerful way to abstract tasks away and make
them repeatable. They allow us to define behavior for classes, so that the
Objects we create can do the things we expect them to. Let’s review
everything we have learned about methods so far.

 Defining a method : Methods have a method signature that declares


their return type, name, and parameters
 Calling a method : Methods are invoked with a . and ()
 Parameters : Inputs to the method and their types are declared in
parentheses in the method signature
 Changing Instance Fields : Methods can be used to change the value of
an instance field
 Scope : Variables only exist within the domain that they are created in
 Return : The type of the variables that are output are declared in the
method signature

As you move through more Java material, it will be helpful to frame the tasks
you create in terms of methods. This will help you think about what inputs you
might need and what output you expect.

Instructions

1.
Now that we’ve learned about behavior, we can apply behavior to
our SavingsAccount class using methods!

We’ve added the functionality for each method inside main() now, but you will
be rebuilding each above main(). Note that your methods can directly access
the balance field.
First, write a method called checkBalance() that prints:

Hello!
Your balance is
with the balance of the account displayed.

It should take in no parameters and return nothing.


Hint
A checkPrice() method for our Store class would have looked like:

public void checkPrice(){


  System.out.println("Welcome!");
  System.out.println("The price is "+ price);
}
How would you do this for checkBalance()?

Don’t forget to call


2.
Now, write a method called deposit() that takes in
an int parameter amountToDeposit and adds it to the balance. It should return
nothing.

If you want, you can also have the method print:

You just deposited amountToDeposit


with the value of amountToDeposit displayed.
Hint
An addInventory() method for our Store class would have looked something
like:

public void addInventory(int inventoryToAdd){


  int newInventory = inventory + inventoryToAdd;
  inventory = newInventory;
}
You can do something similar for deposit()!
3.
Now, write a method called withdraw() that takes in
an int parameter amountToWithdraw and subtracts it from the balance. It should
return the amountToWithdraw.

If you want, you can also have the method print:

You just withdrew amountToWithdraw


with the value of amountToWithdraw displayed.
Hint
A sellItems() method for our Store class would have looked something like:

public int addInventory(int numItems){


  int newInventory = sellItems - numItems;
  inventory = newInventory;
  return numItems;
}
You can do something similar for withdraw()!
4.
Test out your methods by trying to replace some of the code in
the main() method with the equivalent methods!

Make sure to use checkBalance(), deposit(), and withdraw() at least once each.


5.
Congratulations! You’ve made a basic SavingsAccount.

If you want, you can add more functionality to this! What other instance fields
might you want to keep track of? What might a toString() look like for this
class?
public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Withdrawing:
    int afterWithdraw = savings.balance - 300;
    savings.balance = afterWithdraw;
    System.out.println("You just withdrew "+300);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Deposit:
    int afterDeposit = savings.balance + 600;
    savings.balance = afterDeposit;
    System.out.println("You just deposited "+600);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
    //Deposit:
    int afterDeposit2 = savings.balance + 600;
    savings.balance = afterDeposit2;
    System.out.println("You just deposited "+600);
    
    //Check balance:
    System.out.println("Hello!");
    System.out.println("Your balance is "+savings.balance);
    
  }       
}
Rez

public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public void checkBalance(){
    System.out.println("Hello!");
    System.out.println("Your balance is "+balance);
  }
  
  public void deposit(int amountToDeposit){
    balance = amountToDeposit + balance;
    System.out.println("You just deposited " + amountToDeposit);
  }
  
  public int withdraw(int amountToWithdraw){
    balance = balance - amountToWithdraw;
    System.out.println("You just withdrew " + amountToWithdraw);
    return amountToWithdraw;
  }
  
  public String toString(){
    return "This is a savings account with " + balance + " saved.";
  }
  
  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    
    //Check balance:
    savings.checkBalance();
    
    //Withdrawing:
    savings.withdraw(300);
    
    //Check balance:
    savings.checkBalance();
    
    //Deposit:
    savings.deposit(600);
    
    //Check balance:
    savings.checkBalance();
    
    //Deposit:
    savings.deposit(600);
    
    //Check balance:
    savings.checkBalance();
    
    System.out.println(savings);
  }       
}
Introduction to Control Flow
Imagine we’re writing a program that enrolls students in courses.

 If a student has completed the prerequisites, then they can enroll in a


course.
 Else, they need to take the prerequisite courses.

They can’t take Physics II without finishing Physics I.

We represent this kind of decision-making in our program


using conditional or control flow statements. Before this point, our code runs
line-by-line from the top down, but conditional statements allow us to be
selective in which portions will run.

Conditional statements check a boolean condition and run a block of code


depending on the condition. Curly braces mark the scope of a conditional
block similar to a method or class.

Here’s a complete conditional statement:

if (true) {

  System.out.println("Hello World!");

}
If the condition is true, then the block is run. So Hello World! is printed.

But suppose the condition is different:

if (false) {

  System.out.println("Hello World!");

}
If the condition is false, then the block does not run.

This code is also called if-then statements: “If (condition) is true, then do


something”.

Instructions

Let’s get started!

Click Next to continue.

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

If-Then Statement
The if-then statement is the most simple control flow we can write. It tests an
expression for truth and executes some code based on it.

if (flip == 1) {

  System.out.println("Heads!");

 The if keyword marks the beginning of the conditional statement,


followed by parentheses ().
 The parentheses hold a boolean datatype.

For the condition in parentheses we can also use variables that reference a
boolean, or comparisons that evaluate to a boolean.

The boolean condition is followed by opening and closing curly braces that
mark a block of code. This block runs if, and only if, the boolean is true.

boolean isValidPassword = true;

if (isValidPassword) {

  System.out.println("Password accepted!");

// Prints "Password accepted!"

int numberOfItemsInCart = 9;

if (numberOfItemsInCart > 12) {

  System.out.println("Express checkout not available");


}

// Nothing is printed.
If a conditional is brief we can omit the curly braces entirely:

if (true) System.out.println("Brevity is the soul of wit");


Note: Conditional statements do not end in a semicolon.

Instructions

1.
The code editor contains an Order class to track retail shipments.

Write an if-then statement that prints High value item! when itemCost is


greater than 24.00.
Hint
Here’s the general structure:

if (condition) {

  // Do something

public class Order {
  
  public static void main(String[] args) {
    
    double itemCost = 30.99;
    
    // Write an if-then statement:
    
    
  }
  
}
If-Then-Else
We’ve seen how to conditionally execute one block of code, but what if there
are two possible blocks of code we’d like to execute?

Let’s say if a student has the required prerequisite, then they enroll in the


selected course, else they’re enrolled in the prerequisite course instead.

We create an alternate conditional branch with the else keyword:

if (hasPrerequisite) {

  // Enroll in course

} else {

  // Enroll in prerequisite

}
This conditional statement ensures that exactly one code block will be run. If
the condition, hasPrerequisite, is false, the block after else runs.

There are now two separate code blocks in our conditional statement. The first
block runs if the condition evaluates to true, the second block runs if the
condition evaluates to false.

This code is also called an if-then-else statement:

 If condition is true, then do something.


 Else, do a different thing.

Instructions

1.
In the code editor, there is an isFilled value, that represents whether the
order is ready to ship.

Write an if-then-else statement that:

 When isFilled is true, print Shipping.
 When isFilled is false, print Order not ready.

Hint
Here’s the structure of an if-then-else conditional statement:

if (condition) {

  // Do one thing

} else {

  // Do another thing

If-Then-Else-If
The conditional structure we’ve learned can be chained together to check as
many conditions as are required by our program.

Imagine our program is now selecting the appropriate course for a student.
We’ll check their submission to find the correct course enrollment.

The conditional statement now has multiple conditions that are evaluated
from the top down:

String course = "Theatre";

if (course.equals("Biology")) {

  // Enroll in Biology course

} else if (course.equals("Algebra")) {

  // Enroll in Algebra course

} else if (course.equals("Theatre")) {

  // Enroll in Theatre course


} else {

  System.out.println("Course not found!");

}
The first condition to evaluate to true will have that code block run. Here’s an
example demonstrating the order:

int testScore = 72;

if (testScore >= 90) {

  System.out.println("A");

} else if (testScore >= 80) {

  System.out.println("B");

} else if (testScore >= 70) {

  System.out.println("C");

} else if (testScore >= 60) {

  System.out.println("D");

} else {

  System.out.println("F");

}
// prints: C
This chained conditional statement has two conditions that evaluate true.
Because testScore >= 70 comes before testScore >= 60, only the earlier code
block is run.

Note: Only one of the code blocks will run.

Instructions
1.
We need to calculate the shipping costs for our orders.

There’s a new instance field, String shipping, that we use to calculate the cost.

Use a chained if-then-else to check for different values within


the calculateShipping() method.

When the shipping instance field equals "Regular", the method should return 0.

When the shipping instance field equals "Express", the method should


return 1.75.

Else the method should return .50.

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    // declare conditional statement here
    
  }
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express");
    Order chemistrySet = new Order(false, 72.50, "Regular");
    
    book.ship();
    chemistrySet.ship();
  }
}

Nested Conditional Statements


We can create more complex conditional structures by creating nested
conditional statements, which is created by placing conditional statements
inside other conditional statements:

if (outer condition) {
if (nested condition) {
Instruction to execute if both conditions are true
}
}
When we implement nested conditional statements, the outer statement is
evaluated first. If the outer condition is true, then the inner, nested statement
is evaluated.

Let’s create a program that helps us decide what to wear based on the
weather:

int temp = 45;


boolean raining = true;
if (temp < 60) {
  System.out.println("Wear a jacket!");
  if (raining == true) {
    System.out.println("Bring your umbrella.");
  } else {
    System.out.println("Leave your umbrella home.");
  }
}
In the code snippet above, our compiler will check the condition in the first if-
then statement: temp < 60. Since temp has a value of 45, this condition is true;
therefore, our program will print Wear a jacket!.

Then, we’ll evaluate the condition of the nested if-then statement: raining ==


true. This condition is also true, so Bring your umbrella is also printed to the
screen.

Note that, if the first condition was false, the nested condition would not be
evaluated.

Instructions

1.
The company offers a temporary deal that, if the consumer uses the
coupon "ship50", the company will reduce the express shipping price.

Let’s rewrite the body of else-if statement from the last exercise. Inside
the else-if statement, create a nested if-then statement that checks
if couponCode equals "ship50".

If the nested condition is true, return the value .85.

If the condition is false, use a nested else statement to return the value 1.75.

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  String couponCode;
  
  public Order(boolean filled, double cost, String shippingMethod, String coupon
) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
    couponCode = coupon;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    if (shipping.equals("Regular")) {
      return 0;
    } else if (shipping.equals("Express")) {
      // Add your code here

      
    } else {
      return .50;
    }
  }
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express", "ship50");
    Order chemistrySet = new Order(false, 72.50, "Regular", "freeShipping");
    
    book.ship();
    chemistrySet.ship();
  }
}

Rez

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  String couponCode;
  
  public Order(boolean filled, double cost, String shippingMethod, String coupon
) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
    couponCode = coupon;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    if (shipping.equals("Regular")) {
      return 0;
    } else if (shipping.equals("Express")) {
      // Add your code here
      if (couponCode.equals("ship50")) {
        return 0.85;
      } else {
        return 1.75;
      }
    } else {
      return .50;
    }
  }
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express", "ship50");
    Order chemistrySet = new Order(false, 72.50, "Regular", "freeShipping");
    
    book.ship();
    chemistrySet.ship();
  }
}

Switch Statement
An alternative to chaining if-then-else conditions together is to use
the switch statement. This conditional will check a given value against any
number of conditions and run the code block where there is a match.

Here’s an example of our course selection conditional as a switch statement


instead:

String course = "History";

switch (course) {
  case "Algebra":
    // Enroll in Algebra
    break;
  case "Biology":
    // Enroll in Biology
    break;
  case "History":
    // Enroll in History
    break;
  case "Theatre":
    // Enroll in Theatre
    break;
  default:
    System.out.println("Course not found");
}
This example enrolls the student in History class by checking the value
contained in the parentheses, course, against each of the case labels. If the
value after the case label matches the value within the parentheses, the switch
block is run.

In the above example, course references the string "History", which


matches case "History":.

When no value matches, the default block runs. Think of this as


the else equivalent.

Switch blocks are different than other code blocks because they are not
marked by curly braces and we use the break keyword to exit the switch
statement.

Without break, code below the matching case label is run, including code under


other case labels, which is rarely the desired behavior.

String course = "Biology";

switch (course) {
  case "Algebra":
    // Enroll in Algebra
  case "Biology":
    // Enroll in Biology
  case "History":
    // Enroll in History
  case "Theatre":
    // Enroll in Theatre
  default:
    System.out.println("Course not found");
}

// enrolls student in Biology... AND History and Theatre!

Instructions

1.
We’ll rewrite the calculateShipping() method so it uses a switch statement
instead.

There’s an uninitialized variable shippingCost in calculateShipping(). Assign the


correct value to shippingCost using a switch statement:

We’ll check the value of the instance field shipping.

 When shipping matches "Regular", shippingCost should be 0.
 When shipping matches "Express", shippingCost should be 1.75.
 The default should assign .50 to shippingCost.

Make sure the method returns shippingCost after the switch statement.

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    double shippingCost;
    // declare switch statement here
    
    
    return shippingCost;
  }
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express");
    Order chemistrySet = new Order(false, 72.50, "Regular");
    
    book.ship();
    chemistrySet.ship();
  }
}

Rez

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    double shippingCost;
    // declare switch statement here
    switch (shipping) {

      case "Regular":
        shippingCost = 0;
        break;
      case "Express":    
        shippingCost = 1.75;
        break;
      default:
        shippingCost = .50; 
    }
    
    return shippingCost;
  }
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express");
    Order chemistrySet = new Order(false, 72.50, "Regular");
    
    book.ship();
    chemistrySet.ship();
  }
}

Review
Before this lesson, our code executed from top to bottom, line by line.

Conditional statements add branching paths to our programs. We use


conditionals to make decisions in the program so that different inputs will
produce different results.

Conditionals have the general structure:

if (condition) {
    // consequent path
} else {
    // alternative path
}
Specific conditional statements have the following behavior:

 if-then:
o code block runs if condition is true
 if-then-else:
o one block runs if conditions is true
o another block runs if condition is false
 if-then-else chained:
o same as if-then but an arbitrary number of conditions
 switch:
o switch block runs if condition value matches case value

Instructions

Our complete Order program is in the text editor but the main() method is


empty.

Create different Order instances and see if you can run the code in all the
different conditional blocks!

public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
    if (cost > 24.00) {
      System.out.println("High value item!");
    } else {
      System.out.println("Low value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
    } else {
      System.out.println("Order not ready");
    }
    
    double shippingCost = calculateShipping();
    
    System.out.println("Shipping cost: ");
    System.out.println(shippingCost);
  }
  
  public double calculateShipping() {
    double shippingCost;
    switch (shipping) {
      case "Regular":
        shippingCost = 0;
        break;
      case "Express":    
        shippingCost = 1.75;
        break;
      default:
        shippingCost = .50; 
    }
    return shippingCost;
  }
  
  public static void main(String[] args) {
    // create instances and call methods here!

  }
}

Conditional-And: &&
Let’s return to our student enrollment program. We’ve added an additional
requirement: not only must students have the prerequisite, but their tuition
must be paid up as well. We have two conditions that must be true before we
enroll the student.

Here’s one way we could write the code:

if (tuitionPaid) {
  if (hasPrerequisite) {
    // enroll student
  }
}
We’ve nested two if-then statements. This does the job but we can be more
concise with the AND operator:

if (tuitionPaid && hasPrerequisite) {


  // enroll student
}
The AND operator, &&, is used between two boolean values and evaluates to a
single boolean value. If the values on both sides are true, then the resulting
value is true, otherwise the resulting value is false.

This code illustrates every combination:

true && true


// true
false && true
// false
true && false
// false
false && false
// false

Instructions

1.
Our Reservation class has the method confirmReservation() which validates if a
restaurant can accomodate a given reservation.

We need to build the conditional logic into confirmReservation() using two


parameters:

 restaurantCapacity
 isRestaurantOpen

Use an if-then-else statement:
If restaurantCapacity is greater than or equal to guestCount and the restaurant
is open, print "Reservation confirmed" and set isConfirmed to true.

else print "Reservation denied" and set isConfirmed to false.

public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    guestCount = count;
    restaurantCapacity = capacity;
    isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    /* 
       Write conditional
       ~~~~~~~~~~~~~~~~~
       if restaurantCapacity is greater
       or equal to guestCount
       AND
       the restaurant is open:
         print "Reservation confirmed"
         set isConfirmed to true
       else:
         print "Reservation denied"
         set isConfirmed to false
    */
  }
  
  public void informUser() {
    System.out.println("Please enjoy your meal!");
  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}

Conditional-Or: ||
The requirements of our enrollment program have changed again. Certain
courses have prerequisites that are satisfied by multiple courses. As long as
students have taken at least one prerequisite, they should be allowed to
enroll.

Here’s one way we could write the code:

if (hasAlgebraPrerequisite) {
  // Enroll in course
}

if (hasGeometryPrerequisite) {
  // Enroll in course
}
We’re using two different if-then statements with the same code block. We
can be more concise with the OR operator:

if (hasAlgebraPrerequisite || hasGeometryPrerequisite) {
  // Enroll in course
}
The OR operator, ||, is used between two boolean values and evaluates to a
single boolean value. If either of the two values is true, then the resulting
value is true, otherwise the resulting value is false.
This code illustrates every combination:

true || true
// true
false || true
// true
true || false
// true
false || false
// false
Keep Reading: AP Computer Science A Students

On some occasions, the compiler can determine the truth value of a logical
expression by only evaluating the first boolean operand; this is known as short-
circuited evaluation. Short-circuited evaluation only works with expressions
that use && or ||.

In an expression that uses ||, the resulting value will be true as long as one of
the operands has a true value. If the first operand of an expression is true, we
don’t need to see what the value of the other operand is to know that the final
value will also be true.

For example, we can run the following code without error despite dividing a
number by 0 in the second operand because the first operand had
a true value:

if (1 > 0 || 2 / 0 == 7) {


  System.out.println("No errors here!");
}
An expression that uses && will only result in true if both operands are true. If
the first operand in the expression is false, the entire value will be false.

Instructions

1.
Let’s write a message inside the Reservation() constructor that warns against
bad input.
Our restaurants can’t seat parties of more than 8 people, and we don’t want
reservations for 0 or less because that would be silly.

Inside Reservation(), write a conditional that uses ||.

If count is less than 1 OR greater than 8 we want to write the following


message: Invalid reservation!.

public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    // Write conditional statement here
    if (count < 1 || count > 8) {
      System.out.println("Invalid reservation!");
    }
    guestCount = count;
    restaurantCapacity = capacity;
    isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    if (restaurantCapacity >= guestCount && isRestaurantOpen) {
      System.out.println("Reservation confirmed");
      isConfirmed = true;
    } else {
      System.out.println("Reservation denied");
      isConfirmed = false;
    }
  }
  
  public void informUser() {
      System.out.println("Please enjoy your meal!");
  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}

Logical NOT: !
The unary operator NOT, !, works on a single value. This operator evaluates to
the opposite boolean to which it’s applied:

!false
// true
!true
// false
NOT is useful for expressing our intent clearly in programs. For example,
sometimes we need the opposite behavior of an if-then: run a code
block only if the condition is false.

boolean hasPrerequisite = false;

if (hasPrerequisite) {
  // do nothing
} else {
  System.out.println("Must complete prerequisite course!");
}
This code does what we want but it’s strange to have a code block that does
nothing!

The logical NOT operator cleans up our example:

boolean hasPrerequisite = false;


if (!hasPrerequisite) {
  System.out.println("Must complete prerequisite course!");
}
We can write a succinct conditional statement without an empty code block.

Instructions

1.
Let’s make informUser() more informative. If their reservation is not confirmed,
they should know!

Write an if-then-else statement and use ! with isConfirmed as the condition.

If their reservation is not confirmed, write Unable to confirm reservation,


please contact restaurant.

Else write: Please enjoy your meal!

public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    if (count < 1 || count > 8) {
      System.out.println("Invalid reservation!");
    }
    guestCount = count;
    restaurantCapacity = capacity;
    isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    if (restaurantCapacity >= guestCount && isRestaurantOpen) {
      System.out.println("Reservation confirmed");
      isConfirmed = true;
    } else {
      System.out.println("Reservation denied");
      isConfirmed = false;
    }
  }
  
  public void informUser() {
    // Write conditional here

  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}

Combining Conditional Operators


We have the ability to expand our boolean expressions by using multiple
conditional operators in a single expression.

For example:

boolean foo = true && !(false || !true)


How does an expression like this get evaluated by the compiler? The order of
evaluation when it comes to conditional operators is as follows:

1. Conditions placed in parentheses - ()


2. NOT - !
3. AND - &&
4. OR - ||
Using this information, let’s dissect the expression above to find the value
of foo:

true && !(false || !true)


First, we’ll evaluate (false || !true) because it is enclosed within parentheses.
Following the order of evaluation, we will evaluate !true, which equals false:

true && !(false || false)


Then, we’ll evaluate (false || false) which equals false. Now our expression
looks like this:

true && !false


Next, we’ll evaluate !false because it uses the NOT operator. This expression
equals true making our expression the following:

true && true


true && true evaluates to true; therefore, the value of foo is true.

Instructions

Take a look at the three expressions in Operators.java.

Using your understanding of the order of execution, find out whether the
value of each expression is true or false.

When you’re ready, uncomment the print statements to find out if you are
right.

public class Operators {
  public static void main(String[] args) {
    int a = 6;
    int b = 3;

    boolean ex1 = !(a == 7 && (b >= a || a != a));
    // System.out.println(ex1);

    boolean ex2 = a == b || !(b > 3);
    // System.out.println(ex2);
    boolean ex3 = !(b <= a && b != a + b);
    // System.out.println(ex3); 

  }
}

Review

Conditional operators work on boolean values to simplify our code. They’re


often combined with conditional statements to consolidate the branching
logic.

Conditional-AND, &&, evaluates to true if the booleans on both sides are true.

if (true && false) {


  System.out.println("You won't see me print!");
} else if (true && true) {
  System.out.println("You will see me print!");
}
Conditional-OR, ||, evaluates to true if one or both of the booleans on either
side is true.

if (false || false) {
  System.out.println("You won't see me print!");
} else if (false || true) {
  System.out.println("You will see me print!");
}
Logical-NOT, !, evaluates to the opposite boolean value to which it is applied.

if (!false) {
  System.out.println("You will see me print!");
}

Instructions

The complete Reservation class is in the code editor.


Play around inside main() and see if you can create instances that will run
every possible conditional branch.

public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    if (count < 1 || count > 8) {
      System.out.println("Invalid reservation!");
    }
    guestCount = count;
    restaurantCapacity = capacity;
    isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    if (restaurantCapacity >= guestCount && isRestaurantOpen) {
      System.out.println("Reservation confirmed");
      isConfirmed = true;
    } else {
      System.out.println("Reservation denied");
      isConfirmed = false;
    }
  }
  
  public void informUser() {
    if (!isConfirmed) {
      System.out.println("Unable to confirm reservation, please contact restaura
nt.");
    } else {
      System.out.println("Please enjoy your meal!");
    }
  }
  
  public static void main(String[] args) {
    // Create instances here
    
  }
}
Introduction
We have seen how to store single pieces of data in variables. What happens
when we need to store a group of data? What if we have a list of students in a
classroom? Or a ranking of the top 10 horses finishing a horse race?
If we were storing 5 lottery ticket numbers, for example, we could create a
different variable for each value:

int firstNumber = 4;


int secondNumber = 8;
int thirdNumber = 15;
int fourthNumber = 16;
int fifthNumber = 23;
That is a lot of ungainly repeated code. What if we had a hundred lottery
numbers? It is more clean and convenient to use a Java array to store the data
as a list.

An array holds a fixed number of values of one type. Arrays


hold doubles, ints, booleans, or any other primitives. Arrays can also
contain Strings as well as object references!

Each index of an array corresponds with a different value. Here is a diagram of


an array filled with integer values:
Notice that the indexes start at 0! The element at index 0 is 4, while the
element at index 1 is 8. This array has a length of 5, since it holds five
elements, but the highest index of the array is 4.

Let’s explore how to create and use arrays in Java, so that we can store all of
our Java data types.

Instructions

1.
In Newsfeed.java, we have created a Newsfeed class to keep track of trending
articles and their associated views and ratings. We did this using Java arrays,
which you’ll learn about throughout the lesson!

For now, run the code to see some of our method calls.
ublic class Newsfeed {
  
  String[] trendingArticles;
  int[] views;
  double[] ratings;
  
  public Newsfeed(String[] initialArticles, int[] initialViews, double[] initial
Ratings){
    trendingArticles = initialArticles;
    views = initialViews;
    ratings = initialRatings;
  }
  
  public String getTopArticle(){
    return trendingArticles[0];
  }
  
  public void viewArticle(int articleNumber){
    views[articleNumber] = views[articleNumber] + 1;
    System.out.println("The article '" + trendingArticles[articleNumber] + "' ha
s now been viewed " + views[articleNumber] + " times!");
  }
  
  public void changeRating(int articleNumber, double newRating){
    if (newRating > 5 || newRating < 0) {
      System.out.println("The rating must be between 0 and 5 stars!");
    } else {
      ratings[articleNumber] = newRating;
      System.out.println("The article '" + trendingArticles[articleNumber] + "' 
is now rated " + ratings[articleNumber] + " stars!");
    }
  }
  
  public static void main(String[] args){
    String[] robotArticles = {"Oil News", "Innovative Motors", "Humans: Extermin
ate Or Not?", "Organic Eye Implants", "Path Finding in an Unknown World"};
    int[] robotViewers = {87, 32, 13, 11, 7};
    double[] robotRatings = {2.5, 3.2, 5.0, 1.7, 4.3};
    Newsfeed robotTimes = new Newsfeed(robotArticles, robotViewers, robotRatings
);
    
    robotTimes.viewArticle(2);
    robotTimes.viewArticle(2);
    System.out.println("The top article is " + robotTimes.getTopArticle());
    robotTimes.changeRating(3, 5);
  }
}

Creating an Array Explicitly


Imagine that we’re using a program to keep track of the prices of different
clothing items we want to buy. We would want a list of the prices and a list of
the items they correspond to. To create an array, we first declare the type of
data it holds:

double[] prices;
Then, we can explicitly initialize the array to contain the data we want to store:

prices = {13.15, 15.87, 14.22, 16.66};


Just like with simple variables, we can declare and initialize in the same line:

double[] prices = {13.15, 15.87, 14.22, 16.66};


We can use arrays to hold Strings and other objects as well as primitives:

String[] clothingItems = {"Tank Top", "Beanie", "Funny Socks",


"Corduroys"};

Instructions

1.
We have an empty Newsfeed class that does not store anything yet.

First, make a method called getTopics(), which:


 is public
 returns a String array
 does not take any parameters

For now, leave the method empty.


Stuck? Get a hint
2.
Inside the getTopics() method, create a String array called topics and set it
equal to an array containing these elements, in order:

Opinion
Tech
Science
Health
Then, return topics from the method!
Stuck? Get a hint
3.
Uncomment the lines in the main method to see how the getTopics() method
works on a Newsfeed instance.

public class Newsfeed {
  
  
  public Newsfeed(){
    
  }
  
  // Create getTopics() below:
  

  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    /*
    String[] topics = sampleFeed.getTopics();
    System.out.println(topics);
    */
  }
}

Rez
public class Newsfeed {
  
  
  public Newsfeed(){
    
  }
    
  // Create getTopics() below:
  public String[] getTopics(){
    String[] topics = {"Opinion", "Tech", "Science", "Health"};
    return topics;
  }
  
  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    String[] topics = sampleFeed.getTopics();
    System.out.println(topics);
  }
}

You might also like