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

Java For Beginners Get From Zero To Object Oriented Programming

This document provides an introduction to learning Java programming for beginners. It outlines the contents of the book, which covers topics like getting started with Java development tools, primitive data types, operators, conditionals, object-oriented programming concepts, arrays, inheritance and polymorphism. Each chapter includes exercise sections for the reader to practice and reinforce the concepts through hands-on coding. The document emphasizes that learning to program requires actively writing and testing code, not just reading about theories. It also provides guidance on where to find help if the reader encounters problems or has additional questions.

Uploaded by

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

Java For Beginners Get From Zero To Object Oriented Programming

This document provides an introduction to learning Java programming for beginners. It outlines the contents of the book, which covers topics like getting started with Java development tools, primitive data types, operators, conditionals, object-oriented programming concepts, arrays, inheritance and polymorphism. Each chapter includes exercise sections for the reader to practice and reinforce the concepts through hands-on coding. The document emphasizes that learning to program requires actively writing and testing code, not just reading about theories. It also provides guidance on where to find help if the reader encounters problems or has additional questions.

Uploaded by

Crazy Jack
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

Java For Beginners: Get From Zero

to Object-Oriented Programming
by Lucas Barzan
Contents
Contents
Introduction
Who is this book for
Who should back away from this book
How to Learn Java
What if something goes wrong?
Chapter 0: Java?
What is Java?
Why Learn Java?
How Java Works
Chapter 1: Getting Started
Java Development Kit
IntelliJ IDEA
What IDE should I download?
Your First Program
What is Camel Case?
The Main Method
Curly braces {}
Indentation
Double quotes " "
Semicolon at the end ;
Chapter 2: Variables and Data Types
Variable Declaration
Primitive Data Types
int
double
boolean
char
Other primitive data types
byte
short
long
float
Comments
Workout Set #1
Answers
Chapter 3: Operators and Math
Arithmetic Operators
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus: %
Increment: ++
Decrement: --
Relational Operators
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Logical Operators
And: &&
Or: ||
Not: !
Precedence
Other assignment Operators
*=
/=
%=
Intro to the Math class
Potentiation
Square root
Workout Set #2
Answers
Chapter 4: Strings and Getting Input
Strings
Input
Workout Set #3
Answers
Chapter 5: Conditionals and Control Flow
If - Else
Ternary Conditional
While Loop
For Loop
Controlling your Loops
Workout Set #4
Answers
Switch
Variable Scope
Workout Set #5
Answers
Chapter 6: Intro to Object-Oriented Java
Classes x Objects
Creating a class
Creating and using an object
Methods
Methods that return something
Objects are accessed through references
Transfer() method
Attributes again
Workout Set #6 - Part One
Answers
Workout Set #6 - Part Two
Answers
Workout Set #6 - Part Three
Answers
Chapter 7: Arrays
Primitive Data Type Array
Object arrays
Iterate through an array
Workout Set #7
Answers
Chapter 8: Access Modifiers and Class Attributes
Controlling access
Encapsulation
Getters and Setters
Constructors
Default constructor
Constructors with arguments
Why do we need a constructor?
Multiple Constructors
Class attributes
Workout Set #8
Answers
Chapter 9: Inheritance and Polymorphism
Inheritance
Super and subclass
Protected
Rewriting a method
Polymorfism
Workout Set #9
Answers
Introduction
I have worked really hard to make this book for you because I know how it
can be difficult to learn programming, especially when you’re starting out.
So I want to teach you in the way I’ve learned, which is by doing.

Who is this book for


This book is for everyone who wants to learn Java and knows nothing or
little about programming. If you want to be a programmer and you want to
start by learning Java, this book is your first step. If you want to develop
Android apps, this book is your first step. If you want to learn something
new, this book is your first step.

Who should back away from this book


First of all, this book is for people who are willing to learn something new.
There will be many times in which you’ll feel confused or overwhelmed,
but you have to able to handle that frustration if you want to achieve your
final goal. Your WHY has to be strong enough so that you won’t give up in
the middle of this book.
Also, I don’t recommend this book if you’re looking for an advanced guide
that will cover absolutely everything about the Java programming language.
I will teach you the essential stuff about Java to get you up and running in
your path to become a programmer.

How to Learn Java


Some books only give you the theory and and don’t even bother to make
you practice. I think that’s a terrible way to teach (programming, at least).
You should get hands-on experience as soon as possible and because of that
you’ll often be writing and running code in your IDE throughout this book.
So I recommend you to be next to a computer. Think of it as a course, not a
romance to read on your bed or on the beach.
Practicing should be taken seriously. It’s the one and only way to be a great
programmer and I can’t guarantee that you’ll learn anything if you don’t do
the exercises. I mean it. There’s no shortcut.
The exercise sections are called Workout Sets because our intelligence is
like a muscle: the more we use it, the more we grow it.
By the end of this book, you’ll have done 70 exercises.
Although I provide the answers to the exercises in most cases, just thinking
about an exercise and jumping to the answer is not practicing. And if you
do that, you’ll just be lying to yourself. So, if you’ve downloaded this book,
you have to make a commitment to yourself. Read. Think. Do the exercises.
Repeat.
Trust the process and great results will come!

What if something goes wrong?


It’s very common to make mistakes when programming, especially in the
beginning. So, if you have any questions that are not covered in this book,
you can follow these steps to solve your problem:
● First, search for your problem. I can almost guarantee you that
someone else has been through the same situation. If you get an error,
search for that error. If you want to know how to implement
something, search for that. You’re probably going to find some
answers on StackOverflow , which is the biggest Q&A website for
developers.
● If you haven’t found any answer – although that’s very unlikely –,
you can create a new question on StackOverflow and wait until
someone answers it (it’s the internet, it won’t take much time to
happen). Follow the website’s instructions to post your question and,
first of all, be sure that there isn’t any similar questions that can help
you, otherwise yours will be removed as a duplicate.
Chapter 0: Java?
What is Java?
According to its official website, “Java is a programming language and
computing platform first released by Sun Microsystems in 1995. There are
lots of applications and websites that will not work unless you have Java
installed, and more are created every day. Java is fast, secure, and reliable.
From laptops to datacenters, game consoles to scientific supercomputers,
cell phones to the Internet, Java is everywhere!”.
Java is a general-purpose language, which means it is used to build almost
anything (i.e. it wasn’t created to solve only one type of coding problem).
And before I forget, Java has nothing to do with Javascript, except for the
similar name and the fact that they are both famous programming
languages.
I will not spam you with pages of Java’s history because that’s out of the
scope of this book. All you need to know is that Java is famous and has
been on the market for a long time, so there isn’t any plans for its death.
Which brings us to the next section...

Why Learn Java?


Although Java is not the most beginner-friendly language out there, it offers
other benefits, such as:
- Programs written in Java are easy to maintain;
- Java has a huge community and you’ll never be alone. If you get an error,
it’s very likely that it happened to other people as well;
- People who know how to program in Java have access to great career
opportunities. Many tech giants such as Google or Amazon also use Java to
develop the backend of their websites, and because it has pretty good
performance, a lot of startups who reach the scaling point would integrate
their apps with Java to power features that need to have good performance;
- Java isn’t going anywhere, unlike other unestablished programming
languages.
How Java Works
1. You write the code
First, we write code in Java. It's called our source code. Here's an example:

public class myFirstClass {

public static void main( String [] args) {


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

Don't worry! You don't understand anything now and it might look very
confusing, I know.
If I were to give me any advice when I started programming, I'd say "Get
used to not knowing what everything means. It's completely OK. It just
means you have things to learn!".

2. You compile it
Then there's javaC, which is our Java Compiler. It checks for errors and
won't let you compile until it's satisfied that everything will run correctly.
The compiler creates a new document, coded into Java bytecode. Any
device capable of running Java will be able to interpret/translate this file
into something it can run. The compiled bytecode is platform-independent.
And that's where JVM comes in.

3. The JVM runs it


The JVM (Java Virtual Machine) interprets the bytecode that was created
and gives instructions that the device will understand. Each OS (whether it's
Windows, MacOS, Linux or even a mobile platform) can have its own JVM
in order to run Java programs.
No matter in what OS the bytecode gets created, it can run on any device
that has a JVM. That's what is called "Write Once, Run Anywhere" .
Chapter 1: Getting Started
Java Development Kit
JVM = Java Virtual Machine.
JRE = Java Runtime Environment, which contains everything you need in
order to execute Java applications.
JDK = Java Development Kit, which contains everything you need in order
to develop Java applications. That’s what we need to download.
WARNING: Unless you have a secret fetish that involves downloading and
preparing stuff, things will be a little bit boring for now. But that's
something we just have to do once. Then you'll only need to do something
like this again if you're updating these tools, which doesn't happen all the
time.
By the time I'm writing this, the newest JDK version is JDK 9. Do a little
research and if there's a newer and also stable version, download it.
Let's start by googling "JDK 9" and clicking on the first result . To
download, you have to Accept License Agreement and then you can select a
file that fits your OS (Windows, MacOS or Linux).

It might take a while for the download to finish. Then, install it. Leave all
the settings as default, unless you really know what you're doing.
IntelliJ IDEA
Doctors have an environment such as a hospital or clinic, that provides
them with a bunch of tools and things that will help them do their work. A
doctor might be able to examine a patient in that person's house, but (s)he
can't do a surgery without a specific environment.
Just like doctors need a surgery room , developers need an IDE , which
stands for Integrated Development Environment . According to
Wikipedia, "an IDE is a software application that provides comprehensive
facilities to computer programmers for software development. An IDE
normally consists of a source code editor, build automation tools and a
debugger. Most modern IDEs have intelligent code completion."
What IDE should I download?
I'll use IntelliJ IDEA in this book, but you can use any IDE. It can be
NetBeans, Eclipse, whatever. Actually, some might argue that these are
better IDEs for some reason.
But as a beginner, that won't make much of a difference, so that's not the
most important thing here and you shouldn't spend more than a few
seconds to decide.
If you'll download IntelliJ, google "IntelliJ IDEA" , click on the first link,
and follow the same steps to download the Community Edition (for free)
that is compatible with your OS.
Your First Program
It’s been a tradition in the programming world to do a “Hello World”
program for the first time you’re using some language or tool. Some might
even say you’ll be cursed otherwise. Anyway, better safe than sorry. A
“Hello World” program is a program that will show a message on the screen
– “Hello World”.
Open your IDE. Click on Create New Project .

Make sure Java is selected on the left tab. Then select the Project SDK.
If no Project SDK is available, click on New... and select the jdk-9 folder. It
probably has this path (if you're using Windows): C:\Program
Files\Java\jdk-9. If you have any trouble doing that, don't worry. You can
always google it.
Then click Next .
Click Next . (We're gonna build the program from scratch – no shortcuts
templates for now!)
In Project Name, type My First Program . You can leave the Project
Location as it is. Then click Finish .
The IDE now has handled everything for us. A folder was created on your
computer to store the files you’re going to create for you program.
Do you see that little triangle next to My First Program in the next image?
If you click on it, it'll show other things that are a part of your project: .idea
, src and My First Program.iml . That’s how you can navigate through your
project structure.

Now right-click on src , go to New and then Java Class .


What we're doing is to create a new Java Class inside our project. Later
we'll understand what that means.

Let's give a name to our class. Type MyFirstClass and hit OK .


Classes names use upper camel case .

What is Camel Case?


Camel Case has this name because it is similar to the humps of a camel. It's
a very common convention between various programming languages.

It is the practice of writing compound words or phrases, where each word


is capitalized and merged without spaces. Examples:
● ClassesStartWithAnUppercaseLetter
● MyClass
● CodenificIsGreat
● LucasBarzan
Lower camel case: the first letter of the entire word is lowercase, but
subsequent first letters are uppercase. Examples:
● functionsAndVariablesDoNot
● variableName
● age
● dateOfBirth
We now have a brand-new class just waiting to be coded. Note that we’ve
just created a file MyFirstClass that ends with .java . It's a Java file.

The Main Method


Go ahead and make your code look like this:

public class MyFirstClass {


public static void main( String [] args) {

}
}

OK, you've just copied the main method into your program. I'll explain it
soon in this chapter.
You're probably wondering: "Do I have to write these weird words EVERY
TIME I want to create a new program?!". Well, they do have to be there.
But you don't have to write them all by yourself. Let the IDE do that for
you.
Just write the initial letters of the main method declaration (psvm ), hit
Enter, and the magic will happen.
Now you get to be lazy again! ;)
Let's run our program. Right-click on the tab (MyFirstClass.java as you can
see in the last image) and select Run 'MyFirstClass.main()' .
After a few seconds, a window will pop up. When you see a message like
that (Process finished with exit code 0 ) it means the program ran and
finished. Apparently, nothing happened. OF COURSE NOTHING
HAPPENED. We only created a class and put the main method inside it.
There's no instruction for the computer to do anything else.
We have to ask for the computer to do things for us, such as showing
messages, doing calculations, creating and modifying files, etc.
Let's start printing some stuff. High priority in our To-do list: get rid of the
Hello World curse. We have to print it, otherwise we will never learn Java
LOL.
There are some commands that can print a message on the screen.
System.out.print() and System.out.println() are the most used ones. The
difference between them is that System.out.println() jumps to a new line
after printing the message . Since we're going to print out only one line of
text, there's no problem in using System.out.print() . But in the next
chapters, we're going to use System.out.println() .
Go ahead and type System.out.print("Hello, World!"); inside the main
method (see image below).

Now the file does three things:


1. It declares a class called MyFirstClass:
The reserved word public indicates that this class/file is public, i.e. it can be
invoked from any point in the program.
The word class introduces a class definition in Java, i.e. defines that the
code between the curly braces will be a class. Then we have the class name.

2. It defines the main method :


-The reserved word void is our return type in this case; it indicates that this
method will perform a task (print the line of text on the screen, in this case)
but will NOT return any information when finished.
-The term String[] args inside the parentheses are arguments passed to this
program and are required in main , although we will not use it here.

3. The main method calls System.out.print to output some text.


In Java, and in all object-oriented programming languages, a class defines
an object . An object is a self-contained item that interacts with other
objects. In Android, such object would include elements in the UI, a
network connection, some location data, and so on.

Each Java program must define a method called main in at least one class.
It is the entry point, where the program starts executing. In the example
above the main method has just one line of code, a call to System.out.print
to output “Hello, World!”.
print() is a method that belongs to the PrintStream class and is included as
part of the System class.
Here are some things I want you to notice about that code:

Curly braces {}
They are used to indicate the beginning and the ending of a class/method
definition body. Every time you open a curly brace {, you have to close it },
otherwise you get a compilation error.

Indentation
Do you see that whitespace before System.out ... and also before public
static void main... ? It's called indentation . In Java, your program will run
even if you don't indent correctly. For example, the code below will
produce the exact same output.

So... why don't we write it like that to save lines? Because it's a
TERRIBLE thing to do!!! (Yes, I AM screaming!) Not only should you
indent your code, but you have to do it. I mean it.
Indentation makes your code a lot more readable (for you and for others)
and, consequently, facilitates the maintenance.
The IDE helps you automatically with that, but if you ever need to put that
whitespace, hit Tab on your keyboard.

Double quotes " "


That message was between double quotes, which means it's a String . We'll
learn about Strings in Chapter 4.

Semicolon at the end ;


At the end of every line, we have to put a semicolon (except for lines that
contain an opening or closing bracket). Java statements end with a
semicolon and our code won't even compile if that kind of error (missing
semicolon) is found.
Pay attention to every detail and try to find patterns. That's a very valuable
skill to have as a programmer!

