You are on page 1of 20

JAVA Notes

Introduction to Java

What's your name?


Java is a programming language designed to build secure, powerful applications that run across
multiple operating systems, including Linux, Mac OS X, and Windows. The Java language is
known to be flexible, scalable, and maintainable.
We will begin with the fundamentals of Java programming: data types, arithmetic, and operators.
Well learn a few concepts that you can apply to the programs you create. By the end of the course,
youll be familiar with the basic building blocks of a Java program.

Data Types I: int


Great job! You've already learned how to print text.
Creating more useful Java programs will likely require you to work with several additional types of
data. Let's explore a few of them.
The first data type we will use is int.

1. int is short for integer, which are all positive and negative numbers, including zero. This
number could represent the number of visits a website has received or the number of
programming languages you know.
2. The int data type only allows values between -2,147,483,648 and 2,147,483,647.

Data Types II: boolean


Fantastic! You just printed an int data type.

The next data type we will use is the boolean.

1. A boolean is a data type that can only be either true or false.

Data Types III: char


Perfect. Let's look at one more Java data type: char.

The char data type is used to represent single characters. That includes the keys on a keyboard that
are used to produce text.
1. char is short for character and can represent a single character.

2. All char values must be enclosed in single quotes, like this: 'G'.
Variables
The int, boolean, and char are fundamental data types of Java that we will see again later in the
course.
Another important feature of Java (and of many programming languages) is the ability to store
values using variables.
1. A variable stores a value.
2. In Java, all variables must have a specified data type.
We can assign a variable to a specified data type, like this:
int myLuckyNumber = 7;

The variable myLuckyNumber now stores the value 7 as an int type.

A semicolon ; is also used to end all Java single code statements. We will cover statements that
should not end in a semicolon later in this course.

Whitespace
Before we explore what we can do with variables, lets learn how to keep code organized in Java.
Whitespace is one or more characters (such as a space, tab, enter, or return) that do not produce a
visible mark or text. Whitespace is often used to make code visually presentable.
Java will ignore whitespace in code, but it is important to know how to use whitespace to structure
code well. If you use whitespace correctly, code will be easier for you and other programmers to
read and understand.

Comments
A comment is text you want Java to ignore. Comments allow you to describe code or keep notes.
By using comments in the Java code, you may help yourself and even other programmers
understand the purpose of code that a comment refers to.
In Java, there are two styles of comments: single line comments and multi-line comments.
1. Single line comments are one line comments that begin with two forward slashes:
// I'm a single line comment!

1. Multi-line comments are generally longer comments that can span multiple lines. They begin
with /* and end with */ . Here's an example:
/*

Hello,
Java!

*/

Math: +, -, *, and /
Now let's try arithmetic in Java. You can add, subtract, multiply, and divide numbers and store them
in variables like this:
int sum = 34 + 113;
int difference = 91 - 205;
int product = 2 * 8;
int quotient = 45 / 3;

Math: %
Good work! Let's explore one more special math operator known as modulo.
1. The modulo operator - represented in Java by the % symbol - returns the remainder of
dividing two numbers.
For example, 15 % 6 will return the value of 3, because that is the remainder left over after
dividing 15 by 6.

Relational Operators
It looks like you're getting the hang of this! Let's explore another set of useful operators available in
Java known as relational operators.
Relational operators compare data types that have a defined ordering, like numbers (since numbers
are either smaller or larger than other numbers).
Relational operators will always return a boolean value of true or false.

Here are a few relational operators:


1. < : less than.
2. <=: less than or equal to.
3. >: greater than.
4. >=: greater than or equal to.

A relational operator is placed between the two operands (the terms that you want to compare using
the relational operator). The result of a relational operation is printed out in the following statement:
System.out.println(5 < 7);

The example above will print out true because the statement "5 is less than 7" is true.
Equality Operators
You may have noticed that the relational operators did not include an operator for testing "equals
to". In Java, equality operators are used to test equality.
The equality operators are:
1. ==: equal to.
2. !=: not equal to.

Equality operators do not require that operands share the same ordering. For example, you can test
equality across boolean, char, or int data types. The example below combines assigning
variables and using an equality operator:
char myChar = 'A';
int myInt = -2;
System.out.println(myChar == myInt);

The example above will print out false because the value of myChar ('A') is not the same value
as myInt ('-2').

Generalizations
Congratulations! You've learned some of the building blocks of Java programming. What can we
generalize so far?

Data Types are int, boolean, and char.


