Java For Fucking Idiots Learn The Basics of Java Programming Without1
Java For Fucking Idiots Learn The Basics of Java Programming Without1
All rights reserved. No portion of this book may be reproduced in any form
without permission from the publisher, except as permitted by U.S.
copyright law. For permissions contact:
scbWriterGuy@gmail.com
CONTENTS
Introduction
Chapter 0: Software Cliff Notes
Chapter 1: What the fuck is a Java?
Chapter 2: Hello, World!
Chapter 3: Objects
Chapter 4: Variables
Chapter 5: Operators
Chapter 6: Conditionals
Chapter 7: Arrays
Chapter 8: Loops
Chapter 9: Instantiation
Chapter 10: Methods
Chapter 11: Strings
Chapter 12: The Java Cinematic Universe
Chapter 13: Object-Oriented Concepts
Chapter 14: Bringing it together
Final Thoughts
INTRODUCTION
Hi, I’m Steve.
I’m here to teach you the fundamentals of Java. Or the basics of Java. One
of those. Or both.
I should probably start the book with a little elevator speech on why it
exists.
SICK OF TRYING TO EARN MONEY BOUNCING FROM JOB TO JOB?
CLICK HERE TO LEARN HOW TO EARN $120,000 A MONTH FROM
HOME!!!
Wait, that’s not right.
Let me start over…
In my experience, many books designed for “absolute beginners” spend
maybe a chapter talking to you like a beginner, then start talking to you like
you’re someone with average intelligence all the sudden. They forget their
audience. It becomes a normal textbook.
I think it’s frustrating. I want to be treated like the idiot I am, damn it.
I assure you that in this book, I will not forget that you’re a fucking idiot
like me.
The only real requirement is you can read. And if you’re downloading an
eBook and can’t read then I’m not sure what to tell you, friend.
5. Emotionally stable
This book will be unfair and lash out at you, making personal attacks at
times. I apologize in advance.
Buckle up
Get your towels ready, it’s about to go down. We’re about to start Chapter
One, and once we start, there’s no turning back.
Unless you turn the page back. In which case, there absolutely is turning
back.
CHAPTER 0: SOFTWARE
CLIFF NOTES
Just kidding, we’re starting at Chapter 0… because programming. Here’s a
quick summary of software in general to get you up to speed.
This is an operating system: Windows . It runs on a computer and talks to
its individual parts, so we don’t have to.
This is a programming language: C++ . It is used by humans to write
programs that run on an operating system.
This is a program: Google Chrome . It’s a web browser, written in a
programming language, that runs on your operating system and lets you
view websites on the internet.
This is the programming language we will use in this book: Java .
This is the powerhouse of the cell: the Mitochondria .
These are parentheses: ( )
These are curly braces: { }
These are square braces / brackets: [ ]
These are angle brackets: < >
This is a giraffe:
Wonderful, now that you’re up to speed… to the rest of the book!
CHAPTER 1: WHAT THE
FUCK IS A JAVA?
Java is a programming language (the most popular one in the world, btw).
A programming language is a special kind of language that computers can
understand.
When you write things down in a programming language, what you create
is often referred to as code . Not Morse code, or any sort of secret code you
use to tell someone you’re upset instead of just saying why you’re upset.
None of that; computer code.
A programmer therefore is someone that writes code, in a programming
language, so that computers can do things for us.
However, computers are idiots, even more so than you are. If you show
your Java code to your computer, it doesn’t know how to read it. Hah!
Stupid machine!
We do something called compilation to turn our programming language
code into a format the computer will understand. Com – pill – ayy – shin.
The act of compiling. Like compiling a list of everything you want to order
from the Chinese restaurant.
Now, when I saw “we” I don’t mean that a human actually does this
“compilation” thing. Only that we rely upon the “compilation” process to
create our programs.
Let me give you an example:
1. Steve writes some code for a program that can generate memes,
automagically!
2. A compiler turns his source code (what he wrote) into machine
code .
3. Steve’s computer runs that machine code so he can enjoy his fresh
memes.
So, Steve’s source code (human readable) is compiled by a compiler to
create machine code (machine readable). And the machine code is what
runs on the computer.
It’s like hiring a translator to speak to someone in a different language.
Source Code -> Compiler -> Machine Code
“Computer, add 2 and 2 please” -> Compiler -> “01100110101”
Make sense?
You write source code, a compiler turns it into machine code, and the
computer runs that machine code. Get it into your thicc skull (two c’s).
Compiling interest
Now, there is a part I left out. You see, machine code is created specifically
for the CPU of a computer.
At this point your eyes are probably about to roll into the back of your head.
Either because you know what this is already, or you’re already confused.
Bear with me.
For those of you out of the loop, the CPU (central processing unit) is the
brain of the machine that does all the hard work. Some people call it the
“chip” or the “processor”. Doesn’t matter what you call it, for all I care you
could call it the doorknob.
Anyways, so we create machine code to run on a computer’s
processor/CPU. What would happen if we gave that machine code to a
different computer?
More specifically, what would happen if I write some code, compile it into
a program to run on my computer (with processor A), then give it to my
friend to run (with processor B)?
Hmm. I write code and compile it for processor A….my friend has
processor B…I guess it will work! Yeah, programs are smart and just work,
it’ll be fine!
NO, the answer is that it won’t work !
Imagine writing a novel in English and hiring a professional to translate it
into Spanish. Would you expect someone who only speaks Swedish to
understand the translator’s product?
Unfortunately for us, CPUs read specific kinds of computer instructions
thanks to how they’re architected. Processor A needs different instructions
than Processor B.
How can we solve this? Death? Maybe!
More realistically, I will need to compile my program for processor A, then
compile it for processor B, then make sure the right version of the program
is given to the right computer.
“Well that sucks!” – Randy Marsh
The Big Idea: Most programming languages are compiled from their
human-readable source code to machine code to run on a specific type of
computer.
Serious time
Do you wish you’d never laid eyes upon such a passage? Do you hate my
guts now?
I don’t blame you, but let’s really quickly touch on some terms that come
up when this topic of programming language, uh… “portability,” is
discussed.
After all, you probably don’t want to quote a fake bible tale when trying to
describe something technical. I still don’t trust you to even attempt to
describe anything technical, but if you need to, this part should help more.
Machine Language: The extremely specific instructions to a computer’s
CPU that tells it how to process the 0s and 1s, perform mathematical
operations, and that kind of confusing shit.
Assembly Language: A type of language that’s a little bit more
understandable than machine language. An assembly language creates the
machine language, on our behalf, for a particular CPU architecture. It’s
basically shorthand for the machine language. Stay away.
Programming Language: The languages that humans in the modern-day
use to write software. Like assembly language, it compiles to the right type
of machine code based on the type of Processor you’re targeting.
But rather than being an obtuse, impossible to understand piece of garbage
like Assembly Language (seriously, google it), we get to use relatively easy
to write and comprehend programming language. The programming
language’s compiler takes care of getting us down to machine code!
Yeah Java 8 is old boomer shit by now, but it suits me well enough right
now.
Anyways if you’re on Windows, grab the Windows x64 one. If you’re on
Mac, grab the Mac one. Run the program that is downloaded. Java is now
installed; ba-da-bing, ba-da-boom.
It’s raw !
While I do think it’s worthwhile to know how to compile and run Java code
manually, I don’t think it’s a good fit for this book. But I’ll point you in the
right direction.
From the command prompt…
> javac HelloWorld.java
Would create a bytecode file called HelloWorld.class
> java HelloWorld
Would then run that program using the generated bytecode.
Read more:
Done! Hah, just kidding. That’s Python. We’re in Java land, which means
we need to do 2x the work to get the same fucking result.
Okay, here’s what you do. Create a file called HelloWorld.java
Put this inside of it:
public class HelloWorld {
//Called when the program is run
public static void main (String[] args) {
System. out .println( "Hello, world!" );
}
}
Compile it.
Run it.
The program spits out “Hello, world!”
Wow. Great. That was both uninteresting and didn’t teach you much. I kind
of hate this program but it’s a rite of passage, in a sense.
There are a few things I want to highlight. Not with a highlighter, just with
words.
First, in English, we put periods at the end of our sentences. You’re don’t
want to do that in Java, as a period is very different. Instead, use a
semicolon.
This is a semicolon:
;
Yeah, it’s that thing you never know how to use in English; does it go
between two sentences, before a list, between some sentence fragments?
Wait I just used one; was that correct? Oh God.
It’s easier in Java. Your Java “sentences” that do things are called
statements and they all end with a semicolon. Don’t worry, if you forget
one, Java will vomit everywhere, and you’ll know you fucked up.
Oh, and those double slashes // ?
Anything you put after those is ignored by the Java compiler. You can write
anything you want at all. It’s called a comment . If it you want to type a
novel on multiple lines, you use a single slash followed by an astric, like
this: /* My Comment */ .
/*
Boy this book is going swimmingly and there’s no way I’ll lose interest or the author will run out of
steam at any point in the near future.
*/ .
No comment
Bad programmers write code that’s impossible to understand and explain it
with these “comments.” Even worse programmers write horrible code but
don’t even have the courtesy to leave some fucking comments.
Try to be the kind of programmer that makes your code readable without
comments, but if you need to resort to them, go for it.
Chapter 2, over! Wow, that was easy.
CHAPTER 3: OBJECTS
“Ryan used me as an object.” – Kelly Kapoor
A lot of Java courses and tutorials wait quite a bit to talk about this, but I’m
going to do it immediately.
You see, Java is so, so , so devoted to the idea of “classes” that you literally
cannot have Java code unless it’s inside a class. So waiting any further will
likely just confuse you. Here’s the skinny:
A class is a blueprint for something that can exist in the Java universe.
Número Uno
I write a class called Airplane .
Número dos
I write a class called Monster .
Número Tres
I write a class called Book .
Hello, world?
Now, let’s back up a smidge see how this knowledge applies to the “Hello,
World!” Program.
Here it is for those of you with short-term memory loss (probably most of
you).
public class HelloWorld {
public static void main (String[] args) {
System. out .println( "Hello, world!" );
}
}
Main method
“Who do you think you are? What gives…what gives you the right?” –
Michael Scott
The main method is the entry point to the program; when the program is
run, the main method is run.
The line of code that has the words “Hello, World!” is inside the main
method. Anything you put between those curly braces {} is inside the main
method, actually.
public class HelloWorld {
public static void main (String[] args) {
System. out .println( "Hello, world!" );
}
}
Why is there a “main” method? What makes it so special? The main
method exists because something needs to run when the program starts.
Remember the whole “which came first, the chicken or the egg” dilemma?
Some say the chicken came first, because all eggs come from
chickens.
Some say the egg came first, because all chickens come from eggs.
The answer in Java is that neither of those objects came first. The main
method did.
Nothing can exist without the main method running first, outside of the
realm of objects.
This is what that static bullshit means. Static properties and methods exist
without objects.
“No object, no problem.” – the static keyword
Alternatively…
“Don’t make things static unless you have to because objects are good.” –
me
If you’re not 100% on this yet, don’t worry about it too much. Only a little
bit.
Okay , you might be thinking. But what about that other stuff in front of the
word main ? public ? Or void ? This is just confusing.
I will cover this more thoroughly later in the book. But I’ll briefly answer
this now as well because I hate when you want to know something, and the
author is just like “hold on we’ll get there.” Bitch I’ll tell you now.
Putting public in front of something says that all the other classes,
even in different folders, can see it. You could also describe some of
your code as private if it is going to the bathroom and needs privacy
or something, but not the main method! It’s always out in public!
Putting void in front of some code means that it does some cool shit
but doesn’t report back. No one asks the main method to say if
things went well or not, or for the value of some math calculation.
Main method doesn’t care if anyone knows.
Got it? If not, read those explanations one more time.
…Okay, fine you’re not going to. I’ll summarize even more briefly:
The main method is how Java begins running your program.
The main method is static because something needs to exist outside of the
realm of objects. And the developers of Java said so.
The main method is void because it doesn’t need to provide a value to
whoever is running it. And the developers of Java said so.
The main method is public because it will be called by someone outside of
this folder, namely Java. And the developers of Java said so.
Declaring a class
Let’s leave “Hello, World!” in the dust for now where it belongs, and I’ll
explain in detail how you declare a class:
class Book {
Java doesn’t care about you pressing the enter key (creating a new line) or
pressing the space bar (creating whitespace).
In general, though, you don’t put curly braces on the same line like that,
though. There’s no real estate market in Java land, so you can take up the
space you need to make your code readable.
But congratulations, you have a class. Proud of you!
Oh, one more thing: they are always capitalized like that. If it needs to be
more than one word, you capitalize the first letter of those words and smush
them together. For example:
class FantasyNovel {
Properties
Okay, so we have a basic class declared.
However, classes are pretty useless when they’re empty like that. Let’s add
a property .
class Book {
String title ;
}
What would properties be in the real world? No, not the Monopoly kind of
properties. Let’s ask the dictionary.
Property: “an essential or distinctive attribute or quality of a thing.”
Yep. That’s about right in Java too.
We call title a property because it pertains to a class. It’s the book’s name. It
doesn’t exist without the book. We can add some more properties:
class Book {
String title ;
String content ;
String[] chapterNames ;
int bookmarkedPage ;
double averageRating ;
boolean hasSequel ;
Author author ;
}
The book has a title, its actual content, chapter names… a number
representing the page that the reader bookmarked… a rating to show in a
store…
Anyway, starting to get the big idea? A class can have information
associated with it called properties.
And just to remind you – those properties will be specific to each object
created from this class. I could create 500 books, and they’d each have a
different title property. I’d also probably write a good one, eventually.
Methods
Remember the main method? Well, it’s called the “main” method because
it’s the big important one that runs first. But you can have more than one.
In fact, it’s highly recommended to have more than one method. Splitting
your code up into many smaller methods makes it easier to read and
understand what a program is doing.
We just briefly touched on properties, which are pieces of data that are
related to the object. The difference between properties and methods?
Just like with properties, you can use dot notation to touch its shit.
bestVideo.resume();
bestVideo.pause();
I just resumed and paused the video really quickly. Hopefully that didn’t
break it and cause it to buffer for an eternity…
Anyways, I realize I left those methods empty. Maybe those methods are
modifying properties (which I didn’t type out) of the Video object.
The great thing about objects and methods is that you’re dividing up the
code’s responsibilities into manageable chunks.
The pause() method doesn’t need to know how to resume() .
The fetchRecommendations() method takes care of finding “related” videos
that YouTube wants to shove down your throat; getTitle() don’t care about
that!
Good programmers keep their methods small, well-named, and
straightforward.
But that’s enough on methods for now – there’s a lot of very basic Java
concepts we need to cover before we dig much more into this. Onwards and
upwards!
CHAPTER 4: VARIABLES
"Not enough variables... hmm... not nearly enough variables." -
Heimerdinger
Okay, it’s time to dig into the nitty gritty of learning the language. Get your
big boy (or girl) pants on, cause shit is about to get real.
Let’s talk variables.
Ever take algebra in middle school? Seen something like this?
7=3+x
Solve for x, right?
Variables are kind of like that.
Here’s an example
int myFavoriteNumber = 7 ;
Making variables
You can declare a variable, basically telling the compiler “hey, this is
something I’m going to use later, OK?” like this:
int numberOfStarsToAwardThisBook;
Alternatively, we could have just done it from the start (declaring and
initializing):
int numberOfStarsToAwardThisBook = 5 ;
Naturally, Amazon does not have code that makes every review 5 stars built
into their software. We would likely show the user a screen to make a
selection, then set this variable equal to the # of stars they selected
afterwards.
Data types
What was the “int” part for?
int is short for integer. Integers are whole numbers. This is honestly
elementary math but as I’ve said before… minimal assumptions.
These are whole numbers: 4, 8, 15, 23, 42, -15, -214
These are not whole numbers: ½, ¾, 0.86, -84.97, 0.01
You can put the word int before a variable to specify that it is a whole
number. That’s the type of variable it is.
Java is absolutely paranoid about these “types” and if you don’t specify
one, the compiler is going to be very upset with you. In fact, every variable
in Java must have a declared type.
Here are some the different kinds of variables that you can make.
Note: All data types that have to do with numbers support positive or
negative values.
byte: A tiny number (-128 to 127) typically used for dealing with files.
int: a whole number that can store quite large numbers. Very common.
short: a smaller int tha- who gives a shit, don’t use these.
long: an integer that can be hyuuuuuuuge.
double: a number that can have decimal points, like 4.20, or 6.90.
float: a stupid and useless version of double.
char: a single character inside single quotes, like ‘g’ or ‘f’.
boolean: true, or false. Nothing else. The data type of Siths.
You can Google “Java data types” or click this link to see all of your
options.
A note on Strings
What’s a String , you ask? Literally anything inside of two double quotes.
Feel free to do something that won’t work. Push the limits of the Java
compiler. For example, you could write this line of code:
int wellThisIsJustWrong = false ;
Then compile and run the code. It will throw a conniption, send a report to
NASA, and inform your internet service provider to immediately cancel
your plan.
CHAPTER 5: OPERATORS
“Hello operator? Get me the navy!
[You’ve reached the Navy’s automated phone service.]
Squidward! The robots have taken over the Navy!
Not the Navy!!!” – Spongebob Squarepants
OK, so now you know the basics of variables. Hopefully.
Now let’s look at operators , or ways that we can interact with our
variables.
What’s an operator?
They’re special symbols that do special things. Maybe you want to add two
values. Or see if two values are the same. Or check if a number is greater
than or equal to another.
Or, you want to do all the above. Operators ahoy!
Note that operators are not variables. They’re not methods, they’re not
objects, they’re not data types, and they’re just not that into you.
They’re like the buttons on your calculator that aren’t the numbers.
Order of operations
An operation is one little chunk of math shit. Your waiter probably waits on
tables (each one an operation) in a certain order, by the time in you arrived,
how much they like you, how much they expect you to tip, where you’re
located in the restaurant, etc.
Math has its own order of operations: PEMDAS.
P arentheses () -> E xponents3 -> M ultiplication & D ivision */ -> A
ddition & S ubtraction +-
There is good news! You’re beautiful.
No, but there are no exponents in Java. You literally just need to remember
that stuff in parentheses happens first, followed by multiplying/dividing
things, followed by adding/subtracting.
And if there’s no combination between those categories you just go left to
right.
Trust me, it’s super easy.
Into the examples, here we go!
Example one!
int x = 5 + 3 - 7 ;
x is 1.
Why? No need to worry about the PEMDAS rules, it’s just
addition/subtraction.
5 + 3 is 8 . And if we subtract 7 from that, we get 1 .
Example two!
int y = 5 - 7 * 6 ;
x is -37.
Why? The multiplication must happen first, because PEMDAS says so.
7 * 6 is 42 . And if we subtract from 42 from 5, we get -37.
Example three!
int z = 28 / ( 3 + 4 );
x is 4.
Why? Even though it’s addition, 3 and 4 must be tackled first because
they’re inside parentheses.
3 + 4 is 7 . Then we can divide 28 by 7 and get 4 .
Modulo
Also… I debated not mentioning it, but fine, there’s another one. It’s called
the modulo operator and it’s stupid. It uses a percentage sign (because fuck
you that’s why).
int remainder = 5 % 2 ;
Because they’re directly written into our source code, those numbers are
hard-coded .
I mentioned this earlier, but no one would ever write Java code like this. If
they want x to be 1, they’ll set it equal to 1 to begin with.
We use these math operators (+ - / *) to calculate things we don’t know the
value of right now, but we will when our program is running!
Maybe you’re making a shopping cart website. Your program might
multiply (*) the current price of a product by the quantity the user selects to
get the total price. Or, your program might decrease (-) the total by one if
the user removes it from their cart.
Or
Let’s create some booleans ! Remember that data type? A boolean value is
either true or false. This data type goes hand-in-hand with these “logical”
operators.
boolean imBored = true ;
boolean imHungry = false ;
//True
boolean imGoingToEatFood = imBored || imHungry;
See how the or operator || works? “I am going to eat food if I’m bored or if
I’m hungry.”
If either one of those conditions are true, then imGoingToEatFood is set to
true.
More examples…
And
That’s not true when it comes to the and (&&) operator. Both need to be
true for the expression to evaluate to true.
boolean wellRested = true ;
boolean motivated = false ;
//False
boolean goingToWorkOut = wellRested && motivated;
Even if I’m well rested, if I have no motivation at all, I won’t work out.
And even if I were motivated to work out, if I have no energy due to lack of
sleep, I’ll probably pass as well.
More examples…
I’m writing an app where the user must log in using their account
information. I only try to sign them in if they’re entered a
username and they’re entered a password.
I’m creating a lighting system that automatically turns off the
lights if the lights are currently on and there has been no one in
the room for 5 minutes.
Seem too easy? It’s “logical”, right? Get it? Logical? Because they’re called
the logica-
Oh, and just like with the math operators; no, you shouldn’t create variables
that are always true, or always false. They’re variables. But I’m trying to
get the concept across right now, kay? More on this when we get into
conditionals and if statements.
How would you say that out loud? Probably something like this:
“x is equal to 7”.
You can do something very similar in Java. Check out this line of code:
int x = 7 ;
Okay, x is 1…
x=x+ 1
Hmm…
Okay, now x is equal to…. x + 1?? Wait… if x is 1, then that means 1 = 1 +
1??
Does that mean that 1 = 2???
Hopefully your mind has awoken from its slumber and is screaming at the
page: “THAT’S NOT POSSIBLE! THAT MAKES NO SENSE! WHY
WOULD THEY MAKE BRAN KING?”
2 is less than 3.
5>4
5 is greater than 4.
Cool. Now, this is wrong.
5>5
5 is greater than 5.
They’re the same value; 5 is not bigger than 5. FALSE, you must be
screaming right now!
Now, what if we wrote this down?
5≥5
Relations!
//True
boolean itsSmaller = 2 < 3 ;
//False
boolean itsBigger = 3 > 4 ;
I know what you’re thinking. I’ve got this in the bag. Those operators are
simple! Comparing values to see if one is bigger or smaller than another?
Hah! What a joke. This guy must think I’m a complete fucking idiot.
Well, yes, that’s the point.
But there’s some more curveballs coming your way.
Remember the “or equal to” bit I mentioned up above? In regular old math,
that’s when you underline the carrot thing, like this: ≥
You can combine an equals sign with one of the comparison operators to
form the same thing; a more craaaazy kind of relational check:
//True
boolean itsBiggerOrTheSame = 5 >= 5 ;
//False
boolean itsSmallerOrTheSame = 3 <= 2 ;
Sure, putting the equals sign after the carrot isn’t as sexy as underlining it
like you do in algebra. But that’s how you do it in Java.
You can keep experimenting with these but you’re probably already getting
the hang of it.
Yeah, I guess you could say that’s a compliment. Keep up the good work
buddy. Isn’t it amazing how easy programming is?!?! You’re so smart! And
a wonderful reader! Also, did you award this book 5 stars yet?
//False
boolean isSameNumber = 5 == 4 ;
The first one (=) is the assignment operator. The next two (==) form one
comparison operator.
Changing requirements
I changed my mind. I want to check if a variable is not equal to something.
Here, we split our comparison operator == in half, and we’re so shocked by
the gruesome fatality that has befallen our beloved operator, that we put an
exclamation point.
!=
Basically, “not equal to.”
boolean isGoodCharacter = character. name != "Brandon Stark" ;
So there you have it. The “not equal to” comparison operator. Want to do
something when something else is false ? Welp, there ya go.
Fancy talk
“Do you mean she puts on airs?
I guess so.
That’s just fancy talk. If you wanna be fancy, hold your pinky up like this.
The higher you hold it, the fancier you are!” – Spongebob Squarepants
Sometimes we are so lazy that we can’t be bothered to type things out in
Java. That’s not surprising; programmers are inherently very lazy.
Let’s say you run a zoo containing only giraffes (that’s fine in my book, by
the way. Haha, my book. That’s funny cause we’re in my book right now.
Get it? Isn’t that hilarious? Anyway, I hate when books have entire
paragraphs inside parentheses. You forget what the original sentence was
even saying); that could be represented with this line of code:
int numGiraffes = 23 ;
Now, let’s say you just received a new giraffe at your zoo. Hooray!!! Maybe
this line of code is executed:
numGiraffes = numGiraffes + 1 ;
Wonderful! But wait, papa Java is knocking at the door. There’s a shorter
way to write this for essentially no reason! How? Like this!!
numGiraffes++;
Wow! That’s shorthand for the same line of code, saying “Take the current
value of numGiraffes , increase it by 1, and set numGiraffes equal to that
value.”
How insanely useful is that?!?! Knocks your socks right off!
King boolean
Remember when I went over the exclamation point (!) and how it basically
is saying “not”?
So “!=” is checking if a value is “not equal to” another value?
There’s an easier way to write this in Java if you’re simply trying to flip
something from true to false (boolean values), or vice versa.
For example, instead of something like this:
boolean isBad = isGood != true ;
You could simply say
boolean isBad = !isGood ;
The exclamation point goes directly in front of the boolean. Wow again!!
That line of code that prints to the system only happens if we have more
than 500 giraffes.
Another example:
Scanner userInputReader = new Scanner(System. in );
int userInputNumGiraffes = userInputReader.nextInt();
if (userInputNumGiraffes <= 0 ) {
System. out .println( "Where they at?" );
}
That line of code prints to the system only if the user typed in a 0. Or a
negative number. I’m going to skip explaining how to get input via a
Scanner , OK? Really, really dull stuff.
Anyway, does the if part make sense? It’s pretty similar to English, really. If
this, do that.
Now, what if we also want to do something when the user types in an actual
value? If you remember the comparison operators, you could add something
like this below that conditional:
if (userInputNumGiraffes <= 0 ) {
System. out .println( "Where they at?" );
}
if (userInputNumGiraffes > 0 ) {
System. out .println( "I shall add them at once." );
}
Two if statements, back-to-back. Could work, right? But that’s stupid. Why
check the value of userInputNumGiraffes in two places? Don’t do that.
Instead, add an else block to the original if statement, as follows:
if (userInputNumGiraffes <= 0 ) {
System. out .println( "Where they at?" );
} else {
System. out .println( "I shall add them at once." );
}
If the first check (the user inputs a value less than or equal to 0) is true , we
go inside the if block. Otherwise (else!) we go to the else block.
Programming is EASY dude.
Oh, and you don’t need to put the word else on the same line as that curly
brace {.
You could press enter and push the else { to the next line, like this:
if (userInputNumGiraffes == 0 ) {
System. out .println( "Where they at?" );
}
else {
System. out .println( "I shall add them at once." );
}
You could also put each curly brace on its own line. You’d be committing a
Java code style atrocity, but you can do it if you really want to piss me off.
OK, I hope you’re with me so far; you can check if something is true or
false, then act appropriately using if/else (conditional) logic. This is called
control flow . You’re controlling the flow of the program.
However, there are situations where it’s not simply “do this if X, else do
something different”. You might want to do different things based on how
many giraffes there are, for instance.
How do we do that? Well, there’s a few ways to skin this cat….
And behold the new and totally correct way to do it, with no mistakes
whatsoever:
switch (keyPressed) {
case 'W' :
player.moveForward();
case 'A' :
player.moveLeft();
case 'S' :
player.moveBackward();
case 'D' :
player.moveRight();
default :
player.stopMoving();
}
Whoa, crazy! We create a “switch ” with the value of the user input, then do
something different for each “case ”. And no, “case” has nothing do with
uppercase or lowercase letters; it’s when the switch equals a particular
value.
If they pressed in ‘W’, then the code under the ‘W’ case is run.
If they pressed ‘D’, then the code under the ‘D’ case is run.
The “default ” is what happens if the user input isn’t any of our cases.
Maybe they pressed space bar. Or some letter we haven’t accounted for.
Make sense? Compare it with the if/else examples further back.
However, there’s one fatal flaw in the switch example code (IT’S
ACTUALLY NOT WITHOUT MISTAKES, CURVEBALL!!!). What
happens if the user presses ‘A’? What direction does the player move?
Think about it. Scroll up/flip back/take a taxi back and look; what could be
wrong with a user pressing ‘A’? Or don’t. I’ll tell you anyway.
The player starts to moveLeft() but is then immediately told to stopMoving()
.
“That’s what’s happened?! But why?? The user pressed ‘A’, so it matched
the ‘A’ case, right? Move left?” – you, maybe.
Well, the “default ” line of code will actually happen every single time, in
addition to the “case”…
Because unless you specify otherwise, a switch will look at every single
‘case’, then hit the ‘default’ block of code. That switch won’t stop!
You need to give a very special word to Java here for each ‘case’. It’s called
a break .
switch (keyPressed) {
case 'W' :
player.moveForward();
break ;
case 'A' :
player.moveLeft();
break ;
case 'S' :
player.moveBackward();
break ;
case 'D' :
player.moveRight();
break ;
default :
player.stopMoving();
break ;
}
Now when one of the cases is matched, Java will hit the kill switch (hehe)
when it sees break and prevent anything else in the switch statement from
running. Java jumps down to any code below the entire switch statement
(outside the curly braces {} )
Why do we need to do this?
“Because fuck you, that’s why.” - Java
Now tell me, which is easier to understand, some if/else ’s, or a
switch/case/break/default cluster? It’s totally your choice. Want to do
something different based upon a certain variable’s value? Pick the one you
like better.
But if you choose a switch you’d better hope you don’t forget your break
statements (and it does happen).
CHAPTER 7: ARRAYS
“Isn’t there anything on TV that isn’t about BOXES?!?!
We now return to Championship boxing.” – Spongebob Squarepants
Pop quiz: What’s the first letter of the alphabet?
Answer: (doo doo, doo doo, doo doo) The Daily Double
Okay, no. It’s actually A .
How would we represent that letter in Java? Which data type?
Tick.
Tock.
Tick.
Tock.
Did you guess a char ? If so you’re right! If not… shucks! I was really
rooting for you, dumbo. Here it is!
char firstLetter = 'A' ;
Congratulations again.
Look at that! Those square brackets [] are saying that the variable alphabet
is an array (or box) of characters. Meaning it can be more than one letter.
Absolutely mesmerizing. Thanks Java!
I should mention that you could also put the square brackets to the right of
the variable name…
char alphabet[];
But no one does that anymore and neither should you if you wanna be cool.
Yes, I got tired of typing. Those three dots (…) don’t mean anything. But do
you see what I did there?
Inside curly brackets {} (or braces, whatever you call them) I put all the
chars, separated by commas. This is how arrays work, basically.
First, you put your variable type (int, char, double , etc.), followed by some
square brackets [].
Then, if you know the values that go in your array when it’s created, then
you can put them in the curly brackets {} .
More examples:
int [] favoriteNumbers = { 6 , 9 , 420 };
double [] doubleDoubles = { 1.7 , 340.4 };
float [] whyUseFloats = { 50.8f , 129.3f , 603.432f };
Cool? Cool.
It prints out 10. Very useful for later when we do loops, keep this in mind!
papa Java coming up with some weird “start at 0” rule, nearly every
Lists
Java has some extremely helpful classes that we can use in place of arrays.
While I won’t be covering them in this book, feel free to take a gander .
CHAPTER 8: LOOPS
“You make a loop de loop and pull
And your shoes are looking cool
You go over and back, left to right
Loop de loop and you pull them tight”
– Spongebob Squarepants
Welcome to the section on loops.
Java has 3 kinds of loops. One of them is used all the time. Another is used
every once in a while. The other is almost never used. I’ll let you guess
them as we go.
You: Hold, on the hell is a loop?
Life. Life is a loop.
You wake up. You get ready for the day. You go to school or work. You
come home exhausted. You try to relax if you have time. You sleep. Repeat.
We can do the same thing, slightly less depressingly, in Java code!
Let’s back up to when I introduced arrays with the alphabet.
char alphabet = { 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , … };
while ( true ) {
System. out .println( "This line of code runs forever." );
}
Continuing on
We’ve seen a while loop that goes forever. Then one that goes through
every letter of the alphabet. Then one that stops when it wants to watch
“The Office” (unsurprisingly).
There’s another Java keyword I feel I must mention. It’s called continue .
You know how break basically kills the loop? Dead, over?
continue says “don’t kill the loop, but skip this iteration.”
Move on to the next iteration. Nothing to see here.
Let’s say you want to print every letter of the alphabet, but not ‘F’. You just
hate that letter.
while (index < alphabet. length ) {
char letter = alphabet[index];
if (letter == 'F' ) {
continue ;
}
System. out .println(letter);
index = index + 1 ;
}
We print out everything except ‘F’. The code after a continue statement is
never reached, instead we return to the top of the loop.
It’s like a break statement’s little brother. It “breaks” this iteration and goes
to the next, but it doesn’t kill the entire loop. Lil boi.
If you hated ‘F’ so much that you wanted to immediately stop printing out
letters, you’d go back to using continue .
A BUG? IN MY CODE?
There’s a problem with my last example. A “bug” as a programmer might
say, where something happens that you didn’t expect.
Did you notice it? Probably not. But can you see it now? Why might this
beautifully written code not do exactly what I described?
Hint: look at where the continue; statement is. What doesn’t happen when
the letter is F?
Did you get it? Take a second.
Answer: the loop runs forever! Look what happens when the letter is an F;
we immediately skip the iteration using a continue; and go to the next
iteration of the loop.
But what letter are we gonna look at next iteration? F. And the next one? F.
We never increased the value of the index!!! We’ll keep pulling F out of the
array since the index doesn’t change. Don’t make this mistake.
Here’s the fixed example. We increase the index immediately after pulling
the letter from the array:
while (index < alphabet. length ) {
char letter = alphabet[index];
index = index + 1 ;
if (letter == 'F' ) {
continue ;
}
System. out .println(letter);
}
Well that’s simply too high! The while loop sees the index isn’t less than
26, so it doesn’t run even once! Not a single letter is printed out.
That’s good though, right? No problem with that. The while statement is
simple and does what it’s supposed to: runs code over and over again while
a certain condition is true.
Here’s comes the fun, doo doo doo doo
However, at some point the Java developers thought: why don’t we fix this?
Oh, it makes sense as-is, but why don’t we add another kind of loop for no
reason?
(Note: this actual conversation didn’t happen)
That’s when we get the “do-while” loop, or “doo doo” while loop, as I call
it. Because it’s stupid and no one uses it, except the one guy reading this
that is infuriated that I’m insulting his favorite language construct.
Here’s how it works:
I write some code. It’s run once. Then, we start a while loop. It might be run
again.
do {
System. out .println( "I hate that I exist." );
} while ( false );
What do you think would happen if we run this code? Take a guess inside
your little noggin.
“I hate that I exist” is print out to the screen once. Then, the condition is
evaluated at the end .
Since I literally wrote false (the opposite of true ), the loop doesn’t keep
going. One could argue the loop never started. This is the opposite of the
while loop, which looks at the condition at the beginning .
I’ll give you some more:
boolean havingFun = false ;
do {
//A game of League of Legends sets havingFun to true or false.
} while (havingFun);
In place of actual code, I left a comment there that describes how such code
would work.
In this code, we always play one game of League of Legends, even if we
aren’t yet having fun today. Then, if we are having fun, we keep playing
until it’s no longer fun.
But really. I have never once encountered a scenario where I found I wanted
to use a do while loop. Maybe I’m just an idiot.
Like with anything there will be someone who argues otherwise; maybe
using a do-while loop 0.00001% of the time it makes the code easier to
read. But I can’t be bothered to care.
You can always write it to fit into the other 2 primary kinds of loops, while
loops and for loops.
//For loop
char [] myArray = { 'A' , 'B' , 'C' , 'D' };
for ( int i = 0 ; i < myArray. length ; i++) {
System. out .println(myArray[i]);
}
Reverse, reverse!
It’s also easy to do different kinds of loops by adjusting the three sections of
the for loop. If you notice, those sections are indeed separated by
semicolons.
For example, maybe you want to go through the array in reverse . Here’s
what those 3 sections would specify:
Try to read through that yourself a few times to understand what each part
is doing. Then I’ll spill the beans. I hate beans.
Here’s how what we’re asking Java to do in English…
Creating an object
Book myBook = new Book();
“I DID IT! I DID IT, DAD! I MADE AN OBJECT!” - you
Alright, you made an object. Yes, you did. But slow down my child. There’s
a ton of complexity in that simple line of code. Let’s do it bit by it.
I’ll label each part of that line.
1. Book 1
This first part says our variable is going to be a Book. Just like we’d make
an int, or a double, or a char, we’re saying that we’re making a variable of a
specific type. In this case, it’s a Book.
2. myBook
This bit is saying the name of our variable is myBook. We can name it
whatever we want. We could have called it “foo,” or “bar,” but I absolutely
loathe variables with those stupid fucking names.
“So the name of the object we just made is myBook?”
Ehhhhhhhhh…. for now, yes, you can say this is the name of our object.
Some sticklers would say “ackshually that’s an object reference variable,
not the object itself, let me explain why you’re wrong-”
But for now, you’re fine to say the object is called myBook .
3. new
This is the absolute magical keyword in that line of code. You are saying I
am making a new object out of this class. Bitch.
You didn’t need to say new when you were using the primitive variable
types like int and double . This is for the object-oriented shit, baby! Wooh!
New Book!
4. Book() 4
Huh? Didn’t we already cover Book? It’s the type of variable we’re making
right?
Why is it at the beginning and then here, at the end? What’s the point?
Because you can do fancy shit with those parentheses right there.
When you make a new Book you could say “hey Java, when you make the
new Book object, make its title this, its author this, etc.
Constructors
“Bob, the Builder!
Can we build it?
Bob, the builder!
Yes we can!”
You know, when I went to write down this quote I had to look it up. It turns
out they changed “Can we fix it?” to “Can we build it?” And you just know
I’ve gotta be accurate with my quotations, so that’s what I used.
Anyways, what’s a constructor?
Bob
A constructor is like Bob, the Builder. You know, the carpenter with a
yellow hardhat. Cool guy.
Bob has a hammer, saw, screwdriver, and all kind of tools to build houses.
In Java, Bob builds the object (the actual house) from your blueprint (the
class). Here’s a sample class:
class House {
String color = "Gray" ;
}
The right side is the important bit; it says make a new House!...and assign it
to the variable on the left.
See those two parentheses ()? With nothing inside of ‘em? That’s us telling
Bob to build a default, normal, vanilla, bland, unimportant house. The
house will be Gray.
System. out .println(stevesHouse. color );
Yep, that will say “Gray”! Also, don’t get me wrong; gray houses are totally
fine. Very adequate.
Default Constructors
Every class has a hidden Bob the Builder by default that looks like this:
class House {
String color = "Gray" ;
House() {}
}
Switch between this example and the previous one. Note the difference.
Well, there’s effectively no difference, but you can choose which way you
prefer. I like setting the property values inside the constructor (this one).
> Gray
> Blue
That’s fine…
Or, you could get it the color you want right from the start.
Check it out!
class House {
String color ;
House(String customColor) {
color = customColor;
}
}
The parentheses are no longer empty! Can you guess what’s happening
here?
Even if you figured it out, the vocabulary is always just memorization. My
least favorite part of any test. Or life.
customColor is called a parameter .
By putting this parameter in our constructor, if someone wants to build a
house, they must now provide a color!
House stevesHouse = new House();
That doesn’t work anymore, dumbass!!! Sorry that was a bit harsh.
Especially since you didn’t write it, I did.
But since you made a constructor that requires the customColor parameter,
Java will murder your firstborn child if you try to build a House without
specifying a color.
How ‘bout this?
House stevesHouse = new House( "Blue" );
System. out .println(stevesHouse. color );
Yep, that works! We build the house, and it’s blue. “Blue” is printed to the
console.
Brain teaser!
What do you think happens here?
class House {
String color = "Gray" ;
House() {
color = "White" ;
}
}
The result?
> Gray
> White
Bob had Gray on his blueprint, but when he went to start building, he
decided on White instead.
Brain teaser over. Your brain is no longer being teased.
House(String color) {
color = color;
}
}
What the hell even happens on a line of code where we say that “color”
should be assigned the value of “color”??? color = color???
The answer is nothing happens. The house’s color property is left alone.
The custom color value that we’re providing Bob is re-assigned the same
value. That’s fucking stupid.
We can fix this by specifying that we want to assign the custom color to our
property color .
class House {
String color ;
House(String color) {
this . color = color;
}
}
Just like you can access an object’s properties and methods with “dot
notation”, a.k.a. a period, an object can refer to its own properties and
methods using this followed by the dot.
Which is great in this case where we need to differentiate between our
property and the parameter, both with the same name.
null
Ever heard of a NullPointerException? No? Well if you take up Java, you’re
going to be seeing them for the rest of your life.
But before we get there, let’s talk about null . You can nullify an object like
you’d nullify your third marriage.
Marriage marriage = null ;
if (stevesHouse != null ) {
stevesHouse. color = "Blue" ;
}
You’d better pray to god that the faucet you want to replace is on the sink,
in the bathroom upstairs, in Steve’s house, and that everything is perfectly
in place, and no one has fucked with the House while you weren’t looking.
Since even one NullPointerException can kill your program, it’s a good
idea to practice defensive coding. That means ensuring your variables have
reasonable values before trying to use them.
CHAPTER 10: METHODS
“Do it.” – Senator Palpatine
Methods do things.
Airplanes fly(). CoffeeMakers brew(). People fly like paper, get high like
planes. Cats meow() for no fucking reason when I’m trying to work god
DAMMIT JASPER I JUST FED YOU SHU-.
class Cat {
String name ;
Cat(String name) {
this . name = name;
}
void meow() {
System. out .println( "Meow!" );
}
}
name is a property.
meow() is a method.
Why do Cats meow? In real life, who fucking knows. In Java, it’s when we
call the appropriate method on the Cat object.
Cat jasper = new Cat( "Jasper" );
jasper.meow();
What did we just do? Well first we instantiated a new Cat, which I covered
in the last chapter, you plumbus.
But after that we used a method called meow . It printed out “Meow!” to the
screen.
We could call what we just did a a whole variety of things. Invoking the
method. Calling the method. Running the method. Executing the method.
“Doing the needful.”
By and large, I see and use the word calling . We called the meow()
method. When the meow() method was called, the cat meowed.
Lost in Translation
class Translator {
String languageFrom ;
String languageTo ;
Wew lad, a new class! This one is responsible for translating text between
two different languages. I’ll hide the code that would actually do the
translating. But it’s great, I assure you.
Let’s create a new translator. I’ll call him Eugene.
Translator eugene = new Translator( "English" , "Spanish" );
We did it. Right? I think we did. But where’s the Spanish translation? Did
Eugene translate it in his head but not even tell us the translation?
EUGENE? WHAT’S THE TRANSLATION? HELLO? USE YOUR
WORDS.
The problem is our translate method is void .
void methods do not give us any data when they’re done executing. They do
something, and that’s it. It’s like sending a text message and hearing
nothing back, no matter how hard you wish they’d just fucking reply.
Eugene translated it in his head but didn’t share with us. We can fix this by
making his method return a String.
String translate(String textToTranslate) {
textToTranslate = textToTranslate.trim();
String translation = //write this code later
return translation;
}
This special keyword return ends the method right there; no code can exist
after a return; statement. Method’s over, result is returned.
Methods can return any of the data types we’ve seen, whether primitive
variables like int, char, boolean, or objects like String, Cat, or Meme.
In this case, we replaced void with String . Now we can learn the translation
from Eugene without having to fire him.
Translator eugene = new Translator( "English" , "Spanish" );
String translatedString = eugene.translate( "Where is the bathroom?" );
System. out .println(translatedString);
Conditional returns!
“What is this, a crossover episode?” – Mr. Peanutbutter
In this little section, conditionals return. Hah. They return. Literally. Cause
they’re back and….alright.
Anywho, you can actually have multiple return statements in your methods.
The rule is that nothing can exist in a method after a return statement; but
what if your return statement is inside a conditional? You’ll need multiple
return statements then!
For non-void methods, Java needs an absolute 100% guarantee that the
method will return a value. This would be unacceptable:
boolean isPositive( int number) {
if (number > 0 ) {
return true ;
}
}
What if the number is less than or equal to 0? You need to explicitly give
your method something to return in all scenarios! Java isn’t smart enough to
infer that anything else would be false , for example.
You’d have to do something like this:
boolean isPositive( int number) {
if (number > 0 ) {
return true ;
} else {
return false ;
}
}
Or, you could provide a “catch-all” return value at the bottom of your
method, which in this example acts the same way:
boolean isPositive( int number) {
if (number > 0 ) {
return true ;
}
return false ;
}
Static methods
Typically, you call methods on objects . The idea is that the methods will
interact with the properties on that object; change the value, retrieve the
value, initialize a value, all that shit.
But you can create methods that don’t need to be called on an object. Just
the class. Those methods are static .
Here’s a few examples
class StringHelpers {
public static boolean startsWithA(String str) {
return str.charAt( 0 ) == 'A' ;
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
}
We don’t need to create a new StringHelpers() object, then use a dot “.” to
call the method on that object. We can straight up just use the StringHelpers
class itself.
String myString = "Alpha" ;
if (StringHelpers. startsWithA (myString)) {
System. out .println( "It starts with A." );
}
In general, you don’t want to make a method static unless it’s some simple
helper methods like these. You’re in an object-oriented language, it’s a good
idea to use objects and their methods, not static methods on classes.
Note: some people would call these static methods “functions .” The
difference between methods and functions is mostly a pissing match
between programmers. Typically, I’m pretty sure methods are just functions
that are attached to objects. And since Java is highly object-oriented, we
typically call them methods.
}
}
That method fly has 0 parameters . There’s nothing inside the parentheses ()
of this method definition. You could simply call it like this:
Airplane airplane = new Airplane();
airplane.fly();
Now the method has 1 parameter: altitude . When you call this method, you
can “pass” the altitude to the method, and the method can use it to fly to the
desired altitude.
airplane.fly( 15000 );
Yup that’s fine. when you call the method, pass the two arguments like so:
Overloading
Remember constructor overloading? No? Well we can do something similar
with methods that makes our objects easier to interact with! It’s called
method overloading and lets us declare multiple versions of that method,
just like an object can have different constructors.
With this technique (TECHNIQUE, TECHNIQUE!), whoever is interacting
with your object can choose the version they like best.
class Airplane {
void fly() {
}
void fly( int altitude) {
}
void fly( int altitude, double speed) {
}
}
Now anyone using an Airplane object can change the altitude without
specifying the speed, or begin flying without specifying anything .
airplane.fly();
airplane.fly( 15000 );
airplane.fly( 0 , 12552.854 );
Yes, that last line will crash the airplane at an astonishing rate. Don’t worry,
the fly method should make sure the argument passed is reasonable.
It’s typically a good idea to overload your methods if you want to allow
more customized behavior when the method is called, but also want to
provide an easy way to call the method without passing so many arguments.
Under the hood, you might even do something like this to make your code
very reusable:
class Airplane {
void fly() {
fly(currentAltitude);
}
void fly( int altitude) {
fly(altitude, currentSpeed);
}
void fly( int altitude, double speed) {
//The actual code to fly
}
}
See how they’re calling each other? This is an example of how you can
reuse your code without copy pasting!!!! It’s like a chain or something.
Just want to start flying? Call fly and it will use the current altitude. Want to
change the altitude? It will fly to that altitude with the current speed. Want
to change both? Call the full fly method.
What’s a string?
You’ve seen ‘em. I’ve talked about ‘em. You probably have a general idea
of what they are by now.
It’s just some text, right? “abc” or “23890chusoao”? Aren’t those Strings?
Yep. The double quotes “ “ are what identify Strings. That or, you know…
the word String. Duh.
But Strings are super special in Java; not only are they extremely common,
they have a ton of built-in methods that make them super powerful. And
you oughtta know why Strings are the best. The kind of “oughta know” that
Alanis Morisette would advocate.
Anything that does not require math (addition, multiplication, that stuff) and
is not a boolean (true or false) value should be a string 99.9% of the time,
ISO (In Steve’s opinion)
Text
Want to represent a single character? You could use a char , right?
char firstLetter = 'A' ;
Just use a String.
String firstLetter = "A" ;
Why bother using a primitive when you can get the real deal? Needless to
say, if you need a string of characters, you’d use a String, too.
String myName = "Steve" ;
Picture a bunch of characters lined up, with a piece of string tying them
together. Not all that firmly; you could snip the string if you wanted to. But
they’re a unit!
Yay, Strings!
Numbers
And numbers? Just because a value looks numerical doesn’t mean it should
be an integer. Don’t get me wrong, lots of times you do need numbers to be
ints or doubles (fuck floats). But not always!
For example, phone numbers…
long jennysNumber = 5558675309L ;
You can use the static String.valueOf method to convert the int to a String.
Same goes for pretty much any other type of variable. Neato!!
String Comparisons
Remember the comparison operator? It’s two equals signs. Here, I’ll remind
you.
boolean isSeven( int number) {
return number == 7 ;
}
System. out .println(isSeven( 5 ));
A. true
B. false
C. null
D. The program crashes
First of all, a primitive cannot be null , so jot that down.
But the answer is B: false ! Yep, those strings are not the same according to
the comparison operator (double equals sign).
We know they’re the same, however. So what’s the deal, why is it saying
they’re not the same?
When it comes to objects, the comparison operator == is literally checking
“are these the same object?”
Well, these aren’t. You created two different objects, right? strOne and
strTwo . You failed.
The lesson? Don’t use the comparison operator for Strings, or any object for
that matter, if you’re trying to see if they’re the same value.
How do we do it, then? Like this!
boolean sameString = strOne .equals (strTwo);
Superpowers
Alright, maybe not superpowers, per se. But Strings are objects, as I said.
You just saw the equals method that checks if two Strings have the same
value.
Unlike the trite and overly simplified examples we’ve used so far, the
String’s superpowers are actually useful methods that accomplish actual
things! Let’s check out some of them!!
equals
We just covered it, but just to reiterate: when you want to compare two
strings, never use ==. Always use the equals method that all Strings have.
boolean sameString = strOne.equals(strTwo);
This is something you actually do a lot in Java. Did the user type in a
certain word or sentence? Does it match a value we expected? Now we can
do that with Strings!
Thanks Java!@! Programming is fun.
equalsignorecase
For when you want to use equals but don’t care if the characters in the
string are uppercase (A) or lowercase (a).
//true
"MEMES" .equalsIgnoreCase( "memes" );
contains
For when you want to see if there’s a particular String inside your String.
Maybe you’re Mark Zuckerberg and want to see if a user’s Facebook post
contains “vaccines”.
//true
"Boy am I glad that vaccines were invented" .contains( "vaccines" );
Note that contains is case sensitive. That means it cares about if the
characters are uppercase or lowercase. i.e.
//false
"BOy I HatE HoW VACccINeS CauSe AUTisM!" .contains( "vaccines" );
Hmm. How can we see if “vaccines” is inside there, no matter what case the
letters are in? I know! We’ll use containsIgnoreCase !
Just kidding – doesn’t exist! Dammit Java.
There’s one easy way to do to this for 99.9% of scenarios. It involves our
next superpower, so we’ll go over it first.
//true
testString.contains( "vaccines" );
If you really wanted to, you could instead change it toUpperCase and look
for “VACCINES”.
charAt
Remember “indexes” from arrays? You know, [0] gets the first element, [1]
gets the second element, and so on? Well that knowledge, unfortunately for
you, is coming back from the dead for this exercise.
"we live in a society" .charAt( 1 );
This returns the ‘e’ character.
"I hate sand" .charAt( 7 );
This returns the ‘s’ character.
Yes, spaces from your spacebar “ “ are characters, so you need to include
them when you’re dealing with the indexes of characters in a String.
Not too bad. Now for the next method. :)
substring
Let’s say we want to get the first 5 letters of a String.
String helloWorld = "Hello, world!" ;
This is saying “get me the 0th character up to the 5th character”. The result of
which is “Hello”.
Wait, 0 to 5? Isn’t that 6 characters? 0, 1, 2, 3, 4, 5….that is 6! What the hell
is happening here?! Why did we only get “Hello” and not the comma too?
Here’s the tricky bit (you knew it was coming): Java don’t work like that.
You are asking to get the 0th character UP TO, NOT INCLUDING the 5th
character. This is known as “inclusive” and “exclusive”.
String firstFive = helloWorld.substring( 0 , 5 );
//"B"
"ABCDEFG" .substring( 1 , 2 );
//"WH"
"WHAT" .substring( 0 , 2 );
//"BCDEFGHIJKLMNOP"
"ABCDEFGHIJKLMNOP" .substring( 1 );
split
I like this method. It creates a bunch of smaller Strings out of your String.
You give Java a character to “split” on. The string is karate chopped at each
occurrence of that character. You’re left with an array of the results.
String sentence = "I just think they’re neat" ;
String[] words = sentence.split( " " );
Guess what? We now have an array of the words! That’s 5 items in the
array!
{ "I" , "just" , "think" , "they're" , "neat" }
When Java saw an empty space, it dropped a tactical missile and split the
String up. The bits to the left and right ended up in the array.
Freaking nice right there.
trim
Okay, last one. That I’m going to mention…there’s a few more. But this
one’s easy.
It removes all the empty whitespace and newlines from beginning and end
of your String.
" This book is great. " .trim();
We trim the fat and are left with “This book is great.”
I trim most of the strings I deal with if a human might have provided it. No
one wants that shit at the beginning and end of the text.
Concatenation
Still with me? Good.
Here’s another big confusing word. Concatenation.
Remember the plus sign? You can use it to add numbers together.
int result = 3 + 2 ;
Answer: 5
Java also uses the plus sign to let us “add”, or “concatenate” (kun-kat-en-
ate) things to Strings.
String helloWorld = "Hello, " + "world!" ;
--> ”Hello, world!”
String cashRegisterDisplayStr = "DISCHARGE " + change + " IN CHANGE TO CUSTOMER"
;
--> “DISCHARGE 7.09 IN CHANGE TO CUSTOMER”
String thisIsNotTwo = "1" + 1
--> “11”
Note: with that last example… if you try to add two things together and one
of them is a String, they will be concatenated, not added. It’s “11”, not 2.
Okay, not too bad! One more example.
Let’s say you’re a shopping website on the interwebs. The user purchases
an item, and you want to thank them for purchasing it. Maybe you’d show
them a message like this:
String itemName = "Everybody Poops" ;
double price = 2.99 ;
String messageToUser =
"Thanks for purchasing the " + itemName + " for $" + price + "." ;
You might see “Thanks for purchasing Everybody Poops for $2.99.” when
we eventually show that String to the user. No, System.out.println() doesn’t
cut it for a website…but that’s a different book.
Also, you bet your ass I added an extra String concatenation to put a period
at the end of my sentence, even for an example. Shit pisses me off.
Anyway, String concatenation is used eeeeeverywhere. I mean really.
Combining Strings with Strings, or with numbers, or objects, or all kinds of
shit. + is an important little dude.
Formatting
That last example was a lot of plus signs to make a big ol’ String. Those
variables really belonged inside the String there, didn’t they? We had to
manually build the String ourselves; cutting up the string into parts, and
inserting the variables where they should fit in.
There’s an easier way. It’s a static method available on the String class
called format . Yes, it’s static, meaning you can literally call String.format
(note that capital S) without needing an object to use the method.
Here’s how you might do the exact same message with this approach.
String messageToUser =
String. format ( "Thanks for purchasing %s for %f." , itemName, price);
See those letters with a percentage sign % before them? No, it’s not a
percentage sign like you’re used to. This isn’t a value out of 100. This isn’t
the modulo operator either.
They’re like little placeholders. Then, when you use String.format, you give
Java the real values! It will insert them where they belong.
There is a method (hehe) to the madness of which letter to use. Basically,
each type of variable has its own letter. And you know what?
I’m not pasting a bit chart here. If you find yourself needing to make a
String that contains variables in it, use your Google-fu to find the table
online . Or just use %s to treat everything as a String. :)
Strings are Immutable
What does immutable mean? Does it describe your remote when you’re
watching TV and need to mute it, but it just won’t work?
No. It means Strings cannot be changed.
Concatenation? That created a new String.
Any time you use one of the String methods we’ve seen? They created new
Strings.
You need to make sure you’re not expecting the String to change by using
one these methods. Instead, you must expect Java to create a new String
from the shit you’re asking it do.
String initialString = "Ah, hello there." ;
initialString.toUpperCase();
System. out .println(initialString);
Packages
One way to reduce complexity and keep things tidy is to organize your
classes into “packages.”
If you don’t specify a package at the top of your class, you’re considered to
be in the “default” package. Never do this unless you’re just messing
around. Even then, stop it. Get some help.
What is a package, though?
You can think of it like a literal brown box package that contains your
classes. When boxing things up for storage or for a move in real life, you
probably have some rhyme or reason to how they’re grouped together.
That’s what a package is for.
Logically, it’s a way to group together related classes; bundling like classes
with other like classes.
In practice, it’s the folder that your Java file is in, combined with a package
declaration at the top of your Java file.
For example, here’s an example, so you can view an example:
Note that I’m using IntelliJ because I’m not a serial killer.
I have a big daddy folder for my project called MemeStore. That’s just what
I wanted to call it, the name doesn’t matter in the slightest.
I then have a folder called “src” that will contain alllllll my Java stuff. This
is just a standard thing for most Java developers to do, but it’s not
mandatory.
Then my package! I just called it “app” because I’m creating an application.
Not very creative, I realize.
Note: A package is just a folder! You could make the directories manually
inside Windows Explorer, or from your command prompt. Doesn’t matter. I
used IntelliJ because I’m not a sociopath.
Then, like I mentioned, the class declares its package at the very top of the
file.
MemeApplication.java
package app;
}
}
It’s literally just the word “package” followed by the directory the Java file
is inside of. Oh, and a semicolon.
And yeah, this class doesn’t do anything right now. It’s just a main method.
Maybe if we actually developed this thing, we’d open a new window and
show the user a list of memes. I’m really just focusing on the packages for
right now, thank you.
Matryoshka dolls
You can keep creating folders inside your folders. And therefore packages
inside your packages. Like those Russian dolls that have a Russian doll
inside the Russian doll inside the Russian doll.
I did mention that we might show the user a list of memes, since it’s a
meme store. Let’s add a new package called “list”. And put a
MemeListScreen class in there.
OK, so we created that new package (literally a folder) and created a new
java file called MemeListScreen.
MemeListScreen.java
package app.list;
}
And surprise, it literally is nothing. But notice the package line. See the
period there?
This is saying that this class belongs to the “app.list” package, which is the
folder structure it’s inside of.
For example, if we were to keep doing this, inside that “list” folder we
could create an “options” folder. And then inside that “options” folder we
could create an “about” folder. We could then have a Class inside the
package app.list.options.about.
Maybe it’s called AboutMemeStoreScreen or some shit. I don’t know.
That class would put this at the top of the file: package app.list.options.about;
Getting confused? The big idea is this: We organize our code to keep things
tidy and easy to understand.
Just like you might put your Word documents in one folder, and your
PowerPoints in another folder, it’s a good idea to put related Java code in
the same folder (package). And you can keep breaking it down further and
further.
com.google.gson
com.google.dagger
com.google.copybara.templatetoken
com.google.common.math
com.google.common.base.internal
Notice every part of a package is lowercase. And that even if a package is
multiple words (see the example “templatetoken”?) we still combine it into
one word.
The most confusing part, by far, is the “com.google” part…why is there a
website name before all the packages? And why is it backwards?? The fuck
is going on?
People, at least in America, have first names, middle names, and last names
to more uniquely identify us, yeah? It’s like that, except way more specific.
Maybe like a social security number.
It makes it straightforward to share code between developers without
package names clashing.
What if Google, Java, Facebook, Amazon, and Steve all had a package
called “math”. And we all wanted to share it with the world, so that no one
has to write code to do math ever gain? We’d have a bad time.
Instead we prefix all of our packages with our website name.
“Okay, but why is it in reverse?”
IDK. People just do that. Also, if you don’t have a domain name, make one
up.
com.stevebrown.memestore.app
Seems good!
}
}
This will come to you naturally in time. I swear. Trust fall?
1. Package by feature
2. Package by layer
3. Package by whatever the hell you feel like
Package by feature
If you like option 3 then you can skip the rest of this section for now.
Wimp.
What does this mean? A feature is, well, a feature of your software.
Something you provide that is valuable. For a piece of software that the
user actually sees, a feature might be a screen. Or collection of screens.
Imagine you’re creating a mobile application for Amazon, the future 4th
branch of the U.S. government.
In a package by feature approach, we might have one top-level package for
each screen (and its related classes). Then, a package for everything else.
Product List
Product Detail
Shopping Cart
Account Settings
Shared
Database
Networking
That’s the structure in plain English (I like English). Here’s what it might
look like using all those packaging conventions we just went over:
Note that Amazon’s app would be wayyyyyyyy more complex than this.
Also I don’t work for them, and I don’t know how they structure their code.
But this is a simplistic example of a “package by feature” approach.
Each feature gets its own big boy package, and anything that isn’t quite a
feature is thrown together somewhere else.
Package by layer
Sure, package by “layer” … or whatever you want to call it. By
functionality, by purpose, etc.
In the last approach, “package by feature”, we had a package for each main
screen of the app…for each “feature” that we provide to the user.
In this approach, “package by layer”, we group by the kind of class it is. For
example, is the class part of the user interface? It goes in the userinterface
(ui) package.
Do you feel me? Are you feeling me?
“package by feature” – group things together by the section of your app or
whatever you would consider a “feature” of your program
“package by layer” – group things together solely by their function, whether
that be user interface, networking, helper classes, creating files, math, that
kind of stuff.
Let’s say there’s some networking related code I want to add that only
affects the ProductDetailScreen. Where would it go?
In Package by Feature, it goes in the productdetail package.
In Package by Layer, it goes into the networking package.
Imports
“It is clear our nation is reliant upon big foreign oil. More and more of our
imports come from overseas.”
– George W. Bush
This quote has nothing to do with anything.
But that last section took fucking forever and I want to reset our minds here.
Whew. Okay…
How do we let our classes interact with each other? What if the
ProductListScreen doesn’t know what products to show without first
making a network call to Amazon? Surely it needs to ask Amazon for
recommendations seeing as they know everything about every aspect of our
lives.
Can we just do something like this inside our ProductListScreen?
Networker networker = new Networker();
Response networkResponse = networker.getProductsToDisplay();
…
It seems reasonable, right? We know that we have a Networker class in our
project. Why wouldn’t we be able to create an object from that class? Why
can’t we just “instantiate” it willy nilly?
Because Java needs you to “import” it. Unless the class you want to use is
in the exact same package as yours, you must put an import statement at the
top of your Java file.
Remember package declarations? It’s the simple one-liner where you
specify what package your class belongs to.
Right below that, still at essentially the top of the file, you simply import all
the classes that you’ll need from outside this file.
package com.amazon.app.productlist;
import com.amazon.app.shared.networking.Networker;
Now, for the rest of the class you can create new Networkers! Go crazy!
Connect to every web site that has ever existed! WEoooohhhhhh!
Ahem.
So yeah, that’s how you would import classes from the rest of your project.
But this same rule applies to using classes from Java.
Just for shits and giggles, suppose I want to generate a random number.
Rather than write my own class or function to do this, I can use the
Random class from the Java standard library.
But I can’t just create a new Random(), just like that! I have to import it. At
the top of my file…
import java.util.Random;
Then in one of my functions, I’m good to go!
Random randomNumberGenerator = new Random();
int randomInt = randomNumberGenerator.nextInt();
Hells yea!
Import class. Adds the import to the top of your class. Boom, done.
Importing it all
See above how we imported the Random class? We could import every
single class inside the java.util package using an astric *.
import java.util.*;
Yep. Now this class could use any class inside the java.util package.
There’s pretty much no reason to do this thanks to the goldfish-proof ways
of managing your imports that IntelliJ and other software provides. But it’s
certainly possible to import like this.
1. The name of the file should match the Java class, with “.java” at
the end.
2. The file should be placed in a folder structure that matches that
package name (just the folders separated by a period).
3. The top of the file should state the package the class belongs to.
4. Underneath the package statement, the file should import every
class it will need to use.
CHAPTER 13: OBJECT-
ORIENTED CONCEPTS
To wrap up this little book, I’ll give you a brief rundown of some of the
software “design” principles that make a language “Object Oriented,” just
because I like you that much.
Abstraction
You go to a restaurant. You ask for a very nice, expensive meal. The waiter
leaves and returns 20-30 minutes later with your meal.
Where did the waiter get the food from? Did he make it himself? Did he go
to the store and buy it? Did he run to the restaurant across the street and
take it from there?
When you ask for a meal, you don’t walk into the kitchen, tell the chefs
how to prepare it, micromanage how they interact with each other, put the
food into the oven yourself, or swing by Walmart to buy the buns the
restaurant has run out of, etc.
You simply ask the waiter for the food; with the expectation they will
provide it to you.
The waiter has abstracted away the details of how the food is prepared.
Good programmers create classes like this. You might have a very large,
powerful program with dozens or hundreds of classes to do something super
complicated. Maybe you have a program that calculates the quickest way to
travel between Point A and Point B on a map.
But does your user interface need to directly talk to all these different
classes to calculate the route? Or can we create a class that abstracts away
all that complexity? Maybe one class that simply takes address 1 as a
String, address 2 as a String, then returns an array of the steps you need to
take.
This is what abstraction is all about: simplicity of the design that is exposed
to other classes or systems.
Encapsulation
We can enforce abstraction. Classes can simply refuse to expose themselves
out in public. And thank god for that.
You could be a class with 500 properties, 1500 methods, and the worst
spaghetti code in the entire world. But you know what? Other classes don’t
need to see that. They don’t have to care. Encapsulation is a way of
abstracting away our code from other classes.
Let’s say we run a pizza business that lets the customer track the progress of
their order. That customer uses an app installed on their phone.
The app needs to make some network calls over the internet to get updates.
No, you don’t need to worry about that. And that’s part of the point.
Assume that every class used in this stupid example is in a totally different
package.
class StatusScreen {
private Order order ;
private Networker networker ;
private is saying that no other class knows how to update the progress bar
on the screen. Only the StatusScreen can call this method. It’s invisible to
the rest of them. Consider private properties and methods to be what is
“abstracted away” from the classes that would interact with it.
public is saying that any other class can call this method. It’s possible we’d
have another part of the user interface that wants to tell this screen to show
the order status. And luckily for us, it would appear that Networker’s
getOrderStatus method is public, since we’re able to use it.
And that’s correct; this is what Networker might look like:
public class Networker {
public String getOrderStatus(String id) {
establishNetworkConnection();
makeRequest();
processResult();
return getStatusFromResult();
}
We get to call the public method getOrderStatus from our user interface
class. And we have no idea that all this complicated networking shit is
happening under the hood.
This is the beauty of encapsulation; we’re forcing abstraction. Other classes
can’t fuck up our shit if they aren’t even allowed access to it.
private and public are access modifiers. There’s two other ones.
If you don’t specify one , your class, method, or property is considered
package private . It’s basically the default. Other classes in the same
package can see you.
protected is a specialized version of that. Except a child class can see that
method or property as well.
Inheritance
Which “inheritance” would you rather have?
What is inheritance?
Defining a class that is a more specific version of another class. Defining a
class that is the “child” of a “parent” class. A way to reuse code without
copy-pasting it. Another way to model our code in an easy-to-understand
way for humans.
In Java, a class does not find another class, hook up, and just have a child.
Unfortunately enough for them…
The child is a specialized version of the parent. The child inherits the
properties and methods of the parent. The child is a “subclass” of the
parent.
When you’re thinking through how you want to write a program, whether
that be a website, app, database utility, video game, or college assignment,
you often will find many parts of the program will share similar traits.
Maybe your app will have a bunch of different screens that share the same
color, or toolbar, or will display information in a similar fashion. No need to
do the same thing in multiple places; declare a class called Screen, then
extend that class for each screen in your app.
Maybe your video game will have a bunch of different types of heroes and
enemies, all of which can deal damage, take damage, die, revive, party up,
use abilities, etc. You can model your code carefully using classes and
inheritance to minimize how huge and confusing your codebase can
become.
How do inheritance?
I’ll start really simple for our first example.
class Meme {
Coitus
Let’s create some actual inheritance of our own:
class Monster {
int health = 10 ;
int damage = 2 ;
void attack(Monster monsterToAttack) {
monsterToAttack. health -= damage ;
}
}
Here, we have a simple Monster class. Any Monster created from this class
starts off with 10 health , 2 damage , and the ability to attack another
monster.
But we’re striving to make the greatest monster-themed video game of the
21st century. One to rival the likes of Pokemon or The Witcher!! Not all of
them will be the same!
Let’s make this more interesting; specialized, child Monster classes!
First, a Goblin . It will have lower health, and lower damage, because
fucking Goblins are always the weakest of the bunch.
class Goblin extends Monster {
Goblin() {
health = 5 ;
damage = 1 ;
}
}
What we did here was create a new class called Goblin that inherits from
Monster . It has its own constructor that specifies its unique values; 5 health
, and 1 damage .
By the magic of inheritance, it also can attack , because it is a Monster. And
the Monster class is the one who defined that method.
Yep, that means you could do this:
Just like before, with the Goblin, we don’t need to define those health and
damage properties again; the parent already did. We’re just assigning them
values of our own.
OK, one more. This one will do more than just have special health and
damage; it will do something different when it attacks!
class Zombie extends Monster {
Zombie() {
damage = 3 ;
}
Look at its attack method! Not only does it attack another monster, but it
heals itself when it does damage!! It’s a zombie, get it? It’s consuming
brains or something? Hah!
Super…
You probably noticed something a bit strange in the Zombie’s attack
method. Instead of just healing itself, as zombies might do, it says
super.attack() first. What’s that business?
Child classes that want to specialize how they behave (their methods) may
want to do some stuff in addition to what their parent does. Those child
classes must tell the parent to do its thing first.
When a method first calls a super method, that is the way of saying “I’m
first going to delegate to my parent here, they know what to do.” You know,
that thing you never do in real life.
On the other hand, child classes that want to completely replace the parent
functionality can simply never call their parents using super . If we did that
in the Zombie scenario, the zombie would heal itself but deal no damage
(because the parent Monster method’s code was never ran).
Honorably, these two will fight until either of their health values reaches or
falls below 0.
Do note that child classes can add new methods of their own; they don’t
only have to modify the parent’s methods; they can add entirely new suites
of functionality.
Polymorphism
Probably the biggest and scariest word for people learning Java. And
honestly, I would not be surprised if a lot of people that program in Java full
time don’t even know what it means.
And that’s not a knock against them. It’s both a tricky concept and a
confusing word. Okay, maybe slightly a knock against them.
But not you. You will know. I will force you to learn... if you voluntarily
read.
What is polymorphism?
Java is smart sometimes. One thing it’s smart at is knowing which method
to call.
It probably sounds easy. I have a class, and it has a method. I create an
instance of that class, and call that method. How could a programming
language get confused?
When inheritance is involved, that’s when.
Let’s harken back to our Monster example. We wrote some code that looked
like this:
Goblin warts = new Goblin();
But we can throw a massive curveball here. See how the data type of the
goblin variable is Goblin ? And the constructor we’re using is Goblin() ?
Since a Goblin is a Monster, we can instead do this:
Monster warts = new Goblin ();
Why polymorphism?
What does this get us? It’s a bit like abstraction; we can abstract away what
is behind the mask.
Remember the fight method on Monster?
public void attack(Monster monsterToAttack) {
monsterToAttack. health -= damage ;
}
Check that out. It’s a new kind of monster that does something totally
different when it attacks; nothing!
Now, what happens if we run this code?
Monster fishy = new Magikarp();
fishy.attack(goblin);
Do we fail to compile?
Do we splash and do 0 damage?
Do we attack and deal 50000 damage?
Does Java call the “attack” method on the parent class Monster,
or the “attack” method on the child class Magikarp?
My head. My poor, poor head.
The answer is we splash around and nothing happens, of course! Note that
the data type of fishy is Monster . But we created a new Magikarp() .
Again, this ability for Java to call the child class’s method, when the
variable is created using the data type of the parent, is called polymorphism
.
When the app is closed, Android loops through those activities, and lets us
know the screen is being destroyed.
for (Activity activity : currentActivities ) {
activity.onDestroy();
}
Java and Android don’t care if it’s a screen for translating text, or a screen
that shows your current GPS coordinates. It doesn’t care if it has a million
lines of code, or 3. It doesn’t care if your subclass even does anything
special in its onDestroy method.
Does your child class override the onDestroy method? It will be called. If it
doesn’t, the parent class’s onDestroy method will be called.
The ability to refer to the parent class, but create the object using the child,
is super cool and very common. And very polymorphic.
CHAPTER 14: BRINGING
IT TOGETHER
What have we learned? Did we hold all this information in our noggins?
Well, I did. I wrote it. I already knew this. I did 0 original research and cited
0 sources.
Anyways, if this were a high school English paper with a 1-3-1 format, it
would be the final “1” conclusion part.
7. You can declare a variable, like int x; then assign it a value later
with an equals sign like x=5;. Or you can declare and assign at
the same time, like int x = 5;
10. The main method is a special method every Java program must
have, which is the first method run in every Java program
(automatically by the Java Virtual Machine).
11. Strings are classes built-in to Java that are used all the time, with
methods like toLowerCase, equals, contains, substring, and trim.
12. There are special characters called “operators” built into Java that
perform basic functions, like add (+), subtract (-), OR (||), AND
(&&) , compare(> >= < <= ==), and more. From these we can
build powerful functions.
13. When a program needs to change what it does based off some
condition, like user input, value of a variable, etc. it uses
conditionals, or if statements. Inside those conditionals, the code
only runs if the condition is considered to be true.
14. Conditionals can be made even more special with “else if” block
which execute under some secondary condition, or “else” blocks
which execute if none of the other conditions are true.
15. Arrays are boxes that can contain multiple values, like an array of
Strings, or an array of numbers. They must have the same size
forever and ever. The first item in the array is at index 0.
16. Loops are ways to run the same code repeatedly, at long as some
condition is true. A while loop just keeps running under that
condition, and a for loop is a souped-up version with a built-in
way to keep track of how many times you’ve looped, and what to
do after a loop.
20. Classes that want to use classes from other packages (very
common) must import them first, with a line like “import
java.util.ArrayList”.
21. A class can “extend” another class to reduce code duplication and
provide a more specific piece of functionality than the parent.
This is called inheritance. Dog might extend Animal.
22. We can create a variable with the data type of the parent, but the
constructor of the child class. Java will still know to call the
child’s methods when the parent’s methods are called. This is
called polymorphism.