Let's run it!


Right-click on the MyFirstClass.java tab that is opened and select Run
'MyFirstClass.main()' like we did earlier. On Windows, the shortcut to
execute the last executed file is Ctrl+Shift+F10 .
You've just finished your first Java program. Congratulations!
For now on, I'm gonna assume that you know how to do all this (open your
IDE, start a new project, create a class and write the main method).
Chapter 2: Variables and Data Types
Consider the following program:
public class Main {
public static void main( String [] args) {
System . out . println(" Score = " + 10 );
System . out . println(" Good job!");
}
}
This program prints out “Score = 10” and then “Good job!”. But by the end
of the third line, the computer doesn’t even remember that score that was
printed. Kind of like when we don’t want to listen to someone and we avoid
saving any information in our brains, we just ignore it. But we could store
that score in our program by using something called a variable . Think of it
as a box in which you can put some data and then come back later to
retrieve it.
Since data comes in different forms, a variable needs to be defined with a
type , which tells Java what is being stored. Some of Java’s primitive data
types include int (for integer), float , double (for double precision floating
point number), and boolean (for a true/false value).
Open your IDE and create a new class called Variables inside the src folder.
Complete the code with the main method (challenge: don’t use the trick I
taught you in the previous lesson and try to remember as much as you can).
You can also delete MyFirstClass if you want to.
This is what it should look like:
Copy and paste the following snippet into the main method:
int i;
i=0;
System . out . println( i);
To run it, right-click on the Variables.java tab and select Run
‘Variables.main()’. After you’ve done it once, you can quickly do it through
that beautiful and green play button:

You can also select a class that was executed recently, like MyFirstClass:

After running Variables.java, this window will show up:


That program somehow printed the number 0. Let’s see how that happened.
Here’s how the full code should look like:
public class Variables {
public static void main( String [] args) {
int i;
i=0;
System . out . println( i);
}
}
● There’s our class header
● There’s the main method
● There are 3 statements inside the main method. The first one declares
a variable (i.e. creates a variable) of type int (integer) named i
● The second one initializes that variable by storing the value of 0
inside it
● The third one prints out the value that is stored in the variable i .
Notice that we’re not printing out the letter “i” , but the value of the
variable i .
Important: You have to declare a variable before using it! Therefore, the
following code is WRONG :
// WRONG!
public class Variables {
public static void main( String [] args) {
System . out . println( i);
int i;
i=0;
}
}
If you make that mistake, your IDE will warn you:

Cannot resolve symbol ‘i’ means the IDE couldn’t find anything about ‘i’.
It’s not declared anywhere before the System.out.println() call.

Human: Hey, can you print out a picture of Hannah?


Computer (thinking): (Who is Hannah? I’ve never heard about her. How
could I print a picture of Hannah? Stupid human…)
Computer says: CANNOT RESOLVE SYMBOL ‘HANNAH’

Just kidding! It’s OK to make mistakes. Actually, you’ll make PLENTY


of them throughout your learning path and career.
Variable Declaration
So here’s a generalization about variables declaration:

That’s how we did it in our program. But we can join declaration and
initialization in one single statement, which is more practical, like this:

Values change. And you can change the values that are inside your
variables. Replace your current code with the following one and then run it
to see what happens:
public class Variables {
public static void main( String [] args) {
int i = 10 ;
System . out . println( i);
i=i+5;
System . out . println( i);
}
}
I’m waiting…
This is the output:
10
15
First, I declared a variable called i that is an integer, assign it the value of 10
and then print it. Then, I add 5 to i , which results in 15, which is the second
value that gets printed.
Instead of i = i + 5; you can write i += 5;
You can also subtract the value of a variable:
public class Variables {
public static void main( String [] args) {
int i = 10 ;
System . out . println( i);
i=i-4;
System . out . println( i);
}
}
The output of the code above is
10
6
Again, instead of i = i - 4; you can write i -= 4;
Sometimes you want to do more than adding and subtracting. Sometimes
you want to change the value of a variable completely.
public class Variables {
public static void main( String [] args) {
int i = 10 ;
System . out . println( i); // prints 10
i += 5 ;
i=7;
System . out . println( i); // prints 7
}
}
On the sixth line, I assigned a new value of 7 to the variable i . All the
previous values are dismissed. Therefore, this is the output:
10
7
Here’s what happened line-by-line.
Line 3: we create a new variable of type int called i and assign it the value
of 10.
Line 4: we print the value of i, which is 10.
Line 5: we add 5 to i. Now i holds 15 as its value.
Line 6: we assign the value of 7 to i. Now i holds 7 as its value.
Line 7: we print the value of i, which is now 7.
We can even combine variables, which is actually a very common thing to
do, like everything else we’ve been doing so far:
public class Variables {
public static void main( String [] args) {
int a = 20 ;
int b = 2 ;
int c = 3 ;
int x = a + b + c;
System . out . println( x);
}
}
System.out.println(x) does not print the letter x; it prints the value that is
stored inside the variable x. Its value is equal to a + b + c which is equal to
20 + 2 + 3 = 25 .
To print the letter x, we would do System.out.println(“x”) .

Primitive Data Types


We’ve created variables of type int earlier in this chapter. But, as I said,
there are other types, which are called primitive data types , a data type
provided by the programming language as a basic building block. They are
not some kind of add-on, but rather a simple component of the language.
Let’s see a little bit of Java’s primitive data types.

int
They have a minimum value of -231 and a maximum value of 231 - 1. That’s
a lot!
Int variables can be used to store your age, a game score and the number of
times you were stupid (if it’s less than 231 -1 LOL ), for example.

double
It can be used to store larger integers or more precise floating-point
numbers (which range from approximately 4.94-324 to 1.80308 ) when
compared to other data types. It’s accurate to 14 or 15 significant digits.
In other words, double is the most used type to store real numbers but it can
also store integers.

// Examples
double bigNumber = 97502250450954097967129782.0 ;
double smallNumber = 1500;
According to Oracle’s documentation, this data type should never be used
for things like currency.
Being able to store larger and more precise values is like having a bigger
and better box which, consequently, demands more [memory] space.

boolean
The boolean data type has only two possible values: true and false . Use
this data type for simple flags that track true/false conditions. This data type
represents one bit of information, but its “size” isn’t something that’s
precisely defined.
// Examples
boolean isOn = true ;
boolean hasWhippedCream = false;

char
They are used to store a single character . Unlike Strings (that require
double quotes) char variables require you to use single quotes.
// Examples
char firstLetter = 'A' ;
char lastLetter = 'Z' ;
char digit = '0' ;
char num = '9';

Other primitive data types


As a beginner, not everything has the same level of importance. For now
you’ll be well served by variables of type int, double, boolean, char (and
Strings - in Chapter 4). But you must know that there are other data types to
satisfy different needs that programmers may have.
byte
It has a minimum value of -128 and a maximum value of 127 (inclusive).
The byte data type can be useful for saving memory where it’s necessary.
// Examples
byte x = - 128 ;
byte y = 127;
short
It has a minimum value of -32,768 and a maximum value of 32,767
(inclusive). As with byte, the same guidelines apply: you can use a short to
save memory.

// Examples
short n = - 32768 ;
short p = 32767;
long
It has a minimum value of -263 and a maximum value of 263 -1. Use this data
type when you need a range of values wider than those provided by int.
float
It’s used to represent floating-point numbers such as 3.14159, 25.0 and
0.0075. The value should have a f at the end, indicating that it is a float.
Otherwise, it’ll be considered a double.
// Example
float n = 1.5f;
Here’s how you can get an error if you don’t put the f at the end of a
number that’s going to be stored in a float variable:

This data type should never be used for really precise values, such as
currency. For that, you will need to use the java.math.BigDecimal class
instead.

Comments
Imagine you finished writing a big and complex program today. Of course
tomorrow you will still remember what each variable stores and what each
part of the program does. But will you remember it a month from now? A
year from now? You probably won’t, especially if you don’t edit the code in
the meanwhile.
There’s another situation. Most of the times, you won’t write code to
yourself: someone else will read it and maybe even complement it.
Unfortunately, other programmers can’t read your thoughts (we’re not there
yet). So, what do we do? We comment our code.
public class Variables {
public static void main( String [] args) {
int a = 20 ; // Creates a variable called a
int b = 2 ; // Creates a variable called b
int c = 3 ; // Creates a variable called c
int x = a + b + c; // Calculates the sum of variables a, b and c
System . out . println( x); // Prints out the sum
}
}
In the code above, you can see examples of single line comments that start
with // . The compiler ignores everything from // to the end of the line, so
you can write whatever you want and it will not interfere. This type of
comment comes in handy when you want to explain what a statement does.
public class Variables {
public static void main( String [] args) {
/* I still want to implement a function that
calculates the sum of any set of variables */
int a = 20 ;
int b = 2 ;
int c = 3 ;
int x = a + b + c;
System . out . println( x);
}
}
In the code above, you can see an example of a multiple line comment that
starts with /* and ends with */ . The compiler ignores everything from /* to
*/. They come in handy when you want to make a bigger comment that
wouldn’t fit in a single line.
Workout Set #1
Write down your answers in a piece of paper to check them in the Answers
page.
1) What primitive data type is similar to a light switch?
2) True or False: "Integer variables can only store positive numbers"
3) "All primitive data types demand the same memory space"
4) Which variable declarations contain some kind of error?
a . int = 1;
b . double bigNumber = 3.402823;
c . Int myNumber = 10;
d . String name = 'Lucas';
e . float pi = 3.14159f;
f . int age = 5
g . boolean hasWhippedCream = true;
h . double bigNumber = 523154137481728.0;
i . char letter = 'C';
5) Write a program that contains two different Integer variables. Assign
them different numbers and then print out the sum.
Answers
1) Boolean

2) False

3) False

4) a, c, d, f

5)
// your class can have a different name, depending on the name of your file
public class Program {
public static void main( String [] args) {
int a, b;
a = 1 ; // it could be any number
b = 2 ; // same here
System . out . println( a + b);
}
}
OR
public class Program {
public static void main( String [] args) {
int a = 1 ;
int b = 2 ;
System . out . println( a + b);
}
}
Chapter 3: Operators and Math
There are a lot more operations other than adding and subtracting and that's
what we're going to explore in this chapter.

Arithmetic Operators
Addition: +
int a, b, c; // That's how you can declare multiple variables of the same type
a = 3;
b = 4;
c = a + b;
System . out . println( c); // 7
System . out . println( a + c); // 10
System . out . println( 15 + 10 ); // 25

Subtraction: -
int a, b, c;
a = 10;
b = 3;
c = a - b;
System . out . println( c); // 7
System . out . println( a - c); // 3
System . out . println( 27 - 17 ); // 10

Multiplication: *
int a, b, c;
a = 5;
b = 3;
c = a * b;
System . out . println( c); // 15
System . out . println( a * a); // 25
System . out . println( 2 * 7); // 14
For the result to be a double, at least one of the numbers must be double.
Therefore, all the expressions below result in 10.0.
● 2.0 * 5
● 2 * 5.0
● 2.0 * 5.0
Do not confuse with float, which has an f at the end (see Chapter 2). This
rule is applied to the other operations as well.

Division: /
System . out . println( 10 / 3); // 3
System . out . println( 10 / 3.0); // 3.3333333333333335
System . out . println( 10.0 / 3); // 3.3333333333333335
System . out . println( 10.0 / 3.0); // 3.3333333333333335
Again! For the result to be a double, at least one of the numbers must be
double. Otherwise, an operation like 10 / 3 will only return the integer
part of the result.

Modulus: %
% is known as the modulus or remainder operator, and returns the
remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by
3 leaves a remainder of 1. You can use % just as you might use +, -, * and /.
int i, j;
i=6;
j=4;
System . out . println( i % j); // 2
System . out . println( 6.0 % 4.0 ); // 2.0

Increment: ++
Instead of writing…
i = i + 1;
...or even…
i += 1;
…You can write…
i++;
That’s what the increment operator does: adding 1 to the number stored in
a variable.