Variables are used to store values.
Whitespace helps make code easy to read for you and others.
Comments describe code and its purpose.
Arithmetic Operators include +, -, *, /, and %.
Relational Operators include <, <=, >, and >=.
Equality Operators include == and !=.

A full understanding of these concepts is key to understanding the remainder of the Java course.
Let's keep going!
Conditionals and Control Flow

Decisions
So far, we've explored primitive data types and Java syntax. As we've seen, Java programs follow
the instructions we provide them, such as printing values to the console.
We can also write Java programs that can follow different sets of instructions depending on the
values that we provide to them. This is called control flow. In this lesson, we'll learn how to use
control flow in our programs.

Boolean Operators: &&


Let's look at a set of operators that let us use control flow in our programs. These operators are
called Boolean operators.
There are three Boolean operators that we will explore. Let's start with the first one: and.
1. The and operator is represented in Java by &&.
2. It returns a boolean value of true only when the expressions on both sides of && are true.

For example, the code below shows one outcome of the Boolean operator &&:
// The following expression uses the "and" Boolean operator
System.out.println(true && true); // prints true

The code below shows the rest of the possible outcomes of the Boolean operators: &&:
// The following expressions use the "and" Boolean operator
System.out.println(false && false); // prints false
System.out.println(false && true); // prints false
System.out.println(true && false); // prints false

We can also use the Boolean operator && with Boolean expressions such as the following:
System.out.println(2 < 3 && 4 < 5);

The example above will print out true because the statements "2 is less than 3" and "4 is less than
5" are both true.

Boolean Operators: ||
Great! The second Boolean operator that we will explore is called or.
1. The or operator is represented in Java by ||.
2. It returns a Boolean value of true when at least one expression on either side of || is true.

The code below shows all the outcomes of the Boolean operator ||:
//The "or" Boolean operator:
System.out.println(false || false); // prints false
System.out.println(false || true); // prints true
System.out.println(true || false); // prints true
System.out.println(true || true); // prints true

We can also use the Boolean operator || with Boolean expressions such as the following:
System.out.println(2 > 1 || 3 > 4);

The example above will print out true because at least one statement "2 is greater than 1" is
true even though the other statement "3 is greater than 4" is false.

Boolean Operators: !
Fantastic! The final Boolean operator we will explore is called not.
1. The not operator is represented in Java by !.
2. It will return the opposite of the expression immediately after it. It will return false if the
expression is true, and true if the expression is false.

The code below shows all the outcomes of the Boolean operator !:
//The "not" Boolean operator:

System.out.println(!false); // prints true


System.out.println(!true); // prints false

We can also use the Boolean operator ! with Boolean expressions such as the following:
System.out.println( !(4 <= 10) );

The example above will print out false because the statement "4 is less than or equal to 10" is
true, but the ! operator will return the opposite value, which is false.

Boolean Operators: Precedence


The three Boolean operators &&, ||, and ! can also be used together and used multiple times to
form larger Boolean expressions.
However, just like numerical operators, Boolean operators follow rules that specify the order in
which they are evaluated. This order is called Boolean operator precedence.
The precedence of each Boolean operator is as follows:
1. ! is evaluated first
2. && is evaluated second
3. || is evaluated third
Like numerical expressions, every expression within parentheses is evaluated first. Expressions are
also read from left to right.
The following statement demonstrates how Boolean operator precedence works:
System.out.println( !(false) || true && false);

The example above will print out true. In order, the expression is evaluated as follows:

1. First, the ! Boolean operator in !(false) returns true.


2. Second, true && false evaluates to false.
3. Finally, the remaining expression true || false evaluates to true.

If Statement
Let's get familiar with how relational, equality, and Boolean operators can be used to control the
flow of our code.
We'll start by exploring the if statement.
1. In Java, the keyword if is the first part of a conditional expression.
2. It is followed by a Boolean expression and then a block of code. If the Boolean expression
evaluates to true, the block of code that follows will be run.

Here's an example of the if statement used with a conditional expression:


if (9 > 2) {
System.out.println("Control flow rocks!");
}

In the example above, 9 > 2 is the Boolean expression that gets checked. Since the Boolean
expression "9 is greater than 2" is true, Control flow rocks! will be printed to the
console.
The if statement is not followed by a semicolon (;). Instead it uses curly braces ({ and }) to
surround the code block that gets run when the Boolean expression is true.

If-Else Statement
Sometimes we execute one block of code when the Boolean expression after the if keyword is
true. Other times we may want to execute a different block of code when the Boolean expression
is false.

We could write a second if statement with a Boolean expression that is opposite the first, but Java
provides a shortcut called the if/else conditional.

