Java Notes
Java Notes
Introduction to Java
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.
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;
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.
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?
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.
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:
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.
The example above will print out true. In order, the expression is evaluated as follows:
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.
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.
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;
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".
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) {
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.
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
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 {
}
}
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.
//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.
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.
//Use instance variables to model our Car class after a real-life car
int modelYear;
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.
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;
modelYear = year;
}
}
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;
modelYear = year;
System.out.println("Vroom!");
}
}
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;
modelYear = year;
System.out.println("Vroom!");
}
}
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.
int modelYear;
modelYear = year;
System.out.println("Vroom!");
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;
modelYear = year;
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;
modelYear = year;
System.out.println("Vroom!");
return 4;
}
}
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;
modelYear = year;
}
}
class Vehicle {
}
}
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;
System.out.println("Woof!");
return age;
}
Generalizations
Great work! Let's review everything that we've learned about object-oriented programming in Java
so far.
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