Decrement: --
This operator does the opposite.
Instead of writing…
i = i - 1;
...or even…
i -= 1;
…You can write…
i--;
That’s what the decrement operator does: subtracting 1 from the number
stored in a variable.

Relational Operators
Relational Operators are used to compare data types that have a defined
ordering, like numbers (since numbers are either smaller or larger than
other numbers).

Equal to: ==
Checks if the values of two operands are equal or not, if yes then condition
becomes true.
System . out . println( 1 == 1 ) // true
System . out . println( 3 == 0 ) // false
Attention! The equality operator == is different from the assignment
operator =.

Not equal to: !=


Checks if the values of two operands are equal or not, if values are not
equal then condition becomes true.
System . out . println( 3 != 1 ) // true
System . out . println( 10 != 10 ) // false

Greater than: >


Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true.
System . out . println( 3 > 1 ) // true
System . out . println( 10 > 10 ) // false
System . out . println( 1 > 10 ) // false

Less than: <


Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true.
System . out . println( 1 < 40 ) // true
System . out . println( 12 < 6 ) // false
System . out . println( 1 < 1 ) // false

Greater than or equal to: >=


Checks if the value of left operand is greater than or equal to the value of
right operand, if yes then condition becomes true.
System . out . println( 12 >= 6 ) // true
System . out . println( 7 >= 7 ) // true
System . out . println( 1 >= 5 ) // false

Less than or equal to: <=


Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.
System . out . println( 6 <= 12 ) // true
System . out . println( 7 <= 7 ) // true
System . out . println( 6 <= 4 ) // false

Logical Operators
Also known as Boolean Operators, they are used to compare boolean values
(true and false ), which can be part of our program’s logic.

And: &&
The and operator is represented in Java by && . It returns a boolean value
of true only when the expressions on both sides of && are true.
System . out . println( true && true ); // prints true
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( 5 > 0 && 9 < 10 );
The example above will print out true because the statements “5 is greater
than 0” and “9 is less than 10” are both true .

Or: ||
The or operator is represented in Java by || . It returns a Boolean value of
true when at least one expression on either side of || is true .
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( 5 > 2 || 1 > 34 );
// Equivalent to:
System . out . println( true || false );
The example above will print out true because at least one statement — “5
is greater than 2” — is true even though the other statement — “1 is greater
than 34” — is false.

Not: !
The not operator is represented in Java by ! .
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 .
System . out . println(! false ); // "Not false" - prints true
System . out . println(! true ); // "Not true" - prints false
We can also use the Boolean operator ! with Boolean expressions such as
the following:
System . out . println( !( 5 <= 25 ) );
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 .

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 ) || false && true );
Step-by-step explanation:
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, false && true evaluates to false.
3. Finally, the remaining expression true || false evaluates to true.
It looks like this when you do it step-by-step:
!( false ) || false && true
true || false
true

Other assignment Operators


We have already seen some of the assignment operators (=, += and -=) but
there are others that will help shorten our code.

*=
Multiply AND assignment operator. It multiplies right operand with the left
operand and assign the result to left operand.
a = a * b;
// is equivalent to:
a *= b;

/=
Divide AND assignment operator. It divides left operand with the right
operand and assign the result to left operand.
a = a / b;
// is equivalent to:
a /= b;

%=
Modulus AND assignment operator. It takes modulus using two operands
and assign the result to left operand.
a = a % b;
// is equivalent to:
a %= b;

Intro to the Math class


To do other arithmetic operations like potentiation and square root, we have
to use the Math class , which contains the needed methods.

Potentiation
To do potentiation, we use Math.pow() .
// 1
System . out . println( Math . pow( 2 , 4 )); // 16.0
// 2
int base , exponent;
base = 4 ;
exponent = 3 ;
System . out . println( Math . pow( base , exponent)); // 64

Square root
To do potentiation, we use Math.sqrt() .
System . out . println( Math . sqrt( 4 )); // 2.0
System . out . println( Math . sqrt( 25 )); // 5.0
int x = 100 ;
System . out . println( Math . sqrt( x)); // 10.0
There are a lot of other methods in the Math class. Here are some things
you can do: calculate the absolute value of a number, sine, cosine, tangent,
logarithms and make conversions between degrees and radians.
Workout Set #2
Write down your answers in a piece of paper to check them in the Answers
page.
1) What will be the output of the following program?
class Program {
public static void main( String [] args) {
int a = 3;
int b = 8;
int c = ( a + b) / 2;
System . out . println( c / 1.0 );
}
}
a) 6
b) 6.0
c) 5.5
d) 5.0
e) 5

2) What will be the output of the following program?


public class WorkoutSet {
public static void main( String [] args) {
int a = 3;
int b = 17 + a - 5;
int c = a * b;
System . out . println( c);
}
}
3) What will be the output of the following program?
public class WorkoutSet {
public static void main( String [] args) {
System . out . println( 5.1 > 5 );
}
}

4) What will be the output of the following program?


public class WorkoutSet {
public static void main( String [] args) {
System . out . println( 2 >= 0 );
}
}

5) What will be the output of the following program?


public class WorkoutSet {
public static void main( String [] args) {
System . out . println(- 10 > - 5 );
}
}

6) What will be the output of the following program?


public class WorkoutSet {
public static void main( String [] args) {
System . out . println( "Hello" == "hello" );
}
}
7) What will be the output of the following program?
public class WorkoutSet {
public static void main( String [] args) {
System . out . println( 'A' == - 1 );
}
}
8) What will be the output of the following program?
public class WorkoutSet {
public static void main( String [] args) {
System . out . println( 10 == 10.0 );
}
}

9) Boolean "and" is represented in Java by what operator?

10) Boolean "or" is represented in Java by what operator?

11) Which expressions evaluate to true? (example: a, b)


a. false && false
b. true && false
c. false && true
d. true && true
12) Which expressions evaluate to true?
a. false || false
b. true || false
c. false || true
d. true || true
13) Which expressions evaluate to true?
a. !( false ) && 10 > 1
b. 5 > 5.1 && true
c. 5 < 6 && 7 > 14 || 5 >= 5 && 12 > 0
d. !( false ) && !( true)
Answers
1) D

2) 45

3) true

4) true

5) false

6) false

7) false

8) true

9) ||

10) &&

11) d

12) b, c, d

13) a, c
Chapter 4: Strings and Getting Input
Create a new class called StringsAreCool and replace the generated code
with the following:
public class StringsAreCool {
public static void main( String [] args) {
// Create a String object called codenific
String codenific = "Codenific" ;
System . out . println( "1. " + codenific);
// Add `.com`
codenific += ".com" ;
System . out . println( "2. " + codenific);
// Extract the word `Codenific` from the String
String onlyCodenific = codenific. substring( 0 , 9 );
System . out . println( "3. " + onlyCodenific);
// Extract the sufix '.com' from the String
String onlyDotCom = codenific. substring( 9 , 13 );
System . out . println( "4. " + onlyDotCom);
// Add some trailing spaces and then remove them with trim()
codenific = " " + codenific + " " ;
codenific = codenific. trim();
System . out . println( "5. " + codenific);
// Now output the string all in UPPERCASE and lowercase
System . out . println( "6. " + codenific. toUpperCase());
System . out . println( "7. " + codenific. toLowerCase());
System . out . println( "-> " + codenific. length());
}
}
First of all, read the code and try to figure out what is being done and how
is that happening.

Strings
The first part of the program creates a String object called “codenific” and
gives it a value of “Codenific”. Although this may look similar to how
you declare and assign an integer or another primitive type, actually
there is a lot more going on here. Java allows simple operators like = and
+ to be assigned simple tasks.
So really String codenific = " Codenific " ; is actually something like
String codenific = new String (" Codenific ") ; , in other words, create a
new object of type String and pass in the value “Codenific” to the
constructor. The constructor is a special method called only once, at the
moment that the object is created. But we will talk more about that on
Chapters 6 and 8.
The next part shows how you can concatenate strings, in this case ".com" is
added to the end of the string.
codenific += ".com" ;
Since String is an object, it can have methods. String.substring() is a
method which returns part of a string. String onlyCodenific = codenific.
substring( 0 , 9 ) ; returns the first nine characters of the "codenific" String
(it includes index 0, but not 9). And String onlyDotCom = codenific.
substring( 9 , 13 ) ; returns the characters from indexes 9 to 13 (it includes
index 9, but not 13).

The image above was taken from a Python post in my blog , but we can use
it to explain Java substrings as well. Consider the String "This is
Codenific" was assigned to a variable called "variable".
The first letter of a String has a zero index. So, in "This is Codenific", if
you want only the third letter, you just have to do something like
variable.substring(2, 3) because the second value isn't inclusive .
In the same way, variable.substring(0, 16) doesn't return the entire String
above, it returns "This is Codenifi". To return the entire String, you have to
do variable.substring(0, 17) .
String.trim() is another method which removes leading and trailing spaces.
String.toUpperCase() and String.toLowerCase() methods are very self-
explaining.
Lastly, our program gets the String.length() and prints it.

Input
The easiest way to get input is by using the Scanner class.
Suppose we wanted to get a number. Copy and paste the following code
into a new class called Inputs:
import java. util. Scanner;
public class Inputs {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a number: " );
int n = scan. nextInt();
scan. close();
System . out . println( "The chosen number is: " + n);
}
}

When you run the program, it asks you a number. I entered 25 and then it
printed "The chosen number is: 25" . That's no magic, I know. But, as I
always say, you have to start somewhere.
How that happened? First, we have to import the Scanner class by writing
import java.util.Scanner; before the class header. By importing it, we get
access to the methods and functions of that class (we'll get back to that later
in this course).
Then we create a Scanner object called "scan" (you can name it however
you want):
Scanner scan = new Scanner ( System . in );
Remember how we could extend a String declaration? Just like that!
String scan = new String ( "Scanning..." );.
The user can't guess what we want, so we have to put some instruction
which, in this case, is printed to the terminal.
We create an integer variable called n that will store the next input as an int
– scan.nextInt() . Therefore, if the user enters a text, for example, the
program will crash:

Once we are done, we have to finish the Scanner object with scan.close().
Finally, we print that number we got: System . out . println( "The chosen
number is: " + n); .
The same can be applied to scan for other data types.
● To get a byte : byte a = scan . nextByte ();
● To get a short : short b = scan . nextShort ();
● To get a float : float c = scan . nextFloat ();
● To get a long : long d = scan . nextLong ();
● To get a double : double e = scan . nextDouble ();
● To get a boolean : boolean f = scan . nextBoolean ();
And to get Strings as input we use scan.next() (assuming that our Scanner
object is called "scan" in this case).
Another way to import
If you type Scanner scan = new Scanner ( System . in ) ; before importing
the Scanner class, you can click in the word "Scanner" and then back away
your cursor to see a red lamp show up. Click on it, select Import Class and
then Scanner (java.util) , so that the IDE will automatically write the
import statement for you!

Another shortcut!
And instead of typing System.out.println(), you can type sout and click
Enter:
Workout Set #3
Create a class for each of the following exercises (like Set3Exercise1) and
write your solution to then compare with mine.
The inputs in the examples are in italic .

1) Write a program that contains a String object in which you will put your
name and then print it.

2) Write a program that asks for the person's name and then greets that
person.
Example:
What is your name?
Lucas
Hello, Lucas!

3) Write a program that removes leading and trailing spaces from a String
entered by the user and then prints the new String.
Example:
Enter a String:
Lucas .
Lucas

4) Write a program that gets two Strings, concatenates and prints them,
following these rules:
● The first String has to be printed as lowercase
● The second String has to be printed as uppercase
● There has to be one space between the two Strings
Example:
Enter a String:
Code
Enter another String:
Nific
code NIFIC

5) Write a program that gets the age of the user and then prints out the year
that he/she was born.
Example (in 2017):
How old are you?
16
You were born in 2001

6) Write a program that, given a number, prints out its predecessor and
successor.
Example:
Enter a number:
10
Predecessor: 9
Successor: 11

7) Write a program that, given a number x, prints:


● 2 times x
● x to the power of 2
● x divided by 2
● square root of x
Example:
Enter a number:
9
18
81
4.5
3

8) Write a program that gets two numbers and prints out the average
(arithmetic mean) of them.
Example 1:
Enter a number:
8
Enter another number:
10
The average is 9.0
Example 2:
Enter a number:
7
Enter another number:
9.5
The average is 8.25

9) Write a program that calculates the price of a product after a 10%


discount.
Example 1:
What is the price of the product?
120
After a 10% discount, this product will be sold for $ 108
Example 2:
What is the price of the product?
253.9
After a 10% discount, this product will be sold for $ 228.51
If you're getting this error: Exception in thread "main"
java.util.InputMismatchException, you might need to use something like
scan.useLocale(Locale.US); (considering your Scanner object is called
"scan") and import java.util.Locale;. Or you could enter the input as 120,0
instead of 120.0, for example. That error is caused because your country's
number formatting is different from the US (like me, Brazilian).

10) Write a program that converts a temperature from Celsius to Fahrenheit.


Use the formula below:

Example:
Enter the temperature in Celsius:
30
30.0ºC is equivalent to 86.0ºF

Again, if you're getting this error: Exception in thread "main"


java.util.InputMismatchException, you might need to use something like
scan.useLocale(Locale.US); (considering your Scanner object is called
"scan") and import java.util.Locale;. Or you could enter the input as 120,0
instead of 120.0, for example. That error is caused because your country's
number formatting is different from the US (like me, Brazilian).
Answers
1)
// your class can have a different name, depending on the name of your file
public class Program {
public static void main( String [] args) {
String name = "Your name here";
System . out . println( name);
}
}

