Java For Beginners Get From Zero To Object Oriented Programming
Java For Beginners Get From Zero To Object Oriented Programming
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.
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.
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.
}
}
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).
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.
You can also select a class that was executed recently, like MyFirstClass:
Cannot resolve symbol ‘i’ means the IDE couldn’t find anything about ‘i’.
It’s not declared anywhere before the System.out.println() call.
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”) .
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';
// 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 =.
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:
*=
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;
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) 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
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
Example:
Enter the temperature in Celsius:
30
30.0ºC is equivalent to 86.0ºF
2)
import java. util. Scanner ;
public class Main {
}
3)
import java. util. Scanner ;
public class Main {
}
4)
import java. util. Scanner ;
public class Main {
}
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 );
int predecessor = n - 1 ;
int successor = n + 1 ;
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:
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" );
}
}
}
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.
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" );
}
}
}
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
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 ();
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;
2) What will be the output of the following program when the user enters 1
as input? (same code)
import java. util. Scanner;
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.
}
}
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...
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.
// 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
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;
double calculateAnnualSalary() {
return this . salary * 12;
}
}
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:
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;
2) Create a new class called “Employee” (if don’t have one yet) and paste
the following code:
Also create a new class called “Company” (if don’t have one yet) and paste
the following code:
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:
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
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 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;
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
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.
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:
// 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.
// 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";
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;
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;
}
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";
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;
}
Employee (???) {
System . out . println(???);
}
}
Output:
Lucas --- 100000.0
Olivia --- 120000.0
…
Employee.java
public class Employee {
String name;
double salary;
Employee () {
System . out . println( "Creating employee..." );
}
Program.java
public class Program {
public static void main( String [] args) {
String name = "Luke";
Employee employee = new Employee ();
}
}
2)
class Client {
String name;
String lastName;
String 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 );
}
}
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;
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;
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:
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 {
// ...
}
Option B
public class 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).
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.
2) Dog.java
public class Dog {
String name;
String color;
char gender;
int canineAge;
Dog () {}
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 .