1. The if/else conditional will run the block of code associated with the if statement if its
Boolean expression evaluates to true.
2. Otherwise, if the Boolean expression evaluates to false, it will run the block of code after
the else keyword.

Here's an example of if/else syntax:


if (1 < 3 && 5 < 4) {
System.out.println("I defy the Boolean laws!")
} else {
System.out.println("You can thank George Boole!");
}

In the example above, the Boolean expression "1 is less than 3" and "5 is less than 4" evaluates to
false. The code within the if block will be skipped and the code inside the else block will run
instead. The text "You can thank George Boole!" will be printed in the console.

f-ElseIf-Else Statement
Good work! In some cases, we need to execute a separate block of code depending on different
Boolean expressions. For that case, we can use the if/else if/else statement in Java.

1. If the Boolean expression after the if statement evaluates to true, it will run the code
block that directly follows.
2. Otherwise, if the Boolean expression after the else if statement evaluates to true, the
code block that directly follow will run.
3. Finally, if all previous Boolean expressions evaluate to false, the code within the else
block will run.
Here's an example of control flow with the if/else if/else statement:
int shoeSize = 10;

if (shoeSize > 12) {


System.out.println("Sorry, your shoe size is currently not in stock.");
} else if (shoeSize >= 6) {
System.out.println("Your shoe size is in stock!");
} else {
System.out.println("Sorry, this store does not carry shoes smaller than a
size 6.");
}

In the example above, the int variable shoeSize is equal to 10, which is not greater than 12,
but it is greater than or equal to 6. Therefore, the code block after the else if statement will be
run.

Ternary Conditional
if/else statements can become lengthy even when you simply want to return a value depending
on a Boolean expression. Fortunately, Java provides a shortcut that allows you to write if/else
statements in a single line of code. It is called the ternary conditional statement.
The term ternary comes from a Latin word that means "composed of three parts".

These three parts are:


1. A Boolean expression
2. A single statement that gets executed if the Boolean expression is true
3. A single statement that gets executed if the Boolean expression is false
Here is an example of a ternary conditional statement:
int pointsScored = 21;

char gameResult = (pointsScored > 20) ? 'W' : 'L';


System.out.println(gameResult);

In the example above, the int variable called pointsScored is equal to 21.

The Boolean expression is (pointsScored > 20), which evaluates to true. This will return
the value of 'W', which is assigned to the variable gameResult. The value 'W' is printed to the
console.

Switch Statement
The conditional statements that we have covered so far require Boolean expressions to determine
which code block to run. Java also provides a way to execute code blocks based on whether a block
is equal to a specific value. For those specific cases, we can use the switch statement, which helps
keep code organized and less wordy.
The switch statement is used as follows:
int restaurantRating = 3;

switch (restaurantRating) {

case 1: System.out.println("This restaurant is not my favorite.");


break;

case 2: System.out.println("This restaurant is good.");


break;

case 3: System.out.println("This restaurant is fantastic!");


break;

default: System.out.println("I've never dined at this restaurant.");


break;
}

In the example above, we assigned the int variable restaurantRating a value of 3. The code
will print a message to console based on the value of restaurantRating.

In this case, This restaurant is fantastic! is printed to the console.


The break statement will exit the switch statement after a condition is met. Without the break
statement, Java will continue to check whether the value of restaurantRating matches any
other cases.
The default case is printed only if restaurantRating is not equal to an int with the value
of 1, 2, or 3.

Generalizations
Great work! Control flow allows Java programs to execute code blocks depending on Boolean
expressions. What did we learn about control flow so far?

Boolean Operators: &&, ||, and ! are used to build Boolean expressions and have a defined
order of operations

Statements: if, if/else, and if/else if/else statements are used to conditionally
execute blocks of code

Ternary Conditional: a shortened version of an if/else statement that returns a value


based on the value of a Boolean expression

Switch: allows us to check equality of a variable or expression with a value that does not
need to be a Boolean

Object-Oriented Overview
Java is an object-oriented programming (OOP) language, which means that we can design classes,
objects, and methods that can perform certain actions. These behaviors are important in the
construction of larger, more powerful Java programs.
In this lesson, we will explore some fundamental concepts of object-oriented programming to take
advantage of the power of OOP in Java.

Classes: Syntax
One fundamental concept of object-oriented programming in Java is the class.
A class is a set of instructions that describe how a data structure should behave.
Java provides us with its own set of pre-defined classes, but we are also free to create our own
custom classes.
Classes in Java are created as follows:
//Create a custom Car class

class Car {

}
The example above creates a class named Car. We will define the behavior of the Car data
structure in the next exercise.

Classes: Constructors
We're off to a good start! We created a Java class, but it currently does not do anything; we need to
describe the behavior of the class for it to be useful.
Let's start by creating the starting state of our class. We can do this by adding a class constructor to
it.
1. A class constructor will allow us to create Dog instances. With a class constructor, we can
set some information about the Dog.
2. If we do not create a class constructor, Java provides one that does not allow you to set
initial information.
The code below demonstrates how a class constructor is created:
class Car {

//The class constructor for the Car class


public Car() {

}
}

In the example above, we created a class constructor for the Car class. This constructor will be
used when we create Car instances later. The public keyword will be explained later in this
course.

Classes: Instance Variables


When we create a new class, we probably have specific details that we want the class to include. We
save those specific details into instance variables.
Here is an instance variable in the Car class that describes a detail that we might want to associate
with a car:
class Car {

//Using instance variables to model our Car class after a real-life car
int modelYear;

public Car() {

}
}
In the example above, we created the instance variable named modelYear. Instance variables
model real-world car attributes, such as the model year of a car. Finally, the instance variable is
represented by the int data type.

Classes: Constructor Parameters


Constructor in java is a special type of method that is used to initialize the object. Java constructor
is invoked at the time of object creation. It constructs the values i.e. provides data for the object
that is why it is known as constructor.

Perfect! By adding a class constructor and creating instance variables, we will soon be able to use
the Dog class. However, the class constructor Dog is still empty. Let's modify this by adding
parameters to the Dog constructor.

You can think of parameters like options at an ice cream store. You can choose to order a traditional
ice cream cone, but other times you may want to specify the size of the cone or the flavor of the ice
cream.
For the Dog class, we can specify the initial dog age by adding parameters to the class constructor.

1. Parameters allow data types to be created with specified attributes.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.
What it means is that different dogs can have different age.
Let's add parameters to our Car class constructor:
class Car {

//Use instance variables to model our Car class after a real-life car
int modelYear;

public Car(int year) {

modelYear = year;
}
}

In the example above, we add the int parameter year to the Car constructor.

The value of modelYear will equal the int value that is specified when we first use this class
constructor.

The main Method


We're almost ready to use our custom Dog class! But first, we need to understand how to structure
and run our Java program.
You may have noticed a mysterious looking line of code in previous lessons that looks like this:
public static void main(String[] args) {

This is Java's built-in main method. We will learn more about methods and keywords around the
main method later on, but first let's understand what the purpose of main is.

1. When Java runs your program, the code inside of the main method is executed.

For now, you can ignore the keywords in the main method that we have not yet covered. You will
learn about them later in the course.

Objects
Perfect! Now that we have a main method in our class, we're ready to start using the Dog class.

To use the Dog class, we must create an instance of the Dog class. An instance of a class is known
as an object in Java.
The example below demonstrates how to create a Car object:
class Car {

int modelYear;

public Car(int year) {

modelYear = year;

public static void main(String[] args){

Car myFastCar = new Car(2007);

}
}

In the example above, we create a Car object named myFastCar. When creating myFastCar,
we used the class constructor and specified a value for the required int parameter year.

2007 is the model year of myFastCar. Note that we declared the new object inside the main
method.
Methods: I
Great work! We created a Dog object inside of the main method, but...nothing happened.

Although we created an object inside of main method, we did not print out anything about the
spike object itself, nor did we instruct the class to perform any actions. Let's learn about how
methods in Java are used to define actions.
A method is a pre-defined set of instructions. Methods are declared within a class. Java provides
some pre-defined methods available to all classes, but we can create our own as well.
Let's create a new method:
class Car {

int modelYear;

public Car(int year) {

modelYear = year;

//Our new method to help us get "started"


public void startEngine() {

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

public static void main(String[] args){

Car myFastCar = new Car(2007);

}
}

In the example above, we added a method called startEngine. When the method is used, it will
print out Vroom!. The void keyword will be explained later in this course.

Note that the startEngine method is created outside of the main method, like the constructor
was.

Methods: I
Great work! We created a Dog object inside of the main method, but...nothing happened.

Although we created an object inside of main method, we did not print out anything about the
spike object itself, nor did we instruct the class to perform any actions. Let's learn about how
methods in Java are used to define actions.
A method is a pre-defined set of instructions. Methods are declared within a class. Java provides
some pre-defined methods available to all classes, but we can create our own as well.
Let's create a new method:
class Car {

int modelYear;

public Car(int year) {

modelYear = year;

//Our new method to help us get "started"


public void startEngine() {

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

public static void main(String[] args){

Car myFastCar = new Car(2007);

}
}

In the example above, we added a method called startEngine. When the method is used, it will
print out Vroom!. The void keyword will be explained later in this course.

Note that the startEngine method is created outside of the main method, like the constructor
was.

Using Methods: I
Great! Now the bark method is available to use on the spike object. We can do this by calling
the method on spike.

Here is an example of calling a method on an object using the Car class:


class Car {

int modelYear;

public Car(int year) {

modelYear = year;

public void startEngine() {

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

public static void main(String[] args){

Car myFastCar = new Car(2007);


myFastCar.startEngine();
}

In the example above, we call the startEngine method on the myFastCar object. Again, this
occurs inside of the main method. Running the program results in printing Vroom! to the console.

Methods: II
Fantastic! Similar to constructors, you can customize methods to accept parameters.
class Car {

int modelYear;

public Car(int year) {

modelYear = year;

public void startEngine() {


System.out.println("Vroom!");
}

public void drive(int distanceInMiles) {

System.out.println("Miles driven: " + distanceInMiles);

public static void main(String[] args){

Car myFastCar = new Car(2007);


myFastCar.startEngine();
myFastCar.drive(1628);

In the example above, we create a drive method that accepts an int parameter called
distanceInMiles. In the main method, we call the drive method on the myFastCar object
and provide an int parameter of 1628.

Calling the drive method on myFastCar will result in printing Miles driven: 1628 to the
console.

Using Methods: II
Let's explore one of the keywords used in declaring a method. In past exercises, when creating new
methods, we used the keyword void.

The void keyword indicates that no value should be returned by the method after it executes all the
logic in the method. If we do want the method to return a value after it finishes running, we can
specify the return type.
1. The void keyword (which means "completely empty") indicates to the method that no
value is returned after calling that method.
2. Alternatively, we can use data type keywords (such as int, char, etc.) to specify that a
method should return a value of that type.
An example of indicating a return value for a method is below:
class Car {

int modelYear;

public Car(int year) {

modelYear = year;

public void startEngine() {

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

public void drive(int distanceInMiles) {

System.out.println("Your car drove " + distanceInMiles + " miles!");

public int numberOfTires() {

return 4;

public static void main(String[] args){

Car myFastCar = new Car(2007)


myFastCar.startEngine();
myFastCar.drive(1628);

int tires = myFastCar.numberOfTires();


System.out.println(tires);

}
}

In the example above, we created the numberOfTires method. This method specifies that it will
return an int data type. Inside of the method, we used the return keyword to return the value of
4 which is an int type.

Within main, we called the numberOfTires method on myFastCar. Since the method returns
an int value of 4, we store the value within an int variable called tires. We then print the
value of tires to the console.
Inheritance
You've created a fully functional Dog class. Congratulations!

One of the object-oriented programming concepts that allows us to reuse and maintain code more
efficiently is called inheritance. It is used to share or inherit behavior from another class. Let's look
at an example:
class Car extends Vehicle {

int modelYear;

public Car(int year) {

modelYear = year;

//Other methods omitted for brevity...

public static void main(String[] args){

Car myFastCar = new Car(2007)


myFastCar.checkBatteryStatus();

}
}

class Vehicle {

public void checkBatteryStatus() {

System.out.println("The battery is fully charged and ready to go!");

}
}

In the example above, the extends keyword is used to indicate that the Car class inherits the
behavior defined in the Vehicle class. This makes sense, since a car is a type of vehicle.

Within the main method of Car, we call the checkBatteryStatus method on myFastCar.
Since Car inherits from Vehicle, we can use methods defined in Vehicle on Car objects.

A program
class Dog {

int age;
public Dog(int dogsAge){

age = dogsAge;

public void bark(){

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

public void run(int feet){

System.out.println("Your dog ran" + feet + "feet!");

public int getAge(){

return age;
}

public static void main(String[] args) {

Dog spike = new Dog(3);


spike.bark();
spike.run(4);
int spikeAge = spike.getAge();
System.out.println(spikeAge);
}
}

Generalizations
Great work! Let's review everything that we've learned about object-oriented programming in Java
so far.

Class: a blueprint for how a data structure should function

Constructor: instructs the class to set up the initial state of an object

Object: instance of a class that stores the state of a class

Method: set of instructions that can be called on an object

Parameter: values that can be specified when creating an object or calling a method

Return value: specifies the data type that a method will return after it runs

Inheritance: allows one class to use functionality defined in another class