2)
import java. util. Scanner ;
public class Main {

public static void main( String [] args) {


System . out . println( "What is your name?" );
Scanner scan = new Scanner ( System . in );
String name = scan. next ();
System . out . println( "Hello, " + name + "!" );
}

}
3)
import java. util. Scanner ;
public class Main {

public static void main( String [] args) {


System . out . println( "Enter a String:" );
Scanner scan = new Scanner ( System . in );
String text = scan. next ();
System . out . println( text. trim());
}

}
4)
import java. util. Scanner ;
public class Main {

public static void main( String [] args) {


Scanner scan = new Scanner ( System . in );

System . out . println( "Enter a String:" );


String s1 = scan. next ();

System . out . println( "Enter another String:" );


String s2 = scan. next ();

System . out . println( s1. toLowerCase() + " " + s2. toUpperCase());


}

}
5)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "How old are you?" );
int age = scan. nextInt();
scan. close();
int born = 2017 - age;
System . out . println( "You were born in " + born);
}
}
6)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );

System . out . println( "Enter a number:" );


int n = scan. nextInt();
scan. close();

int predecessor = n - 1 ;
int successor = n + 1 ;

System . out . println( "Predecessor: " + predecessor);


System . out . println( "Successor: " + successor);
}
}
7)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a number:" );
int n = scan. nextInt();
scan. close();
System . out . println( 2 * n);
System . out . println( Math . pow( n, 2 )); // or n*n
System . out . println( n / 2.0 );
System . out . println( Math . sqrt( n));
// or Math.pow(n, 0.5) if you're really high xD
}
}
8)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a number:" );
int n1 = scan. nextInt();
System . out . println( "Enter another number:" );
int n2 = scan. nextInt();
scan. close();
double average = ( n1 + n2) / 2.0 ;
System . out . println( "The average is " + average);
}
}
9)
import java. util. Locale ;
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
// Use this if you're getting java.util.InputMismatchException:
scan. useLocale( Locale . US);
System . out . println( "What is the price of the product?" );
double price = scan. nextDouble();
scan. close();
double newPrice = price * 0.9 ;
System . out . println( "After a 10% discount, this product will be sold
for $ " + newPrice);
}
}
10)
import java. util. Locale ;
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
// Use this if you're getting java.util.InputMismatchException:
scan. useLocale( Locale . US);
System . out . println( "Enter the temperature in Celsius:" );
double c = scan. nextDouble();
scan. close();
double f = 9 / 5.0 * c + 32 ;
System . out . println( c + "ºC is equivalent to " + f + "ºF" );
}
}
Chapter 5: Conditionals and Control
Flow
We make decisions on a daily basis. Whether it’s about what you’re eating
for breakfast or where should you travel to, we often make those decisions
based on certain conditions. For example: if it’s raining, you use an
umbrella; if you’re hungry, you eat; if you want to cross the street, you only
do it after you’re sure that the cars have stopped. I could do this forever, but
you get it. If a predefined condition is met, something happens or not.
We can apply the same principle to control the flow of our programs.

If - Else
In Java, the keyword if is the first part of a conditional expression. It is
followed by a Boolean expression inside parenthesis and then a block of
code. If the Boolean expression evaluates to true , the block of code that
follows will be run.
if ( condition) {
// Do stuff here
}
For example:
if ( 10 > 7 ) {
System . out . println( "Codenific.com" );
}
Step-by-step explanation:
In the example above, 10 > 7 is the Boolean expression that gets checked.
Since the Boolean expression "10 is greater than 7" is true ,
"Codenific.com" 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.
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.
The if /else conditional will run the block of code associated with the if
statement if its Boolean expression evaluates to true .
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:

boolean isRaining = false;


if ( isRaining) {
System . out . println( "I will stay at home")
} else {
System . out . println( "I will go to the beach" ); // this one gets printed
}

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.
If the Boolean expression after the if statement evaluates to true , it will run
the code block that directly follows.
Otherwise, if the Boolean expression after the else if statement evaluates to
true , the code block that directly follows will run.
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 age = 17;
if ( age >= 21 ) {
System . out . println( "You can drive. And you can buy an alcoholic
drink" );
} else if ( age >= 16 ) {
System . out . println( "You can drive" );
} else {
System . out . println( "You will have to wait" );
}
Step-by-step explanation:
In the example above, the int variable age is equal to 17, which is not
greater than or equal to 21, but it is greater than or equal to 16. Therefore,
the else if block of code 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. It has:

● A Boolean expression
● A single statement that gets executed if the Boolean expression is
true
● A single statement that gets executed if the Boolean expression is
false

Example:
int points = 10;
String gameResult = ( points >= 10 ) ? "Winner" : "Loser";
System . out . println( gameResult);
char justALetter = ( points >= 10 ) ? 'W' : 'L';
System . out . println( justALetter);
Step-by-step explanation:
In the example above, the Boolean expression is (points >= 10), which
evaluates to true. This will return the value of "Winner" , which is assigned
to the variable gameResult and then gets printed to the console.
The same applies to other data types, not just Strings! See the second
ternary condition with char.

While Loop
Imagine you want to print out "Hello" two times.
System . out . println( "Hello" );
System . out . println( "Hello" );
It's easy to copy and paste the statement to execute the action twice. But
what if you wanted to print out the same message 100 times? Don't just go
out copying and pasting everything. There's a better way to do that: using a
loop .
A loop is basically a set of instructions that get executed for a number of
times. It lets the computer do the hard work for you, not the other way
around.
This is how a while loop is formatted:
while ( condition) {
// Do stuff here
}
The instructions inside of the loop will be executed while the condition is
met.
Here's how we could print out "Hello" 10 times:
int i = 0 ;
while ( i < 10 ) {
System . out . println( "Hello" );
i++; // same as i = i + 1;
}
Step-by-step explanation:
First, I created an int variable called i to keep track of the times "Hello" was
printed. While i is less than 10, "Hello" will be printed and i will be
incremented by one.
After several incrementations, there will be a point in which i is equal to 9.
"Hello" will be printed; i will be incremented by 1 again and have a value
of 10. That's when the loop breaks, because the condition i < 10 is no
longer satisfied. This is the output:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Infinite while loop
If we didn't increment that i variable, it would always be less than 10.
Hence, the condition would be always met and the loop would never break.
That can be a bad thing – except when you want it to happen in a
specific environment (I’ll talk about that later). The program would keep
printing "Hello" indefinitely. Here are some examples where that happens:
public class Main {
public static void main( String [] args) {
int i = 0 ;
while ( i < 10 ) {
System . out . println( "Hello" );
}
}
}

public class Main {


public static void main( String [] args) {
while ( true ) {
System . out . println( "Hello" );
}
}
}
This is what an apparently infinite while loop looks like:
import java. util. Scanner;

public class Main {


public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a word:" );
String s;
while ( true ) {
s = scan . next ();

if ( s . equals ( "Hello" )) {
System . out . println ( "Correct!" );
break;
} else {
System . out . println ( "Try again!" );
continue;
}
}
}
}
Step-by-step explanation:
At the beginning, I created a Scanner object and gave it a name of scan . I
printed out “Enter a word:” to let the user know that I’m asking for an
input and I also created a String variable to store that input. Then I have
while (true) which basically means that the loop won’t stop UNLESS we
break it. Moving on, if the input is equal to “Hello” , “Correct!” gets
printed out and the loop breaks with the break statement. Else, if the input is
not equal to “Hello” , “Try again!” gets printed out and the loop continues
with the continue statement until “Hello” is entered by the user.

For Loop
For Loop is a commonly used loop and even better than while .This is its
syntax:
for ( initialization; condition; increment) {
// Do stuff here
}
Here’s that same example we did with a while loop (print "Hello" 10
times):
for ( int i = 0 ; i < 10 ; i++) {
System . out . println( i + " Hello" );
}
Or you can do it like this:
for ( int i = 1 ; i <= 10 ; i++) {
System . out . println( i + " Hello" );
}
Let’s see what each part means:
for (int i = 0; i < 10; i++ ) {
System.out.println(i + " Hello");
}
It creates a temporary variable of type int called i . While i is less than 10 , i
+ “Hello” will be printed and the variable i will be increased by one .
Similarly, if you wanted to print the numbers from 10 to 20:
for ( int i = 10 ; i <= 20 ; i++) {
System . out . println( i);
}
// OR
for ( int i = 10 ; i < 21 ; i++) {
System . out . println( i);
}
Note that this type of loop does not require you to keep track of a count
variable “manually”, so it’s easier to set up.

Controlling your Loops


Suppose we wanted to print out only the even numbers from 10 to 20. That
means there will be a condition: “Print the numbers in the range of 10 to 20
IF the number is even”. Here’s how we can do it with both while and for
loops.
for ( int i = 10 i <= 20 ; i++) {
if ( i % 2 == 0 ) {
System . out . println( i);
}
}

int i = 0;
while ( i < 10 ) {
if ( i % 2 == 0 ) {
System . out . println( "Hello" );
}
i++;
}
There’s also something called a nested loop . It happens when you put a
loop inside another loop. Like a for loop inside another for loop.

Workout Set #4
1) What is the output of the following program?
public class Main {
public static void main( String [] args) {
int age = 20;
boolean isMinor = age < 21;
if ( isMinor) {
System . out . println( "You can NOT buy drinks in the US" );
} else {
System . out . println( "You can buy drinks in the US" );
}
}
}
2) What is the output of the following program?
public class Main {
public static void main( String [] args) {
boolean boo = 5 > 4.7 && 3.9 > 8.2;
if ( boo) {
System . out . println( "Boo!" );
} else {
System . out . println( "Nope" );
}
}
}

3) What is the output of the following program?


P.S. The method .equals() tests if a String is equal to another and returns a
boolean. In this case it tests if the String stored in the variable t is equal to
"Te"
public class Main {
public static void main( String [] args) {
String s = "Text";
String t = s. substring( 0 , 2 );
if ( t. equals( "Te" )) {
System . out . println( "OOO" );
} else {
System . out . println( "UUU" );
}
}
}
4) What is the output of the following program?
public class Main {
public static void main( String [] args) {
boolean x, y;
x = 2 * 4 > 2 * 3 && 10 / 2 < 5.1;
y = 32 < 31 || false;
System . out . println( "Boom" );
if ( x || y) {
System . out . println( "Yay" );
} else {
System . out . println( "Wow" );
}
System . out . println( "OK" );
}
}

5) Write a program that gets a number from the user and tells if it's even or
odd.
Example 1:
Enter a number:
4
4 is even
Example 2:
Enter a number:
3
3 is odd
Remember to use the remainder operator!

6) Write a program that gets the name of the user, his/her year of birth and
then tells if he/she can already drive in the US. A person can drive in the
US if the age is greater than or equal to 16.
Example (in 2017):
What is your name?
Lucas
In what year were you born?
2001
Lucas, you are 16 and you can drive in the US

7) Write a program that gets a letter (String) as input. If it's "Y" or "y", print
"Yes". If it's "N" or "n", print "No". Else, print "Invalid letter".
Example 1:
Enter one letter:
y
Yes
Example 2:
Enter one letter:
N
No
Example 3:
Enter one letter:
L
Invalid letter
8) What will be the value of x after the For loop is over?
public class Main {
public static void main( String [] args) {
int x = 0;
for ( int i = 1 ; i < 4 ; i++) {
x += i;
}
}
}
9) What will be the value of n after the For loop is over?
public class Main {
public static void main( String [] args) {
int n = 10;
for ( int i = 0 ; i < 3 ; i++) {
n -= i;
}
}
}
10) What will happen after the following program gets executed?
public class Main {
public static void main( String [] args) {
int n = 10;
while ( n > 10 ) {
System . out . println( "Hello" );
}
}
}
a) An error will occur
b) "Hello" will be printed 10 times
c) "Hello" will be printed 9 times
d) Nothing will be printed
e) "Hello" will be printed once

11) How many times "n is greater than 0" will be printed?
public class Main {
public static void main( String [] args) {
int n = 2;
n++;
while ( n > 0 ) {
System . out . println( "n is greater than 0" );
n--;
}
}
}
a) 0
b) 1
c) 2
d) 3
e) 4

12) What will be the value of y after the For loop is over?
public class Main {
public static void main( String [] args) {
int y = 2;
while ( y < 20 ) {
y += 2;
}
}
}
a) 20
b) 19
c) 22
d) 18
e) 21

13) What does this code do?


public class Main {
public static void main( String [] args) {
for ( int i = 1 ; i <= 10 ; i++) {
System . out . println( i);
}
}
}
It…
a) Prints the numbers from 0 to 10
b) Prints the numbers from 1 to 10
c) Prints the numbers from 1 to 11
d) Prints the numbers from 1 to 9

14) Write a program that prints out the numbers from 150 to 300, including
150 and 300.

15) The "Fizz-Buzz test" is an interview question designed to help filter out
the 99.5% of programming job candidates who can't seem to program their
way out of a wet paper bag. The text of the programming assignment is as
follows:
"Write a program that prints the numbers from 1 to 100. But for multiples of
three print “Fizz” instead of the number and for the multiples of five print
“Buzz”. For numbers which are multiples of both three and five print
“FizzBuzz”."
Answers
1) You can NOT buy alcohol in the US

2) Nope
3) OOO

4) Boom
Yay
OK

5)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a number:" );
int n = scan. nextInt();
if ( n % 2 == 0 ) {
System . out . println( n + " is even" );
} else {
System . out . println( n + " is odd" );
}
}
}

6)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "What is your name?" );
String name = scan. next ();

System . out . println( "In what year were you born?" );


int age = 2017 - scan. nextInt();

if ( age >= 16 ) {
System . out . println( name + ", you are " + age + " and you can
drive in the US" );
} else {
System . out . println( name + ", you are " + age + " and you can not
drive in the US" );
}
}
}

