Introduction To Java
Introduction To Java
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.
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.
}
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.
}
Like classes, we used curly braces to mark the beginning and end of a method.
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.
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”.
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.
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..."
"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.
/*
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.
/**
* 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.
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!");
}
}
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.
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.
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.
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.
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.");
}
}
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 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.
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!
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?
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.
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!");
}
}
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.
java Whales
Note that we leave off the .class part of the filename.
javac Welcome.java
The terminal shows no errors, which indicates a successful compilation.
java Welcome
The following is printed to the screen:
Instructions
1.
Let’s compile and execute our program!
We’ve also learned rules and guidelines for how to write Java programs:
Instructions
1.
The text editor holds an empty file named Review.java. Fill it in!
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.
Case-Sensitivity
Comments
Classes
Methods
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.
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.
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.
Autocomplete
When the IDE knows your programming language, it can anticipate what
you’re going to type next!
Debugging
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.
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.
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.
// datatype variableName
int age;
double salaryRequirement;
boolean isEmployed;
The names of the variables above are age, salaryRequirement, and isEmployed.
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!
Instructions
1.
In Creator.java, we have defined some variables related to James Gosling, the
creator of Java.
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.
ints hold positive numbers, negative numbers, and zero. They do not store
fractions or numbers with decimals in them.
Instructions
1.
The file CountComment.java has a number of comments in it.
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.
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.
These questions are answered with a boolean, a type that references one of
two values: true or false.
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:
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.
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!
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:
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.
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?
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:
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.
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:
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.
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.
GuessinGame.java
public class GuessingGame {
public static void main(String[] args) {
int mystery1 = 8 + 6;
int mystery2 = 8 - 6;
}
}
// 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.
PlusAndMinus.java
public class PlusAndMinus {
public static void main(String[] args) {
int zebrasInZoo = 8;
int giraffesInZoo = 4;
}
}
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.
Print the total variable!
2.
There were 4 people who bought this meal together and want to split the cost.
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?
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?
Modulo.java
public class Modulo {
public static void main(String[] args) {
int students = 26;
}
}
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:
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.
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?
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
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);
}
}
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.
GreaterLessThan.java
public class GreaterLessThan {
public static void main(String[] args) {
double creditsEarned = 176.5;
double creditsOfSeminar = 8;
double creditsToGraduate = 180;
}
}
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.
EqualNotEqual.java
public class EqualNotEqual {
public static void main(String[] args) {
int songsA = 9;
int songsB = 9;
int albumLengthA = 41;
int albumLengthB = 53;
}
}
Instructions
1.
You have been trying to complete a 30 day challenge to drink enough water
per day.
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.
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:
Instructions
1.
In our zoo, we have a certain number of animals, stored in animals, of a certain
species, stored in species.
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.
Instructions
1.
Create an unchangeable double variable called pi and set its value to 3.14.
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:
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.
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.
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.
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.
}
// 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.
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.
public Car() {
// instructions for creating a Car instance
}
If we were to output the value of ferrari we would see its memory address:
Car@76ed5528
Keep Reading: AP Computer Science A Students
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
Instructions
1.
Let’s explore how code execution moves around the file with two methods.
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.
Hint
When printing a variable, do not use double quotes.
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);
}
}
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.
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.
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);
}
}
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!
// 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.
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.
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.
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) {
}
}
The type of the value given to the invocation must match the type declared
by the parameter.
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".
/*
accessing a field:
objectName.fieldName
*/
ferrari.color;
// "red"
Keep Reading: AP Computer Science A Students
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;
}
}
We can create an instance of Dog with a breedType of "retriever" like so:
public class Store {
// instance fields
String productType;
// constructor method
public Store(String product) {
productType = product;
}
// main method
public static void main(String[] args) {
}
}
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.
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.
Instructions
1.
Add two new instance fields for Store.
String breed;
boolean isWagging;
int age;
2.
Update the Store constructor method with the new parameters.
You must use that order and include the types for each parameter.
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.
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 behavior tells us what tasks a savings account should be able to perform:
In this lesson, we’ll learn how to create and call our very own methods inside
of our programs.
Instructions
1.
We have made a SavingsAccount class without using any methods
beyond main() and the constructor, SavingsAccount().
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 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.
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.
}
2.
Inside the advertise() method, type two print statements. They should result
in the printouts:
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:
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.
String color;
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.
Instructions
1.
Last exercise, we defined a new method, advertise(), but we didn’t actually see
it run.
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.
class Car {
String color;
int milesDriven;
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:
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!
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?
class Car {
String color;
// 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 +
"!");
}
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:
}
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:
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");
}
}
public SavingsAccount{
double balance;
public SavingsAccount(double startingBalance){
balance = startingBalance;
}
}
}
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.
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.
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.
The void keyword (which means “completely empty”) indicates that no value is
returned after calling that method.
Unlike void methods, non-void methods can be used as either a variable value
or as part of an expression like so:
class CarLot {
Car carInLot;
public CarLot(Car givenCar) {
carInLot = givenCar;
}
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:
Then, return totalPrice.
Hint
You can also accomplish this by defining a variable called tax, and then
multiplying by tax instead:
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);
}
}
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.
String color;
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?
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.
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.
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 (true) {
System.out.println("Hello World!");
}
If the condition is true, then the block is run. So Hello World! is printed.
if (false) {
System.out.println("Hello World!");
}
If the condition is false, then the block does not run.
Instructions
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!");
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.
if (isValidPassword) {
System.out.println("Password accepted!");
int numberOfItemsInCart = 9;
// Nothing is printed.
If a conditional is brief we can omit the curly braces entirely:
Instructions
1.
The code editor contains an Order class to track retail shipments.
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?
if (hasPrerequisite) {
} else {
}
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.
Instructions
1.
In the code editor, there is an isFilled value, that represents whether the
order is ready to ship.
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) {
} else {
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:
if (course.equals("Biology")) {
} else if (course.equals("Algebra")) {
} else if (course.equals("Theatre")) {
}
The first condition to evaluate to true will have that code block run. Here’s an
example demonstrating the order:
System.out.println("A");
System.out.println("B");
System.out.println("C");
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.
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.
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();
}
}
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:
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".
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.
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.
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.
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");
}
Instructions
1.
We’ll rewrite the calculateShipping() method so it uses a switch statement
instead.
When shipping matches "Regular", shippingCost should be 0.
When shipping matches "Express", shippingCost should be 1.75.
The default should assign .50 to shippingCost.
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.
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
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.
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:
Instructions
1.
Our Reservation class has the method confirmReservation() which validates if a
restaurant can accomodate a given reservation.
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.
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.
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:
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.
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.
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!
Instructions
1.
Let’s make informUser() more informative. If their reservation is not confirmed,
they should know!
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();
}
}
For example:
Instructions
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
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
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:
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);
}
}
double[] prices;
Then, we can explicitly initialize the array to contain the data we want to store:
Instructions
1.
We have an empty Newsfeed class that does not store anything yet.
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);
}
}