7)
import java. util. Scanner ;
public class Main {
public static void main( String [] args) {
Scanner scan = new Scanner ( System . in );
System . out . println( "Enter a letter:" );
String letter = scan. next ();
if ( letter. toUpperCase(). equals( "Y" )) {
System . out . println( "Yes" );
} else if ( letter. toUpperCase(). equals( "N" )) {
System . out . println( "No" );
} else {
System . out . println( "Invalid letter" );
}
}
}
8) 6

9) 7

10) d

11) d

12) a

13) b
14)
public class Main {
public static void main( String [] args) {
for ( int i = 150 ; i <= 300 ; i++) {
System . out . println( i);
}
}
}

15) There are several ways to solve the FizzBuzz problem and it’s ok to
have a different solution as long as it is efficient and does what is asked.
Here’s one solution:
public class FizzBuzz {
public static void main( String [] args) {
for ( int i = 1 ; i <= 100 ; i++) {
if ( i % 15 == 0 ) { // or i % 3 == 0 && i % 5 == 0
System . out . println ( "FizzBuzz")
} else if ( i % 3 == 0 ) {
System . out . println ( "Fizz" );
} else if ( i % 5 == 0 ) {
System . out . println ( "Buzz" );
} else {
System . out . println ( i );
}
}
}
}
You can read more about the test here .
Switch
The following code example was taken from the official documentation. It
declares an int named month whose value represents a month. The code
displays the name of the month, based on the value of month , using the
switch statement.
public class SwitchDemo {
public static void main( String [] args) {
int month = 8 ;
String monthString;
switch ( month) {
case 1 : monthString = "January" ;
break ;
case 2 : monthString = "February" ;
break ;
case 3 : monthString = "March" ;
break ;
case 4 : monthString = "April" ;
break ;
case 5 : monthString = "May" ;
break ;
case 6 : monthString = "June" ;
break ;
case 7 : monthString = "July" ;
break ;
case 8 : monthString = "August" ;
break ;
case 9 : monthString = "September" ;
break ;
case 10 : monthString = "October" ;
break ;
case 11 : monthString = "November" ;
break ;
case 12 : monthString = "December" ;
break ;
default : monthString = "Invalid month" ;
break ;
}
System . out . println( monthString);
}
}
In this case, "August" is printed out, because month is equal to 8.
So, this is the Switch basic syntax:
switch ( variable) {
case value: action;
break ;
case value2: action2;
break ;
// ...
default : defaultAction;
break ;
}

Variable Scope
Remember how we associated the idea of variables with boxes in which
you can put some data and then come back later to retrieve it? If you lock
that box in a room, you can’t access it from the outside – your kitchen, for
example – because your room is the scope. That’s a metaphor to explain
variable scope, which is the name given to the code snippet where that
variable exists and where it can be accessed.
// here variable i does not exist
int i = 5 ;
// variable i exists from now on
If you declare a variable inside a block of code (a piece that is surrounded
by curly braces) you can only access the variable within that block.
Otherwise, it’s like it never existed. Look:
// here variable i does not exist
int i = 5 ;
// variable i exists from now on
while ( condition) {
// variable i can be accessed here
int j = 7 ;
// variable j exists from now on
}
// here j no longer exists, but i does
Workout Set #5
1) What will be the output of the following program when the user enters
3972 as input?
import java. util. Scanner;

public class Main {


public static void main( String [] args) {
Scanner scan= new Scanner ( System . in );
System . out . println( "Enter a number:" );
int n = scan. nextInt();
switch ( n % 2 ) {
case 0:
System . out . println( "E" );
break;
default:
System . out . println( "O" );
break;
}
}
}

2) What will be the output of the following program when the user enters 1
as input? (same code)
import java. util. Scanner;

public class Main {


public static void main( String [] args) {
Scanner scan= new Scanner ( System . in );
System . out . println( "Enter a number:" );
int n = scan. nextInt();
switch ( n % 2 ) {
case 0:
System . out . println( "E" );
break;
default:
System . out . println( "O" );
break;
}
}
}

3) What will be the output of the following program?


public class Main {
public static void main( String [] args) {
String password = "252525";
switch ( password) {
case "123456":
System . out . println( "Access granted" );
break;
case "654321":
System . out . println( "Access denied" );
break;
case "252525":
System . out . println( "Access granted" );
break;
default:
System . out . println( "Invalid password" );
break;
}
}
}

4) What will happen after the following program gets executed?


public class Main {
public static void main( String [] args) {
int i = 10;
System . out . println( n);
}
}
a) 10 will be printed
b) Nothing will be printed
c) An error will occur

5) What will happen after the following program gets executed?


public class Main {
public static void main( String [] args) {
int i = 10;
for ( int x = 1 ; x <= 5 ; x++) {
System . out . println( i);
}
}
}
a) 10 will be printed five times
b) 10 will be printed once
c) x will be printed
d) Nothing will be printed
e) An error will occur

6) What is wrong with the code below?


public class Main {
public static void main( String [] args) {
int a = 10;
for ( int b = 1 ; b <= 5 ; b++) {
int c = 5;
System . out . println( b);
}
System . out . println( c);
}
}

7) What is wrong with the code below?


public class Main {
public static void main( String [] args) {
int n = 10;
while ( n == 10 ) {
System . out . println( n);
}
}
}

8) If you've come this far, congratulations!


Now you're going to build a game that involves variables, input
manipulation, relational operators, loops, conditionals and a class called
Random to generate pseudorandom numbers. Pay close attention to the
following instructions and read them until you completely understand what
is asked, before writing any code.

This is how it works: the computer generates a (secret) random integer in


the range of 1 to 10 (including 1 and 10). The user keeps trying to guess the
secret number, until he/she gets it right. Every time the user doesn't type the
right value, he/she gets a tip ("The secret number is greater than that" or
"The secret number is less than that"). Once the correct number is entered,
the game ends and the user receives a message of "Congratulations! You
won!".

I won't provide you the answer to this question, but I can give you some
advice:
● To keep asking for input while the given number is not correct use a
while (true) loop that will keep asking for input, guiding the user, and
will only break when the number is correct (when the number entered
by the user is equal to the number generated by the computer).
Answers
1) E

2) O

3) Access granted

4) c

5) a

6) The variable 'c' gets created inside the for loop, therefore it can't be
accessed from the outside (i.e., it no longer exists after the loop is
completely executed). The lines after the for loop are out of the scope of 'c'.

7) The condition (n == 10) will always evaluate to true, because 'n' is never
increased or decreased. That results in an infinite while loop.

8) -
Chapter 6: Intro to Object-Oriented Java
Object-oriented programming (OOP) is a programming language model
organized around objects rather than "actions" and data rather than logic.
Examples of objects range from human beings (described by name, address,
and so forth) to buildings and floors – whose properties (attributes ) can be
described and modified (through methods ) down to the little.
What are the advantages of programming in object-oriented languages like
Java?
● Being more organized
● Writing less
● Concentrating responsibilities at the right points, making your
application more flexible, encapsulating business logic.
Soon we will see all this advantage, but first you need to know a bit more
about the syntax and creation of types and references in Java.

Classes x Objects
In a banking software, a crucial part of the system is an account . The idea
is to generalize some information, along with functionalities that every bank
account must have. Like…
● Bank account number
● Name of the owner
● Bank account balance
● Limit (to withdraw)
What every account does that is important to us? That is, what would we
like to ask the account to do?
● Draw an amount of x dollars
● Deposit an amount of x dollars
● Print out the name of the owner
● Get the current balance
● Get the limit
● Transfer an amount of x dollars to another account
● Get the type of account
With those things in mind, we have the project of a bank account. Can we
take that project and get its current balance? No. What we have is just a
project. First, we have to build an actual account in order to access it and
ask it to do something.

Notice the image: although the paper on the left side specifies an Account,
is it an Account? Do we deposit and take money out of that paper? No. We
use the Account specification to be able to create instances that really are
accounts, where we can perform the operations we create.
Even though we declare that every account has a balance, a number, and an
agency on the piece of paper (as on the left in the image), it is in the
instances of this project that there is room to store those values.
That “project” (specifications for a bank account) is called a class . And
what we can construct from that class are called objects .
The word class in this context comes from biology’s taxonomy. All living
things that belong to the same biological class have a series of attributes
and behaviors in common, but they aren’t equal, because the values of
these attributes and behaviors can differ from one living being to another.
Homo sapiens sapiens defines a group of beings that have characteristics in
common, but is the definition/idea/concept of a Homo sapiens sapiens an
actual human being? Everything is specified in Homo sapiens sapiens
class, but in order to ask a person to run, eat or jump, we’ll need to
instantiate that class, by creating an object of type Homo sapiens sapiens .
Another example: a cake recipe. We don’t eat a cake recipe, but we use it to
make an actual cake. The recipe is the class and the cake is the object . We
can create thousands of cakes based on that single recipe. Some cakes may
be similar and some might even be identical, but they are different objects
.
Think about a class as a blueprint and the object as the tangible thing.

Creating a class
Open your IDE, create a new Java class called Account and start typing
what you see next. Let’s start with what an account has:
public class Account {
int number;
String owner;
double balance;
}
These are the attributes that every created account will have. Note that
those variables were not declared inside a block, like we did when we had
the main method. When a variable is declared directly inside the scope of a
class, it’s called an object variable, or attribute. The balance will be a
double, but it shouldn’t be used for currencies.

Creating and using an object


We already have a class in Java that specifies what every object of that class
must have. But how can we use it? Besides that class, we will have
Program.java, in which we’ll use the Account class.
To create (construct, instantiate) an Account, we have to use the keyword
new and parenthesis.
public class Program {
public static void main( String [] args) {
new Account ();
}
}
Well, the code above creates an object of type Account , but how can we
access that object? We need a way to reference it. We need a… variable! In
this case, a variable of type Account.
public class Program {
public static void main( String [] args) {
Account myAccount;
myAccount = new Account ();
}
}
Through myAccount , we can access the newly created object to change its
owner , balance , limit , etc.
public class Program {
public static void main( String [] args) {
Account myAccount;
myAccount = new Account ();

myAccount. owner = " Lucas ";


myAccount. balance = 10000.0;

System . out . println(" Current balance: " + myAccount. balance);


}
}
It’s important to say that the dot was used to access something in
myAccount . In the code above, myAccount belongs to Lucas – me! – and
has 10,000 dollars.
Methods
Inside the class, we’ll also declare what each account does and how it’s
done – its behaviors. For example, if there’s a specific way to draw an
amount of money, we’re going to put it inside the Account class itself.
That’s why those “functions” are called methods , because they are a way
to do some operation with an object.
We want to create a method that draws an amount of money from the
account and doesn’t retrieve any information to whom uses this method.
public class Account {
// other attributes and methods...

void draw( double amount) {


double newBalance = this . balance - amount;
this . balance = newBalance;

}
}
The keyword void indicates that no information is going to be sent back to
whom asked to draw from the account.
When someone asks to draw from the account, that person will also say
how much he/she wants to draw. That’s why we have to declare the method
with something inside the parenthesis. And what goes inside it is called the
method’s argument (or parameter ). You can have multiple parameters in
the same method. That variable is also called a temporary or local variable
that no longer exists once the method is done executing.
We declared a variable inside the method (newBalance ) that will be
destroyed by the end of the method, because that is its scope. We used the
keyword this to show that balance was an attribute, not just a simple
variable.
Note that the person can violate the limit that was fixed by the bank,
because there’s no actual limitation so far. But we’re going to fix that soon.
We can also have a method to make a deposit:
public class Account {
// other attributes and methods...

void deposit( double amount) {


this . balance += amount;
}
}
Do you see how we didn’t declare more variables this time? And we also
used the operator += to keep things short.
We also use the dot to send a message to the object and ask it to execute a
method. That’s called method invocation .
The following code withdraws money from the account and then deposits
another amount.
public class Program {
public static void main( String [] args) {
Account myAccount;
myAccount = new Account ();

myAccount. number = 12345;


myAccount. owner = "Lucas";
myAccount. balance = 1000.0;

myAccount. draw( 200.0 );


myAccount. deposit( 500.0 );

System . out . println( myAccount. balance);


}
}

Methods that return something


When a method does not return anything, we use the keyword void . But we
can return some value of any data type. In our draw method, we could
return a boolean value to tell if the operation was completed successfully.
public class Account {
// other attributes and methods...

boolean draw( double amount) {


if ( this . balance < amount) {
return false;
} else {
this . balance -= amount;
return true;
}
}
}
In the code above, the operation won’t happen if there isn’t enough money
in the account. In this case, the method will return false . Else, the operation
will happen and true will be returned.
Note that I replaced void with boolean , to indicate the new return type.
And inside the method there are return statements that return the value we
want. Don’t forget the semicolon. Our method stops once something is
returned.
Therefore…
public class Account {
// other attributes and methods...

boolean draw( double amount) {


if ( this . balance < amount) {
return false;
System . out . println (" False ");
} else {
this . balance -= amount;
return true;
System . out . println (" True ");
}
}
}
With the code above, nothing would be ever printed, because the
System.out.println() statements are placed after the return statements.
Here’s how we could use that new draw method:
public class Program {
public static void main( String [] args) {
Account myAccount = new Account ();
myAccount. balance = 1000.0;

boolean success = myAccount. draw( 200.0 );


if ( success) {
System . out . println (" I got my money !");
} else {
System . out . println (" Where is my money ?");
}
}
}
I can even eliminate the intermediate variable (success ):
public class Program {
public static void main( String [] args) {
Account myAccount = new Account ();
myAccount. balance = 1000.0;
if ( myAccount. draw( 200.0 )) {
System . out . println (" I got my money !");
} else {
System . out . println (" Where is my money ?");
}
}
}
And, of course, you can have multiple accounts in the same program:
public class Program {
public static void main( String [] args) {
Account myAccount = new Account ();
myAccount. balance = 1000.0;

Account mySecondAccount = new Account ();


mySecondAccount. balance = 500.0;
}
}

Objects are accessed through references


When we declare a variable and assign it an object, the variable does not
hold the object itself, but rather a way to access it, which is called a
reference .
That’s why we need to use new when declaring the variable, unlike what
we do with primitive data types like int and long .
Account a1;
a1 = new Account ();
Account a2;
a2 = new Account ();
In the code above, we can not say that a1 is an object, because a1 is a
variable that references an object . So keep in mind that, in Java, a
variable is never an object .

On the inside, a1 and a2 will keep a number that identifies in which


position of the memory the Account is. This way, by using “. ” to navigate,
Java will access the Account that is in the desired position, not another one.
public class TestReferences {
public static void main( String args[]) {
Account a1 = new Conta ();
a1. deposit( 100 );
Account a2 = a1; // !!!
a2. deposit( 200 );
System . out . println( a1. balance);
System . out . println( a2. balance);
}
}

What happens when you run the code above?


The operator = copies the value of a variable. But what is the value of
variable a1 ? Is it the object? No. Actually, the stored value is the reference
(address) of the object in the memory.
Account a1 = new Account ();
Account a2 = a1;
So, when I wrote a2 = a1 , a2 now references that same object that is
referenced by a1. Hence, in this particular case, it doesn’t matter if we use
a1 or a2, because they both reference to the same object! That means the
expression a1 == a2 would evaluate to true.
Another way to see that happening is knowing that we used the keyword
new only once, so there is only one Account object in the memory.
public static void main( String [] args) {
Account a1 = new Account ();
a1. owner = "Luke" ;
a1. balance = 250 ;
Account a2 = new Account ();
a2. owner = "Luke" ;
a2. balance = 250 ;
if ( a1 == a2) {
System . out . println( "Equal accounts!" );
}
}
The operator == compares the value that is stored inside the variables a1
and a2 , but those variables don’t hold an object, they hold its address .
Since two different Accounts were created and each variable references to
one of them, they have different addresses. Therefore, a1 == a2 evaluates
to false because we’re talking about different objects in the memory. It’s a
little tricky, because we tend to compare their attributes which, in this case,
are identical.
Transfer() method
What if we want to transfer money from one account to another? This is
how it would look like:
public class Account {
// other attributes and methods...

void transfer( Account destiny, double amount) {


this . balance -= amount;
destiny. balance += amount;
}
}
We could be tempted to get 2 parameters of type Account (account1 and
account2 ), but that would be a procedural way of programming.
We want to call the transfer() method on an object of type Account (which
will be this ), therefore the method gets only one parameter of type Account
– the destiny of the money.
Let’s use that method and transfer some money.
public class Program {
public static void main( String [] args) {
Account a1 = new Account ();
a1. balance = 1000.0;
Account a2 = new Account ();
a2. balance = 500.0;

a1. transfer( a2, 250 ); // !!!

System . out . println( "a1 = " + a1. balance);


System . out . println( "a2 = " + a2. balance);
}
}

See how I did a1. transfer( a2, 250 ) ; to transfer 250 dollars to a2 ? In this
case, a1 is that “this ” I talked about and a2 is the destination. We might as
well call that method transferTo because it makes more sense.
Let’s also implement some logic to avoid transferring money from an
account that doesn’t have enough funds. And make the method return a
boolean to tell if the operation was completed successfully. I know we’re
not in a Workout Set, but try to implement those things on your own. Come
on!

This is how it will look like after those changes:
boolean transferTo( Account destiny, double amount) {
if ( this . balance < amount) {
return false;
} else {
this . balance -= amount;
destiny. balance += amount;
return true;
}
}
We should go even further and use the methods we’ve created earlier to
draw money from a1 and make a deposit to a2 . Try to implement that too!

boolean transferTo( Account destiny, double amount) {
if ( this . draw( amount)) {
destiny. deposit( amount);
return true;
} else {
return false;
}
}

Attributes again
Remember those attributes we created for the Account class?
class Account {
int number;
String owner;
double balance;
// methods…
}
When we create an object, these variables get a default value. Numeric
variables get 0 , booleans get false , and objects get null (e.g. String). But
you can also set your default values, like this:
public class Account {
int number = 12345;
String owner = “Lucas”;
double balance = 0;
// methods…
}
In this case, the attributes will be populated with these default values when
you create a new Account object.
Imagine we start to grow our class and want to put other information such
as the person’s last name and address. Should we put it in the Account
class? Actually, an Account does not have a name, or and address. You
know who has all these attributes? A Client . So we should create another
class for Clients. Soon we’ll make the connections.
public class Client {
String name;
String lastName;
String address;
}
And this is how the Account class should be now:
public class Account {
int number;
double balance;
double limit;
Client owner; // !!!

// methods...
}
If you try to access a method or attribute of an object that hasn’t been
assigned any value yet (i.e., it points to null ), you will get an error during
execution: NullPointerException .
Besides the Bank that we are creating, let's see how certain classes related
to a car factory would look like. Let's create a Car class, with certain
attributes that describe its characteristics and certain methods that describe
its behavior.

public class Car {


String color;
String model;
double currentSpeed;
double maxSpeed;

// turns on the car


void on() {
System . out . println( "The car is on" );
}

// accelerates a certain amount


void accelerate( double amount) {
double newSpeed = this . currentSpeed + amount;
if ( newSpeed <= maxSpeed) {
currentSpeed = newSpeed;
}
}
Let’s test our car in a new program:
public class TestCar {
public static void main( String [] args) {
Car myCar = new Car ();
myCar. color = " Green ";
myCar. model = " Lamborghini ";
myCar. currentSpeed = 0;
myCar. maxSpeed = 70;

// Turns on the car


myCar. on();

// Accelerates the car


myCar. accelerate( 20 );
System . out . println(" Current Speed : " + myCar. currentSpeed);
}
}
We know our car has an engine. So why don’t we create a class to describe
it?
public class Engine {
int power;
String type;
}

// This is the new Car class


public class Car {
String color;
String model;
double currentSpeed;
double maxSpeed;
Engine engine; // !!!

// methods...
}
We can create multiple cars and engines , just like we did with Accounts
and Clients in our imaginary Bank. How cool is that?
Workout Set #6 - Part One
The following employee model will be used in the exercises of the next
chapters.
The goal here is to create a system for managing Bank employees. The
exercises in this chapter are extremely important.
1) Create a class called Employee that will have these attributes: name
(String ), his/her date of birth (String ), the day he/she was hired (String
), job (String), and salary (double , represents the monthly payment).
Example:
name: “Lucas”
dateOfBirth: “25/10/2001”
wasHiredOn: “01/09/2017”
job: “CEO”
salary: 50000.0

Create some methods:


● promote : increases the employee's salary according to the parameter
amount passed as argument. No return.
● calculateAnnualSalary : does not receive any parameters; returns the
salary multiplied by 12 (months).

2) Create a class to test your Employee class. I’ll call mine TestEmployee ,
but you can call it whatever you want.
This class must have the main method. Create a new object of type
Employee and give it the attributes you want to.
Answers
1)
public class Employee {
String name;
String dateOfBirth;
String wasHiredOn;
String job;
double salary;

void promote( double amount) {


this . salary += amount;
}

double calculateAnnualSalary() {
return this . salary * 12;
}
}

2) Here’s an example of how your test class might look like:


public class TestEmployee {
public static void main( String [] args) {
Employee e = new Employee ();
e. name = "Lucas";
e. dateOfBirth = "25/10/2001";
e. wasHiredOn = "01/09/2017";
e. job = "CEO";
e. salary = 50000.0;

e. promote( 1000.0 );
double annualSalary = e. calculateAnnualSalary();
System . out . println( "Annual Salary = " + annualSalary);
}
}
Workout Set #6 - Part Two
3) Create a show() method, which neither receives nor returns any
parameters and simply prints all the attributes of our employee. That way,
you don’t have to keep copying and pasting a bunch of System.out.println()
for every changes and testings you do with each of your employees. With
that method, you're simply going to do:

Employee employee = new Employee ();


// …
employee . show();
Answers
3)
void show() {
System . out . println( "Name: " + this . name);
System . out . println( "Date of Birth: " + this . dateOfBirth);
System . out . println( "Hired on: " + this . wasHiredOn);
System . out . println( "Job: " + this . job);
System . out . println( "Salary: " + this . salary);
System . out . println( "Annual Salary: " + this .
calculateAnnualSalary());
}
Workout Set #6 - Part Three
It's time to train your learning muscles!
Create the following classes with the respective attributes and methods.
Don’t be afraid to play around, it’s time to discover things on you own!
1) Class: Person
Attributes: name - String
age - int
Method: void oneMoreYear() - increases the age of the person by 1

Create a person, put her/his name and initial age, make birthdays (increase
age) and print the person’s name and age.

2) Class: Door
Attributes: opened - boolean
color - String
dimensionX - double
dimensionY - double
dimensionZ - double
Methods: void open() - opens the door
void close() - closes the door
void paint(String s) - paints the door with color s
boolean isOpen - returns true if the door is open, and false
if the door is closed

Create a door, open and close it, paint it in different colors, change its
dimensions, and use the open() method to check if it is open.

3) Class: House
Attributes: color - String
door1 - boolean
door2 - boolean
door3 - boolean
Methods: void paint(String s) - paints the door with color s
int howManyDoorsOpened() - returns the number of doors
that are opened
Create a house and paint it. Open and close the three doors as desired.
Use howManyDoorsOpened() method to print the number of open doors.
Answers
No answers this time!
Chapter 7: Arrays
Primitive Data Type Array
Imagine you want to store your age in a variable. You probably thought of
something like this:
int age;
And you’re correct. But what if you need to store the ages of a big group of
people? Let’s say 10.
int age1;
int age2;
int age3;
int age4;
int age5;

That doesn’t seem very practical, right? Because it really isn’t. I’m glad you
noticed that.
So, what is the solution?
Arrays.
In this case, integer arrays, which you can declare like this:
int [] ages;
// or:
int ages[];
int[] is a type. An array is always an object, therefore, variable ages is a
reference. Let’s create an object to use that array with 10 ages:
ages = new int [ 10 ];
The statement above created an array of integers with 10 positions and
assigned its “address” in the memory.
Notice how variable ages references to the array we’ve created.

We can access those positions of our array. Remember how you sliced
Strings in Chapter 4? The process here is very similar. Let’s say we want to
put age 32 in the first position.
ages[ 0 ] = 32;
In Java, array indexes range from 0 to n - 1 (n being the size of the array, in
this case n = 10).

If you try to access a position that is outside of that range, you get an error.
A common mistake is to access the last index using the number that
represents the size of the array (n) instead of the real last index (n - 1).

Object arrays
Instead of storing numeric values like 10, 25 and 32, arrays can also
reference to other objects . We could create an array for our Account
objects from last chapter.
Account [] myAccounts;
myAccounts = new Account [ 10 ];
How many Accounts were created in the code above? None , actually.
We’ve just created 10 positions (spaces in memory) that can be used to
store references to the Accounts we want. For now, they reference to
nowhere (null ). If you try to do the following, an error will occur…
System . out . println( myAccounts[ 0 ]. balance);
The first position of the array is pointing to null . You have to populate your
array before trying to access its positions.
Account a = new Account ();
a. balance = 2500.0;
myAccounts[ 0 ] = a;
Or you can do it more directly:
myAccounts[ 1 ] = new Account ();
myAccounts[ 1 ]. balance = 1000.0;

An array of primitive data types stores values and an object array


stores references.

Iterate through an array


Imagine you want to print out all the values in your array, or plenty of them,
for example. It’s unsustainable to do...
System . out . println( myArray[ 0 ]);
System . out . println( myArray[ 1 ]);
System . out . println( myArray[ 2 ]);
System . out . println( myArray[ 3 ]);
Instead, we use a for loop (Chapter 5).
public static void main( String [] args) {
int [] ages = new int [ 10 ];
for ( int i = 0 ; i < 10 ; i++) {
ages[ i] = i * 2;
}
for ( int i = 0 ; i < 10 ; i++) {
System . out . println( ages[ i]);
}
}
First, I populated the array:

for ( int i = 0 ; i < 10 ; i++) {


ages[ i] = i * 2;
}
For every i in the range or 0 to 10 (including 0 but not 10), the respective
position in the array (ages[ i ] ) will be assigned a value of i * 2 .
So, this is the array represented graphically:

Then I printed each element of the array:


for ( int i = 0 ; i < 10 ; i++) {
System . out . println( ages[ i]);
}
And this is what gets printed:
0
2
4
6
8
10
12
14
16
18
However, in many cases, we get arrays we didn’t create and we might not
now how big they are. So, when should our for loop stop? Here’s an
example with a function that would print the items of a given array.

void printArray( int [] array) {


for ( int i = 0 ; i < ????; i++) {
System . out . println( array[ i]);
}
}
To solve that problem, we can use an attribute that every array in Java has:
length.
void printArray( int [] array) {
for ( int i = 0 ; i < array. length; i++) {
System . out . println( array[ i]);
}
}
Oh! And Arrays can’t change its size.
Once you create an array, it will have the same size (number of positions) as
long as it exists. If you need more spaces, you’ll have to create a new array
and copy the elements from the old array.
Java 5.0 has a new syntax to iterate through arrays when you don’t need a
temporary variable to keep track of the current index. It’s an enhanced-for
loop. See the code example:
public class MyClass {
public static void main( String [] args) {
int [] ages = new int [ 10 ];
for ( int i = 0 ; i < 10 ; i++) {
ages[ i] = i * 10 ;
}

// print all the items in the array


for ( int x : ages) {
System . out . println( x);
}
}
}
Here’s that same function but written with an enhanced-for loop:
void printArray( int [] array) {
for ( int x : array) {
System . out . println( x);
}
}
The same is true for reference arrays. This is for nothing more than a trick
to make it easier to iterate through arrays and make the process more
readable.
Workout Set #7
1) Write a program that creates an array and populates it with the numbers
from 1 to 10 and then prints them out by iterating through the array.

2) Create a new class called “Employee” (if don’t have one yet) and paste
the following code:

public class Employee {


String name;
double salary;
}

Also create a new class called “Company” (if don’t have one yet) and paste
the following code:

public class Company {


Employee [] employees = new Employee [ 3 ];
int i = 0;

void add( Employee employee) {


this . employees[???] = employee;
i += ???;
}

void showEmployees() {
for ( Employee e : employees) {
System . out . println(???);
}
}
}
Finally, create a new class called “Program” (if don’t have one yet) and
paste the following code:

public class Program {


public static void main( String [] args) {
Employee e1 = new Employee ();
e1. name = "Lucas";
e1. salary = 100000;

Employee e2 = new Employee ();


e2. name = "Mary";
e2. salary = 120000;

Employee e3 = new Employee ();


e3. name = "Nick";
e3. salary = 85000;

Company company = new Company ();


company. add( e1);
company. add( e2);
company. add( e3);

company. showEmployees();
}
}

Now replace every “???” with the correct code in order to do this:
● add() takes an Employee as argument and adds it to the array
employees in the first empty position of the array.
● showEmployees() does not return anything. It just prints out the
employee’s name and salary for every employee in the array
employees .
● You can only replace the question marks with new code
● This is the desired output:
Lucas -> 100000.0
Mary -> 120000.0
Nick -> 85000.0

3) Let’s do the FizzBuzz exercise again, but now using arrays.


"Write a program that prints the numbers from 1 to 100. But for multiples of
three print “Fizz” instead of the number and for the multiples of five print
“Buzz”. For numbers which are multiples of both three and five print
“FizzBuzz”."

Create an array of length 100 and populate it with the numbers from 1 to
100. Then iterate through that array to print the numbers by following the
conditions.

4) Create an array of any length and populate it with any numbers. Now
iterate through it to copy those numbers to a new array.
Answers
1)
public class Program {
public static void main( String [] args) {
int [] array = new int [ 10 ];
for ( int i = 0 ; i <= 9 ; i++) {
array[ i] = i + 1;
}
for ( int x : array) {
System . out . println( x);
}
}
}

2)
public class Company {
Employee [] employees = new Employee [ 3 ];
int i = 0;

void add( Employee employee) {


this . employees[ i] = employee;
i += 1;
}

void showEmployees() {
for ( Employee e : employees) {
System . out . println( e. name + " -> " + e. salary);
}
}
}

3)
public class Program {
public static void main( String [] args) {
int [] array = new int [ 100 ];
for ( int i = 1 ; i <= 100 ; i++) {
array[ i- 1 ] = i;
}
for ( int x : array) {
if ( x % 15 == 0 ) {
System . out . println ( "Fizzbuzz" );
} else if ( x % 5 == 0 ) {
System . out . println ( "Buzz" );
} else if ( x % 3 == 0 ) {
System . out . println ( "Fizz" );
} else {
System . out . println ( x );
}
}
}
}

4)
public class Program {
public static void main( String [] args) {
int [] oldArray = new int [ 3 ];
oldArray[ 0 ] = 1;
oldArray[ 1 ] = 2;
oldArray[ 2 ] = 3;
int [] newArray = new int [ 3 ];
for ( int i = 0 ; i <= 2 ; i++) {
newArray[ i] = oldArray[ i];
}
}
}
Chapter 8: Access Modifiers and Class Attributes
Controlling access
We’re going to get back to the Account class we created earlier in Chapter 6.
public class Account {
int number;
double balance;
double limit;
Client owner;

boolean draw( double amount) {


if ( this . balance < amount) {
return false;
} else {
this . balance -= amount;
return true;
}
}

void deposit( double amount) {


this . balance += amount;
}

boolean transferTo( Account destiny, double amount) {


if ( this . draw( amount)) {
destiny. deposit( amount);
return true;
} else {
return false;
}
}
}
We fixed the draw() method with an if-else to prevent it from taking money that wasn’t in the account and
leaving a negative balance.
But what if someone (another programmer) tries to draw money from the account or change its balance
not by using the method we created, but by modifying the balance variable directly? Like this:
public class Program {
public static void main( String [] args) {
Account account = new Account ();
account. balance = - 100;
}
}
The best way to solve that is by making the person use the draw() method we provided to change the
balance value. This solution does that by not allowing the attribute to be directly accessed.
In Java, we use the keyword private . It’s called an access modifier or visibility modifier.
public class Account {
private double balance;
private double limit;
// ...
}
And this is what happens once we change that:

We can no longer access the variables balance and limit directly!


In object-oriented programming (OOP), protecting your attributes with private is almost an
obligatory practice.
Each class is responsible for controlling its attributes , so it must judge whether the new value for an
attribute is valid or not! This validation should not be done by those who are using the class, but by the
class itself, centralizing that responsibility and making future changes in the system a lot easier. There are
times when we don’t even want other classes to know the existence of a certain attribute, so we hide it
completely, since it’s a part of the inner workings of the objects that come from that class.
Note that anyone who invokes the draw() method has no idea that there is a limit that is being checked. A
person that is going to use this class just needs to know what the method does and not how exactly it does
(what a method does is always more important than how it does, because changing the implementation is
easy, but changing the signature* of a method will generate problems).
*A method signature is part of the method declaration. It is the combination of the method name and the
parameter list.
The private keyword can also be used to modify access to a method . This functionality is used in several
scenarios, the most common being: a) when there is a method that is only used to assist the class itself
and b) when there is code repeated within two methods of the class. We should always expose as few
functionalities as possible to create a low coupling between our classes.
On the other hand, we also have the public access modifier, which allows everyone to access a particular
attribute or method:
public class Account {
// ...
public boolean draw( double amount) { // anyone can access this method
if ( amount > this . balance + this . limit) {
return false;
} else {
this . balance -= amount;
return true;
}
}
Note that our classes were declared with the modifier public , in which case those classes are visible to all
classes everywhere.
See how the IDE shows open and closed locks to represent public and private things, respectively:

What about methods/attributes that don’t have an access modifier, like deposit() , owner , number
and transferTo() ? They are neither public nor private. They are default , as you can see below.
Visibility Public Protected Default Private

From the same class Yes Yes Yes Yes

From any class in the same package Yes Yes Yes No

From a subclass in the same package Yes Yes Yes No

From a subclass outside the same package Yes Yes, through No No


inheritance
From any non-subclass class outside the Yes No No No
package

We’re not diving into the details of each access modifier now (I haven’t even talked about Protected yet!).
I just want you to know for now that there are some differences between each keyword and you don’t
have to memorize them. Keep in mind that they are like security levels for your attributes and methods.
It is very common to make your attributes private and almost all your methods public, although
that’s not a rule.

Encapsulation
What we began to see in this chapter is the idea of encapsulating , that is, hiding all members of a class,
as well as hiding how the routines (methods) of our system work.
Encapsulating is key to making your system susceptible to changes: we will not need to change a business
rule in multiple places, but in only one place, since that rule is encapsulated. (see the draw() method
example).
The set of public methods in a class is also called the class interface , since they are the only way you can
communicate with objects of that class. See how that’s represented in the image below:

It is always a good idea to program with the interface of your class in mind – how your users will be
using it – and not just how it will work.
The implementation itself (the content of the methods) doesn’t not matter so much to the user of the class,
since he/she only needs to know what each method does, not how it does (as it may change with time).
Whenever we are going to access an object, we use its interface. There are several analogies in the real
world. Here’s one:
When you drive a car, what matters to you are the pedals and the steering wheel (interface) - not the
engine you are using (implementation). Of course a different engine can give you better results, but what
it does is the same as a less powerful engine, the difference lies in how it does. If you get a new engine,
you don’t have to relearn how to drive! Changing the implementation does not imply in changing the
interface, which allows other classes to continue using it the same way.

Getters and Setters


The private modifier causes no one to be able to modify, or even read, a desired attribute. So how can we
show the balance of an Account, if we can no longer access it?
Let’s use a method then! It makes sense to call it getBalance() :
public class Account {
// ...
private double balance;

public double getBalance() {


return this . balance;
}
// ...
}
Here’s how we can access the balance of an account:
public class Program {
public static void main( String [] args) {
Account account = new Account ();
account. deposit( 250 );
System . out . println( "Balance = " + account. getBalance());
}
}
To allow access to the attributes (since they are private) in a controlled way, the most common practice is
to create two methods: one that returns the value and another that changes the value.
The convention is that they start with the words get and set , respectively. This is how our class would
look like if we wanted to write getters and setters for balance , limit and owner :
public class Account {
private double balance;
private double limit;
private Client owner;

public double getBalance() {


return balance;
}

public void setBalance( double balance) {


this . balance = balance;
}

public double getLimit() {


return limit;
}

public void setLimit( double limit) {


this . limit = limit;
}

public Client getOwner() {


return owner;
}

public void setOwner( Client owner) {


this . owner = owner;
}
}
But you don’t have to write all those methods by yourself. Use your IDE! Let your cursor in an empty line
in which you want to put the getters and setters. Select Code >> Generate...

Select Getter and Setter.

Use Shift or Ctrl (Windows) to select the attributes you want to generate getter/setter for (balance , limit
and owner in this case) and then hit OK.
There you go!
It is a bad practice to create a class and then create getters and setters for all its attributes. You should
only create a getter or setter if you really need it . Note that in this example setBalance() should not
have been created, since we want everyone to use deposit() and draw() .
Another important detail: a getX method does not necessarily return the value of an attribute called X that
belongs to the respective object. This is interesting for encapsulation. Imagine this situation: we want the
bank to always show the balance as limit + balance (a common practice among banks to deceive their
customers).
We could always call account.getLimit() + account.getBalance() , but this could generate a "replace all"
situation when we needed to change how the balance is shown. Let’s encapsulate it inside the
getBalance() itself. Look:

public double getBalance() {


return this . balance + this . limit;
}
And we also shouldn’t create getLimit() and setLimit() or even getOwner() and setOwner() right now
since we don’t need those yet. That leaves us with just the necessary for now:
public class Account {
// attributes...

public double getBalance() {


return this . balance + this . limit;
}

// methods...
}
Using getters and setters not only helps you protect your attributes, but it also allows you to make changes
in just one place – what we call encapsulating –, because it hides the way objects store their data. It is a
very important practice!
There is still another issue with our class. If a person deposits a negative amount (even though it doesn’t
exist in real life, it can happen here), the balance will be negative. Like this:
public class Program {
public static void main( String [] args) {
Account account = new Account ();
account. deposit(- 250 );
}
}
What method should we fix in order to prevent that from happening?
The deposit() method, of course! It has to check if the amount entered is positive before depositing it. And
thanks to encapsulation, that’s the only change we need to do. Go ahead and do that.

void deposit( double amount) {
if ( amount > 0 ) {
this . balance += amount;
}
}

Constructors
When we use the new keyword, we’re constructing an object. new always runs the class constructor ,
which is a block of code with the same name of the class:
public class Account {
// attributes...

// constructor:
Account () {
System . out . println( "Constructing an account..." );
}

// methods...
}
So when we do:
public class Program {
public static void main( String [] args) {
Account account = new Account ();
}
}
“Constructing an account…” gets printed. It’s like a initialization routine for whenever we create a new
object. A constructor is not a method! (even though it looks like one)

Default constructor
When you don’t declare a constructor in your class, Java creates one for you. This constructor is the
default constructor, it receives no arguments and its body is empty.
That’s why we could create new objects earlier, even without having specified any constructor. Now the
default constructor is no longer in use, because we provided ours.

Constructors with arguments


Constructors can receive arguments, to initialize some kind of information. Look how awesome is that:
public class Account {
// attributes…

Account ( Client owner) {


this . owner = owner;
System . out . println( "Constructing an account for " + owner. name + "..." );
}

// methods...
}
this.owner = owner means that the owner of the new account (this.owner) will be the client that is entered
as argument (owner).
Now you have to enter a Client when creating a new Account object:
public class Program {
public static void main( String [] args) {
Client myClient = new Client ();
myClient. name = "Lucas";

Account account = new Account ( myClient);


}
}
And this is printed: Constructing an account for Lucas...
Awesome!

Why do we need a constructor?


We survived before having a constructor. So why do we need one?
Since every Account needs an owner , the best thing you can do is to require an owner at the moment
you’re creating an object of type Account.
That’s what a constructor does. It gives possibilities or forces the user to enter some data when
creating a new object.

Multiple Constructors
You can have multiple constructors in your class and the appropriate one will be chosen.
public class Account {
int number;
private double balance;
private double limit;
Client owner;

Account ( Client owner) { // #1


this . owner = owner;
}

Account ( int number, Client owner) { // #2


this . owner = owner;
this . number = number;
}
}
--------------------------------------------
public class Program {
public static void main( String [] args) {
Client c1 = new Client ();
c1. name = "Olivia";

Account a1 = new Account ( c1); // #1

Client c2 = new Client ();


c2. name = "Fitz";
Account a2 = new Account ( 199525 , c2); // #2
}
}
Note that Account a1 uses the constructor #1 and Account a2 uses the constructor #2 .
But there is some repetition in constructor #2: this . owner = owner; gets repeated.
To solve that, we call constructor #1 within constructor #2, like this:
public class Account {
int number;
private double balance;
private double limit;
Client owner;

Account ( Client owner) {


this . owner = owner;
}

Account ( int number, Client owner) {


this ( owner); // !!!
this . number = number;
}
}
In this ( owner) , you can think of this ( ) as Account ( ) . And since it’s only taking owner as argument,
it’s calling the constructor #1 – Account ( Client owner) .

Class attributes
Suppose our Bank also wants to control the quantity of existing accounts. How could we implement that?
A simple idea would be:
public class Program {
public static void main( String [] args) {
int totalOfAccounts = 0;

Client c1 = new Client ();


c1. name = "Olivia";

Account a1 = new Account ( c1);


totalOfAccounts += 1;
}
}
But doing that would spread statements all over our code, making it hard to track them and change stuff.
Imagine having to increment that variable manually every time we created a new Account object! It
would be hard to remember, right? So why don’t we automate that?
What about this…?
public class Account {
private int totalOfAccounts;
// ...

Account ( Client owner) {


this . owner = owner;
totalOfAccounts += 1;
}
}
If we create two objects, for example, each one will have its own totalOfAccounts variable that will be
equal to 1. That’s not what we wanted.
We want this variable to be unique , shared by all objects in that class . In this way, when you change it
through an object, another object would see the same value. To do this in Java, we declare the variable as
static .
private static int totalOfAccounts;
When we declare an attribute as static , it becomes a class attribute , which is stored by the class, not by
a single object. To access a static attribute, we don’t use the keyword this , but rather the name of the class
itself.
public class Account {
private static int totalOfAccounts;
// ...
Account () {
Account . totalOfAccounts += 1;
}
}
Since the attribute totalOfAccounts is private , we need a getter to access its value from outside the
Account class. Let’s create one:
public class Account {
private static int totalOfAccounts;
// ...
Account () {
Account . totalOfAccounts += 1;
}

public int getTotalOfAccounts() {


return Account . totalOfAccounts;
}

}
How can we know how many accounts were created?
public class Program {
public static void main( String [] args) {
Client c1 = new Client ();
c1. name = "Olivia";

Account a1 = new Account ( c1);


int total = a1. getTotalOfAccounts();
}
}

But there’s a problem: we have to create an account in order to get the total of accounts. We want to
access that value without depending on an object.
getTotalOfAccounts( ) should belong to the whole class, not each object. Just like we did with variable
totalOfAccounts .
public class Account {
private static int totalOfAccounts;
// ...
public static int getTotalOfAccounts() {
return Account . totalOfAccounts;
}
// ...
}
And this is how we access it now:
public class Program {
public static void main( String [] args) {
int total = Account . getTotalOfAccounts();
}
}
Workout Set #8
1)
Employee.java
public class Employee {
private String name;
private double salary;
}

Program.java
public class Program {
public static void main( String [] args) {
Employee e1 = new Employee ();
e1. name = "Lucas";
e1. salary = 100000;
}
}

What is wrong with those codes in the way they are presented? Write
down your answer.

2) Create a new class called “Client” (if don’t have one yet) and paste the
following code:

class Client {
String name;
String lastName;
String address;
}

Now manually create getters and setters for all attributes.


Attention! That’s not something you should do when creating a real
program. We’re just doing this to practice. Only create getters and setters
when they are needed!
3) Paste the following codes in the appropriate Java classes and replace the
question marks with the correct code to produce the desired output:

public class Program {


public static void main( String [] args) {
Employee e1 = new Employee ( "Lucas" , 100000 );
Employee e2 = new Employee ( "Olivia" , 120000 );
Employee e3 = new Employee (???); // Enter your name and salary
}
}

public class Employee {


String name;
double salary;

Employee (???) {
System . out . println(???);
}
}

Output:
Lucas --- 100000.0
Olivia --- 120000.0

4) What will be printed after Program.java gets executed?

Employee.java
public class Employee {
String name;
double salary;

Employee () {
System . out . println( "Creating employee..." );
}

Employee ( String name) {


System . out . println( "Creating employee " + name + "..." );
}
}

Program.java
public class Program {
public static void main( String [] args) {
String name = "Luke";
Employee employee = new Employee ();
}
}

5) What happens when you declare something as static ?


Answers
1) The attributes name and salary are private , so they can’t be accessed
directly from outside the class Employee . We need getters/setters to do that.

2)
class Client {
String name;
String lastName;
String address;

public String getName() {


return name;
}

public void setName( String name) {


this . name = name;
}

public String getLastName() {


return lastName;
}

public void setLastName( String lastName) {


this . lastName = lastName;
}

public String getAddress() {


return address;
}
public void setAddress( String address) {
this . address = address;
}
}

3)
public class Program {
public static void main( String [] args) {
Employee e1 = new Employee ( "Lucas" , 100000 );
Employee e2 = new Employee ( "Olivia" , 120000 );
Employee e3 = new Employee ( "Your name" , 0 );
}
}

public class Employee {


String name;
double salary;

Employee ( String name, double salary) {


System . out . println( name + " --- " + salary);
}
}

4) “Creating employee…”. Since no argument is given to the constructor,


the object will be created by using the following:
Employee () {
System . out . println( "Creating employee..." );
}
5) When we declare an attribute as static , it becomes a class attribute ,
which is stored by the class, not by a single object. Something static in Java
is unique , shared by all objects in that class . In this way, when you
change it through an object, another object would see the same value. To
access a static attribute, we don’t use the keyword this , but rather the name
of the class itself.
Chapter 9: Inheritance and
Polymorphism
Inheritance
In Workout Set #6, you created a class called Employee. Now we’re going
to use it, but with less attributes:
public class Employee {
String name;
String id;
double salary;
}
This is what your project structure should look like:

Go ahead and delete classes that we’re no longer using / create new ones
that are missing.
Besides regular employees, a bank has job titles like managers. They have
the same data that other employees have plus extra information like a
password to access the internal banking system and the number of
employees that are managed.
public class Manager {
String name;
String id;
double salary;
int password;
int numberOfEmployeesManaged;

public boolean authenticate( int password) {


if ( this . password == password) {
System . out . println ( "Access granted!" );
return true;
} else {
System . out . println ( "Access denied!" );
return false;
}
}
// ...
}
Do we really need another class?
Well, you could think “Why don’t we put all those attributes inside the
Employee class and some of them woul be just optional?”. That’s a
possibility, but if there are so many optional attributes, the class would start
looking weird and not very readable. Think about the methods:
authenticate() doesn’t even make sense in the Employee class.
So, we need another class, but this way we’re copying and pasting a bunch
of code that is the same in both classes. Imagine if we had to create another
one for a different job title!
There is a way, in Java, of connecting classes in such a way that one of
them inherits everything the other has. In our case, we would like to make
the Manager have everything an Employee has, we would like it to be an
extension of the class Employee . We do this through the keyword extends .
public class Manager extends Employee {
int password;
int numberOfEmployeesManaged;

public boolean authenticate( int password) {


if ( this . password == password) {
System . out . println ( "Access granted!" );
return true;
} else {
System . out . println ( "Access denied!" );
return false;
}
}
// password setter...
}
When we create an object of type Manager , it has all the attributes that
objects of type Employee have. Because, after all, a manager is an employee
in the bank.
The Manager class inherits all the attributes and methods of the parent
class (Employee). It also inherits private attributes and methods, but
can not access them directly . In order to access a private member in the
“child” indirectly, it would be necessary for the “parent” to expose another
visible method that invokes this private attribute or method.

Super and subclass


The most used nomenclature is:
● Employee is the superclass of Manager
● Manager is the subclass of Employee
It’s another way of saying that Employee is the parent and Manager is the
child .

Protected
What do we do if we need to access the attributes we inherited? Leaving
them public is not an option, because everyone would be able to access
them. There’s another access modifier that is between private and public:
protected .
protected attributes are visible to its class and subclasses. There are more
details about protected , but you can see the table and search for more.
public class Employee {
protected String name;
protected String id;
protected double salary;
}
In the same way, you can create a class called Director that extends
Manager , or whatever makes sense in the business logic. A class can have
multiple “children”, but only one “parent”!

Rewriting a method
At the end of the year, our imaginary Employees get a raise of 10% and
Managers get a raise of 15%. Let’s write a public method in Employee that
can be accessed in Manager .
public class Employee {
protected String name;
protected String id;
protected double salary;

public double getRaise() {


return this . salary * 0.10;
}
}
Manager class will inherit that method, but we’re not there yet. Managers
get a bigger raise, so let’s implement that by rewriting the method
getRaise() inside our Manager class.
public class Manager extends Employee {
int password;
int numberOfEmployeesManaged;

public boolean authenticate( int password) {


// ...
}

public double getRaise() {


return this . salary * 0.15;
}
}
Now the method fits our needs.

See how an icon appears next to the method to say that it overrides a
method in Employee. Which leads us to another thing: you can explicit that
fact by using the annotation @Override above our code:

The advantage of using @Override is that we have to rewrite an existing


method, that is, we couldn’t change the name of the method, for example.
And that prevents us from creating a new method and leaving “duplicates”.
See what happens if I change the name to getTheRaise() .
After overriding a method, you can’t access the original method from
the superclass!
Now imagine that Manager s always get a raise of $1000 more than
Employee s. So, if Employees get a raise of $500, Managers get $1500.
Employees $1500, Managers $2500, and so forth. We could do something
like this for Managers:
@Override
public double getRaise() {
return this . salary * 0.10 + 1000;
}
But if Employees start to get a bigger or smaller raise (different than 10%),
we would have to change the method in Manager to keep up with the
Employess’ raise.
Remember: in this case we would like to just complement the original
method, by adding an extra 1000 dollars to the raise that was calculated for
Employees.
To do that, we can access the getRaise() that is in the Employee class by
using the keyword super :
@Override
public double getRaise() {
return super . getRaise() + 1000;
}

Polymorfism
In inheritance, we said that every Manager is an Employee, because the
Manager class extends the Employee class . We can refer to a Manager as
being an Employee. That’s the semantics of inheritance.
Polymorphism is the ability of an object to be referenced in various
ways . Polymorphism does not mean that the object gets transformed.
Remember: objects belong to the same type, from the moment they get
created until they get destroyed – what can change is the way we refer to it.
Manager manager = new Manager ();
Employee employee = manager;
employee. setSalary( 5000.0 );
What do you think will happen if I do the following?
employee. getRaise();
What does that method return? 500? 750?
In Java, method invocation will always be decided at runtime. Java will
look for the object in memory and then decide which method to call,
always relating to its true class, not the one we are using to reference it .
Although we are referring to this Manager as being an Employee , the
method executed is the Manager’s. The return is 750.
It seems weird to create a Manager object and refer to it as an Employee .
Why would we do that? In fact, we could use that to send the Manager as
an argument to a method that requires an Employee :
public class PaymentRecord {
private double totalOfPayments = 0 ;
public void register ( Employee employee) {
this . totalOfPayments += employee. getRaise();
}
public double getTotalOfPayments() {
return this . totalOfPayments;
}
}
And somewhere in our program we could invoke those methods:
PaymentRecord record = new PaymentRecord ();
Manager employee1 = new Manager ();
employee1. setSalary( 6000.0 );
record. register ( employee1); // !!!
Employee employee2 = new Employee ();
employee2. setSalary( 2000.0 );
record. register ( employee2);
System . out . println( record. getTotalOfPayments());
Workout Set #9
1) What is the correct way of representing inheritance between classes Car
and Ferrari?
Option A
public class Ferrari {
// ...
}

public class Car extends Ferrari {


// ...
}

Option B
public class Car {
// ...
}

public class Ferrari extends Car {


// ...
}

2) Create a Dog class and a GoldenRetriever class that extends Dog . Create
the attributes and methods that are necessary to get this result in the
Program class:
Here are some tips for you:
● In Dog , create two constructors: the one where you put all those
arguments and assign them to your new object; and a default one that
has no instructions inside.
● Create a public int canineToHumanAge ( ) method that returns the
human equivalent to the age of the dog. If a dog was born a year ago,
it’s as if he/she had 9 years old (approximately).
● Create a public void bark ( ) method that prints out “Woof woof!!!
I’m “ + the name of the dog.
● The GoldenRetriever ’s constructor doesn’t get color as argument
because it sets it automatically to “Golden” (don’t forget to implement
that).

3) What is wrong with the following code?

Employee.java
public class Employee {
protected double salary;
public double getRaise() {
return this . salary * 0.10;
}
}

Manager.java
public class Manager extends Employee {
@Override
public double getValueOfRaise() {
return this . salary * 0.15;
}
}

4) A programmer was writing attributes for two classes: Person and Dog.
He/She noticed that both classes would have the attributes name, age and
gender. Because of that, the programmer decided to make the Dog class
inherit the attributes from the Person class in order to save a few lines of
code.

public class Person {


String name;
int age;
char gender;
}

public class Dog extends Person {


// ...
}

Considering what you’ve learned about inheritance, does that make


sense? Why?
Answers
1) Option B, of course. Every Ferrari is a car, but not every car is a Ferrari.
And a Ferrari has extra features when compared to a regular car.

2) Dog.java
public class Dog {
String name;
String color;
char gender;
int canineAge;

Dog () {}

Dog ( String name, String color, char gender, int canineAge) {


this . name = name;
this . color = color;
this . gender = gender;
this . canineAge = canineAge;
}

public int canineToHumanAge() {


return this . canineAge * 9;
}

public void bark() {


System . out . println( "Woof woof!!! I'm " + this . name);
}
}
GoldenRetriever.java
public class GoldenRetriever extends Dog {
GoldenRetriever ( String name, char gender, int canineAge) {
this . name = name;
this . color = "Golden";
this . gender = gender;
this . canineAge = canineAge;
}
}

3) In Manager.java, we’re trying to override a getValueOfRaise( ) method


that does not exist in the super class. We are actually creating a new
method, but the @Overrid e annotation doesn’t allow us to do that. The
person probably changed the name of the method and forgot to refactor
every occurrence.

4) That’s not a good practice, because Dogs and People aren’t related in any
way (hierarchically speaking). A dog is not a person and a person is not a
dog. Even though they have some characteristics in common, there are a lot
more differences between them. Read more about some mistakes on
inheritance here .

You might also like