Core Theme: This video series teaches Java programming fundamentals, starting with setting up the development environment (JDK and IDE) and progressing through basic syntax, variables, control flow (if/else, switches), loops (while, for), methods, arrays, strings, exception handling, file I/O, and object-oriented programming concepts like inheritance, polymorphism, and encapsulation. It culminates in building practical projects like a calculator, a number guessing game, a shopping cart, a compound interest calculator, a weight converter, a simple banking application, a dice rolling game, a slot machine, a countdown timer, an alarm clock with music, and a basic Hangman game.
Key Points:
Environment Setup: Essential tools like JDK and IDE (IntelliJ) are covered for starting Java development.
Mind Map
Click to expand
Click to explore the full interactive mind map • Zoom, pan, and navigate
hey how's it going everybody in this
video I'm going to teach you everything
you need to know to start coding with
Java this series even contains about 15
Hands-On projects that we're going to
code together our final project will be
a functioning alarm clock that plays
music of your choice if you've never
coded anything in your life don't worry
we're going to start from the very
beginning I encourage you to sit back
show I don't like boring introductions
so we're just going to Jump Right In to
start coding with Java you'll need two
things a Java development kit also known
as a jdk a jdk contains a compiler a
compiler will compile your source code
your written code into bite code which
can run on a machine you'll also need an
integrated development environment IDE
an IDE is a fancy term for a workspace
in which we can write code because
sometimes notepad just doesn't cut it
we'll get started by downloading a jdk a
Java development kit okay here's how to
download the jdk the Java development
kit you can easily just Google or do a
search for jdk download we're going to
use the one by Oracle so we'll click on
this link I'll also post the link in the
description of this video if you would
like to access it that way we will
download the latest jdk version as of
the filming of this video we're on jdk
23 we're going to look for our operating
system I'm running Windows I will
download the 64- bit installer by
clicking this
download the download is complete we're
going to open this
next our jdk has been successfully
installed we can close it and that's all
we got to do for the
jdk now we need to install an IDE an
integrated development
environment one I recommend is intellig
you can easily just Google or do a
search for intellig
download we'll select the top
link now if you're not brought to this
page let's say you're at a different
page go to the top right where it says
get intellig click it and you should be
brought to a download page this version
is a 30-day trial but if you scroll down
there is a free version this is the
Community Edition because I don't like
to pay for things select the correct
download for your operating system I'm
executable once the download is complete
we will open this executable for
intellig select
next choose a destination folder I'll
keep it as is Click
next you can create a desktop shortcut I
now this is important too you can update
the path variable it basically tells
your operating system where to find the
executable files this is useful if
you're going to be running Java code
from command prompt or terminal but we
won't be doing that in this series you
can always come back later and update
install all right and we can finish we
might as well start intellig right away
I'm going to check this check boox to
run intellig and
finish we should now be at a welcome
screen for intellig we need to create a
project select new project I'll name my
project my first
project select the latest version of
your jdk I have jdk version 23 there is
a checkbox and it's most likely going to
be checked that says add sample code
just as a beginner I recommend
unchecking this it'll autogenerate some
sample code for us but we're going to do
that ourselves I'll show you how and then
then
create within our project folder
navigate to your Source folder it has a
name of
SRC we need to create a main Java file
go to the top toolbar go to file new
Java class we'll name this class main
it's going to contain the main body of
our code then select class
now the font is probably going to be really
really
small here's how to change
that go to the top toolbar go to
settings go to editor
editor
General and you can check this checkbox
for change font size with Control Plus
Mouse wheel apply okay now you should be
able to zoom in if you hold control and
scroll your mouse wheel now we can
actually read something in Java in order
to get some code to run you need a main
method within our class of main there's
a set of curly braces we'll type the
following public static void main add a
set of parentheses then a set of curly
braces within the set of parentheses
you're going to type the following
string straight brackets
args like you're a pirate
you need this method in order for your
program to run over the course of this
series we'll learn what each of these
keywords means but as a beginner think
of it as a magic spell that you have to
say in order to get your program to run
to run your program you're going to
click the screen Arrow or you can hold
F10 if we have written the main method
successfully we should have no
errors it says processed finished with
exit code zero that means everything is
running fine if I were to delete this
main method we can't actually run the
program so be sure that that method is
in to Output some text to the console
window we're going to type system with a
capital s. out. print add a set of
parentheses then a
semicolon in Java you'll end most of
your statements with a semicolon it's
kind of like a period at the end of a
sentence in the English language
within the set of parentheses we'll add
a set of double quotes whatever we would
like to Output we're going to type
within the set of double quotes think of
a food you like I'll type I like
pizza and then we can run this and this
should be the
output again I'm going to go to the
Green Arrow or you can hold shift
F10 and a console window should pop up
that says I like pizza or whatever your
here let's add another line of
system.out.print end it with the
semicolon within quotes which we type I
like pizza it's really
good let's run it
again all right here's our output I like
pizza it's really good
now these are both on the same line to
move your output down to the next line
you can use print Ln meaning print
line now it should look something like
good if you type back sln that's an
escape sequence for a new line and that
works too besides print line I like
pizza it's really good
let's add another line of text
system.out.print or print
line I like pizza it's really good buy me
me
character I like pizza it's really good
buy me
pizza or again you could use print
thing now you can write a comment
comments aren't displayed as output to
write a comment you use two forward
slashes and the text should be gray out
comments are good as notes for yourself
or for other developers let's add a
comment that this is my first Java
program when we run this this won't
display us out output it's really just
used as notes we still have our output
it hasn't
changed you can even add a multi-line
comment with a forward slash then an
asterisk to end a multi-line comment you
need an asterisk then a forward slash
I'll write this is a
multi- line
comment this won't output either
we don't see either of these
comments this is specific for intellig
but you can change the console font and
the colors I kind of find this hard to
read to do that we're going to go to the
top menu under file go to
settings under color scheme go to
console font here you can change the
font if you would like or the colors
I'll change the colors I'll make the
output bright green so it's easier to
read I'll go to console
standard output and select a new color
I'll select something
green apply and I think that looks
pretty good it's more readable that way
I'll also change the system output
too I'll make it kind of gray out that's pretty
pretty
good yeah and there's our output I like
pizza it's really good buy me
pizza now a shortcut to type system. out
at print line if you're using intellig
is to type s o u t then hit tab that's
going to autogenerate a print line
statement for you I didn't realize this
trick until a little bit later so you
don't always need to type out this
statement you can just autogenerate it
all right everybody and that is your
first Java program your homework in the
comment section is to post three print
line statements maybe type A poem or
some song lyrics or something and well
everybody that is your first Java program
all right everybody so we are moving on
to variables in Java probably back in
elementary school or middle school you
learned about variables in algebra a
variable was a representation of a
number well in programming we have
variables too a variable is a reusable
container for a value a variable behaves
as if it was the value it contains but
variables can contain more than just
numbers they can contain characters and
even entire words there's different data
types a whole number would be an integer
a number that includes a decimal would
be a double there's two categories of
variables we'll discuss primitive and
reference primitive variables are simple
values like numbers they're stored
directly in memory usually in a location
known as the stack reference variables
actually hold memory addresses on the
stack they point to a location in a
different area known as the Heap think
of it this way if I give you a primitive
variable that would be the same as me
handing you
$10 but if I give you a reference
variable a memory address that would be
the same as me giving you an IOU that
says I owe you $10 but the actual money
I owe you is at the bank that might be a
beginner's way of thinking of the
difference between a primitive and
reference data type primitive I'm giving
you $10 a reference data type I'm giving
you an IOU that I owe you $10 we'll
discuss the different data types we'll
begin with integers an INT short for
integer is a primitive data type I'll
show you how we can create an integer
variable in Java there's two steps to
creating a variable the first is
declaration the second is assignment
let's say we would like to create a
variable that stores a whole number an
integer with the first step of
Declaration we're going to first type
the data type of what we would like to
store exactly so for integers we will
type int then we should think of a
unique variable name we don't want to
say X or something similar that would
make sense in basic algebra but in
programming you want your variables to
be descriptive like shut up in
programming you want your variables to
be descriptive so let's say we are
working with let's say in age end this
line with a semicolon so this is
declaration step one we are creating a
variable named age if I was to print my
variable of age system.out.print
system.out.print
is variable age might not have been
initialized we're using a variable but
we've never given it a value we've never
completed step two of
assignment so we can set age equal to a
value so on my YouTube channel the
average age of my viewers is
approximately 21 or so so let's set age
to be 21 and then we'll print
it so that outputs 21 if I were to
change this to
30 then my variable age would behave as
if it was the number 30 so those are
integers they're whole numbers let's say
that I'm
30.5 let's see what happens exactly you
can see that intellig is already giving
us a warning that we're working with a
different data type known as doubles so
if I were to run this we get an error
message we have incompatible types from
double to in if we declare a variable as
an integer they can only store whole
integers let's think of a few more
examples another example of an integer
could be a year so let's say the year is 2025
2025
then we'll print our year
year
2025 or maybe a quantity int
quantity equals
1 then we'll print our
quantity one so in working with
quantities they're whole numbers usually
right we wouldn't have let's say half a
product 1.5 I would like 1.5 Nintendo
switches that wouldn't make sense right
they would would be whole numbers like
two now you can output a variable with a
string of text as
well let's say the year
is then I'll add plus a variable year
make sure that the variable is not within
within
quotes So currently this says the year is
is
2025 you do have to pay attention to the
spacing so after the word is I'm going
to add a space to separate is and the variable
variable
year the year is
2025 now if our variable was within
quotes we would literally be printing
the word year the year is year so don't
do that unless it's
intentional let's go on to the next data
type the next data type is double double
is a number but it can contain a decimal
portion unlike int ins are whole
numbers so this time we will create a
variable type of double what are some
examples of a variable that could be a
double let's say a price there could be
$19.99 or perhaps a GPA a grade point
3.5 or a temperature
double temperature equals
12.5 all right let's output some of
these let's do Price
Price system.out.print
system.out.print
price
19.99 let's add a unit of currency I'll
so Dollar Sign Plus price
$19.99 if you were to assign a variable
that's a double data type but store an
integer here's what would
happen we would just add 0 Z to the end
it's still a double so those are doubles
they're numbers that can contain a
decimal portion unlike
integers okay then the next data type we
have is charart
meaning character Char pronounced like
the word
Charizard so with chars what are a few
examples of single characters we could
use let's say a grade like a letter
grade with chars characters we enclose
them within single quotes let's say we
have the letter A that's the grade we
got on the last test or
maybe I'll put an exclamation point or
something or currency Char currency
equals pick a unit of currency I'll pick
dollars okay then let's output some of these
these system.out.print
system.out.print
grade which is an
A or our symbol
an exclamation point or our
currency which is American
dollars so then we have something called
booleans booleans are either true or
false we will declare this variable as a
Boolean let's check to see if somebody
is a student our variable name will be
is student and this equals true or false
so if I am a student I would say true
now a common naming convention in Java
is called camel case naming convention
if your variable name takes up two words
such as is and student when you combine
them the first letter of the first word
should be lowercase then any word after
the first letter is going to be
uppercase so is student and I will set
that to be true maybe something is for
sale or not Boolean for sale equals
false it's not for sale is somebody
online Boolean is online now I will set
that to be true these are a few examples
of Boolean
variables now you could output them
directly using system.out.print line
Let's test it system.out.print line
let's output is student
are we a student that is true is
something for sale for
sale that is false now with Boolean
variables we don't typically output them
directly to the console we tend to use
them more internally within a
program one place in which you might see
them is with the use of if statements
and this is a future topic we'll revisit
it later but I want to demonstrate the
usefulness of booleans so this is an if
statement we can check some condition
parenthesis then curly
braces if our condition is true if is
student double equals true but we could
simplify this
to if is student if this variable
contains true which it does we can
execute some code system.out.print
system.out.print
line we will print the following
you are a
student if this Boolean variable
contains true we will print the
following you are a
student or we could add else an else
Clause else let's
print you are not a
student So currently we're still a
student but if this Boolean variable
contained a value of false we would
perform form the else
statement you are not a student so we'll
cover if statements in a future topic
you don't necessarily need to know how
these work right now but that's one of
the uses of booleans they can only
contain true or
false these are a few of the basic
primitive data types for beginners int
for integers they contain whole numbers
doubles are numbers but they can contain
a decimal chars meaning characters are
single characters and booleans which are
either true or false these are a few of
the beginner primitive data types but
there's still a lot more than this
there's floats there's long doubles all
sorts of different data types but you
don't need to know those as a beginner I
would just stick to these four for now
so then we have the reference data types
A few of which include strings arrays
and objects in this topic we're only
going to discuss strings a series of
characters phas and objects are really
complex we'll revisit these later so
we're going to create a string a series of
of
characters so the data type is going to
be string an example of a series of
characters could be a name what's your
name with strings we enclose them within
double quotes chars single characters
are single quotes it's really easy to
mix the two up you might do it a few
times as a beginner so type in your name
in including a space I'll use my YouTube channel
channel
name and then we will output our name
name and your first and last name should
appear now we could use this variable of
name within another string this is known
as string
concatenation so let's say
say
hello plus our name
hello bro code or whatever your name is
what are a few other examples of strings
we could
write let's add string food
equals again within a set of double
quotes add your favorite food mine is
pizza then let's type again system.out.print
line your favorite food is
plus the variable
pizza what about an email string email
equals make up an email fake1 123@gmail.com
strings they can contain numbers but we
treat them more as characters rather
than actual numbers that we can use for
any sort of math or
arithmetic so let's print our email your email
email
or what about a
car string
car think of a car that you like I will
pick a Mustang that's another example of
a string or a color
string color equals
red so strings are a series of
characters they have a reference data
type you may have also noticed that the
font color of strings is different from
the primitive data types too of booleans
chars doubles and Ins at least within my
workspace the font color is orange and
with strings the font color of these
data types is white now we're going to
cover a few exercises
so let's start with our name
system.out.print line we will print
hello plus our name variable it's a
string hello your first and last
name let's print our age system.out.print
system.out.print
line u
r we're going to insert our variable age
then add another string another string
literal you are age years old again do
pay attention to the
spacing you are 30 years
old let's use my
GPA that's a
line your GPA
is then we will insert our GPA
your GPA is
grade system.out.print
line your average letter grade
is our variable
grade your average letter grade is is a
now within a single print line statement
we're going to combine multiple
variables let's say we're going to
Output our
color a
year and our
car all within one print statement system.out.print
system.out.print
line let's say we're choosing a car your
choice is a We'll add our color variable
plus the
year plus our car let's see what happens
exactly if we attempt
this so we've combined all three
variables red 2025 and our car of
Mustang so we're going to add some space
characters between each to separate them
so plus a space character add that after the
the
color after the
year we'll add a space between color and
year and year and
car so your choice is a red 2025
Mustang let's display the
price system.out.print
is plus currency
I picked American
price the price is
$9.99 uh for a car let's up that that's
way too cheap that's too good to be true
99 that's more
realistic now we're going to use this
Boolean variable of for
sale if
for sale if this is true then we're
print there is
is
a plus
Car Plus the text of for
sale else we will print something else
let's say
the plus Car Plus is not for sale for sale
sale
currently that's set to false the
true there is a Mustang for sale for
sale is set to true all right everybody
so those are variables in Java a
variable is a reusable container for a
value a variable behaves as if it was
the value that it contains there's two
different categories of variables
primitive and reference primitive data
types are simple values like integers
floats single characters and
booleans they're stored directly in
memory usually in a location known as
the stack reference variables such as
strings which are a series of characters
like your name or an email they're more
complicated we store a memory address
that points to a location in the Heap
and your homework assignment is in the
comment section post five variables a
string an integer a double A Char and a
Boolean and if you don't do your
homework you're going to make me sad and
well everybody that is an introduction
Java hello again friends so today I'm
going to show you how we can accept user
input in Java we will need the help of
what is called a scanner a scanner is an
object that allows us to accept user
input in Java however in order to use a
scanner we actually need to import it
from the certain package called
utilities or util at the top of our Java
file we're going to write the following
statement import Java do
util this is a package do scanner
scanner is a class so make sure you have
this import at the top before we get
started to sum up programming we
typically accept input process it then
produce output so that's why accepting
user input is important we would like to
do something with the input so to accept
user input we're going to create a
scanner object so type this scanner
that's the name of the class
class scanner that's going to be the
name of the object we'll be working with
do pay attention to the
capitalization our scanner object is all
lowercase characters whereas in the
first scanner has an uppercase
s scanner scanner equals new scanner add
a set of parenthesis then a semicolon
within the set of parentheses we're
going to type
system.in our scanner object can read
user input however it is good practice
if you create a scanner object at the
end of your program when you're done
we're going to take our scanner object
and use the close
method so scanner. close parenthesis
semicolon if you don't close your
scanner it can lead to unexpected
behavior for example let's say that we
read a file well after we're done
reading the file we'll want to close the
file when we open something we typically
want to close
it we're going to create a prompt within
our console that says enter your name
then a user will be able to type in
their name we'll need a user prompt to
work with so let's say system.out.print
name after receiving this prompt a user
is going to be able to type in their
name we're going to use our scanner
object scanner
next line parentheses semicolon so a
user is going to be able to type in a
string of text so let's type in our full
name then hit
enter however with this user input we're
not doing anything with it so let's
assign it to a
variable so with our line of scanner.
next line we will declare a variable and
assign it string name equals scanner.
nextline we have declaration and
assignment those two
steps and then once we have our name
let's output it system.out.print line
name so enter your name type in your
full name hit enter and the output
should be hello whatever your first and
last name is now if you prefer we can
put the input on the same line as the
prompt we're going to use print instead
of print Line Print line will add a new
line character to the
end so let's stick with
print so the input will be on the same
line as the prompt if you prefer it that
way so the next line method of our
scanner object it reads A String of
characters including any spaces if you
so if I were to type in my full name
with the first and last name separated
with the
space we only get the first name next
doesn't read any
spaces so use what you would prefer I
typically just use next
line to read an integer there's a
different method called Next int this
time let's create a prompt of enter your
age I'll use print instead of print line
we will assign a variable of age int age
equals use our scanner
object use the built-in next int
method then once we have our integer of
age let's output it system.out.print
line u
enter your name type in your name enter
your age oops I'm going to add a colon
and a space after my prompt just because
better okay enter your full
name enter your age hello your name you
are whatever your age is years old so
that's how to accept an integer if you
were to type in a floating point number
or a double anything that includes a
decimal now check this out our variable
of age should be an integer if we type
in something that contains a decimal
like a floating Point number or a double
let's say that I'm
25.9 well we get an error here it says
we have an error at line 12 where we
accept an integer so if you need a
double there's a next Double method of
scanners so this time let's ask for a
GPA what is your GPA your grade point
average we will assign a variable that's
going to be of the double data type
double GPA equals again use our
scanner use the next Double
method and then let's output
it system.out.print
line your GPA is plus our variable
GPA so again let's go through the
prompts type in your name type in your
age what is your GPA uh let's use print
Line enter your name enter your age what
is your GPA let's say my GPA is 2.1 I'm
just barely passing hey C get degrees
right your GPA is the GPA variable so
that's how to accept the double use the
next Double method of scanners now for
some reason if you need a Boolean
booleans are either true or false here's
how we can accept
that system.out.print line let's ask are
you a
student then I'll add a prompt for
true or false so the US user knows to
type in one of these instead of yes or
no so we will create a Boolean variable
of is student equals use our scanner
object use the next Boolean
method and then let's output
it system.out.print
line let's say student colon space plus
is student I think an if statement would
be better we'll cover that in a
moment again go through the prompts type
in your name type in your age type in a
GPA are you a student true or false
let's say that's true student
true and again I'm going to use print
instead of print
line not necessary but I think it looks
better let's use an if statement instead
when checking is student is true or not
so if is student again if statements
will be a future lesson we'll cover
pretty soon if is student if that's true
then we will
print let's print you are
enrolled as a
student else we will print something
else if that's not true if it's false you
are
okay enter your name enter your age
enter a GPA are you a student let's say
that it's
false okay we have our name our age our
GPA and then we're outputting you are
not enrolled you are not enrolled in
classes because we said
well then we get the output you are
enrolled as a student that's how to
accept user input of different data
types A few of which include strings
integers doubles and
booleans now there's one common issue
when accepting an integer or double than
demonstrate so we have our scanner
let's say we ask for a user's
age enter your
age and I'll make this a print statement
instead of print
line int age equals use our scanner use
the next int
method and then let's ask what the
user's favorite color is enter your favorite
favorite
color we will store that within a
variable named color and it's going to
be of the string data type string color
equals use our scanner object use the in
next line
method then we'll output the
following system.out.print line you are Plus
Plus
Age years
old as well
as you like the
color plus our variable color
happens enter your age 25 hit
enter enter your favorite color you are
25 years old you like the color so
what's going on here exactly so when we
type in a number for example 25 then hit
enter within the input buffer there's
still a new line character because we
hit enter
so the next line method is picking up
that new line character and using that
as the
input so we need to get rid of that new
line character this is a common problem
that you might see in Java if you accept
an integer or a double then accept a
string of text so one way in which we
can clear the input buffer to get rid of
that new line character is after
accepting an integer or a double we can
use our scanner and call the next line
method but don't assign it to anything
that should get rid of that new line
character in the input buffer if that
problem comes up so let's try this again
enter an age enter a color you are 25
years old you like the color red so if
you encounter that problem I would just
call the next line method of your
scanner object to clear the input buffer
now we're going to cover an
exercise in this exercise we're going to
calculate the area of a rectangle
what I like to do when creating a
project is declare all of my variables
at the top again make sure that you're
importing the scanner class I will
create a double variable of width I'll
set that to be
zero and a double variable of height also
also
zero and double
area I will set that to be
zero we're going to accept some user input
input
and reassign width and
height so we need a scanner object to
accept user input scanner scanner equals
new scanner parentheses semicolon within
the parenthesis we will type
system.in and again since we're opening
a scanner it's good practice to close it
I sometimes forget to do that scanner.
close we'll create a prompt to tell the
user to enter in a width we can use
system.out.print line or print for
prompts I like to use
print enter the
width we will take our width we've
already declared our width once we don't
need to type the data type again we can
reuse it width equals use our scanner
object use the an next Double method
because we're accepting a double a width
let's do this with height I'll just copy
height all right let's test it
currently let's make up some numbers 3.1 and
and
4.2 all right once we have the width and
the height we have to calculate the area
so we're going to take our area variable equals
equals
height and then let's output
it system.out.print line the area
is plus our variable
area so let's say 3.2 and
after area We'll add centimeters you
could do centimet squared if you prefer
or you could even add a superscript of
two so if you're on Windows make sure
num lock is on hold alt then type 0178
on the
numpad if you would like a superscript
of two you know because we're working with
with
areas so let's say
5.3 and
we're going to create a game of Mad Libs
Mad Libs is a game where you have a
story and a user fills in different
words the result is that it gives you a
story that's really silly or doesn't
necessarily make sense at times but
that's what we'll be doing in this video
it will help us practice accepting user
input since we're accepting user input
we'll need to import the scanner class
at the top of our Java file import java.util.scanner
java.util.scanner
a scanner is going to help us accept
user input we'll declare that and assign
it scanner scanner equals new scanner parenthesis
parenthesis
semicolon then within the parenthesis we
system.in when writing a program I like
to declare all of my variables first all
these variables are going to be of the
string data type we will need an
adjective you're going to get an English
lesson today
too adjective one an adjective describes
something like Fast slow cheap
expensive we'll need a noun string noun
one a noun is a person place or thing
we'll need another
adjective adjective
two we'll need a verb a verb is an
action like sleeping or running verb one
then another adjective a again an
adjective describe something all right
so let's work on our
lines so for the first line we'll say
today I went to
a we'll insert an adjective adjective
one we're going to describe a zoo that
we went to
we haven't asked for user input yet
we're getting a warning that this
variable has not been initialized that's
okay we'll take care of that
soon so today I went to a a description
an adjective
exhibit I saw
a plus a noun a noun is a person place
or thing like a gorilla or
harambe then we'll add some punctuation a
a
and our verb verb one then add some punctuation
so we could say that harambe was big and
action I
was plus adjective
three then add some
punctuation all right now we just need
to accept user input so let's do that
after assigning the variables we'll need
statements we will prompt the user to
enter an
adjective enter an adjective I'll give a
hint that an adjective is a
something enter a
noun I'll give a hint that we are
looking for
person we'll need another adjective we
can just copy this
line then we need a
verb enter a verb and we want it in
present tense so ending with ing like
running I'll give a hint that a verb is an
an
action and then another
adjective all right now we just need to
assign these variables we've already declared
declared
them adjective one equals take our
method and really we can just copy this
line paste it and then change what we're
assigning it to
we're accepting strings for each of
these lines we have adjective one noun
one adjective
2 verb one and adjective
3 all right now the last thing that I'm
forgetting since we opened up a scanner
it is good practice to close it at the
end of our file if we don't it can lead
to unexpected Behavior if we leave any open
open
resources scanner. close all right we
are ready to run this
I'm going to prefix a new line character
before displaying our
story just so that it's not so close to
the prompts when outputting
it enter an adjective a
suspicious enter a noun so I like making
fun of Mark Zuckerberg I'm going to
write the name of a person Mark
Zuckerberg enter an adjective
smelly enter a verb ending with ing
ing
screaming enter an adjective
happy and here's our Mad Libs game today
I went to a suspicious zoo in an exhibit
I saw a Mark
Zuckerberg Mark Zuckerberg was smelly
and screaming I was happy so for your
Mad Libs game post your results in the
comment section because I would like to
read them I want to see what you you
guys wrote or if you wrote a different
story post that too and well everybody
that is a simple Mad Libs game that we
Java all right everybody so we got a
really important topic to discuss today
although I can be a little dry and that
is the use of different arithmetic
operators in Java when it comes to
programming you got to math sometimes
it's a pretty important topic so let's
start with some basic addition in this
demonstration we will have three
variables X will equal 10 y will equal 2
and Z will store the result we'll
declare it but not yet assign it so for
basic addition we'll store our result
within z z equals X for addition you can
use the plus sign
Y what is 10 + 2 then we'll display
it we're storing the result within
Z which gives us 12
then we have
subtraction z = x -
y 10 - 2 is 8
8
multiplication for multiplication we're
going to use an asterisk 10 *
2 is
20 for division we use a forward slash z
= x / y 10 /
2 is
5 there's also the modulus operator
which is a percent sign that would give
you the remainder of any
division Z is going to store the
remainder this time x modulus y so
modulus is a percent sign 10 divides by
two evenly so the remainder is going to be
be
zero but if we divided 10 by three that
doesn't divide evenly
10 modulus 3 gives us a remainder of one
the modulus operator is really useful if
you need to determine if a number is
even or not or when working with time
you need to see if something is
divisible by 60 seconds or 60
minutes we'll get more into that later
but you should at least know what the
modulus operator
is now we have something called
augmented assignment operators instead
of storing the result within Z this time
we're going to reassign the result to
variable X so let's say we would like to
add 10 and 3 together but store it
within X well we could say x = x + y
this would technically
work so 10 + 3 is 13 but there is a
shortcut though that we could use and
that is by using augmented assignment
operators we'll condense some of these
steps instead of saying x = x + y we
simply say x + = y and that does the same
same
thing 10 + 3 is
13 there's also
subtraction x = X -
y 10 - 3 is 7 but we could condense it
to be x - equal
y that gives us
7 or multiplication x = x * y 10 * 3 is
30 but we can condense it to be x * =
y that is also
30 for division x = x /
y that gives us three now one thing to
pay attention to with division all right
so 10 / 3 should be 3.33 repeating right
well we're using something called
integer division we're not able to store
the decimal portion because we're
working with whole integers so that's
something to pay attention to when
you're using integer Division if we were
working with
doubles then we would retain that
decimal portion so do pay attention to
that we'll discuss that in another video
when it comes to typ casting for the
augmented assignment version that would
be x / = Y and let's change that to be 2
so 10 / 2 is
5 then we have the modulus operator x =
x modulus y 10 divides by 2
evenly X will be zero the augmented
assignment version of this would be X
modulus equals
y and that would also be 0o but if y were
were
three then that would be one now we have
increment and decrement operators you
see this a lot with looping structures
let's say that x equal 1 this time
instead of saying x = x + 1 which would
give us 2 or even the augmented
assignment inversion which would be X+ =
1 well there's even a shortcut for this
if we're only incrementing by one and
that is
x++ we're incrementing X by
one you tend to see this in a lot of
looping structures but that's a topic
for another day each time I increment X by
by
1 it's going to be retained so now x = 3
x ++ again well now X is
4 now there's also the decrement
operator x = X - one of course that's
going to be zero this
time so to decrement you can use x - minus so now X is zero let's do it again
minus so now X is zero let's do it again X
X -- now X is -1 x
-- now X is -1 x -- X is
-- X is -2 so those are the increment and
-2 so those are the increment and decrement operators you'll see these
decrement operators you'll see these again when we reach the topic on Loops
again when we reach the topic on Loops the last thing I need to discuss today
the last thing I need to discuss today is the order of operations and there's
is the order of operations and there's an acronym PEMDAS it's parentheses
an acronym PEMDAS it's parentheses exponents multiplication division
exponents multiplication division addition then subtraction in that order
addition then subtraction in that order you may hear the phrase to remember this
you may hear the phrase to remember this please excuse my dear Aunt Sally but I
please excuse my dear Aunt Sally but I like the phrase please excuse my dope
like the phrase please excuse my dope ass swag that's my version that I like
ass swag that's my version that I like to use let's say we have the equation
to use let's say we have the equation double result equals 3 + 4 time
double result equals 3 + 4 time parentheses 7 - 5 divided by
parentheses 7 - 5 divided by 2.0 I'm dividing by 2.0 because right
2.0 I'm dividing by 2.0 because right now we're using integer division which
now we're using integer division which we previously talked about so I'm going
we previously talked about so I'm going to use 2.0 so we retain that decimal
to use 2.0 so we retain that decimal portion again that's a topic for another
portion again that's a topic for another day let's display the
day let's display the result so I don't know what the result
result so I don't know what the result is but it is 7
is but it is 7 7.0 in what order do we solve this
7.0 in what order do we solve this equation exactly well we can use that
equation exactly well we can use that acronym of pendos
acronym of pendos from the left to the right we solve
from the left to the right we solve anything within parentheses first so
anything within parentheses first so going from the left to the right we skip
going from the left to the right we skip over any addition multiplication we're
over any addition multiplication we're looking for parentheses which we have
looking for parentheses which we have right here if you enclose part of an
right here if you enclose part of an equation within parentheses you would
equation within parentheses you would solve that first 7 - 5 is 2 there's no
solve that first 7 - 5 is 2 there's no more
more parentheses then we check any exponents
parentheses then we check any exponents there are no
there are no exponents
exponents multiplication well we have
multiplication well we have multiplication right here we would solve
multiplication right here we would solve that next 4 * 2 is 8 there's no more
that next 4 * 2 is 8 there's no more multiplication then we have
multiplication then we have division we have 8 / 2 which gives us
division we have 8 / 2 which gives us 4 then any addition 3 + 4 is 7 and that
4 then any addition 3 + 4 is 7 and that was our original result and then you
was our original result and then you would do any subtraction last so that is
would do any subtraction last so that is the order of operations when it comes to
the order of operations when it comes to arithmetic operators all right everybody
arithmetic operators all right everybody so that is some basic arithmetic and
so that is some basic arithmetic and different operators you can use in
different operators you can use in Java hey everybody so in this video
Java hey everybody so in this video we're going to create a shopping cart
we're going to create a shopping cart program a user is going to be able to
program a user is going to be able to type in an item set a price for each and
type in an item set a price for each and then ask for a quantity the output is
then ask for a quantity the output is that it's going to give you a total
that it's going to give you a total based on the price and how much you're
based on the price and how much you're buying this would be a good exercise for
buying this would be a good exercise for us to get us more comfortable with
us to get us more comfortable with accepting user input all right let's get
accepting user input all right let's get started everybody we'll need the help of
started everybody we'll need the help of a scanner the scanner allows us to
a scanner the scanner allows us to accept user input we'll need to import
accept user input we'll need to import that at the at the top so be sure that
that at the at the top so be sure that you have this line of code import
you have this line of code import java.util.scanner
java.util.scanner we'll create a scanner object scanner
we'll create a scanner object scanner scanner equals new scanner parentheses
scanner equals new scanner parentheses semicolon type
semicolon type system.in then if we open a scanner it's
system.in then if we open a scanner it's good practice to close it when we're
good practice to close it when we're done with it scanner. close if you leave
done with it scanner. close if you leave resources open it can lead to unexpected
resources open it can lead to unexpected behavior when creating a project I like
behavior when creating a project I like to declare all of my variables at the
to declare all of my variables at the top let's say we have an item name that
top let's say we have an item name that data type is going to be a string string
data type is going to be a string string item what are we buying
item what are we buying exactly we need a price that would be a
exactly we need a price that would be a double because there might be dollars
double because there might be dollars and cents a quantity how many of
and cents a quantity how many of something are we buying int quantity
something are we buying int quantity pick a unit of currency this could be a
pick a unit of currency this could be a character char
character char currency I'm going to initialize this
currency I'm going to initialize this right away American
right away American dollars and then a total we're going to
dollars and then a total we're going to multiply the price by the quantity to
multiply the price by the quantity to give a
give a total double total now if you would like
total double total now if you would like you can initialize some of these right
you can initialize some of these right away and assign them for example let's
away and assign them for example let's say we are at a pizza
say we are at a pizza restaurant I could set the item to be
restaurant I could set the item to be pizza right
pizza right away or within this program we could
away or within this program we could fill it in then let's create some
fill it in then let's create some prompts I'll use
system.out.print what item would you like to
like to buy then let's accept user input we're
buy then let's accept user input we're going to assign our string of item equal
going to assign our string of item equal to use our scanner object and use the in
to use our scanner object and use the in next line
next line method then let's just print it to
method then let's just print it to verify that it's working
what item would you like to buy maybe this time I am buying a hamburger that
this time I am buying a hamburger that will output hamburger we know that we
will output hamburger we know that we can get user input so let's delete this
can get user input so let's delete this line I was just testing it let's ask for
line I was just testing it let's ask for a
a price you could set an initial
price you could set an initial price if you would
price if you would like or we could ask for one depending
like or we could ask for one depending on how you want to write this
on how you want to write this program so let's system. about the
print what is the price for each if we're working with a price a
each if we're working with a price a double we'll use the next Double method
double we'll use the next Double method we're going to assign our price equal to
we're going to assign our price equal to use our scanner. next
use our scanner. next Double and then let's test it by
Double and then let's test it by outputting the
price okay let's say I'm buying a pizza this time what is the price for each
this time what is the price for each $4.99 and that outputs
$4.99 and that outputs $4.99 so it is a good idea every once in
$4.99 so it is a good idea every once in a while to test your code just to be
a while to test your code just to be sure that it all works as you go
sure that it all works as you go along then we'll need a
like we will assign our quantity variable
variable equals
equals scanner. next int since we're working
scanner. next int since we're working with whole numbers this
with whole numbers this time then let's test our quantity to see
time then let's test our quantity to see if it
if it works I don't know maybe I'm buying a
works I don't know maybe I'm buying a hot dog this time what is the price per
hot dog this time what is the price per each
each $4.99 how many would you like I would
$4.99 how many would you like I would like 12 hot dogs
like 12 hot dogs 12 and I'm just going to make sure I'm
12 and I'm just going to make sure I'm using print instead of print line just
using print instead of print line just because I think it looks better
now we'll create a total we don't need user input for that we're going to use
user input for that we're going to use the variables that we've already had
the variables that we've already had after assigning them total equals the
after assigning them total equals the price times the
total maybe I'm buying a pizza or pizzas each is $4.99
pizzas each is $4.99 and I buying three of
and I buying three of them
following I'm going to use a new line character just to separate our output
character just to separate our output from the
from the prompts you have
quantity plus a space character plus our variable
variable item but it might be more than one so
item but it might be more than one so let's say/ s it might be pizza or
let's say/ s it might be pizza or pizzas then we will display the price
pizzas then we will display the price including the unit of
currency your total is I'll add our unit of currency it's a
is I'll add our unit of currency it's a character I picked American dollars but
character I picked American dollars but pick whatever you would like plus our
pick whatever you would like plus our total
total that we have
that we have calculated all right let's see the
calculated all right let's see the result what item would you like to buy I
result what item would you like to buy I would like to buy a pizza what is the
would like to buy a pizza what is the price for each
price for each $4.99 how many would you like I would
$4.99 how many would you like I would like eight pizzas maybe it's for a party
like eight pizzas maybe it's for a party you have bought eight pizzas your total
you have bought eight pizzas your total is
$19.92 all right everybody so that is a shopping cart program that you can write
shopping cart program that you can write as an exercise using
Java hello everybody today we're going to discuss if statements in Java an if
to discuss if statements in Java an if statement performs a block of code if
statement performs a block of code if its condition is true we've discussed
its condition is true we've discussed how Boolean variables can be used within
how Boolean variables can be used within if statements we may be a little
if statements we may be a little familiar with them already in this
familiar with them already in this demonstration we will have a variable of
demonstration we will have a variable of age set it equal to be some
age set it equal to be some age age will be an integer I would like
age age will be an integer I would like to check if my variable of age is
to check if my variable of age is greater than or equal to 18 if so we can
greater than or equal to 18 if so we can print a message that you are an adult to
print a message that you are an adult to write an if statement will type if
write an if statement will type if parentheses curly braces within the set
parentheses curly braces within the set of curly braces we can check a condition
of curly braces we can check a condition to see if it's true so let's check to
to see if it's true so let's check to see if age is greater than or equal to
18 if that's true we'll print the following you are an
adult that would result in US outputting you are an
you are an adult now if this condition was false if
adult now if this condition was false if it's not true let's say that my age is
it's not true let's say that my age is 12 well then we skip over the if
12 well then we skip over the if statement we check if this condition is
statement we check if this condition is true if it is we perform this code if
true if it is we perform this code if not we skip it alternatively we could
not we skip it alternatively we could add an else clause
add an else clause this would be another statement we would
this would be another statement we would add else if this is false then do
add else if this is false then do something else so let's output the
something else so let's output the following you are a
following you are a child since the age is 12 we would
child since the age is 12 we would output you are a
child there's also an else if Clause so we have one of two
we have one of two possibilities do this or do that now we
possibilities do this or do that now we could add something called else if
could add something called else if Clause let's check else
Clause let's check else if age is less than
if age is less than zero if this statement is
zero if this statement is true then let's say you haven't been
true then let's say you haven't been born
born yet now we're doing one of three
yet now we're doing one of three things but it all depends on these
things but it all depends on these conditions our else Clause is kind of
conditions our else Clause is kind of like the default if none of the above
like the default if none of the above conditions are
conditions are true so let's test this my age variable
true so let's test this my age variable is set to
is set to 19 this would display you are an
19 this would display you are an adult if my age variable was -1 we would
adult if my age variable was -1 we would display you haven't been born
display you haven't been born yet this statement was false so we go
yet this statement was false so we go down to the next
down to the next one this is true NE 1 is less than zero
one this is true NE 1 is less than zero so we do
so we do this or if I was 10
this or if I was 10 well then these top two conditions are
well then these top two conditions are both false so we do whatever is within
both false so we do whatever is within the lse
the lse statement you can add as many else if
statement you can add as many else if Clauses as you would
Clauses as you would like so here's another
one else if our variable age is equal to zero
if our variable age is equal to zero exactly double equals is the comparison
exactly double equals is the comparison operator we're checking if a variable or
operator we're checking if a variable or a value is equal to another value or
a value is equal to another value or variable you don't want to use single
variable you don't want to use single equals because that's the assignment
equals because that's the assignment operator Java thinks we're trying to
operator Java thinks we're trying to assign a variable when making a
assign a variable when making a comparison you use double
comparison you use double equals is our variable age equal to
equals is our variable age equal to zero then we'll print something else
zero then we'll print something else okay we're going to print you are a
okay we're going to print you are a baby I will set variable H to be zero
baby I will set variable H to be zero you are a baby because our variable age
you are a baby because our variable age is equal to zero
is equal to zero exactly let's add another L
exactly let's add another L statement there's something I want to
statement there's something I want to demonstrate let's check to
demonstrate let's check to see if age is greater than or equal to
see if age is greater than or equal to 65 then we will print you are a
65 then we will print you are a senior I'll set age to be 70
senior I'll set age to be 70 here's the
here's the result you are an adult so why did we
result you are an adult so why did we print this statement rather than this
print this statement rather than this one well with these if statements we
one well with these if statements we check them from the top down this
check them from the top down this condition is technically true as well as
condition is technically true as well as this one 70 is greater than or equal to
this one 70 is greater than or equal to 18 so we execute this code and skip over
18 so we execute this code and skip over the rest even though this one is also
the rest even though this one is also true you do have to pay attention to the
true you do have to pay attention to the positioning of your if and else if
positioning of your if and else if statements in this situation it would be
statements in this situation it would be better if we were to check to see if
better if we were to check to see if somebody's age was greater than or equal
somebody's age was greater than or equal to 65 first so let's turn this into the
to 65 first so let's turn this into the if
statement and then where we check if age is greater than or equal to 18 we will
is greater than or equal to 18 we will use an else if Clause instead now this
use an else if Clause instead now this should
work you are a senior but if the age was 50
well then you are an adult now we're going to modify this program
going to modify this program slightly this time we will ask for user
slightly this time we will ask for user input we'll need the help of a scanner
input we'll need the help of a scanner at the top of our Java file we're going
at the top of our Java file we're going to import
to import java.util dothe class of
java.util dothe class of scanner we'll need to create a scanner
scanner we'll need to create a scanner object scanner scanner equals new
object scanner scanner equals new scanner within the set of parentheses
scanner within the set of parentheses type system.in
type system.in then when we open a scanner it is a good
then when we open a scanner it is a good idea to close it when we're done with
idea to close it when we're done with it just so we don't leave any resources
it just so we don't leave any resources open with our variable of age we're
open with our variable of age we're going to create a prompt to have a user
going to create a prompt to have a user enter in their age I'm going to declare
enter in their age I'm going to declare a variable of age but we'll assign it
a variable of age but we'll assign it later let's create a
later let's create a prompt enter your
prompt enter your age I'll use print instead of print
age I'll use print instead of print line and then we will assign age equal
line and then we will assign age equal to scanner. next
to scanner. next int okay let's try this
int okay let's try this again and to your age let's say that I'm
again and to your age let's say that I'm 21 you are an
adult what if I was 99 you are a senior I am negative 1 years old you
senior I am negative 1 years old you haven't been born
haven't been born yet I am zero exactly you are a
yet I am zero exactly you are a baby or maybe I'm 10 you are a
baby or maybe I'm 10 you are a child so with if statements we check a
child so with if statements we check a condition if it's true we do it we do
condition if it's true we do it we do this code if not we don't otherwise we
this code if not we don't otherwise we can check another condition with else if
can check another condition with else if and if none of these conditions are true
and if none of these conditions are true we can perform whatever is within an
we can perform whatever is within an else statement else acts like the
else statement else acts like the default code if none of the above
default code if none of the above conditions are true now this time we're
conditions are true now this time we're going to work with strings
going to work with strings we're going to create a variable of name
we're going to create a variable of name and it's going to be a string we'll
and it's going to be a string we'll declare it but not yet assign
declare it but not yet assign it we will prompt the user to enter in
it we will prompt the user to enter in their name I will use print instead of
their name I will use print instead of print
print Line enter your
Line enter your name we will assign our variable of name
name we will assign our variable of name equal to scanner. next line to get a
equal to scanner. next line to get a line of text
this group of if else if and else statements let's set this to be group
statements let's set this to be group two we're going to create another
set this will be group one for the name when somebody enters in their name
name when somebody enters in their name they could skip the prompt like this
they could skip the prompt like this enter your name I'm just going to hit
enter your name I'm just going to hit enter to skip
enter to skip it we will check if our name variable is
it we will check if our name variable is empty here's how
empty here's how if we'll check if our name is empty
if we'll check if our name is empty there's a string method for this we
there's a string method for this we haven't discussed string Methods yet
haven't discussed string Methods yet instead of saying name is equal to an
instead of saying name is equal to an empty space there is a built-in method
empty space there is a built-in method of strings and that is to take our
of strings and that is to take our variable name dot is
variable name dot is empty this is another way to check to
empty this is another way to check to see if a string is empty this will be
see if a string is empty this will be our condition is empty will give you a
our condition is empty will give you a Boolean of true or false
Boolean of true or false so let's print the following if our name
so let's print the following if our name variable is
variable is empty let's say you didn't enter your
empty let's say you didn't enter your name else if our name is not empty that
name else if our name is not empty that means somebody typed in their name let's
means somebody typed in their name let's say hello plus name and I'll add an
say hello plus name and I'll add an exclamation
exclamation point okay let's try this
point okay let's try this again enter your name if I hit enter
again enter your name if I hit enter we'll perform then whatever is within
we'll perform then whatever is within the if statement then enter an age you
the if statement then enter an age you didn't enter your name you are an adult
didn't enter your name you are an adult this time let's type in our name our
this time let's type in our name our first
name hello whatever your name is you are an
an adult this time we have two groups of if
adult this time we have two groups of if else statements group one is for the
else statements group one is for the name group two is for the user's age
name group two is for the user's age this time let's create a
this time let's create a Boolean Boolean is
student then we'll create a prompt let's ask are you a student but
prompt let's ask are you a student but we need a value of true or
we need a value of true or false cuz booleans can only be true or
false cuz booleans can only be true or false
false normally is student equals use our
normally is student equals use our scanner to get some user input next
Boolean now we'll create another group of if and lse if
of if and lse if statements group
statements group three we need an if
statement so with booleans we could say is student is equal to true but there is
is student is equal to true but there is a way to simplify this a
a way to simplify this a shortcut you can just say is student it
shortcut you can just say is student it holds a direct value of true or false we
holds a direct value of true or false we don't necessarily need to write like a
don't necessarily need to write like a whole condition
whole condition so if we're a student we'll
so if we're a student we'll output you are a
output you are a student else if a student is
student else if a student is false then we'll output you are not a
false then we'll output you are not a student we have three groups of if else
student we have three groups of if else statements group three is for is
statements group three is for is student group two is for the
student group two is for the age group one is for the
age group one is for the name just to make this more fun I'm
name just to make this more fun I'm going to add some emojis I think it
going to add some emojis I think it would make it more interesting but you
would make it more interesting but you don't have to so if somebody doesn't
don't have to so if somebody doesn't enter their name I'm going to add a
enter their name I'm going to add a pouting
pouting face if somebody enters their name I
face if somebody enters their name I will add a smiley
will add a smiley face if somebody is a senior maybe we
face if somebody is a senior maybe we can find an emoji for a
adult you haven't been born yet uh we could do like a spirit or
something you are a baby you are a
school you are not a student we could do an
an office all right so this is our final
office all right so this is our final program
again we have three groups of if statements this time one for the name
statements this time one for the name one for the age and one for is student
one for the age and one for is student and then for the prompt for are you a
and then for the prompt for are you a student I'm going to use print instead
student I'm going to use print instead of print
line here's the result enter your name enter your age are you a
student hello your name you are an adult you are not a student
you are not a student let's try some of the other statements
let's try some of the other statements I'm not going to enter a name for the
I'm not going to enter a name for the age let's say that I'm
age let's say that I'm ne1 are you a student
ne1 are you a student true you didn't enter your name you
true you didn't enter your name you haven't been born yet you are a
haven't been born yet you are a student so those are if statements
student so those are if statements everybody they perform a block of code
everybody they perform a block of code if its condition is true check a
if its condition is true check a condition if it's true do this if not
condition if it's true do this if not you can do something else and well
you can do something else and well everybody that summar mizes if
everybody that summar mizes if statements in
statements in Java hey everybody in this video I'm
Java hey everybody in this video I'm going to show you how we can work with
going to show you how we can work with the random class and generate some
the random class and generate some random numbers let's begin to work with
random numbers let's begin to work with random numbers we'll need to import the
random numbers we'll need to import the random class at the top of our Java file
random class at the top of our Java file we will import java. u.
we will import java. u. random much like what we do with the
random much like what we do with the scanner class we're going to follow a
scanner class we're going to follow a similar pattern for creating a random
similar pattern for creating a random object much like a scanner object we
object much like a scanner object we will type the name of the class random
will type the name of the class random the name of the random object random
the name of the random object random equals new
equals new random so random random equals new
random so random random equals new random let's say we have an integer an
random let's say we have an integer an integer variable of number I'm going to
integer variable of number I'm going to assign our number variable equal to and
assign our number variable equal to and here's where we'll generate a random
here's where we'll generate a random number we will take our random object
number we will take our random object then we will use the next int method
then we will use the next int method this will generate a random number
this will generate a random number however there's one issue with this I'm
however there's one issue with this I'm going to print our
going to print our number the number is going to be very
number the number is going to be very large so the random number that's
large so the random number that's generated it's going to be within a
generated it's going to be within a range between just about -2 billion and
range between just about -2 billion and positive2 billion I'm guessing you don't
positive2 billion I'm guessing you don't want a number that big So within the
want a number that big So within the next integer method we can set some
next integer method we can set some bounds if I would like a random number
bounds if I would like a random number between 1 and six like I'm rolling a
between 1 and six like I'm rolling a dice or die I would say 1 comma 6 this
dice or die I would say 1 comma 6 this is actually going to give us a random
is actually going to give us a random number between 1 and
five the first number is inclusive the second number is exclusive no matter how
second number is exclusive no matter how many times I rerolled this die I'm never
many times I rerolled this die I'm never going to get
six since this number is exclusive I'm going to inrease this to be seven that
going to inrease this to be seven that will give us 1 through
six and there's six let's say this time you would like three random numbers
you would like three random numbers you're rolling three dice let's say we
you're rolling three dice let's say we have number one number two and number
have number one number two and number three all
three all integers we'll assign number one with a
integers we'll assign number one with a random integer and we'll do this with
random integer and we'll do this with numbers two and three as well number one
numbers two and three as well number one number two number number
number two number number three then we will print them number one
three then we will print them number one number two number
three 2 46 23 4
46 23 4 225 good enough for random numbers
225 good enough for random numbers between 1 and 100 the second number is
between 1 and 100 the second number is going to be 101 because it's
going to be 101 because it's exclusive so now we're generating three
exclusive so now we're generating three random numbers between 1 and 100
not only can you generate random numbers you can Generate random
number let's change the data type and number to be
double we're going to use the next Double method
this is going to generate a random number between zero and
number between zero and one just the decimal portion
really you can also generate a Boolean this might be good in a situation where
this might be good in a situation where you need to flip a coin let's say we
you need to flip a coin let's say we have a Boolean of is
have a Boolean of is heads when we flip a coin is it heads
random. nextext Boolean then we will display if the coin
Boolean then we will display if the coin we flip is heads or not is it heads or
we flip is heads or not is it heads or it's Tails that's true it is
it's Tails that's true it is heads now it's false it's
heads now it's false it's Tails we could even use an if
Tails we could even use an if statement if is heads if our coin flip
statement if is heads if our coin flip is on
is on heads let's
heads let's print heads
print heads else we will
else we will print
Tails so this will simulate us flipping a
Tails all right everybody that is how you can Generate random numbers and use
you can Generate random numbers and use the random module in Java
hey everybody in this video we're going to cover some useful math related
to cover some useful math related constants and methods that you may be
constants and methods that you may be interested in as a beginner then at the
interested in as a beginner then at the end of this topic we'll cover a few
end of this topic we'll cover a few exercises let's begin if at any time you
exercises let's begin if at any time you need the value of pi there's a built-in
need the value of pi there's a built-in constant of the math class so I'm going
constant of the math class so I'm going to print the
to print the following math with a capital M Pi all
following math with a capital M Pi all capital so that would give you the value
capital so that would give you the value 3.14 and some change so instead of
3.14 and some change so instead of creating a variable for pi it's always
creating a variable for pi it's always available to you within the math class
available to you within the math class you just have to access it there's also
E this is the exponential constant also known as ul's number you may never use
known as ul's number you may never use this but it's available to you in case
this but it's available to you in case you do so again access the math class
you do so again access the math class Dot to name the
Dot to name the constant this time let's create a double
constant this time let's create a double variable named result here's a few
variable named result here's a few methods I'm going to reassign result
methods I'm going to reassign result equal to access math dot to raise a base
equal to access math dot to raise a base to a given power you can use the pal
to a given power you can use the pal method let's raise 2 to the^ of 3 then
method let's raise 2 to the^ of 3 then print
print it let's print our variable result 2 ^
it let's print our variable result 2 ^ of 3 would be 8
of 3 would be 8 and again I'm using a double that's why
and again I'm using a double that's why we have the decimal portion 2^ of 4
we have the decimal portion 2^ of 4 would
would be 16 2 the^ of
be 16 2 the^ of 5 is
5 is 32 po meaning power you can raise a base
32 po meaning power you can raise a base to a given power these can be values or
to a given power these can be values or variables there's the absolute value
variables there's the absolute value method math.abs for absolute value
method math.abs for absolute value what's the absolute value
of5 that would be five positive 5 basically speaking the absolute value
basically speaking the absolute value method gives you that number but
method gives you that number but positive if it's negative think of it as
positive if it's negative think of it as the distance away from zero if that
the distance away from zero if that helps for square root there's a square
helps for square root there's a square root method result equals
root method result equals math.sqrt
math.sqrt what is the square root of 9 I did make
what is the square root of 9 I did make a spelling mistake here if you're
a spelling mistake here if you're accessing the math class make sure it's
accessing the math class make sure it's with a capital m so the square root of 9
with a capital m so the square root of 9 would be
3 we can also round a number again access the math class use
number again access the math class use the round
method let's round 3.14 round will round a number to the
3.14 round will round a number to the nearest whole
integer again we're working with the double though so that gives us
3.0 to always round up there's the ceiling
ceiling method math. c
method math. c l again I accidentally used lowercase M
l again I accidentally used lowercase M it's capital M let's round 3.14 up to
it's capital M let's round 3.14 up to the
the ceiling so 3.14 rounded up is four to
ceiling so 3.14 rounded up is four to always round down you can use the floor
always round down you can use the floor method
method math.
math. floor so this time let's round 3.99 down
floor so this time let's round 3.99 down normally it should round up
normally it should round up right so 3.99 rounded down is
right so 3.99 rounded down is three you can find the max between two
three you can find the max between two values or variables
values or variables math. Max method we'll have two numbers
math. Max method we'll have two numbers which are comma separated 10 and 20 what
which are comma separated 10 and 20 what is the max between these two values or
is the max between these two values or variables
the greater number is 20 there's also Min I'll just copy this cuz I'm lazy
Min I'll just copy this cuz I'm lazy replace Max with Min what is the minimum
replace Max with Min what is the minimum value between these two
value between these two values that would be
values that would be 10 so those are a few useful math
10 so those are a few useful math methods and constants that you may be
methods and constants that you may be interested in we're going to cover some
interested in we're going to cover some math related exercises if you would like
math related exercises if you would like additional practice
in this first exercise we're going to find the hypotenuse of a right triangle
find the hypotenuse of a right triangle you can follow this formula C the
you can follow this formula C the hypotenuse equals the square root of a^
hypotenuse equals the square root of a^ 2 one of the sides plus b^2 the other
2 one of the sides plus b^2 the other side we're going to accept some user
side we're going to accept some user input we'll need a scanner we need to
input we'll need a scanner we need to import the scanner class import
import the scanner class import java.util do
java.util do scanner then we'll create a scanner
scanner then we'll create a scanner object scan scanner scanner equals new
object scan scanner scanner equals new scanner then place system.in within the
scanner then place system.in within the set of
set of parentheses then when we open a scanner
parentheses then when we open a scanner it is a good idea to close it so we
it is a good idea to close it so we don't leave any resources open scanner.
don't leave any resources open scanner. close we'll prompt the user to enter in
close we'll prompt the user to enter in the length of side A and B let's declare
the length of side A and B let's declare those as variables double a double b
those as variables double a double b we'll also declare Double C that will
we'll also declare Double C that will store the hypotenuse
store the hypotenuse Double
Double C we'll need two
C we'll need two prompts I will use print instead of
prompts I will use print instead of print
print Line enter the length of side
a with inside a within our variable of a we'll assign it to scanner. next
we'll assign it to scanner. next Double let's do this with side B we can
Double let's do this with side B we can copy these two lines paste them replace
copy these two lines paste them replace a with
a with B that is lowercase
B that is lowercase b let's do a test run just to be sure
b let's do a test run just to be sure that these two work
that these two work temporarily I'm going to print a then
B enter the length as side a 3 B will be four these work I just wanted to test
four these work I just wanted to test that it is a good idea to test your code
that it is a good idea to test your code as you're writing it then we have to
as you're writing it then we have to follow this
follow this equation C equals math. square root of
equation C equals math. square root of a^2 +
a^2 + b^2 there is a square root method within
b^2 there is a square root method within the math class but we have to raise side
the math class but we have to raise side a to the power of two plus b to the^ of
a to the power of two plus b to the^ of two here's how we can do that so within
two here's how we can do that so within the square root method we're going to
the square root method we're going to raise a to the power of two first math
raise a to the power of two first math po to raise a base to a given power
po to raise a base to a given power raise a comma to the power of
raise a comma to the power of two plus again math.pow to raise a base
two plus again math.pow to raise a base to a given power B to the power of
to a given power B to the power of two and that's it so let's display
two and that's it so let's display whatever C is the
hypotenuse the
the hypotenuse I'll write that this is C
hypotenuse I'll write that this is C side
C is the following plus
C if side a is three side B is four side C should be five which it is if you
C should be five which it is if you would prefer we can add a unit of
would prefer we can add a unit of measurement such as centimet or inches
measurement such as centimet or inches so after side C add cm for centimet or I
so after side C add cm for centimet or I for inches whatever you
for inches whatever you prefer so let's try that again side a
prefer so let's try that again side a will be four side B will be
will be four side B will be five and side C is this really long
five and side C is this really long number we haven't talked about the print
number we haven't talked about the print F statement yet using print F you can
F statement yet using print F you can display a given amount of digits but we
display a given amount of digits but we do have centimeters at the end which is
do have centimeters at the end which is what we were looking for so let's try
what we were looking for so let's try three and four and that gives us 5
three and four and that gives us 5 cm all right let's cover another
exercise given the radius of a circle or a sphere we'll return the circumference
a sphere we'll return the circumference the area then the volume that's if we're
the area then the volume that's if we're working with the sphere given the radius
working with the sphere given the radius so be sure that we're importing our
so be sure that we're importing our scanner at the top and we'll create a
scanner at the top and we'll create a scanner object scanner scanner equals
scanner object scanner scanner equals new
new scanner system.in then be sure to close
scanner system.in then be sure to close your
your scanner scanner .
scanner scanner . close we'll prompt the user for a
close we'll prompt the user for a radius because we need a radius to work
radius because we need a radius to work with we'll create a variable it will be
with we'll create a variable it will be a double named radius we'll declare it
a double named radius we'll declare it but not yet assign
but not yet assign it we'll prompt the user using print
it we'll prompt the user using print instead of print
instead of print Line enter the
Line enter the radius then we will assign our radius
radius then we will assign our radius variable radius
variable radius equals scanner.
equals scanner. next
next Double once we have a radius we have to
Double once we have a radius we have to follow these formulas so we need a
follow these formulas so we need a circumference area and volume let's
circumference area and volume let's declare those at the top of our program
declare those at the top of our program but assign them later double
but assign them later double circumference I think I spelled that
right double area double
area double volume we will calculate the
volume we will calculate the circumference
here's the Formula 2 times we need pi to work with
Formula 2 times we need pi to work with instead of typing
instead of typing 3.14159 so on and so forth we can access
3.14159 so on and so forth we can access that from the math class
that from the math class math.pi Pi is always available to
math.pi Pi is always available to us then multiply this by the
us then multiply this by the radius let's perform a test
radius let's perform a test run I will display the circumference
run I will display the circumference the
the circumference
circumference is plus our variable of
is plus our variable of circumference then I'll add a unit of
circumference then I'll add a unit of measurement afterwards centimeters is
measurement afterwards centimeters is good or whatever you
prefer enter the radius I'll enter in five the circumference is 31.4 CM in the
five the circumference is 31.4 CM in the future using print F we can limit the
future using print F we can limit the amount of digits that are displayed I'll
amount of digits that are displayed I'll show you how to do that later on in this
show you how to do that later on in this video then we need the
video then we need the area area
area area equals here's the formula again we need
equals here's the formula again we need Pi Pi is always available to us math. pi
Pi Pi is always available to us math. pi times our radius to the^ of two so we
times our radius to the^ of two so we need the power method of math
need the power method of math math.pow raise the radius to the power
math.pow raise the radius to the power of
of two and I'll just copy this line because
two and I'll just copy this line because I'm
I'm lazy the area is our variable area now
lazy the area is our variable area now when working with an area the unit of
when working with an area the unit of measurement is going to be squared so we
measurement is going to be squared so we can raise it to the power of two or you
can raise it to the power of two or you can use superscript to if you're on
can use superscript to if you're on Windows make sure numlock is on hold alt
Windows make sure numlock is on hold alt then on the numpad type
then on the numpad type 0178 for a superscript of two if you
0178 for a superscript of two if you would like to use that
would like to use that instead so now what is the
instead so now what is the area enter the radius 5
area enter the radius 5 the area is 78.53982
doubles times math. pi and again make sure the m is
3 math. power method raise our radius to the power of
three then display the volume the volume is our variable volume cm
is our variable volume cm cubed for a superscript of three make
cubed for a superscript of three make sure numb lock is on hold alt then type
sure numb lock is on hold alt then type 0179 that's if you're on
0179 that's if you're on Windows all right let's print the
Windows all right let's print the volume again my radius is
volume again my radius is five then we have the
five then we have the circumference the area and the
circumference the area and the volume and the unit of measurement is
volume and the unit of measurement is cenm cubed now we haven't talked about
cenm cubed now we haven't talked about the print F statement we could display
the print F statement we could display just a few digits here's
just a few digits here's how again this is a future topic replace
how again this is a future topic replace print line with print
F instead of adding plus our variable name we're going to add a
name we're going to add a placeholder
placeholder percent F to display a double but if you
percent F to display a double but if you would like one digit between the percent
would like one digit between the percent and F type .1 so let's do this with area
and F type .1 so let's do this with area and
and volume replace the plus with a
comma then instead of adding plus centim after our
after our placeholder add
placeholder add CM then cm
CM then cm squar and cm
squar and cm cubed then we can get rid of the portion
cubed then we can get rid of the portion where we add the centimeters to the end
so let's say the radius is five then we should add a new line character to the
should add a new line character to the end of each of
these that looks much better we're only displaying one digit
better we're only displaying one digit after the decimal again don't worry
after the decimal again don't worry about this this is a future topic the
about this this is a future topic the print F statement but if you would only
print F statement but if you would only like to display one digit that's how you
like to display one digit that's how you can do that again we'll cover this later
can do that again we'll cover this later all right everybody so those are a few
all right everybody so those are a few math related constants and methods that
math related constants and methods that you may be interested in as a
beginner what's up everybody in this video I'm going to discuss the print F
video I'm going to discuss the print F statement in Java print f is a method
statement in Java print f is a method used to format output we already do have
used to format output we already do have a little bit of experience using print F
a little bit of experience using print F in the last few topics involving math
in the last few topics involving math we'll get more in depth with the print F
we'll get more in depth with the print F stat in this topic print f is an
stat in this topic print f is an alternative to print and print line
alternative to print and print line wherever we would like to insert a
wherever we would like to insert a variable we can add a placeholder of a
variable we can add a placeholder of a percent sign then add one of a few
percent sign then add one of a few characters following it to format the
characters following it to format the output in this demonstration let's
output in this demonstration let's create a few variables let's create a
create a few variables let's create a string of name I'll assign some name
string of name I'll assign some name I'll pick SpongeBob because many people
I'll pick SpongeBob because many people know who SpongeBob is we'll need a
know who SpongeBob is we'll need a character let's say character first
character let's say character first letter equals
letter equals s int age equals
s int age equals 30 and a double double
30 and a double double height equals
height equals 60.5 and a Boolean Boolean is
60.5 and a Boolean Boolean is employed I will set that to be true
employed I will set that to be true SpongeBob is employed at the K crusty
SpongeBob is employed at the K crusty Krab so we have some variables they're
Krab so we have some variables they're all different data types we can insert
all different data types we can insert them into print F statements when we
them into print F statements when we output string literal here's a
demonstration instead of using print line I'm going to use print
line I'm going to use print F we will display the
F we will display the following
following hello then I would like to insert this
hello then I would like to insert this variable of name we're going to use a
variable of name we're going to use a percent sign as a
percent sign as a placeholder percent then we need a
placeholder percent then we need a specifier our character what is the data
specifier our character what is the data type of the variable we're trying to
type of the variable we're trying to insert if you're trying to insert a
insert if you're trying to insert a string you're going to use a lowercase
string you're going to use a lowercase s so after this word of hello we're
s so after this word of hello we're adding a placeholder then inserting a
adding a placeholder then inserting a string at this location so instead of
string at this location so instead of adding plus the variable
adding plus the variable name we're going to comma separate any
name we're going to comma separate any variables we're inserting so comma name
variables we're inserting so comma name here's the
output hello our variable name which contains
contains SpongeBob if we need to insert a
SpongeBob if we need to insert a character that would be lower case C so
character that would be lower case C so let's use
let's use system.out.print
system.out.print F I don't know let's say your name
F I don't know let's say your name starts with a we're going to insert a
starts with a we're going to insert a variable we need a placeholder that
variable we need a placeholder that perent sign lower case C for a Char
perent sign lower case C for a Char variable then comma separate any
variable then comma separate any variables comma our variable of first
letter so here's an important thing too with a print F statement we have to
with a print F statement we have to manually insert any new line characters
manually insert any new line characters we'll end each print F statement with a
we'll end each print F statement with a new line
new line character so after our format specifier
character so after our format specifier We'll add back sln to insert a new
line that's better otherwise the output is going to be all on the same
is going to be all on the same line so that's how to insert a character
line so that's how to insert a character percent C for
percent C for chars then for an integer we use
chars then for an integer we use D so print
f u r we're going to insert a variable we use D for
we use D for integers you are our variable age years
integers you are our variable age years old than a new line character then we
old than a new line character then we will insert our variable
age you are 30 years old and in the middle is our variable of
and in the middle is our variable of age for a double that would be
f system.out.print
f you are add a placeholder f for floating Point number think of that as a
floating Point number think of that as a double inches tall or you can pick
double inches tall or you can pick centimeters up to you
centimeters up to you then we will insert our variable of
height you are 60.5 then a bunch of zeros inches tall
60.5 then a bunch of zeros inches tall we can limit the amount of digits that
we can limit the amount of digits that are displayed after the decimal we'll
are displayed after the decimal we'll have to set a Precision but I'll explain
have to set a Precision but I'll explain that
that later then a Boolean all we need is the
later then a Boolean all we need is the letter
letter b
b system.out.print
system.out.print f let's say
f let's say employed add a
employed add a placeholder B then a new line
placeholder B then a new line character we will display our variable
character we will display our variable of is
employed employed then our variable of true now you can insert multiple
true now you can insert multiple variables within the same line here's
variables within the same line here's how we'll use
how we'll use system.out.print
system.out.print f we're going to inst insert our
f we're going to inst insert our variable of name
variable of name SpongeBob for a string the specifier
SpongeBob for a string the specifier character is going to be lowercase s for
character is going to be lowercase s for a string so string SpongeBob
a string so string SpongeBob is we're inserting an integer we need
is we're inserting an integer we need percent
percent D years old we'll comma separate all
D years old we'll comma separate all variables we're inserting we have a
variables we're inserting we have a string followed by an integer so that
string followed by an integer so that would be name comma age we're inserting
would be name comma age we're inserting two variables of this time SpongeBob is
two variables of this time SpongeBob is 30 years
30 years old so those are specifier characters
old so those are specifier characters add a percent sign a placeholder then
add a percent sign a placeholder then follow this placeholder with a specifier
follow this placeholder with a specifier character depending on what the data
character depending on what the data type is s for Strings C for
type is s for Strings C for chars D for integers f for doubles or
chars D for integers f for doubles or other floating Point numbers and B for
other floating Point numbers and B for booleans it might take a little bit of
booleans it might take a little bit of time to remember
time to remember these now we'll cover Precision with
these now we'll cover Precision with setting the Precision we can limit the
setting the Precision we can limit the amount of digits that display after a
amount of digits that display after a decimal let's create three different
decimal let's create three different prices and these will be of the double
prices and these will be of the double data type price 1 equals
$9.99 price two I'm just making up numbers here
10.15 and double price 3 equals 5
equals 5 $41 we're going to use print F to
$41 we're going to use print F to display these
display these prices
prices system.out.print F we're going to insert
system.out.print F we're going to insert we'll use that percent placeholder then
we'll use that percent placeholder then use f to display a double f for floating
use f to display a double f for floating Point
Point number comma our variable of price one
number comma our variable of price one then we'll do this with price two and
then we'll do this with price two and price
price three price one price two price three
three price one price two price three and here are the prices oh and we have
and here are the prices oh and we have to add a new line character too because
to add a new line character too because they're all in the same line I forgot to
they're all in the same line I forgot to do that so back sln back
do that so back sln back sln back
sln back sln that's better naturally when we're
sln that's better naturally when we're using print F to display a floating
using print F to display a floating Point number such as a double normally
Point number such as a double normally it displays six digits after the decimal
it displays six digits after the decimal point but we would like to limit that
point but we would like to limit that here's how we're going to set the
here's how we're going to set the Precision
Precision to display one digit after the decimal
to display one digit after the decimal between the percent sign and the F Type
between the percent sign and the F Type .1 to display one
digit so we have 10.0 this will automatically round the
10.0 this will automatically round the output so we have 10.0 100.2 and
output so we have 10.0 100.2 and 54.0 for two digits that would be 02
999 10.15 and
10.15 and 54.1 or we could do
54.1 or we could do three
3F then we have three digits after the decimal so that is precision it's useful
decimal so that is precision it's useful for displaying prices then we have Flags
for displaying prices then we have Flags next let's set the Precision to be 0.2
here's different flags that we can add by adding a plus after the percent sign
by adding a plus after the percent sign we can output a plus for any positive
numbers positive 999 positive 10.15 54.1 is still
54.1 is still negative to display a plus before any
negative to display a plus before any positive numbers just add a plus sign
positive numbers just add a plus sign let's increase these
let's increase these prices let's add three zeros to the end
prices let's add three zeros to the end of
each if you add the flag of a comma it's a comma grouping separator for any
a comma grouping separator for any thousand's place after the percent sign
thousand's place after the percent sign add a
add a comma at any thousand's place we have a
comma at any thousand's place we have a comma grouping separator again this is
comma grouping separator again this is useful for displaying prices
by adding a single left parentheses any negative numbers are enclosed in a set
negative numbers are enclosed in a set of parentheses so let's revert these
of parentheses so let's revert these prices
prices back after the percent sign add a left
parentheses so we only have one negative price-
54.1 and then we have a space character this will display a minus if negative
this will display a minus if negative space space if positive we have two
space space if positive we have two positive numbers in one negative one so
positive numbers in one negative one so by using a space
character any positive numbers are preceded with a space 54.1 is negative
preceded with a space 54.1 is negative so we do not have that space it's good
so we do not have that space it's good for aligning
for aligning numbers the last specifier we have to
numbers the last specifier we have to talk about is
talk about is width we're going to create some ID
width we're going to create some ID numbers these will be integers int id1 =
numbers these will be integers int id1 = 1 int id2 =
1 int id2 = 23 in
23 in ID3 equal
7890 these integers have a varying number of digits 1 2 3 4 by setting the
number of digits 1 2 3 4 by setting the width we can align them here's how again
width we can align them here's how again we're going to use print F we're
we're going to use print F we're displaying an integer so we need percent
displaying an integer so we need percent D we will Begin by displaying
D we will Begin by displaying id1 then let's do this with 2 three and
id1 then let's do this with 2 three and four as
four as well 2 3
4 and again I am missing that new line character new line new line
character new line new line new
new line new
line new line that's better so we have our four
line that's better so we have our four IDs by adding a zero after the percent
IDs by adding a zero after the percent sign we can zero pad some of these
values but Java is giving us a warning by how many characters do we want to pad
by how many characters do we want to pad these numbers with
these numbers with zero let's say four we have one variable
zero let's say four we have one variable that has four digits we'll set it to be
that has four digits we'll set it to be four to be the maximum so
04 and here we are these ID numbers are all now zero
all now zero padded and they align vertically which
padded and they align vertically which is kind of
is kind of nice so to add some zero padding follow
nice so to add some zero padding follow our placeholder with zero then the
our placeholder with zero then the amount of digits to Zer pad in this case
amount of digits to Zer pad in this case four by setting a positive number we can
four by setting a positive number we can WR justify these variables
WR justify these variables so let's replace zero with just
so let's replace zero with just four rather than having that zero
four rather than having that zero padding we just have some spaces if you
padding we just have some spaces if you would prefer it that
would prefer it that way or with a negative number we can
way or with a negative number we can left justify these
left justify these values so let's set four to be instead
values so let's set four to be instead -4 now these values are left Justified
-4 now these values are left Justified and we still have those spaces
and we still have those spaces afterwards except for the last variable
afterwards except for the last variable because it's already four digits
because it's already four digits all right everybody so that is the print
all right everybody so that is the print F statement it's a method used to format
F statement it's a method used to format output you add a placeholder then one of
output you add a placeholder then one of a few characters afterwards there is
a few characters afterwards there is Flags width precision and specifier
Flags width precision and specifier characters depending on the data type of
characters depending on the data type of what you want to display we'll have more
what you want to display we'll have more practice with this in the future and
practice with this in the future and well everybody that is print F in
Java hey everybody this video serves as a project we're going to create a
a project we're going to create a compound interest calculator using Java
compound interest calculator using Java if you put money in a bank account or
if you put money in a bank account or the stock market using the given formula
the stock market using the given formula we can determine what our final amount
we can determine what our final amount is going to be plus interest after a
is going to be plus interest after a given amount of time this project serves
given amount of time this project serves as an exercise using Java let's begin
as an exercise using Java let's begin all right let's get started everybody
all right let's get started everybody the first thing we'll need is a scanner
the first thing we'll need is a scanner we'll need to import it at the top of
we'll need to import it at the top of our Java file import input
our Java file import input import
import java.util.scanner
we need to create a scanner object again scanner scanner equals new
scanner scanner equals new scanner then within the set of
scanner then within the set of parentheses type
parentheses type system.in when you open a scanner it is
system.in when you open a scanner it is good practice to close the scanner when
good practice to close the scanner when you're done with it so you don't leave
you're done with it so you don't leave any resources
any resources open after creating our scanner here the
open after creating our scanner here the different variables we'll need double
different variables we'll need double principal this will store the principal
principal this will store the principal amount what's our original investment an
amount what's our original investment an interest rate double rate
interest rate double rate an integer for times compounded how
an integer for times compounded how often does our interest compound like
often does our interest compound like yearly quarterly
yearly quarterly monthly then we need an amount of time
monthly then we need an amount of time such as years into
years and the final amount double
double amount now we have to get some user
amount now we have to get some user input we'll need some prompts first we
input we'll need some prompts first we need the principal amount all use
system.out.print enter the principal I never spell principal right enter the
never spell principal right enter the principal
amount we are working with the double so we need the next Double method of our
we need the next Double method of our scanner principal equals our
scanner principal equals our scanner do next
Double then we need the interest rate this is going to be a
this is going to be a double
system.out.print enter the interest rate I'll add within our prompt that
rate I'll add within our prompt that this is in a percentage form like 5% or
this is in a percentage form like 5% or so the number five instead of
so the number five instead of 05 so then we have our interest
05 so then we have our interest rate so we need our scanner do next
rate so we need our scanner do next double so let's say somebody types in
double so let's say somebody types in five for
five for 5% we would like the rate to be 05
5% we would like the rate to be 05 rather than 5 after accepting the user
rather than 5 after accepting the user input let's divide that number by 100 or
input let's divide that number by 100 or let's say somebody types in seven we
let's say somebody types in seven we don't want the rate to be seven we want
don't want the rate to be seven we want it to be
it to be 07 that's why we're dividing by
07 that's why we're dividing by 100 we'll fill in the times compounded
100 we'll fill in the times compounded variable we're going to use print
enter the number of times
times compounded per
compounded per year so this could be yearly that would
year so this could be yearly that would be one quarterly four or monthly would
be one quarterly four or monthly would be 12 in most cases it's probably going
be 12 in most cases it's probably going to be one for yearly times
to be one for yearly times compounded equals use our
scanner next int cuz we're accepting an
next int cuz we're accepting an integer then we need the amount of times
integer then we need the amount of times our money is going to be
invested enter the number of years then we need to assign our
years then we need to assign our variable years years equals
variable years years equals scanner. next int because we're working
scanner. next int because we're working with an integer then we need to
with an integer then we need to calculate the total amount here's the
calculate the total amount here's the formula
amount equals we need our principal
amount times access the math class use the power
the power method raay is 1 plus the interest
rate divided by the variable times compounded so this is going to be the
compounded so this is going to be the base we Comm separate the base and the
base we Comm separate the base and the power we are raising this part of our
power we are raising this part of our equation to the
equation to the power of times
power of times compounded times the number of
compounded times the number of years and that's our
years and that's our formula it's a little confusing but it
formula it's a little confusing but it should
should work then we will display the
work then we will display the amount system.out.print
amount system.out.print line the amount
after plus years plus
plus is pick a unit of currency I'll pick
is pick a unit of currency I'll pick American
dollars plus amount let's test
amount let's test this so let's say we have $10,000 or so
this so let's say we have $10,000 or so and we're putting it in the
and we're putting it in the bank what is the interest rate
bank what is the interest rate maybe
maybe 3% so I'm going to type three enter the
3% so I'm going to type three enter the amount of times compounded per year I'll
amount of times compounded per year I'll go with
go with one enter the number of years
one enter the number of years one so we should have 10,300 in our
one so we should have 10,300 in our bank which we do
bank which we do 10,300 if you would like you can use a
10,300 if you would like you can use a print F statement to format the
print F statement to format the output so if you're familiar with that
output so if you're familiar with that let's replace print line with print
let's replace print line with print F instead of concatenating these
F instead of concatenating these variables we'll add some placeholders
instead so to display an integer we need percent D within print
percent D within print F
F years is then to display a double we
years is then to display a double we need percent F then we'll list our
need percent F then we'll list our arguments
arguments years comma
amount so to display two decimals within a double between the percent and the F
a double between the percent and the F we're going to type 2 to display two
we're going to type 2 to display two digits after the
digits after the decimal we'll proceed this placeholder
decimal we'll proceed this placeholder with the unit of currency let's do
with the unit of currency let's do American dollars okay let's see the
American dollars okay let's see the total
total amount enter the principal amount
amount enter the principal amount $110,000 enter the interest rate 2%
$110,000 enter the interest rate 2% enter the number of times compounded per
enter the number of times compounded per year this time let's do quarterly so
year this time let's do quarterly so four because there's four quarters in a
four because there's four quarters in a year enter the number of years let's do
year enter the number of years let's do two
two actually and here's the amount in our
actually and here's the amount in our bank account after 2 years
$1,477 all right everybody so that is a compound interest calculator you can
compound interest calculator you can write using
Java what is going on everybody in this video I'm going to explain nested if
video I'm going to explain nested if statements in Java
statements in Java in Java it is possible to have if
in Java it is possible to have if statements within other if statements
statements within other if statements kind of like
kind of like this after checking some condition you
this after checking some condition you could follow with another condition if
could follow with another condition if the first condition is true you can add
the first condition is true you can add if
if statements L if
statements L if statements and or else
statements and or else statements really depends on the program
statements really depends on the program that you're trying to write so what
that you're trying to write so what we're going to do in this demonstration
we're going to do in this demonstration is have two Boolean
is have two Boolean variables a Boolean of is
variables a Boolean of is student let's say that we're selling
student let's say that we're selling movie tickets if somebody's a student
movie tickets if somebody's a student they get a 10% discount on their movie
they get a 10% discount on their movie ticket we also have a senior discount
ticket we also have a senior discount Boolean is
Boolean is senior if somebody is 65 or older they
senior if somebody is 65 or older they get a 20% senior
get a 20% senior discount or if they're a student and a
discount or if they're a student and a senior they get a combined total of 30%
senior they get a combined total of 30% off their ticket
off their ticket price let's say we have a double of
price let's say we have a double of price the price of a movie ticket will
price the price of a movie ticket will be $9.99 let's say that's actually kind
be $9.99 let's say that's actually kind of cheap
of cheap nowadays we'll write an if statement to
nowadays we'll write an if statement to check to see if somebody is a student if
check to see if somebody is a student if is student is equal to true but since
is student is equal to true but since this is a Boolean variable we don't need
this is a Boolean variable we don't need the equals true portion we can just say
the equals true portion we can just say if is student I will go ahead and set
if is student I will go ahead and set this to be true right away so if
this to be true right away so if somebody is a student they get a student
somebody is a student they get a student discount else they
won't so if a student is true let's output the
output the following you get a
following you get a student discount of
student discount of 10% then we will take our
10% then we will take our price price equals price time
price price equals price time 0.9 that will give you a 10% discount
0.9 that will give you a 10% discount account you could shorten this using the
account you could shorten this using the augmented assignment operator price
augmented assignment operator price times equals
times equals 0.9 that will set the price to be
0.9 that will set the price to be 90% or a 10% discount so to say if
90% or a 10% discount so to say if somebody's not a student they're going
somebody's not a student they're going to pay full price price times equals 1
to pay full price price times equals 1 that really doesn't do anything but it
that really doesn't do anything but it might help with this
might help with this visualization then we'll output the
is pick unit of currency then I'll add our price let's perform a test
our price let's perform a test run currently we're a student you get a
run currently we're a student you get a discount of 10% the price of a ticket is
$8.99 to limit the amount of digits that display let's use a printf statement
display let's use a printf statement we'll use print F instead of print line
we'll use print F instead of print line after the dollar sign I will add a
after the dollar sign I will add a format specifier we're going to display
format specifier we're going to display a double we'll use f for a floating
a double we'll use f for a floating Point
Point number comma price to display two digits
number comma price to display two digits after the decimal use 0
after the decimal use 0 2 now we can display a
2 now we can display a price you get a student discount of 10%
price you get a student discount of 10% the price of a ticket is
the price of a ticket is $8.99 now if we weren't a student I'll
$8.99 now if we weren't a student I'll set this to be
false we don't get that discount the price of a ticket is $9.99 what it was
price of a ticket is $9.99 what it was originally now what if somebody is a
originally now what if somebody is a senior and a student within our if
senior and a student within our if statement we'll write a nested if
statement we'll write a nested if statement as well as an else
statement as well as an else statement if is senior they get a
statement if is senior they get a student discount and a senior
student discount and a senior discount let's cut these two lines
discount let's cut these two lines within the if statement and stick them
within the if statement and stick them within the nested else statement
within the nested else statement if somebody is a senior and a
if somebody is a senior and a student you get a senior
20% and a student discount of 10% so let's take our original
10% so let's take our original price times equals
so let's say is senior is true for now okay else if they're not a student
now okay else if they're not a student but they are a
senior we'll check that with a nested if statement within the else
statement within the else statement if is senior they get that
statement if is senior they get that senior
senior discount but it's only 20% instead of 30
discount but it's only 20% instead of 30 because they're not also as
student price times equals 0.8 you could add
0.8 you could add else price times equals
else price times equals 1 that's if somebody is not a student
1 that's if somebody is not a student and not a senior but you don't
and not a senior but you don't necessarily need the sell
necessarily need the sell statement all right let's perform a test
run let's say that we're not a student and not a senior
the price of a ticket is $9.99 what if we were a student but not
$9.99 what if we were a student but not a
a senior you get a student discount of 10%
senior you get a student discount of 10% the price of a ticket is
the price of a ticket is $8.99 what if we're not a student but we
$8.99 what if we're not a student but we are a
senior you get a senior discount of 20% the price of a ticket is
the price of a ticket is $7.99 what if we're both a student and a
senior you get a senior discount of 20% you get a student discount of 10% the
you get a student discount of 10% the price of a ticket is
price of a ticket is $6.99 that's how nesa if statements can
$6.99 that's how nesa if statements can be useful you could check another
be useful you could check another condition after checking a condition
condition after checking a condition already so that's just one example of
already so that's just one example of nesa if statements and well everybody
nesa if statements and well everybody those are Nesta if statements in
Java hey yeah so today I'm going to show you a few useful string Methods you may
you a few useful string Methods you may be interested in as a beginner using
be interested in as a beginner using Java in this demonstration let's create
Java in this demonstration let's create a variable of name the data type is
a variable of name the data type is going to be a string type in your full
going to be a string type in your full name including a
name including a space I'll just use my YouTube channel
space I'll just use my YouTube channel name if at any time you need the length
name if at any time you need the length of a string you can use the length
of a string you can use the length method I'll store that as an integer int
method I'll store that as an integer int length equals to access these string
length equals to access these string Methods you need a string or a variable
Methods you need a string or a variable that is a string
that is a string dot then we have one of a few methods if
dot then we have one of a few methods if you need the length you can use the
you need the length you can use the length
length method and then let's print
it print the length how many characters are in the string
are in the string eight 1 2 3 4 5 6 7 8 this could be
eight 1 2 3 4 5 6 7 8 this could be useful let's say somebody is setting a
useful let's say somebody is setting a password and you have a maximum size of
password and you have a maximum size of 12 characters well you can check the
12 characters well you can check the length to see if it's under 12
length to see if it's under 12 characters so that is the length
characters so that is the length method there's Char at that will give
method there's Char at that will give you the character at a specified index
you the character at a specified index we'll be given a single character we'll
we'll be given a single character we'll store that as a variable Char letter
store that as a variable Char letter equals take our string of name use the
equals take our string of name use the Char at
Char at method within the Char at method we'll
method within the Char at method we'll list an index zero is the index of the
list an index zero is the index of the first character because computers like
first character because computers like to start at zero what what is the
to start at zero what what is the character at index
character at index zero well that letter is B at index
zero well that letter is B at index one that would be R and
one that would be R and two would be
two would be o that is the charat method it returns a
o that is the charat method it returns a character at a given index within a
character at a given index within a string we also have the capability of
string we also have the capability of finding a letter at a given
finding a letter at a given index let's say we have a variable of
index let's say we have a variable of index take our name use the index of
index take our name use the index of method find the first occurrence of an
method find the first occurrence of an O so in my example that should be 2 0 1
O so in my example that should be 2 0 1 2 that is the first index of this
2 that is the first index of this character o what about a
character o what about a space well that would be three 0 1 2
3 there's also last index last index equals take our string
index last index equals take our string of
of name then use the last index of
name then use the last index of method what is the last index of an O
method what is the last index of an O because index of gives you the first
because index of gives you the first index last gives you well the last
index last gives you well the last one what is the last index of O where is
one what is the last index of O where is it exactly
it exactly five 0 1 2 3 4 5
five 0 1 2 3 4 5 we can take a string and make all the
we can take a string and make all the characters uppercase all reassign that
characters uppercase all reassign that to our name variable so we're going to
to our name variable so we're going to take our name use the two uppercase
take our name use the two uppercase method then print our name after
method then print our name after reassigning
reassigning it now all the letters are
it now all the letters are uppercase there's also two
uppercase there's also two lowercase we'll replace upper with
lowercase we'll replace upper with lower and I should probably turn this
lower and I should probably turn this into a comment
into a comment now all the characters are
lowercase we can trim any white space before and after a string let's add a
before and after a string let's add a few spaces before and after then print
few spaces before and after then print the
the name we can eliminate all this white
name we can eliminate all this white space we'll use the trim method for that
space we'll use the trim method for that we'll reassign name equals name and use
we'll reassign name equals name and use the trim
method now while that white space is gone we can replace a character with
gone we can replace a character with another
another one name equals name we will replace one
one name equals name we will replace one character with another let's replace any
character with another let's replace any o's with A's for your own name feel free
o's with A's for your own name feel free to change
these so what is my name now
now broade there are methods that return
broade there are methods that return Boolean values to check to see if a
Boolean values to check to see if a string is empty you can use the is empty
string is empty you can use the is empty method this would return a Boolean to
method this would return a Boolean to demonstrate I'm going to put this within
demonstrate I'm going to put this within a print
statement so my string is not empty that's false but if it was it would
that's false but if it was it would return true but I have to turn these
return true but I have to turn these lines into
comments that would return true my name is empty this could be useful within an
is empty this could be useful within an if statement
if name do is empty method if our name is empty we will
method if our name is empty we will print your name is
print your name is empty else we will
print hello plus
hello plus name currently my name is
name currently my name is empty your name is
empty your name is empty this method returns true but if it
empty this method returns true but if it wasn't
wasn't it would return
it would return false hello whatever your name
is I'll use a multi-line comment just to comment all this
out we can check to see if our string contains a character that would return a
Boolean let's check to see if our name contains any spaces
true your name contains a
contains a space else will print your
space else will print your name doesn't
name doesn't contain any
contain any spaces so my name does contain a
spaces so my name does contain a space that would return true your name
space that would return true your name contains a
contains a space if we're working with let's say a
space if we're working with let's say a username usernames typically don't
username usernames typically don't contain
contain spaces your name doesn't contain any
spaces your name doesn't contain any spaces there is a method to check to see
spaces there is a method to check to see if two strings are
if two strings are equal again I'm going to use a
equal again I'm going to use a multi-line comment just to comment this
out if our name equals
name equals using the equals method we can check to
using the equals method we can check to see if two strings are equal the given
see if two strings are equal the given characters within them let's see if our
characters within them let's see if our name equals
password this actually would be more appropriate if we were working with the
appropriate if we were working with the string named password if our name if the
string named password if our name if the string of name is equal to this string
string of name is equal to this string if they have the same characters exactly
if they have the same characters exactly then we'll print your name can't be
then we'll print your name can't be password
else we will print
print hello plus
hello plus name I will set my name to be
password your name can't be password but if it
wasn't well then this returns false these two strings are not equal and we
these two strings are not equal and we execute the L statement hello your name
execute the L statement hello your name now the equals method doesn't account
now the equals method doesn't account for case sensitivity so let's say our
for case sensitivity so let's say our password has a capital
P well then this method returns false hello password to ignore case
hello password to ignore case sensitivity you can use equals ignore
sensitivity you can use equals ignore case then that would return true your
case then that would return true your name can't be password all right
name can't be password all right everybody those are a few useful string
everybody those are a few useful string Methods you may be interested in as a
Methods you may be interested in as a beginner using
beginner using Java all right everybody in this video
Java all right everybody in this video I'm going to explain how the substring
I'm going to explain how the substring method Works in Java substring is a
method Works in Java substring is a method that's used to extract a portion
method that's used to extract a portion of a string strings have a built-in
of a string strings have a built-in method of substring within the substring
method of substring within the substring method you can list one of two indices
method you can list one of two indices this method will create a new string
this method will create a new string based on the positioning of the indices
based on the positioning of the indices the start and the end I can best
the start and the end I can best demonstrate this with us creating an
demonstrate this with us creating an email SCE ER program so what we'll do in
email SCE ER program so what we'll do in this demonstration is create a string of
this demonstration is create a string of email type in your own email I don't
email type in your own email I don't want to give you guys my actual email
want to give you guys my actual email because some of you guys are weird no
because some of you guys are weird no offense my email will be bro1
offense my email will be bro1 23@gmail.com
our variable of email is a string strings have a built-in method of
strings have a built-in method of substring we can create a new string
substring we can create a new string from portions of the original string
from portions of the original string here's
here's how let's say I would like the first six
how let's say I would like the first six letters but depending on your own email
letters but depending on your own email it may be different the substring method
it may be different the substring method will return a new string so let's create
will return a new string so let's create a new variable the data type of string
a new variable the data type of string of usern
of usern name equals to create a substring we
name equals to create a substring we will take the original string use the
will take the original string use the substring
substring method then list one of two possible
method then list one of two possible indexes or indices the first index will
indexes or indices the first index will be zero at what position would we like
be zero at what position would we like this substring to end I would like to
this substring to end I would like to end right before this at sign so that
end right before this at sign so that would be 0 1 2 3 4 5
would be 0 1 2 3 4 5 6 the second index is exclusive so we're
6 the second index is exclusive so we're creating a new string of username by
creating a new string of username by using the substring method of our
using the substring method of our original string of email then let's
original string of email then let's print it to test it we will display our
print it to test it we will display our username and now we have a new string
username and now we have a new string mine is bro 1 123 but depending on what
mine is bro 1 123 but depending on what you wrote for your email it may be
you wrote for your email it may be different now I would like a new
different now I would like a new substring of every character after the
substring of every character after the at sign this will be a variable named
at sign this will be a variable named domain what is the domain of our email
domain what is the domain of our email again we're taking our original string
again we're taking our original string using the substring method then list one
using the substring method then list one of two possible indices so again let's
of two possible indices so again let's count this is index zero because in
count this is index zero because in programming we tend to start with zero 1
programming we tend to start with zero 1 2 3 4 5 6
7 so 7 8 9 10 11 12 13 14 15 16 then we will display our
domain so my domain is gmail.com within your substring method
gmail.com within your substring method if you have a starting index but you
if you have a starting index but you would like all the characters that come
would like all the characters that come after all the way till the end you don't
after all the way till the end you don't necessarily need an ending index X we
necessarily need an ending index X we could just say seven that would work too
could just say seven that would work too gmail.com there's one issue with how we
gmail.com there's one issue with how we wrote this program what if somebody has
wrote this program what if somebody has a different length of an email there's a
a different length of an email there's a greater or lesser number of characters
greater or lesser number of characters so let's say I have a different
email this program doesn't work as intended it's not flexible so my domain
intended it's not flexible so my domain is 1@gmail.com
is 1@gmail.com I could could modify the indices of the
I could could modify the indices of the substring method so 0 1 2 3 4 5 6
78 then the domain would be nine because I want everything after the at
sign and then my username let's check that so this would be my username bro
that so this would be my username bro code one to make this program more
code one to make this program more flexible instead of manually entering
flexible instead of manually entering the indices we can determine this number
the indices we can determine this number should be with another string method
should be with another string method we're going to use the index of method
we're going to use the index of method in place of a number we're going to find
in place of a number we're going to find the at character let's replace our
the at character let's replace our second
second index with email our string dot using
index with email our string dot using the index of method then we will find
the index of method then we will find the index of our at character we're
the index of our at character we're going to replace this number with email.
going to replace this number with email. index of and find the at sign so now
index of and find the at sign so now let's try printing our
let's try printing our username so here's my
username so here's my username then let's print the
domain currently we have that at sign the index of method returns a number
the index of method returns a number which we're using as the index it's
which we're using as the index it's returning the index of this at sign I'm
returning the index of this at sign I'm going to increase it by one so we get
going to increase it by one so we get everything after the at sign so plus
everything after the at sign so plus one and now the at sign is removed
one and now the at sign is removed even better yet let's accept some user
even better yet let's accept some user input we'll need a scanner import
input we'll need a scanner import java.util do scanner we'll create a
java.util do scanner we'll create a scanner
scanner object scanner scanner equals new
object scanner scanner equals new scanner then we will need
scanner then we will need system.in then when we open a scanner it
system.in then when we open a scanner it is a good idea to close it when we're
is a good idea to close it when we're done with it I sometimes forget
we'll create a prompt for a user to type in their
in their email enter your email I'll use print
email enter your email I'll use print instead of print line I'm going to
instead of print line I'm going to declare my variables after our scanner
declare my variables after our scanner that's just how I like to arrange things
that's just how I like to arrange things we'll declare our email but not yet
we'll declare our email but not yet assign
assign it same thing applies with our
it same thing applies with our username and our
username and our domain we've already declared these
domain we've already declared these variables we don't need to do that again
instead of manually assigning our email we're going to use our scanner to accept
we're going to use our scanner to accept user input scanner. nextt
user input scanner. nextt line let's display our username and our
domain okay enter your email I'll make up something bro1 123@gmail.com
up something bro1 123@gmail.com here's my username
here's my username and the
and the domain we can take this a step further
domain we can take this a step further too we can check to see if our email is
too we can check to see if our email is valid we'll use some of the string
valid we'll use some of the string Methods we learned about in the last
Methods we learned about in the last video so after accepting our email we're
video so after accepting our email we're going to write an if
going to write an if statement if our email contains the at
character our email is only valid if we have this at character if it is
have this at character if it is then we'll perform all this code so
then we'll perform all this code so let's cut it then stick it within the if
let's cut it then stick it within the if statement else we will do something
statement else we will do something else let's print emails must contain
else let's print emails must contain at let's type in an email that's not
at let's type in an email that's not valid I won't include the at
sign emails must contain the at character let's try that
character let's try that again fake
again fake guy one at maybe they're using Yahoo
guy one at maybe they're using Yahoo yahoo.com so my username would be fake
yahoo.com so my username would be fake guy one the domain is
guy one the domain is yahoo.com all right everybody so that is
yahoo.com all right everybody so that is the substring method and how to create
the substring method and how to create an email slicer program the substring
an email slicer program the substring method is used to extract a portion of a
method is used to extract a portion of a string you can list one of two possible
string you can list one of two possible indices within the substring method a
indices within the substring method a starting index and an ending index we
starting index and an ending index we use the substring method on an email
use the substring method on an email then created two new substrings one of
then created two new substrings one of username and the other of domain and
username and the other of domain and well everybody that is the substring
well everybody that is the substring method in
method in Java hey everybody in this video we're
Java hey everybody in this video we're going to create a weight conversion
going to create a weight conversion program to convert a weight from pounds
program to convert a weight from pounds to kilogram or vice versa it will help
to kilogram or vice versa it will help us become more familiar with if
us become more familiar with if statements so let's get started okay
statements so let's get started okay let's get started everybody what might
let's get started everybody what might be helpful to you as a beginner when
be helpful to you as a beginner when creating a project is to use comments to
creating a project is to use comments to describe what you want to do at each
describe what you want to do at each part of your program this is also known
part of your program this is also known as pseudo code for example the first
as pseudo code for example the first thing we'll do is declare our variables
thing we'll do is declare our variables declare
message then a prompt for user input prompt for user input or
Choice we'll say option one convert lbs meaning pounds to to kgs
one convert lbs meaning pounds to to kgs kilog option two convert kgs to
kilog option two convert kgs to LBS if somebody doesn't select option
LBS if somebody doesn't select option one or two we'll use an else statement
one or two we'll use an else statement else print not a valid
else print not a valid choice so here's a rough outline of our
choice so here's a rough outline of our program and what it's going to do we'll
program and what it's going to do we'll begin at the top we'll declare any
begin at the top we'll declare any variables that we'll need so we will
variables that we'll need so we will need a scanner we'll create a scanner
need a scanner we'll create a scanner object scanner scanner equals new
object scanner scanner equals new scanner then type system.in within set
scanner then type system.in within set of parentheses if you hover over the
of parentheses if you hover over the word scanner you can import it
word scanner you can import it automatically import
automatically import java.util.scanner or otherwise you can
java.util.scanner or otherwise you can type it
type it in what are some other variables we'll
in what are some other variables we'll need double weight for the original
need double weight for the original weight double new
weight double new weight that's after we convert the
weight that's after we convert the weight we'll need to store it and int
weight we'll need to store it and int choice
choice a user is going to type in one to
a user is going to type in one to convert pounds to kilograms or two to
convert pounds to kilograms or two to convert kilograms to
convert kilograms to pounds we have our variables now we need
pounds we have our variables now we need a welcome
a welcome message I'll use a few print
message I'll use a few print statements let's say weight
statements let's say weight conversion
program one C and space this means opt one convert lbs
space this means opt one convert lbs meaning pounds to kgs
meaning pounds to kgs kilog or Choice
kilog or Choice 2 to colon space convert kilogram to
2 to colon space convert kilogram to pounds
pounds lbs then we'll prompt for a user's
Choice I'll use print instead of print line choose an option
then we'll need to store that choice variable Choice equals use our scanner
variable Choice equals use our scanner to accept user input we're accepting an
to accept user input we're accepting an integer we'll use next
integer we'll use next int let's do a test run and I will print
int let's do a test run and I will print our choice
temporarily weight conversion program one to convert pounds to kilograms or
one to convert pounds to kilograms or two to convert kilograms to pounds I'll
two to convert kilograms to pounds I'll type in one we get one
type in one we get one or
or two then we output two we can delete
two then we output two we can delete this print line statement we were just
this print line statement we were just checking to see if it
checking to see if it works okay option one if somebody
works okay option one if somebody selects option one we have to convert
selects option one we have to convert pounds to
pounds to kilograms well we'll need to check to
kilograms well we'll need to check to see if choice is one we can use an if
see if choice is one we can use an if statement for
statement for that if choice is equal to one be sure
that if choice is equal to one be sure you use double equals that is the
you use double equals that is the comparison operator we're checking if
comparison operator we're checking if these two values are equal if you use a
these two values are equal if you use a single equals that is the assignment
single equals that is the assignment operator and Java thinks you're trying
operator and Java thinks you're trying to assign one to choice so double equals
to assign one to choice so double equals for
for comparisons we're converting pounds to
comparisons we're converting pounds to kilograms we'll ask a user to enter the
kilograms we'll ask a user to enter the weight in
weight in lbs I'll use print instead of print
line we we will assign our weight equals use our scanner then use
weight equals use our scanner then use the next Double method then we will
the next Double method then we will accept a double value so once we have
accept a double value so once we have our weight we have to convert it to
our weight we have to convert it to kilograms because it's currently in
kilograms because it's currently in pounds we will assign our new weight
pounds we will assign our new weight equal to the weight our current weight
equal to the weight our current weight that
that is times
is times 0.45 3592
weight the new weight in
new weight in kgs
kgs is then we'll add our new
is then we'll add our new weight okay let's perform a test
weight okay let's perform a test run we'll type in one to convert pounds
run we'll type in one to convert pounds to kilogram enter the weight in pounds
to kilogram enter the weight in pounds what's 150 lb converted to kilog
what's 150 lb converted to kilog 68.0
68.0 388 if you would like to limit the
388 if you would like to limit the amount of digits that display after the
amount of digits that display after the decimal you can use a print F statement
decimal you can use a print F statement instead of print line so to do that
instead of print line so to do that we'll convert this to print
we'll convert this to print F where we would like to insert a value
F where we would like to insert a value or variable we'll use percent since
or variable we'll use percent since we're displaying a double we'll use f
we're displaying a double we'll use f meaning floating Point number to display
meaning floating Point number to display two digits after the decimal we'll use 0
two digits after the decimal we'll use 0 2 or 0.1 to display one digit depending
2 or 0.1 to display one digit depending on your preference replace the plus with
on your preference replace the plus with a
a comma we're inserting this variable at
comma we're inserting this variable at this location this placeholder let's
this location this placeholder let's perform that
perform that again choose an option convert pounds to
again choose an option convert pounds to kilograms enter the weight in pounds 150
kilograms enter the weight in pounds 150 is good the new weight in kilogram is
is good the new weight in kilogram is 68.4
68.4 kilg now if Choice equals 2 we're going
kilg now if Choice equals 2 we're going to convert kilog to pounds and really we
to convert kilog to pounds and really we can just copy the if statement paste it
can just copy the if statement paste it then convert
then convert it else if Choice equals 2 the user
it else if Choice equals 2 the user wants to convert kilogram to pounds
wants to convert kilogram to pounds enter the weight in
enter the weight in kilog the new formula is going to be
kilog the new formula is going to be weight time
weight time 2.24
2.24 62 the new weight in pounds lbs is our
62 the new weight in pounds lbs is our new
new weight let's try
weight let's try it choose an option we will convert
it choose an option we will convert kilograms to pounds I'm going to press
kilograms to pounds I'm going to press two enter the weight in kilogram let's
two enter the weight in kilogram let's say 68
say 68 kg the new weight in pounds is
kg the new weight in pounds is 14991
14991 lb what if somebody types in a number
lb what if somebody types in a number that's not
that's not valid so we can get rid of this comment
valid so we can get rid of this comment is use an else statement to print print
is use an else statement to print print that the user didn't select a valid
that the user didn't select a valid choice we will follow this with an lse
choice we will follow this with an lse statement we will follow else if with an
statement we will follow else if with an else statement else
else statement else print that was not a valid
choice we have options one or two if I type in three we execute the L statement
type in three we execute the L statement that was not a valid
that was not a valid choice and again like usual I'm
choice and again like usual I'm forgetting to close my scanner because I
forgetting to close my scanner because I sometimes forget to do that so at the
sometimes forget to do that so at the end of your program close your scanner
end of your program close your scanner scanner. close because you don't want to
scanner. close because you don't want to leave resources
leave resources open okay let's do one final test run
open okay let's do one final test run let's convert pounds to kilograms what's
let's convert pounds to kilograms what's 200 lb converted to
200 lb converted to kilograms 90.7
kilograms 90.7 2 all right everybody so that is a
2 all right everybody so that is a weight conversion program you can write
weight conversion program you can write using
using [Music]
[Music] Java hey everybody in this video I'm
Java hey everybody in this video I'm going to show you how we can use the
going to show you how we can use the tary operator in Java in Java the tary
tary operator in Java in Java the tary operator is a question mark followed by
operator is a question mark followed by one of two possible values here's the
one of two possible values here's the formula we check a condition then use a
formula we check a condition then use a question mark like we're asking a
question mark like we're asking a question is this condition true if it is
question is this condition true if it is we'll return a value if not we return
we'll return a value if not we return something else a different value it's a
something else a different value it's a simpler version to an if else statement
simpler version to an if else statement here's a
here's a demonstration let's say we have an
demonstration let's say we have an integer of a score score will equal 70
integer of a score score will equal 70 that's technically
that's technically passing using an if statement I will
passing using an if statement I will check if my score is greater than or
check if my score is greater than or equal to
60 if it is then we will print pass else we will
print fail so this does work with a score of 70 I have passed if
work with a score of 70 I have passed if it were 55
it were 55 well then I fail there's another way in
well then I fail there's another way in which we can write this and that is by
which we can write this and that is by using the tary
using the tary operator what we're going to do let's
operator what we're going to do let's create a variable a string variable of
create a variable a string variable of pass or
pass or fail and we're basically just following
fail and we're basically just following this formula we have our condition is
this formula we have our condition is our score greater than or equal to
our score greater than or equal to 60 question mark we're asking a question
60 question mark we're asking a question is this condition true if it is let's
is this condition true if it is let's return a string of pass colon think of
return a string of pass colon think of it like
it like otherwise will return
otherwise will return fail and then I will print pass or fail
fail and then I will print pass or fail to display it so 55 that means we fail
to display it so 55 that means we fail but if it were
but if it were 75 that means we pass by using the tary
75 that means we pass by using the tary operator it's an alternative to writing
operator it's an alternative to writing an if else statement and it can be
an if else statement and it can be simpler in many cases here's a few other
simpler in many cases here's a few other examples let's create a variable of
examples let's create a variable of number set it equal to some
number set it equal to some number using the Turner operator we will
number using the Turner operator we will check if this number is even or
check if this number is even or odd I'll create a string of even or odd
odd I'll create a string of even or odd equals our
equals our condition we can check if a number is
condition we can check if a number is even or odd by using the modulus
even or odd by using the modulus operator
operator we will take our
we will take our number modulus 2 the modulus operator
number modulus 2 the modulus operator gives you the remainder of any division
gives you the remainder of any division does 3 divide by two evenly if it does
does 3 divide by two evenly if it does that would equal
zero 3 doesn't divide by two evenly there's a remainder of one and that does
there's a remainder of one and that does not equal
not equal zero is this number divisible by two
zero is this number divisible by two we'll use the trary operator if it is
we'll use the trary operator if it is we'll return a string of even otherwise
we'll return a string of even otherwise we'll return a string of odd is my
we'll return a string of odd is my number even or
number even or odd so three is
odd so three is odd but if it were
odd but if it were four well then it's
four well then it's even here's a more practical example
even here's a more practical example let's say we're working with a
let's say we're working with a time in hours this will be in military
time in hours this will be in military time hours equals
time hours equals 13 that would be the the same as 1
13 that would be the the same as 1 p.m. I will create a string of time of
p.m. I will create a string of time of day equals we'll check if our hours is
day equals we'll check if our hours is greater than or equal to 12 if it is
greater than or equal to 12 if it is we'll return PM if not will return
we'll return PM if not will return am hours less than
am hours less than 12 tary operator is our hours less than
12 tary operator is our hours less than 12 if it is we'll return a.m.
12 if it is we'll return a.m. otherwise will return
otherwise will return p.m and then we will display the time of
p.m and then we will display the time of day 13 hours that's the same as 1:
day 13 hours that's the same as 1: p.m. yep the time is 1: p.m. or if the
p.m. yep the time is 1: p.m. or if the hours were 9 that would be
hours were 9 that would be am all right last example let's say we
am all right last example let's say we have an income or
have an income or salary income equals $60,000
let's pretend that you're a software engineer in the united states in the
engineer in the united states in the United States we have different tax
United States we have different tax brackets depending on your income this
brackets depending on your income this time we will assign a variable of tax
time we will assign a variable of tax rate equals we'll check if our
rate equals we'll check if our income is greater than or equal
income is greater than or equal to $40,000 for
$40,000 question mark turnar operator if that's true then our tax
operator if that's true then our tax rate is going to be
rate is going to be 0.25 otherwise it will be
0.15 so with our income what is the tax rate
rate 0.25 but if I changed it to
0.25 but if I changed it to 30,000 well then our tax rate would be
30,000 well then our tax rate would be 0.15 for
0.15 for 15% so that is the tary operator you
15% so that is the tary operator you follow this formula you check a
follow this formula you check a condition within a set of parentheses
condition within a set of parentheses then use the tary operator like you're
then use the tary operator like you're asking a question if this condition is
asking a question if this condition is true return this otherwise if it's false
true return this otherwise if it's false return something else and then if you
return something else and then if you would like you can assign it to a
would like you can assign it to a variable and well everybody that is the
variable and well everybody that is the tary operator in
Java all right everybody in this video we're going to create a temperature
we're going to create a temperature conversion program to convert from
conversion program to convert from Celsius to Fahrenheit or Fahrenheit to
Celsius to Fahrenheit or Fahrenheit to Celsius this is a practice project to
Celsius this is a practice project to get us more familiar using the tary
get us more familiar using the tary operator so let's get started we will be
operator so let's get started we will be accepting some user input so let's get
accepting some user input so let's get the scanner out of the way first scanner
the scanner out of the way first scanner scanner equals new scanner we need a
scanner equals new scanner we need a scanner to accept user input within the
scanner to accept user input within the set of parentheses type
set of parentheses type system.in and then I will just
system.in and then I will just automatically import this class so at
automatically import this class so at the top of your Java file you need this
the top of your Java file you need this import import
import import java.util.scanner then when you open a
java.util.scanner then when you open a scanner it is a good idea to close it at
scanner it is a good idea to close it at the end of your file when you're done
the end of your file when you're done with it because you don't want to leave
with it because you don't want to leave resources open we have our scanner to
resources open we have our scanner to accept user input let's declare some
accept user input let's declare some variables what will we need we will need
variables what will we need we will need the original temperature this will be of
the original temperature this will be of the double data type double temp we'll
the double data type double temp we'll need a new temperature let's say double
need a new temperature let's say double new temp that's after we convert it and
new temp that's after we convert it and a unit we could use Char for the unit
a unit we could use Char for the unit you know the letter F or c for
you know the letter F or c for Fahrenheit or Celsius but just to keep
Fahrenheit or Celsius but just to keep it simple I'm going to use a string
it simple I'm going to use a string because there's a built-in method of two
because there's a built-in method of two uppercase we can take the input and make
uppercase we can take the input and make it uppercase automatically just to make
it uppercase automatically just to make it simple we'll use a string rather than
it simple we'll use a string rather than a Char for the
a Char for the unit okay now we just need to get the
unit okay now we just need to get the temperature we'll need a prompt I'll use
temperature we'll need a prompt I'll use print instead of print line we will ask
print instead of print line we will ask the user to enter the
temperature we will assign the temperature temp equals scanner. next
temperature temp equals scanner. next Double because we're accepting a value
Double because we're accepting a value we're signing a variable of the double
we're signing a variable of the double data type now we need the unit is it
data type now we need the unit is it going to be Celsius or
going to be Celsius or Fahrenheit we'll need another prompt
Fahrenheit we'll need another prompt I'll use print instead of print
I'll use print instead of print line we will ask the user convert to
line we will ask the user convert to Celsius or Fahrenheit
F let's ass our unit variable use our
variable use our scanner then use the next method to get
scanner then use the next method to get the next character we'll use the next
the next character we'll use the next method to get the next
method to get the next character we don't necessarily need next
character we don't necessarily need next line we just want a single
line we just want a single character so check this out I'm going to
character so check this out I'm going to Output our temp
Output our temp and our
unit what if somebody types in a lowercase C or F so let's say the
lowercase C or F so let's say the temperature is
temperature is 75 75° F and we would like to convert it
75 75° F and we would like to convert it to Celsius I'll type lowercase C rather
to Celsius I'll type lowercase C rather than uppercase
C our unit is currently a lowercase C we can convert it to be
can convert it to be uppercase following the next method of
uppercase following the next method of our scanner where we assign our unit
our scanner where we assign our unit we're going to do something called
we're going to do something called method
method chaining we'll add another dot then use
chaining we'll add another dot then use the two uppercase method of
the two uppercase method of strings let's try that again and see if
strings let's try that again and see if it
it works
works 75 I'll type in lower case
C the two uppercase method will take that lowercase C and make it uppercase
that lowercase C and make it uppercase which is what we'll need in this next
which is what we'll need in this next section we can delete these two
section we can delete these two statements now we're going to use the
statements now we're going to use the tary
tary operator how the trary operator works is
operator how the trary operator works is that we check a
that we check a condition followed by a question mark
condition followed by a question mark like we're asking a question we will
like we're asking a question we will return some code if that condition is
return some code if that condition is true colon meaning else if it's false
true colon meaning else if it's false we'll do some other code or return some
we'll do some other code or return some other value we're going to follow this
other value we're going to follow this formula so what is our condition let's
formula so what is our condition let's check to see if our unit is equal to a c
check to see if our unit is equal to a c take our variable of
take our variable of unit use the equals method because
unit use the equals method because strings have a built-in method of
strings have a built-in method of equals does our unit equal in uppercase
equals does our unit equal in uppercase C question mark That's the tary operator
C question mark That's the tary operator we're asking a
we're asking a question if this is true that means
question if this is true that means we're trying to convert from Fahrenheit
we're trying to convert from Fahrenheit to Celsius
to Celsius the formula to do that would be the
the formula to do that would be the following we would be executing this
following we would be executing this code since it's
code since it's true take our temp subtract
true take our temp subtract 32 then multiply 5 /
32 then multiply 5 / 9 now what if our unit does not equal C
9 now what if our unit does not equal C that means we're trying to convert to
that means we're trying to convert to Fahrenheit we'll need that colon for the
Fahrenheit we'll need that colon for the next part of the
next part of the section now here's the formula to
section now here's the formula to convert from Celsius to Fahrenheit
convert from Celsius to Fahrenheit this will be the false section of the
this will be the false section of the trinary
trinary operator take our temp * 5 /
operator take our temp * 5 / 9 +
9 + 32 with the trinary operator how we've
32 with the trinary operator how we've written this code is that we're going to
written this code is that we're going to be returning a double after converting
be returning a double after converting it we need to do something with it so
it we need to do something with it so we're going to assign it to a variable
we're going to assign it to a variable our variable of new temp then we can do
our variable of new temp then we can do something with it
something with it once we have our new temperature let's
once we have our new temperature let's display it I'll perform a test run let's
display it I'll perform a test run let's print our new
print our new temp let's say it's 100° F and we're
temp let's say it's 100° F and we're going to convert to Celsius I'll type in
going to convert to Celsius I'll type in see well the temperature in Celsius is
see well the temperature in Celsius is 37.7 repeating we're going to format
37.7 repeating we're going to format this in a
this in a moment let's add a degree
moment let's add a degree symbol plus a string on Windows to add a
symbol plus a string on Windows to add a degree symbol make sure num lock is on
degree symbol make sure num lock is on hold alt then type
0176 plus our unit we're converting to let's try that
let's try that again what is 100° fah converted to
again what is 100° fah converted to Celsius
Celsius 37.7 repeating de
37.7 repeating de C to limit the amount of digits that
C to limit the amount of digits that display after the decimal we we can use
display after the decimal we we can use a print F statement let's convert our
a print F statement let's convert our print line for the new temp to be print
print line for the new temp to be print F rather than print
F rather than print line we'll add a
placeholder we're displaying a double so we need F to display one digit type 0.1
we need F to display one digit type 0.1 between the percent sign and the
between the percent sign and the F comma new
temp after our placeholder We'll add our degree symbol again I'm holding alt numb
degree symbol again I'm holding alt numb lock is on I'm typing
lock is on I'm typing 0176 then we will display the unit it's
0176 then we will display the unit it's a string percent s for
a string percent s for Strings we're inserting a new variable
Strings we're inserting a new variable we're going to comma separate them then
we're going to comma separate them then add our
add our unit and let me just close this Gap
unit and let me just close this Gap let's see what the final product
let's see what the final product is let's convert
is let's convert 30.1 this will be in Celsius to
30.1 this will be in Celsius to Fahrenheit
Fahrenheit and the temperature in Fahrenheit is
and the temperature in Fahrenheit is 48.7 De
48.7 De fahit okay everybody that is a
fahit okay everybody that is a temperature conversion program that you
temperature conversion program that you can write using the tary operator in
Java why hello there today I got to explain something called enhanced
explain something called enhanced switches in Java in Java there switches
switches in Java in Java there switches and then there's enhanced switches
and then there's enhanced switches enhanced switches are a Java 14 feature
enhanced switches are a Java 14 feature I would recommend using using enhanced
I would recommend using using enhanced switches over standard switches so what
switches over standard switches so what is a switch exactly a switch is a
is a switch exactly a switch is a replacement to using many l statements
replacement to using many l statements here's an example of us using a lot of
here's an example of us using a lot of lse if statements in this sample program
lse if statements in this sample program we have a day of the week I set mine to
we have a day of the week I set mine to be Friday with each of these if
be Friday with each of these if statements I am checking to see if the
statements I am checking to see if the day equals Monday Tuesday so on and so
day equals Monday Tuesday so on and so forth currently my day is set to
forth currently my day is set to Friday this would give me it is a
Friday this would give me it is a weekday
weekday if I set the day to be
if I set the day to be Saturday well then it is the
Saturday well then it is the weekend or Sunday let me show you the
weekend or Sunday let me show you the code it is the weekend then I have an
code it is the weekend then I have an else statement if none of the above
else statement if none of the above conditions are true for example let's
conditions are true for example let's say day is pizza day which doesn't exist
say day is pizza day which doesn't exist but it really
but it really should Pizza day is not a day this code
should Pizza day is not a day this code does work but it could be more efficient
does work but it could be more efficient we have a lot of redundancies we're
we have a lot of redundancies we're using a lot of else if statements that
using a lot of else if statements that all basically do the same
thing an improvement would be to use an enhanced switch let me demonstrate how
enhanced switch let me demonstrate how to make
to make that so let's set our day to be Monday
that so let's set our day to be Monday for example to create a switch we will
for example to create a switch we will type switch at a set of parentheses then
type switch at a set of parentheses then a set of curly
a set of curly braces it's similar to an if statement
braces it's similar to an if statement already with within the set of
already with within the set of parentheses for the switch we're going
parentheses for the switch we're going to examine a value or variable we're
to examine a value or variable we're going to examine our string of day we
going to examine our string of day we will examine this value against any
will examine this value against any matching cases the first case will be a
matching cases the first case will be a string of
string of Monday if day is equal to this value a
Monday if day is equal to this value a string of Monday we'll do
string of Monday we'll do something we'll use an arrow an arrow is
something we'll use an arrow an arrow is the arrow operator in Java think of it
the arrow operator in Java think of it as meaning do something do this if day
as meaning do something do this if day equals Monday do this code so let's
equals Monday do this code so let's print
print something let's print it is a
something let's print it is a weekday and then for fun you don't have
weekday and then for fun you don't have to but I'm going to add an
to but I'm going to add an emoji nobody likes Mondays let's be
emoji nobody likes Mondays let's be honest if day is Monday do this code
honest if day is Monday do this code let's add another case let me zoom in a
let's add another case let me zoom in a little if Case is
little if Case is Tuesday Arrow op operator meaning do
Tuesday Arrow op operator meaning do this code we will print we'll print the
this code we will print we'll print the same thing it is a
same thing it is a weekday we'll do this with the other
weekday we'll do this with the other days too I'll just copy this code then
days too I'll just copy this code then repurpose it to save some time case
repurpose it to save some time case Wednesday it is a
Wednesday it is a weekday case
weekday case Thursday it is a
Thursday it is a weekday case
weekday case Friday it is a weekday now if it's sat
Friday it is a weekday now if it's sat Saturday that means it's the
Saturday that means it's the weekend case
weekend case Saturday it is the weekend let's change
Saturday it is the weekend let's change the
weekend let's perform a test run if you're using intellig you may have These
you're using intellig you may have These Warnings it's basically saying that
Warnings it's basically saying that these sections of code are unreachable
these sections of code are unreachable we're manually setting a variable these
we're manually setting a variable these sections of code are not going to
sections of code are not going to execute so I would just ignore that for
execute so I would just ignore that for now so let's perform a test
now so let's perform a test run my day is Monday day is equal to the
run my day is Monday day is equal to the case of Monday so we do this code if it
case of Monday so we do this code if it were
Friday case Friday we do this code if Case were Saturday
well we do this code and
Sunday case Sunday so we do this code it is the
is the weekend what if we have a day that
weekend what if we have a day that doesn't exist like pizza
day well we can add a default case here's how we'll type the keyword
here's how we'll type the keyword default Arrow meaning do
default Arrow meaning do this we'll print
this we'll print our variable
our variable day plus a string of is not a
day Pizza day is not a day the default case it behaves similarly to your else
case it behaves similarly to your else statement if no above conditions are
statement if no above conditions are true then we will do
true then we will do this so what we'll do now is accept some
this so what we'll do now is accept some user input using a scanner we'll need to
user input using a scanner we'll need to create a scanner object scanner scanner
create a scanner object scanner scanner equals new scanner within the set of
equals new scanner within the set of parentheses type
parentheses type system.in and then I'm just going to
system.in and then I'm just going to automatically import this class at the
automatically import this class at the top of my Java file import
top of my Java file import java.util.scanner
java.util.scanner we'll create a prompt for a user to type
we'll create a prompt for a user to type in the
in the day enter the day of the week and I will
day enter the day of the week and I will use print instead of print line instead
use print instead of print line instead of manually assigning a variable we'll
of manually assigning a variable we'll use our scanner scanner. nextt line to
use our scanner scanner. nextt line to accept a
string okay let's try this again enter the day of the week it is
again enter the day of the week it is Tuesday it is a weekday let's try that
Tuesday it is a weekday let's try that again enter the day of the week it is
again enter the day of the week it is Saturday it is the
Saturday it is the weekend and let's make up a
weekend and let's make up a day uh let's go with taco
day uh let's go with taco day taco day is not a
day taco day is not a day we could actually improve this widg
day we could actually improve this widg even further intellig is saying we have
even further intellig is saying we have a duplicate branch in our switch we have
a duplicate branch in our switch we have two or more cases that are doing the
two or more cases that are doing the same thing we are outputting it is a
weekday we could consolidate some of these cases here's how the cases of
these cases here's how the cases of Monday Tuesday Wednesday Thursday and
Monday Tuesday Wednesday Thursday and Friday they all output the same thing so
Friday they all output the same thing so we're going to consolidate them I'll
we're going to consolidate them I'll copy one of these print statements and
copy one of these print statements and delete all of them
we can comma separate these cases so case Monday
case Monday comma
comma Tuesday
Tuesday comma
comma Wednesday
Wednesday comma
comma Thursday
Thursday comma
comma Friday then Arrow
Friday then Arrow if our case is Monday Tuesday Wednesday
if our case is Monday Tuesday Wednesday Thursday or Friday then do the following
Thursday or Friday then do the following we'll print it is a
we'll print it is a weekday now Saturday and Sunday do the
weekday now Saturday and Sunday do the same thing
same thing too let's cut one of these
too let's cut one of these lines and delete
lines and delete them case
them case Saturday comma
Saturday comma Sunday Arrow meaning do this it is the
Sunday Arrow meaning do this it is the weekend then we'll keep keep our default
weekend then we'll keep keep our default case in case there are no matches let's
case in case there are no matches let's try this
try this again enter the day of the week it is
again enter the day of the week it is Wednesday it is a
Wednesday it is a weekday it is
weekday it is Saturday it is the
Saturday it is the weekend it is Sunday it is the
weekend uh then let's go with uh Hamburger
Hamburger Day hamburger day is not a day
Day hamburger day is not a day so those are enhanced switches they're a
so those are enhanced switches they're a replacement to using many LF
replacement to using many LF statements if you find yourself using a
statements if you find yourself using a lot of lsif statements I would recommend
lot of lsif statements I would recommend using a switch instead but not just any
using a switch instead but not just any switch an enhanced switch which is a
switch an enhanced switch which is a Java 14 feature that you should know
Java 14 feature that you should know about and well everybody those are
about and well everybody those are enhanced switches in
Java what is going on everybody in this video we're going to create a simple
video we're going to create a simple calculator program using what we've
calculator program using what we've learned with enhanced switches this is
learned with enhanced switches this is meant to be more of a practice project
meant to be more of a practice project let's get started the first thing we'll
let's get started the first thing we'll need is a scanner we will create a
need is a scanner we will create a scanner object scanner scanner equals
scanner object scanner scanner equals new scanner within the set of
new scanner within the set of parentheses type
parentheses type system.in and then when you open a
system.in and then when you open a scanner it is a good idea to close it
scanner it is a good idea to close it when you're done with
when you're done with it scanner. close then be sure to import
it scanner. close then be sure to import the class at the top of your Java file
the class at the top of your Java file make sure you have this import import
make sure you have this import import java.util.scanner
java.util.scanner what are the different variables we'll
what are the different variables we'll need a user is going to type in two
need a user is going to type in two numbers and an operator such as a plus
numbers and an operator such as a plus for addition minus for subtraction so on
for addition minus for subtraction so on and so forth the first variable will be
and so forth the first variable will be up the double data type double num
up the double data type double num one double num two then an operator this
one double num two then an operator this will be a Char Char operator
will be a Char Char operator and a result double
result there's going to be one more variable but we'll fill that in later so
variable but we'll fill that in later so we'll stick with these four for now
we'll stick with these four for now we'll prompt a user to type in the first
we'll prompt a user to type in the first number followed by an operator than the
number followed by an operator than the second
second number here's how we can write
number here's how we can write that let's ask the user to enter the
that let's ask the user to enter the first number and I will use print
first number and I will use print instead of print line
we will assign num one equal to use our scanner to get user
scanner to get user input next
Double then we need the operator we will use a print
use a print statement enter n
statement enter n operator we'll have Plus for addition
operator we'll have Plus for addition minus for subtraction an asterisk for
minus for subtraction an asterisk for multiplication a for slash for division
multiplication a for slash for division let's add one more let's add a carrot
let's add one more let's add a carrot this will raise a base to a given
this will raise a base to a given power feel free to add more if you would
power feel free to add more if you would like but we'll just stick with these
like but we'll just stick with these five a user is going to enter in a
five a user is going to enter in a character one of these operators
character one of these operators hopefully we will assign our variable of
hopefully we will assign our variable of operator equal to
operator equal to scanner.
next the next method will give you a string we can method chain the Char at
string we can method chain the Char at method to return a single character when
method to return a single character when a user types in something just give me
a user types in something just give me the first character this will also
the first character this will also convert it to be a character rather than
convert it to be a character rather than keep it a
keep it a string so ideally our operator is going
string so ideally our operator is going to be a plus a minus an asterisk a
to be a plus a minus an asterisk a forward slash or a
forward slash or a carrot then we need num two we can just
carrot then we need num two we can just copy these two lines paste them change
copy these two lines paste them change first to be second and num one to be num
first to be second and num one to be num two we have our two numbers and our
two we have our two numbers and our operator we have to determine what the
operator we have to determine what the operator is we can use an enhanced
operator is we can use an enhanced switch for that we will create a
switch for that we will create a switch within the set of
switch within the set of parentheses we are examining our
parentheses we are examining our operator we're examining our operator
operator we're examining our operator against any matching cases the first
against any matching cases the first case will be a plus sign and these cases
case will be a plus sign and these cases are going to be within single quotes not
are going to be within single quotes not double quotes because we're working with
double quotes because we're working with a character not a
a character not a string with our switch if our operator
string with our switch if our operator is a plus character we're going to write
is a plus character we're going to write an arrow meaning do
an arrow meaning do this we will take our variable of
this we will take our variable of result set it equal to be num one that's
result set it equal to be num one that's the first number plus num two
the first number plus num two that will be the case for addition then
that will be the case for addition then we have
we have subtraction case minus Arrow do this
subtraction case minus Arrow do this assign our result equal to num one minus
assign our result equal to num one minus num
num 2 multiplication would be
2 multiplication would be case a character vaster risk arrow take
case a character vaster risk arrow take our result equals num one * num
two now for division we have a forward
we have a forward slash arrow take our result equals num
slash arrow take our result equals num one divided by num
one divided by num two now with division if somebody
two now with division if somebody divides by zero we'll return to this
divides by zero we'll return to this case later and make it a little more
case later and make it a little more sophisticated where we check to see if
sophisticated where we check to see if num 2 is zero I would like for us to get
num 2 is zero I would like for us to get a solid foundation first for this
a solid foundation first for this program so if somebody would like to
program so if somebody would like to raise a base to a given power we will
raise a base to a given power we will use the
carrot we will assign our result equal to now we're going to use the math
to now we're going to use the math class the power method of the math class
class the power method of the math class we can raise a base to a given power we
we can raise a base to a given power we will raise num one to the power of num
two let's perform a test run just to be sure that it
sure that it works I'm going to display our result
works I'm going to display our result after the
after the switch so Java is giving us a warning
switch so Java is giving us a warning that variable result might not have been
that variable result might not have been initialized that's because it's possible
initialized that's because it's possible there's no matching
there's no matching cases and we would be keeping our result
cases and we would be keeping our result uninitialized so to clear that up when
uninitialized so to clear that up when we declare our variable we can also
we declare our variable we can also assign it I'll just set it to be
assign it I'll just set it to be zero let's perform a test
run enter the first number let's do 3.14 enter an operator let's do addition
3.14 enter an operator let's do addition and the second number
and the second number 1.1 the result is
1.1 the result is 4.24 let's do subtraction
4.24 let's do subtraction 3.14 minus 1.1 which gives us
3.14 minus 1.1 which gives us 2.04
2.04 multiplication
multiplication 3.14 times let's do
3.14 times let's do two
divided by two that gives us
two that gives us 1.57 then we have power what is
1.57 then we have power what is 3 to the power of
3 to the power of three that is
three that is 27 3 * 3 is 9 * 3 is 27 3 ^ of
27 3 * 3 is 9 * 3 is 27 3 ^ of 3 we have one potential issue though
3 we have one potential issue though what if somebody divides by zero here's
what if somebody divides by zero here's what happens
what happens what is
what is 3.14 /
3.14 / 0 we get the output of
0 we get the output of infinity here's how we could prevent
infinity here's how we could prevent that underneath the case where we do
that underneath the case where we do division we'll write a few lines rather
division we'll write a few lines rather than just one but we're going to enclose
than just one but we're going to enclose them within a set of curly
them within a set of curly braces then I'm going to cut this line
braces then I'm going to cut this line of
of code within this case we'll write an if
code within this case we'll write an if statement we'll
statement we'll check
check if num 2 is equal to
if num 2 is equal to zero that's because we can't normally
zero that's because we can't normally divide by zero if it is then let's print
divide by zero if it is then let's print cannot divide by
zero else we'll assign our result of num one
else we'll assign our result of num one / by num 2 we'll execute the L statement
/ by num 2 we'll execute the L statement if num 2 doesn't equal zero because if
if num 2 doesn't equal zero because if it did this would be true and we execute
it did this would be true and we execute this code instead let's try that
this code instead let's try that again what is
again what is 3.14 /
3.14 / 0 cannot divide by
0 cannot divide by zero however we still do display a
zero however we still do display a result and that is by using this print
result and that is by using this print statement what if somebody types in an
statement what if somebody types in an operator that doesn't exist 3.14
operator that doesn't exist 3.14 I'm going to type in pizza for the
I'm going to type in pizza for the operator type in I don't know
operator type in I don't know one well we still display a result so
one well we still display a result so let's modify this program let's display
let's modify this program let's display a result only if we have a valid
a result only if we have a valid operator because right now we don't
operator because right now we don't Pizza is not a valid
operator let's add a Boolean variable of valid
valid operation I will set this to be true
operation I will set this to be true from the
beginning if somebody attempts to divide by zero I'm going to take our valid
by zero I'm going to take our valid operation variable and set it to be
operation variable and set it to be false because we do not want to continue
false because we do not want to continue and display the
result we're going to add a default case the default case will be the
following so I'm going to write two lines of code for the default
lines of code for the default case let's
case let's output invalid
operator then we will take our Boolean variable of valid operation and set it
variable of valid operation and set it to be
to be false so this is what our switch looks
false so this is what our switch looks like feel free to pause the video if you
like feel free to pause the video if you would like a moment to look it
would like a moment to look it over within our case of division we do
over within our case of division we do have a few lines of code same thing
have a few lines of code same thing applies with the default
applies with the default case we're only going to print the
case we're only going to print the result if our Boolean of valid operation
result if our Boolean of valid operation is
is true if valid operation is equal to true
true if valid operation is equal to true but really we can just shorten this to
but really we can just shorten this to if valid
if valid operation then we'll print the
operation then we'll print the result then we don't necessarily need an
result then we don't necessarily need an else
else statement because we're already printing
statement because we're already printing either invalid operator or cannot divide
either invalid operator or cannot divide by zero
by zero okay let's run this one final
okay let's run this one final time
time 3.14 plus
3.14 plus 2.1 is
2.1 is 5.24
5.24 3.14
3.14 minus 1.1 is
3.14 time 2.1 is 6594
2.1 is 6594 4
4 3.14 okay 3.14 / 0 Let's see what
3.14 okay 3.14 / 0 Let's see what happens cannot divide by zero and we do
happens cannot divide by zero and we do not display the result because our
not display the result because our equation is invalid which is good we
equation is invalid which is good we don't want to display the result we're
don't want to display the result we're displaying a type of error message
instead let's raise 4 to the
4 to the power of two which gives us
power of two which gives us 16 now let's type in an operator that
16 now let's type in an operator that doesn't exist
3.14 Pizza
Pizza 69 invalid operator that's because Pizza
69 invalid operator that's because Pizza is not a valid
is not a valid operator all right everybody that is a
operator all right everybody that is a calculator program that you can write
calculator program that you can write the purpose of this program is to more
the purpose of this program is to more or less help us with enhanced switch
or less help us with enhanced switch statements depending on the operator we
statements depending on the operator we can perform one of a few operations
can perform one of a few operations we've also learned that your cases can
we've also learned that your cases can take up more than one line if you would
take up more than one line if you would like and well everybody that is a
like and well everybody that is a calculator program in
Java yo yo yo in today's video I'm going to explain logical operators in Java
to explain logical operators in Java logical operators they allow us to check
logical operators they allow us to check or modify more than one condition
or modify more than one condition there's and or not we'll discuss and
there's and or not we'll discuss and first which is represented by two Amper
first which is represented by two Amper Sands let's declare a variable of
Sands let's declare a variable of temperature temp meaning temperature I
temperature temp meaning temperature I will set this to be 20 I would like to
will set this to be 20 I would like to check to see if my temperature Falls
check to see if my temperature Falls within a certain range well to do that I
within a certain range well to do that I could use the and logical operator we
could use the and logical operator we can check more than one
can check more than one condition so first I would like to see
condition so first I would like to see if my
if my temp is less than or equal to 30 30°
temp is less than or equal to 30 30° C and if the temp is greater than or
C and if the temp is greater than or equal to zero
equal to zero we have two conditions this time if this
we have two conditions this time if this is true and this is true then do this
is true and this is true then do this code so let's output the
code so let's output the following if our temperature Falls
following if our temperature Falls within this range we'll
within this range we'll output the weather is good and for fun
output the weather is good and for fun I'll let a smiley face cuz why not okay
I'll let a smiley face cuz why not okay let's see how this works the temperature
let's see how this works the temperature is currently 20 20° C
is currently 20 20° C the weather is good if the temperature
the weather is good if the temperature were 40 40°
were 40 40° C well we don't do
C well we don't do anything this condition evaluated to be
anything this condition evaluated to be false but this one is true our
false but this one is true our temperature is greater than or equal to
temperature is greater than or equal to zero that is true but this one is false
zero that is true but this one is false and using the and logical operator both
and using the and logical operator both conditions must be true in order for
conditions must be true in order for this entire statement to be true
this entire statement to be true since only one of them was true where
since only one of them was true where temp is greater than or equal to zero we
temp is greater than or equal to zero we don't execute this code the and logical
don't execute this code the and logical operator is used to check more than one
operator is used to check more than one condition we can add as many as we would
condition we can add as many as we would like to this time let's create a
like to this time let's create a variable of is sunny this will be a
variable of is sunny this will be a Boolean Boolean is sunny is it sunny
Boolean Boolean is sunny is it sunny outside I will set that to be
outside I will set that to be true not only are we going to check to
true not only are we going to check to see if our temperature is within a
see if our temperature is within a certain range we're also going to check
certain range we're also going to check and is sunny is this true so now we are
and is sunny is this true so now we are linking three different conditions all
linking three different conditions all three must be true so if all three are
three must be true so if all three are true we'll outut the following it is
true we'll outut the following it is sunny
outside let's set is sunny to be false and then we are going to set our
and then we are going to set our temperature to not
temperature to not 240
20 these two conditions are true but this one is false so we don't do any of
this one is false so we don't do any of it we skip over it with the and logical
it we skip over it with the and logical operator all conditions must be
operator all conditions must be true if is sunny we're true
true if is sunny we're true then well then we execute this code the
then well then we execute this code the temperature Falls within this range this
temperature Falls within this range this is true and this this is true and this
is true and this this is true and this is true all three conditions are true so
is true all three conditions are true so we execute this code the weather is good
we execute this code the weather is good and it is sunny
and it is sunny outside we check more than one condition
outside we check more than one condition and both must be true there's also the
and both must be true there's also the not logical operator it's a little
not logical operator it's a little different how it works is that it gives
different how it works is that it gives you the opposite you can check to see if
you the opposite you can check to see if something is not true let's add an elive
something is not true let's add an elive statement we're going to copy these
statement we're going to copy these three conditions but make one change
three conditions but make one change we're going to precede is Sunny with the
we're going to precede is Sunny with the not logical operator represented by an
not logical operator represented by an exclamation
exclamation point it checks the opposite we are
point it checks the opposite we are checking to see if something is not true
checking to see if something is not true is our temperature less than or equal to
is our temperature less than or equal to 30 and greater than or equal to zero and
30 and greater than or equal to zero and is it not
is it not Sunny so if something is normally false
Sunny so if something is normally false using the not logical operator it
using the not logical operator it becomes true if it's normally true it
becomes true if it's normally true it becomes false it gives you the opposite
becomes false it gives you the opposite for a Boolean value
for a Boolean value basically if the weather is good but
basically if the weather is good but it's not Sunny that must mean it's
it's not Sunny that must mean it's cloudy it is cloudy outside then I'll
cloudy it is cloudy outside then I'll add an emoji of a
cloud the temperature is good but we'll set is sunny to be
false the weather is good but it is cloudy
good but it is cloudy outside the temperature Falls within
outside the temperature Falls within this
this range and it is not
range and it is not Sunny the not logical operator checks to
Sunny the not logical operator checks to see if something is not true then we
see if something is not true then we have the or logical operator represented
have the or logical operator represented by two vertical bars or is similar to
by two vertical bars or is similar to the and logical operator however only
the and logical operator however only one condition needs to be true that are
one condition needs to be true that are linked by the or logical operator with
linked by the or logical operator with and both must be true let's say our
and both must be true let's say our temperature is really cold it is -10°
temperature is really cold it is -10° C but it is sunny
outside we actually don't end up doing anything we skip over the if statement
anything we skip over the if statement and the else if statement let's add
and the else if statement let's add another LF
another LF statement we're going to check to see if
statement we're going to check to see if our temperature is really hot or really
our temperature is really hot or really cold we will check if our temp is
cold we will check if our temp is greater than 30
greater than 30 or using two vertical bars temp is less
or using two vertical bars temp is less than
than zero then we'll
bad if our temperature is -10 the weather is bad with the or
-10 the weather is bad with the or logical operator at least one condition
logical operator at least one condition must be true this condition was false
must be true this condition was false but this one was true so we execute this
but this one was true so we execute this code because using the or logical
code because using the or logical operator at least one condition needs to
operator at least one condition needs to be
be true or if the temperature was 35 35°
true or if the temperature was 35 35° C this time this condition was true but
C this time this condition was true but this one was false so we execute this
this one was false so we execute this code all right let's go over another
code all right let's go over another example we're going to use these logical
example we're going to use these logical operators to validate a username when
operators to validate a username when somebody tries to set a
somebody tries to set a username so in this project we'll need a
username so in this project we'll need a scanner scanner scanner equals new
scanner scanner scanner equals new scanner we're going to type
scanner we're going to type system.in then import this
system.in then import this class then be sure to close your scanner
class then be sure to close your scanner at the end of the file scanner.
close our username has a few rules I'll add these as comments
rules I'll add these as comments username must be between 4 through 12
characters username must not
not contain
contain spaces or
underscores we'll create a string variable of
variable of username we'll create a prompt to have a
username we'll create a prompt to have a user enter in a
username enter your new username I'll use print instead of print
username I'll use print instead of print line we will assign our username using
line we will assign our username using the scanner username equals scanner.
the scanner username equals scanner. next
line we'll write a condition to check if our username is between 4 to 12
our username is between 4 to 12 characters we're going to check if our
characters we're going to check if our username is under four characters or
username is under four characters or greater than 12 characters we'll check
greater than 12 characters we'll check that within an if
that within an if statement if our username
statement if our username use the length method to return the
use the length method to return the length of this string if the length of
length of this string if the length of our username is less than four use the
our username is less than four use the or logical operator or our
or logical operator or our username the length of it using the
username the length of it using the length method is greater than 12 that
length method is greater than 12 that means our username is too short or too
means our username is too short or too long we'll output the following username
long we'll output the following username must be between 4 through 12 characters
must be between 4 through 12 characters let's perform a test
let's perform a test run enter your new username I'll type in
run enter your new username I'll type in something that's less than four
something that's less than four characters username must be between 4 to
characters username must be between 4 to 12
12 characters let's type in a really long
characters let's type in a really long username I'll just make up something
username I'll just make up something username must be between 4 to 12
username must be between 4 to 12 characters let's type in something
characters let's type in something actually within that
range oh and then we need to add an lse state statement because I
state statement because I forgot else we will
forgot else we will print
print welcome plus
username welcome whatever your username is the second part of this assignment is
is the second part of this assignment is that we need to check to make sure that
that we need to check to make sure that there are no spaces or underscores
there are no spaces or underscores within our username after the if
within our username after the if statement We'll add an L if statement to
statement We'll add an L if statement to check
check that using the contains method of
that using the contains method of strings we can check if a string
strings we can check if a string contains a certain character with our
contains a certain character with our username we will use the contains method
username we will use the contains method does our username contain any
does our username contain any spaces or does our
spaces or does our username
username contains any
contains any underscores if so we'll output the
underscores if so we'll output the following user usame must
following user usame must not contain spaces or
underscores let's perform another test run type in your first and last name
run type in your first and last name including a space username must not
including a space username must not contain spaces or
contain spaces or underscores this time I will use an
underscores this time I will use an underscore to separate the first and
underscore to separate the first and last
last name username must not contain spaces or
name username must not contain spaces or underscores let's type in a usern name
underscores let's type in a usern name that follows the
that follows the rules that seems to
rules that seems to work so that is the or logical operator
work so that is the or logical operator if at least one condition is true then
if at least one condition is true then the entire statement is true and we
the entire statement is true and we execute it all right everybody so those
execute it all right everybody so those are logical operators and checks more
are logical operators and checks more than one condition both must be true or
than one condition both must be true or checks more than one condition at least
checks more than one condition at least one needs to be true not not is a little
one needs to be true not not is a little different it checks if something is not
different it checks if something is not true basically does the inverse and well
true basically does the inverse and well everybody those are logical operators in
Java what is going on everybody in this video I need to explain while Loops in
video I need to explain while Loops in Java if I could summarize a while loop
Java if I could summarize a while loop in one sentence a while loop will repeat
in one sentence a while loop will repeat some code Forever while some condition
some code Forever while some condition remains true first I'll give you a
remains true first I'll give you a demonstration using an if statement then
demonstration using an if statement then we'll convert it to be a while loop and
we'll convert it to be a while loop and we'll see how it's useful we'll need to
we'll see how it's useful we'll need to accept user input in this demonstration
accept user input in this demonstration I will create a scanner I'm pretty sure
I will create a scanner I'm pretty sure we know how to create one by
we know how to create one by now be assured to import the scanner
now be assured to import the scanner class import java.util.scanner then be
class import java.util.scanner then be sure to close your scanner because I
sure to close your scanner because I always forget to do
always forget to do that all right we are going to create a
that all right we are going to create a string of
string of name I'll use an if statement to check
name I'll use an if statement to check to see if my name is
to see if my name is empty if name use the is empty method
empty if name use the is empty method now Java wants us to assign this name
now Java wants us to assign this name right away okay so I'm going to go ahead
right away okay so I'm going to go ahead and initialize it we can initialize it
and initialize it we can initialize it with an empty space if our name is empty
with an empty space if our name is empty which it will be we will prompt the user
which it will be we will prompt the user to enter your name I'll use print
to enter your name I'll use print instead of print line to keep it on the
instead of print line to keep it on the same line then we will assign our
same line then we will assign our variable of name name equals scanner.
variable of name name equals scanner. next
next line after we escape the if statement
line after we escape the if statement we'll output our name let's say hello
we'll output our name let's say hello Plus
Plus name so this program will work but
name so this program will work but there's one issue what if I don't type
there's one issue what if I don't type in anything when I enter my name I'll
in anything when I enter my name I'll just hit
just hit enter well we still continue with the
enter well we still continue with the rest of the program the output is hello
rest of the program the output is hello we don't display a name because we
we don't display a name because we didn't type in anything how can we
didn't type in anything how can we prevent people from doing stuff like
prevent people from doing stuff like this skipping
this skipping prompts well we could use a while loop
prompts well we could use a while loop rather than an if statement replace if
rather than an if statement replace if with while
with while what we're doing is while this condition
what we're doing is while this condition remains true continue this code Forever
remains true continue this code Forever Until this condition is no longer true
Until this condition is no longer true let's try that
let's try that again enter your name I'm just going to
again enter your name I'm just going to hit enter enter your name no enter your
hit enter enter your name no enter your name no enter your name no okay I give
name no enter your name no okay I give up I'll type in my name then we escape
up I'll type in my name then we escape the while loop hello your
the while loop hello your name so that's why a while loop Loop is
name so that's why a while loop Loop is useful we can repeat some code possibly
useful we can repeat some code possibly Forever at times we may not want a user
Forever at times we may not want a user to continue without doing something a
to continue without doing something a while loop would be really helpful for
while loop would be really helpful for that they would be stuck until this
that they would be stuck until this condition is no longer true at the end
condition is no longer true at the end of your while loop we go back to the
of your while loop we go back to the beginning to check the condition if the
beginning to check the condition if the condition is no longer true then we
condition is no longer true then we escape the while loop and move on with
escape the while loop and move on with the rest of the program there's one
the rest of the program there's one thing you should be cautious of though
thing you should be cautious of though and that is an infinite Loop let me give
and that is an infinite Loop let me give you a
you a demonstration with our while loop if we
demonstration with our while loop if we have a condition that we can't change
have a condition that we can't change from within the loop that's called an
from within the loop that's called an infinite Loop so let's say while the
infinite Loop so let's say while the number one is equal to 1 even my IDE
number one is equal to 1 even my IDE intellig is giving me a warning that 1
intellig is giving me a warning that 1 is equal to 1 is not updated inside the
is equal to 1 is not updated inside the loop I would not recommend following me
loop I would not recommend following me along for this part your computer might
along for this part your computer might freeze up but I'm going to print
freeze up but I'm going to print help I'm stuck in a loop
help I'm stuck in a loop within this while loop I have no way to
within this while loop I have no way to change it from inside of it so we're
change it from inside of it so we're going to be stuck in this while loop
going to be stuck in this while loop forever here's a
demonstration we're just going to print this code
this code forever let's check back later one
forever let's check back later one eternity later it's still going we're
eternity later it's still going we're stuck in a loop this may happen to you
stuck in a loop this may happen to you if you have some condition that you
if you have some condition that you can't change within your while loop
can't change within your while loop you'll need some way to update your
you'll need some way to update your condition
let me give you another example again we'll need our
scanner we're going to pretend that we're playing a game for a user to quit
we're playing a game for a user to quit they have to press the q key we will
they have to press the q key we will declare a string of
declare a string of response we'll use a while
response we'll use a while loop now for my condition for us to be
loop now for my condition for us to be able to escape the while
able to escape the while loop our response I'm going to use the
loop our response I'm going to use the not logical
not logical operator
operator equals a capital Q and this will be a
equals a capital Q and this will be a string so while our response does not
string so while our response does not equal Q we continue the loop forever in
equal Q we continue the loop forever in order for somebody to escape this game
order for somebody to escape this game they have to press Q to quit Java wants
they have to press Q to quit Java wants me to assign this variable right away
me to assign this variable right away and initialize it so I'll do so we don't
and initialize it so I'll do so we don't want our variable to be empty when we
want our variable to be empty when we use it to check a condition
use it to check a condition then intellig is giving us another
then intellig is giving us another warning that our response is not updated
warning that our response is not updated inside the loop if we don't update it
inside the loop if we don't update it we'll be stuck in an infinite
we'll be stuck in an infinite Loop let's pretend that we're playing a
Loop let's pretend that we're playing a game you are playing a
game then we'll output
output press Q to quit
then we will need to update our response response equals use our scanner for
response equals use our scanner for Single Character we can use
Single Character we can use next in case somebody types in a
next in case somebody types in a lowercase que we'll follow this method
lowercase que we'll follow this method with the two uppercase
with the two uppercase method if a user was to type in a
method if a user was to type in a lowercase Q we'll convert it to be an
lowercase Q we'll convert it to be an uppercase q so that it
uppercase q so that it matches once we escape the while loop
matches once we escape the while loop we'll
we'll print you have have quit the
game okay let's perform a test run you are playing a game press Q to
run you are playing a game press Q to quit no
quit no yes
yes okay as long as our response does not
okay as long as our response does not equal Q we are still playing our
equal Q we are still playing our imaginary
game in order for us to quit to escape the while loop we have to press Q to
the while loop we have to press Q to quit I will press q and we escape the
quit I will press q and we escape the loop you have quit the
loop you have quit the game while our response using the not
game while our response using the not logical operator while our response does
logical operator while our response does not equal Q continue the loop forever
not equal Q continue the loop forever let's go over another example we'll ask
let's go over another example we'll ask a user for their
a user for their age int age I will set this to be zero
age int age I will set this to be zero right
right away we'll prompt a user to enter in
away we'll prompt a user to enter in their age enter your
their age enter your age we will assign our age
age we will assign our age variable AG equal scanner. next
variable AG equal scanner. next int then at the end of this program I
int then at the end of this program I will
will print you are our variable
print you are our variable age plus years
old let's say I would like to prevent somebody from typing in a negative
somebody from typing in a negative number like -1 you are ne1 years old
number like -1 you are ne1 years old well we could use a while loop to
well we could use a while loop to reprompt the user before displaying the
reprompt the user before displaying the result so after we assign our age once
result so after we assign our age once let's use a while
let's use a while loop while age is less than zero we'll
loop while age is less than zero we'll output the
following your age can't be negative then we'll reprompt the user again we
then we'll reprompt the user again we can just copy these two lines and then
can just copy these two lines and then paste them within the while loop we'll
paste them within the while loop we'll ask the user to enter in their age again
ask the user to enter in their age again and reassign
and reassign it if we keep on typing negative
it if we keep on typing negative numbers we can't escape the while
numbers we can't escape the while loop we're stuck until we type in
loop we're stuck until we type in something that's
valid you are 21 years old that's a valid
valid number from the beginning if I type in
number from the beginning if I type in something that's valid we don't enter
something that's valid we don't enter the while loop at all it is possible to
the while loop at all it is possible to skip over
skip over it we check the condition of a while
it we check the condition of a while loop before entering it if we type in a
loop before entering it if we type in a number that's valid let's say ages
number that's valid let's say ages 25 we check the condition it's false
25 we check the condition it's false from the beginning so we don't enter the
from the beginning so we don't enter the while loop at all we skip over it and go
while loop at all we skip over it and go straight to the end in this program we
straight to the end in this program we only get caught in the while loop if we
only get caught in the while loop if we type in user input that's not
type in user input that's not valid there's a variation of the while
valid there's a variation of the while loop known as a do while loop we do some
loop known as a do while loop we do some code first and then check the
code first and then check the condition if I was to convert this code
condition if I was to convert this code to be a do while loop I would cut the
to be a do while loop I would cut the while part do this code then check the
while part do this code then check the condition at the
condition at the end this is how the program would run
end this is how the program would run now it's going to be a little bit
different your age can't be negative enter your age I am years old your age
enter your age I am years old your age can't be negative enter your age you are
can't be negative enter your age you are whatever your age is years old so with
whatever your age is years old so with the do while loop we do this code first
the do while loop we do this code first and then check the condition at the end
and then check the condition at the end where it's different compared to a
where it's different compared to a standard while loop is that with the
standard while loop is that with the standard while
standard while loop you may not enter the while loop at
loop you may not enter the while loop at all if this condition is false but with
all if this condition is false but with the do while loop you always do this
the do while loop you always do this code at least once and then check the
code at least once and then check the condition at the end let's go over one
condition at the end let's go over one last example with the do while loop
last example with the do while loop we'll prompt a user to type in a number
we'll prompt a user to type in a number that's between a certain range we will
that's between a certain range we will have int number and I will assign this
have int number and I will assign this to be zero right
to be zero right away let's use a basic while loop
away let's use a basic while loop first
first while our number is less than one we'll
while our number is less than one we'll use the or logical operator to check or
use the or logical operator to check or if our number is greater than 10
if our number is greater than 10 then do
this prompt the user to enter a number between 1 through
10 then we will assign our variable of number equals use our scanner use the
number equals use our scanner use the next int
next int method and then at the end we will print
method and then at the end we will print our
our number you picked
plus number so let's run this our number is
number so let's run this our number is set to
zero enter a number between 1 and 10 let's do negative
let's do negative 1 11 -2 one
1 11 -2 one kajillion I think I broke it okay I'll
kajillion I think I broke it okay I'll type in something that's valid like five
type in something that's valid like five you picked
you picked five rather than check the the condition
five rather than check the the condition from the beginning we could check it at
from the beginning we could check it at the end so let's convert the while loop
the end so let's convert the while loop to a do while loop do this code once and
to a do while loop do this code once and then check the
similarly so do this code once check the condition at the
condition at the end all right everybody so those are
end all right everybody so those are while Loops they allow you to execute
while Loops they allow you to execute some code possibly forever while some
some code possibly forever while some condition remains true they're really
condition remains true they're really useful when accepting user input because
useful when accepting user input because the user might not type in something
the user might not type in something that's valid and you have to keep on
that's valid and you have to keep on repr prompting them that's one good use
repr prompting them that's one good use there's two variations of while Loops a
there's two variations of while Loops a standard while loop and a do while
standard while loop and a do while loop it depends if you want to check the
loop it depends if you want to check the condition before entering the loop and
condition before entering the loop and well everybody those are while Loops in
well everybody those are while Loops in Java
hello everybody in today's video we're going to create a number guessing game
going to create a number guessing game using Java let's get started in this
using Java let's get started in this program we'll be using random numbers
program we'll be using random numbers we'll need to create a random object
we'll need to create a random object random random equals new
random random equals new random then import this class so at the
random then import this class so at the top of our Java file import
top of our Java file import java.util random this random object can
java.util random this random object can Generate random numbers for us we'll
Generate random numbers for us we'll also accept user input we'll need a
also accept user input we'll need a scanner scanner scanner equals new
scanner scanner scanner equals new scanner then within the set of
scanner then within the set of parentheses type
parentheses type system.in then import this class as well
system.in then import this class as well import
import java.util.scanner we have a random
java.util.scanner we have a random object to Generate random numbers and a
object to Generate random numbers and a scanner object to accept user
scanner object to accept user input what are the different variables
input what are the different variables we'll need we'll need the following an
we'll need we'll need the following an integer to hold our
integer to hold our guess so let's say we're going to guess
guess so let's say we're going to guess a random number between 1 and 100 we'll
a random number between 1 and 100 we'll use the scanner to accept an integer and
use the scanner to accept an integer and place it within this variable of
place it within this variable of guess for example the guess might be
guess for example the guess might be 50 we need to keep track of the amount
50 we need to keep track of the amount of attempts it took a user to get the
of attempts it took a user to get the correct number int attempts we'll assign
correct number int attempts we'll assign these
these later and we'll need a random number int
later and we'll need a random number int random number
random number let's go ahead and assign this right
let's go ahead and assign this right away to generate a random number we're
away to generate a random number we're going to use our random
going to use our random object use the next int method of a
object use the next int method of a random object within this method we can
random object within this method we can list two numbers a range if I would like
list two numbers a range if I would like a number between let's say 1 and 10 my
a number between let's say 1 and 10 my two numbers would be 1 comma 11 the
two numbers would be 1 comma 11 the first number is inclusive the second
first number is inclusive the second number is
number is exclusive let's perform a test run of a
exclusive let's perform a test run of a random number I just want to be sure
random number I just want to be sure that it's generating correctly when
that it's generating correctly when writing a program it is a good idea to
writing a program it is a good idea to test your code every once in a while
test your code every once in a while just to be sure that everything is
just to be sure that everything is working so we should get random numbers
working so we should get random numbers between 1 and 10 1 10 5 8 good enough a
between 1 and 10 1 10 5 8 good enough a random number stores a random number
random number stores a random number after generating
after generating it let's create a welcome message let's
it let's create a welcome message let's say number guessing
say number guessing game we will prompt the
game we will prompt the user guess a
user guess a number
number between let's start with 1 through 10
between let's start with 1 through 10 later on we'll increase it to
100 now we'll need a while loop but not just any while loop we'll create a do
just any while loop we'll create a do while loop so do this code once while
while loop so do this code once while this condition remains true and let me
this condition remains true and let me zoom in a little
zoom in a little bit so what's our condition going to be
bit so what's our condition going to be we're going to continue playing this
we're going to continue playing this game while our
game while our guess does not equal our random number
guess does not equal our random number we'll keep on playing until we get the
we'll keep on playing until we get the random number exclamation point equals
random number exclamation point equals means not equal so if our guess does not
means not equal so if our guess does not equal our random number this return
equal our random number this return turns true then we want to keep playing
turns true then we want to keep playing while our guess doesn't equal the random
while our guess doesn't equal the random number within this do while
number within this do while loop will prompt the user to enter in
loop will prompt the user to enter in their guess I'm going to use print line
their guess I'm going to use print line instead of print for guess a number
instead of print for guess a number between 1 and
between 1 and 10 now we'll prompt the user to enter a
10 now we'll prompt the user to enter a number enter a guess enter a
number enter a guess enter a guess for this I'll use print instead of
guess for this I'll use print instead of print line we will assign Our Guest
print line we will assign Our Guest variable equal to use our scanner use
variable equal to use our scanner use the next int
method we're also keeping track the amount of attempts it takes a user to
amount of attempts it takes a user to get the correct
get the correct number so we can increment attempts by
number so we can increment attempts by adding
Plus+ and let's go ahead and initialize attempts we'll set that to be zero
temporarily outside the while loop I'm going to
going to print you have
print you have one my random number right now is only
one my random number right now is only between 1 and 10 I'm just going to keep
between 1 and 10 I'm just going to keep guessing until we get the right
number so I'll just start with one and go all the way to
10 the answer was nine we escaped the wild
wild Loop so we know that this is working
Loop so we know that this is working currently one thing this program is
currently one thing this program is missing is that we'll want to give a
missing is that we'll want to give a user a clue if their guess is too low or
user a clue if their guess is too low or too high because we have no way to
too high because we have no way to tell I'm just typing in random numbers
tell I'm just typing in random numbers and I have no clue how close I am to the
and I have no clue how close I am to the actual number that we need to
actual number that we need to guess let's get rid of this print
guess let's get rid of this print statement we were using it for testing
statement we were using it for testing purposes within the do while loop we'll
purposes within the do while loop we'll write an if statement we'll check if our
write an if statement we'll check if our guess is less than our random
guess is less than our random number that means we guess too
number that means we guess too low if that's the case we'll output the
low if that's the case we'll output the following two low try
again else if our guess is greater than our random
if our guess is greater than our random number that means we guess too
number that means we guess too high too high try
high too high try again if our guess isn't lower than our
again if our guess isn't lower than our random number and our guess isn't
random number and our guess isn't greater than our random number that
greater than our random number that means our guess must equal the random
means our guess must equal the random number so if that's the case we would be
number so if that's the case we would be executing this lse statement because the
executing this lse statement because the preceding two conditions would be false
preceding two conditions would be false that means we have the right answer the
that means we have the right answer the right guess so we'll output the
correct the let me zoom out the number
out the number was plus our random
number and then we'll display the amount of attempts it
of attempts it took number of attempts
took number of attempts plus our variable of attempts after each
plus our variable of attempts after each guess we increment it by
guess we increment it by one the last thing I'm forgetting is to
one the last thing I'm forgetting is to close my scanner because I always forget
close my scanner because I always forget to close
to close it scanner.
it scanner. close okay let's perform a test run
close okay let's perform a test run we're only guessing a number between 1
we're only guessing a number between 1 and 10
and 10 currently I'll guess something right in
currently I'll guess something right in the middle five too low try again the
the middle five too low try again the random number we have to guess should be
random number we have to guess should be between 5 and 10 then I'll go with seven
between 5 and 10 then I'll go with seven too low 8 too low nine too low okay it
too low 8 too low nine too low okay it must be 10 then correct the number was
must be 10 then correct the number was 10 number of attempts it took
10 number of attempts it took five we're going to improve this code
five we're going to improve this code now what if we would like the numbers 1
now what if we would like the numbers 1 through 100 this time well we could make
through 100 this time well we could make this program a little more flexible
this program a little more flexible instead of hardcoding these numbers
instead of hardcoding these numbers within the next integer method we'll
within the next integer method we'll Place some variables here instead we
Place some variables here instead we will create int Min equals whatever you
will create int Min equals whatever you want the minimum to be let's say one int
want the minimum to be let's say one int Max I will set the max to be 100 let's
Max I will set the max to be 100 let's replace these two
replace these two numbers the first one will be Min comma
numbers the first one will be Min comma Max so these variables behave as if they
Max so these variables behave as if they were these numbers within this range the
were these numbers within this range the second number is exclusive so TW include
second number is exclusive so TW include 100 I'm going to add +
100 I'm going to add + one give me the numbers between 1 and
one give me the numbers between 1 and 100 within this print statement let's
100 within this print statement let's use print F
use print F instead we'll replace these numbers with
instead we'll replace these numbers with the format specifier a placeholder we
the format specifier a placeholder we will display an integer so we need D
will display an integer so we need D let's do the same thing with 10
d uh let's do comma Min comma Max and then add a new line at the
end let's do one final run so now we're guessing a number
run so now we're guessing a number between one and 100 I'll guess something
between one and 100 I'll guess something right in the middle too high try again
right in the middle too high try again our numberers going to be between 1 and
our numberers going to be between 1 and 50 then 25 too high 12 too high 6 too
50 then 25 too high 12 too high 6 too high three
high three too low between three and six four
too low between three and six four correct the number was four the number
correct the number was four the number of attempts it took six
of attempts it took six attempts all right everybody so that is
attempts all right everybody so that is a number guessing game that you can
a number guessing game that you can create using
Java hi there everybody so in this video I'm going to explain four Loops in Java
I'm going to explain four Loops in Java a four Loop is similar to a while loop
a four Loop is similar to a while loop however a for Loop executes some code a
however a for Loop executes some code a certain amount of times a for Loop is
certain amount of times a for Loop is different from a while loop a while loop
different from a while loop a while loop could execute an infinite amount of
could execute an infinite amount of times until its condition is no longer
times until its condition is no longer true so with for Loops we want to do
true so with for Loops we want to do something a certain amount of times to
something a certain amount of times to create a for Loop type four parentheses
create a for Loop type four parentheses curly braces now within the condition of
curly braces now within the condition of the for Loop there's three statements
the for Loop there's three statements each is separated with a
each is separated with a semicolon we have statement one
semicolon we have statement one statement two and statement three the
statement two and statement three the first statement is used for ini ization
first statement is used for ini ization we can create a counter to keep track of
we can create a counter to keep track of how many times we have iterated this
how many times we have iterated this Loop basically we're declaring a
Loop basically we're declaring a variable a counter this will be int now
variable a counter this will be int now a common practice for a for Loop is to
a common practice for a for Loop is to create a counter named I meaning index
create a counter named I meaning index in I equal Z or some other number I is
in I equal Z or some other number I is going to be used as a counter within
going to be used as a counter within this Loop also known as a loop control
this Loop also known as a loop control variable the second statement is a
variable the second statement is a condition when do we want to
condition when do we want to stop maybe we would like to execute some
stop maybe we would like to execute some code 10 times we'll continue this loop
code 10 times we'll continue this loop as long as I is less than
as long as I is less than 10 now the third statement the third
10 now the third statement the third statement is the step we can increment
statement is the step we can increment our counter of I by One or another
our counter of I by One or another number or even decrement after each
number or even decrement after each iteration let's increase I by One
iteration let's increase I by One i++ let's perform a test run I'm just
i++ let's perform a test run I'm just going to print the word
pizza so we should execute this code 10 times using this for Loop 1 2 3 4 5 6 7
times using this for Loop 1 2 3 4 5 6 7 8 9
8 9 10 so a for Loop is good if you want to
10 so a for Loop is good if you want to repeat some code a certain amount of
repeat some code a certain amount of times but there's a little bit of setup
times but there's a little bit of setup you have to do we'll need some sort of
you have to do we'll need some sort of index or counter a condition in which
index or counter a condition in which you want to stop and you'll need to
you want to stop and you'll need to update the counter
update the counter one way or another
one way or another initialization condition update we can
initialization condition update we can also print this index of I rather than
also print this index of I rather than printing the word Pizza let's print I to
printing the word Pizza let's print I to see what we're working with during the
see what we're working with during the first iteration I is zero after our Loop
first iteration I is zero after our Loop is complete we increment I by One our
is complete we increment I by One our counter so we have 0 1 2 3 4 5 6 7 8 9
counter so we have 0 1 2 3 4 5 6 7 8 9 We're looping 10 times
We're looping 10 times but we set I to be zero to begin with if
but we set I to be zero to begin with if I were to set I to be 1 and I want to
I were to set I to be 1 and I want to iterate 10 times I could say while I is
iterate 10 times I could say while I is less than or equal to
less than or equal to 10 so now we're starting at 1 and
10 so now we're starting at 1 and counting up to
counting up to 10 we can even decrement
10 we can even decrement to let's set I to be 10 we'll continue
to let's set I to be 10 we'll continue the loop as long as I is greater than
the loop as long as I is greater than zero to decrement we'll set I to be
zero to decrement we'll set I to be minus
minus minus now we're starting at 10 and
decrementing but we're still looping 10 times let's go back to the
beginning using the update statement we can even increment by a certain number
can even increment by a certain number instead of incrementing by one let's
instead of incrementing by one let's increment by two and see what
increment by two and see what happens so this time we start at one and
happens so this time we start at one and update our counter of I two each time or
update our counter of I two each time or even three i+ equal
even three i+ equal 3 1 4 7
3 1 4 7 10 we can decrement by a given
10 we can decrement by a given number let's set I to be 10 we'll
number let's set I to be 10 we'll continue this loop as long as I is
continue this loop as long as I is greater than zero and we will decrement
greater than zero and we will decrement our step we will decrement by 2 i - = 2
our step we will decrement by 2 i - = 2 now we're starting at 10 and
now we're starting at 10 and decrementing by two or even three IUS =
decrementing by two or even three IUS = 3
10741 for this next example we're going to accept user input again we'll need a
scanner import the scanner class and close your scanner at the end
we'll create a prompt enter how many times you want to
Loop I'll create a variable of Max Max will equal use our scanner use the next
will equal use our scanner use the next int
int method and now we're going to create a
method and now we're going to create a loop a for Loop
statements each separated with a semicolon we'll need an index or counter
semicolon we'll need an index or counter to keep track of how many times we have
to keep track of how many times we have looped let's say in I equals
looped let's say in I equals 0 for the next statement what's our
0 for the next statement what's our condition we want to continue as long as
condition we want to continue as long as I is less than the max I is less than
I is less than the max I is less than our Max variable
our Max variable then increment I by
else let's try this how many times do you want to Loop let's Loop five
you want to Loop let's Loop five times 1 2 3 4
times 1 2 3 4 5 again we set I to be zero so that's
5 again we set I to be zero so that's why we're beginning with
why we're beginning with zero if you would rather begin with one
zero if you would rather begin with one we can set I to be 1 then the condition
we can set I to be 1 then the condition would be I is less than or equal to Max
would be I is less than or equal to Max let's try that again let's Loop six
let's try that again let's Loop six times 1 2 3 4 5
times 1 2 3 4 5 6 all right now we're going to create a
6 all right now we're going to create a mini
mini project we'll create a program to
project we'll create a program to simulate a
countdown perhaps we have a variable of int
int start let's start at 10 we're counting
start let's start at 10 we're counting down from
down from 10 then we'll create a for
10 then we'll create a for Loop we will set our index of I equal to
Loop we will set our index of I equal to our
our start our start variable behaves as if
start our start variable behaves as if it was the number
it was the number 10 we'll continue as long as I is
10 we'll continue as long as I is greater than zero then we will decrement
greater than zero then we will decrement by one with IUS
by one with IUS minus during each iteration let's just
minus during each iteration let's just print
print I then when we escape the the for Loop
I then when we escape the the for Loop let's print happy New
let's print happy New Year kind of like it's a countdown to a
Year kind of like it's a countdown to a new year here's what we have
currently we start at 10 count down to one then display happy New Year if you
one then display happy New Year if you would like we can use the thread class
would like we can use the thread class and have our program sleep for about 1
and have our program sleep for about 1 second between each
second between each Loop here's how you can do that after
Loop here's how you can do that after printing I this is a little Advan Java
printing I this is a little Advan Java at this level you don't need to
at this level you don't need to understand how this works but we're
understand how this works but we're going to use the thread class called The
going to use the thread class called The Sleep Method then pass in an amount of
Sleep Method then pass in an amount of milliseconds in which we would like to
milliseconds in which we would like to sleep 1,000
sleep 1,000 milliseconds now Java wants us to add
milliseconds now Java wants us to add the
the following Java wants this method of main
following Java wants this method of main to throw this exception if our thread is
to throw this exception if our thread is interrupted this is intermediate Java we
interrupted this is intermediate Java we will need the section of code in order
will need the section of code in order for our program to sleep after you
for our program to sleep after you finish this lesson be sure to remove
finish this lesson be sure to remove throws interrupted exception we'll no
throws interrupted exception we'll no longer need it print I then our program
longer need it print I then our program is going to sleep for 1 second 1,000
is going to sleep for 1 second 1,000 milliseconds all right and here's our
milliseconds all right and here's our mini
mini project 10 9 8 7 6 5 4 3 2 one Happy New
project 10 9 8 7 6 5 4 3 2 one Happy New Year
Year let's modify this program a little bit
let's modify this program a little bit now we'll use a scanner to accept user
now we'll use a scanner to accept user input scanner scanner equals new
input scanner scanner equals new scanner we have already imported the
scanner we have already imported the class with start we're going to accept
class with start we're going to accept some user
some user input but we'll need a
input but we'll need a prompt how many seconds to countown
from we will assign start to be use our scanner then use the next int method
again let's say I would like to count down from
20 and it looks like it's working I'll fast forward the video till we get to
fast forward the video till we get to the
the end 3 2
end 3 2 1 happy New
1 happy New Year so those are four Loops we can
Year so those are four Loops we can execute some code a certain amount of
execute some code a certain amount of times it's very similar to a while loop
times it's very similar to a while loop in fact there's a lot of overlap where
in fact there's a lot of overlap where you could use either a for Loop or a
you could use either a for Loop or a while loop use a for Loop if you want to
while loop use a for Loop if you want to do something a limited amount of times
do something a limited amount of times and well everybody those are four Loops
and well everybody those are four Loops in
Java I have a pretty short video for you today we're going to discuss two
today we're going to discuss two important keywords when it comes to
important keywords when it comes to Loops break and continue break is used
Loops break and continue break is used to break out of a loop continue skips
to break out of a loop continue skips the current iteration of a loop think of
the current iteration of a loop think of the break keyword as the stop button on
the break keyword as the stop button on a remote continue would be similar to
a remote continue would be similar to skip with break we're stopping with
skip with break we're stopping with continuing we're skipping let me give
continuing we're skipping let me give you a
you a demonstration let's create a for Loop
demonstration let's create a for Loop that will iterate 10 times let's say in
that will iterate 10 times let's say in I equals 0 will continue as long as I is
I equals 0 will continue as long as I is less than
less than 10 then increment I by 1 during each
10 then increment I by 1 during each iteration I'll just print I then add a
iteration I'll just print I then add a space here's what we
space here's what we got we have the numbers 0 through 9 so
got we have the numbers 0 through 9 so let's say when we reach five I would
let's say when we reach five I would like to break out of the loop we're
like to break out of the loop we're going to stop it well I could add an if
going to stop it well I could add an if statement let's
statement let's say if I is equal to 5 then we will use
say if I is equal to 5 then we will use the break keyword
the break keyword and break out of the loop
and break out of the loop entirely here's what
entirely here's what happens once we hit five we break out of
happens once we hit five we break out of the loop previously we continued all the
the loop previously we continued all the way until
way until 9 now with the continue keyword we don't
9 now with the continue keyword we don't break out of the loop we just skip the
break out of the loop we just skip the current iteration like a skip button on
current iteration like a skip button on a remote this time let's use continue
a remote this time let's use continue rather than
rather than break and we'll see the differences
break and we'll see the differences between the two
now since we're using continue the number five is missing we skipped that
number five is missing we skipped that specific cycle of the loop and went back
specific cycle of the loop and went back to the beginning that's why five is
to the beginning that's why five is missing between four and six but we
missing between four and six but we still continue to the end when working
still continue to the end when working with loops if you ever need to break out
with loops if you ever need to break out you can use the break keyword to skip
you can use the break keyword to skip the occurrent iteration you can use
the occurrent iteration you can use continue and well everybody that is both
continue and well everybody that is both the break and continue keywords in Java
the break and continue keywords in Java hello again friends today I'm going to
hello again friends today I'm going to explain nested Loops in Java a nested
explain nested Loops in Java a nested Loop is really just a loop inside of
Loop is really just a loop inside of another loop you often see nested Loops
another loop you often see nested Loops within a matrix or matrices or when we
within a matrix or matrices or when we reach the topic of data structures and
reach the topic of data structures and algorithms they might not come up for a
algorithms they might not come up for a while yeah this can be any combination
while yeah this can be any combination of for Loops or while Loops any kind of
of for Loops or while Loops any kind of loop inside of another loop let me give
loop inside of another loop let me give you a
you a demonstration let's say I would like to
demonstration let's say I would like to print the numbers 1 through N9 I can do
print the numbers 1 through N9 I can do that pretty easily with a for Loop so we
that pretty easily with a for Loop so we will create a for loop I will set an
will create a for loop I will set an index of I equal to 1 we'll continue
index of I equal to 1 we'll continue this loop as long as I is less than or
this loop as long as I is less than or equal to 9 then I will increment I by
equal to 9 then I will increment I by One during each iteration I will display
One during each iteration I will display I so this will print the
I so this will print the numbers 1- N9 or if you prefer you can
numbers 1- N9 or if you prefer you can have it all on the same l line by using
have it all on the same l line by using print instead of print line then it
print instead of print line then it would look something like
would look something like this 1 2 3 4 5 6 7 8 9 you can even
this 1 2 3 4 5 6 7 8 9 you can even separate them with the space after
separate them with the space after printing our index of I let's print a
printing our index of I let's print a space
space character and now the output looks
character and now the output looks something like
something like this what if you would like to do this
this what if you would like to do this code three times let's say print the
code three times let's say print the numbers 1 through 9 three
numbers 1 through 9 three times well you could copy and paste this
times well you could copy and paste this for
for Loop then do that two additional
Loop then do that two additional times so we have the numbers 1 through 9
times so we have the numbers 1 through 9 three
three times to put each row on a new line can
times to put each row on a new line can use an empty print line
statement then it would look something like this a
like this a matrix we seem to be repeating our code
matrix we seem to be repeating our code a lot in programming we like to follow
a lot in programming we like to follow the dry principle don't repeat yourself
the dry principle don't repeat yourself if you don't have to
if you don't have to instead why don't we create a for Loop
instead why don't we create a for Loop and stick this for Loop inside of that
and stick this for Loop inside of that Loop let's create a for Loop to iterate
Loop let's create a for Loop to iterate three times I will create an index of I
three times I will create an index of I equal to 1 we'll continue as long as I
equal to 1 we'll continue as long as I is less than or equal to three then
is less than or equal to three then increment I by One all we're going to do
increment I by One all we're going to do is take our code including the for Loop
is take our code including the for Loop and stick it within this other for Loop
and stick it within this other for Loop do pay attention to the
do pay attention to the indentation but we have we have one
indentation but we have we have one problem we're reusing this index of I
problem we're reusing this index of I you can see that Java is already giving
you can see that Java is already giving us a warning here's what
us a warning here's what happens variable I is already defined in
happens variable I is already defined in method
method main if we have a loop inside of another
main if we have a loop inside of another loop we can't use the same
loop we can't use the same index a common naming convention for a
index a common naming convention for a nested Loop is to use an index of J
nested Loop is to use an index of J rather than
rather than I because J comes next in the alphabet
I because J comes next in the alphabet after I
after I instead of printing I we're going to
instead of printing I we're going to print
print J let's see how this works and here's
J let's see how this works and here's our Matrix of data we're printing our
our Matrix of data we're printing our index of J three
times after escaping the nested for Loop we have a print line statement here if I
we have a print line statement here if I were to get rid of
were to get rid of that we'll print the numbers 1 through 9
that we'll print the numbers 1 through 9 three times all on the same
three times all on the same line let's put that back in
line let's put that back in nested Loops are really good when you're
nested Loops are really good when you're working with a matrix of data nested
working with a matrix of data nested Loops come up pretty often in the topic
Loops come up pretty often in the topic of data structures and algorithms
of data structures and algorithms because we have to Loop over sets of
because we have to Loop over sets of data now we're going to cover a mini
data now we're going to cover a mini project we're going to create a matrix
project we're going to create a matrix of a symbol that a user is going to type
of a symbol that a user is going to type in a user will set the rows and columns
in a user will set the rows and columns for this Matrix we'll declare the
for this Matrix we'll declare the following variables int
following variables int rows int
rows int columns and and Char
symbol we'll need a scanner so let's declare that we'll need a scanner
declare that we'll need a scanner scanner scanner equals new
scanner scanner equals new scanner within the set of parentheses
scanner within the set of parentheses type
type system.in let's be sure to import this
system.in let's be sure to import this class of scanner at the top of our Java
class of scanner at the top of our Java file and close the scanner when we're
file and close the scanner when we're done with it scanner.
close we're going to accept some user input a user is going to specify the
input a user is going to specify the rows the columns and the symbol we're
rows the columns and the symbol we're going to
going to use let's create some
use let's create some prompts enter the
prompts enter the number of rows I'll use print instead of
number of rows I'll use print instead of print line we will assign our variable
print line we will assign our variable of
of rows equal to use our scanner use the
rows equal to use our scanner use the next int
next int method then let's do this with columns
method then let's do this with columns enter the number of
columns columns equals scanner. nextend and the symbol we're going to
use enter the symbol to use we will assign our symbol equal to
use we will assign our symbol equal to scanner.
scanner. nextt and we can use the chart at method
give me the character at index of zero let's create a for Loop for the
zero let's create a for Loop for the columns
first let me zoom in we're going to set in
in we're going to set in I we can set it equal to
I we can set it equal to zero we'll continue as long as I is less
zero we'll continue as long as I is less than our columns whatever the user types
than our columns whatever the user types in then increment I by One
in then increment I by One during each
during each iteration I'll use print instead of
iteration I'll use print instead of print line we will print our
print line we will print our symbol let's perform a test
symbol let's perform a test run enter the rows it doesn't matter we
run enter the rows it doesn't matter we didn't set up the rows yet uh for the
didn't set up the rows yet uh for the columns let's do
columns let's do eight enter the symbol to use Let's
eight enter the symbol to use Let's do let's do a dollar sign that'd be
do let's do a dollar sign that'd be cool we have the column set set up
cool we have the column set set up currently we should have eight dollar
currently we should have eight dollar signs 1 2 3 4 5 6 7 8 we need to repeat
signs 1 2 3 4 5 6 7 8 we need to repeat this for Loop for as many rows as we
this for Loop for as many rows as we have so we're going to stick this Loop
have so we're going to stick this Loop within another
loop with our nested Loop let's replace our index of I with j
for the outer for Loop we will create a new index of I equal to zero we'll
new index of I equal to zero we'll continue this as long as I is less than
continue this as long as I is less than the rows the number of rows that a user
the rows the number of rows that a user types in then increment I by
types in then increment I by One let's perform another test
One let's perform another test run let's say I would like three rows of
run let's say I would like three rows of six and I will use an at
six and I will use an at sign so these are all on the same line
sign so these are all on the same line we should have a total of
we should have a total of 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$501 that seems to have worked let's show our balance our balance is now
$49.99 the last step is to exit and display a goodby
message let's print the following thank
following thank you have a nice
you have a nice day just so the user knows that they
day just so the user knows that they have exited the
have exited the program and for fun I'm going to add
program and for fun I'm going to add some text decoration some
some text decoration some separators not necessary but I think
separators not necessary but I think it'll look
nice all right let's run this one last time banking program enter your choice I
time banking program enter your choice I will show our balance we have 0 I will
will show our balance we have 0 I will make a deposit I will deposit
make a deposit I will deposit $11,000 show our balance we have
$11,000 show our balance we have $1,000 I will
$1,000 I will withdraw let's withdraw a single penny
withdraw let's withdraw a single penny 0.01 show our balance we now have
0.01 show our balance we now have $999.99
$999.99 sense I will press for to exit and we
sense I will press for to exit and we exit thank you have a nice
exit thank you have a nice day all right everybody that is a Java
day all right everybody that is a Java banking program that you can write as a
beginner hey there everybody in this video we're going to create a dice
video we're going to create a dice rolling program a user is going to type
rolling program a user is going to type in a number of dice they would like to
in a number of dice they would like to roll based on the roll of each die we
roll based on the roll of each die we will displace masy art then at the end
will displace masy art then at the end we will give the user a total the sum of
we will give the user a total the sum of all the dice that they have rolled so if
all the dice that they have rolled so if that sounds good to you let's begin as a
that sounds good to you let's begin as a beginner it might be helpful to you to
beginner it might be helpful to you to break down a large project into smaller
break down a large project into smaller steps let's list the order of steps
steps let's list the order of steps we're going to take we will Begin by
we're going to take we will Begin by declaring our
declaring our variables declare
variables declare variables then we need to get the number
variables then we need to get the number of Dice from the
of Dice from the user after we have the number of dice
user after we have the number of dice let's check to see if it's greater than
let's check to see if it's greater than zero we don't want somebody rolling
zero we don't want somebody rolling negative dice check if number of
negative dice check if number of dice is greater than
dice is greater than zero we will roll all the
dice get the total or the sum you could say the final
total or the sum you could say the final part of this project we will display the
part of this project we will display the asy art of
asy art of dice all right here's a rough outline of
dice all right here's a rough outline of our project the first step is to declare
our project the first step is to declare our
our variables we're accepting user input so
variables we're accepting user input so we'll need a scanner scanner scanner
we'll need a scanner scanner scanner equals new
equals new scanner type
scanner type system.in import this class import
system.in import this class import java.util.scanner and then close our
java.util.scanner and then close our scanner when we're done with it scanner.
scanner when we're done with it scanner. close we'll be working with random
close we'll be working with random numbers we'll need a random object to
numbers we'll need a random object to Generate random numbers random random
Generate random numbers random random equals new random
equals new random import the
import the class import java. u. random we'll need
class import java. u. random we'll need a number of dice the user is going to
a number of dice the user is going to fill this in int num of dice how many
fill this in int num of dice how many dice are we
dice are we rolling and a total int total we'll sum
rolling and a total int total we'll sum up all the dice for a
up all the dice for a total all right now we need to get the
total all right now we need to get the number of Dice from the user we'll need
number of Dice from the user we'll need some input but we'll create a prompt
some input but we'll create a prompt first enter
first enter the number of dice to
the number of dice to roll I'll use print rather than print
roll I'll use print rather than print line we will assign our variable of
line we will assign our variable of number of dice number of dice we will
number of dice number of dice we will use our scanner to accept some user
use our scanner to accept some user input we are looking for an integer
input we are looking for an integer we'll use the next int method of our
we'll use the next int method of our scanner scanner. next
scanner scanner. next in now we need to to check to see if the
in now we need to to check to see if the number of dice number of dice is greater
number of dice number of dice is greater than
than zero so let's take care of that we'll
zero so let's take care of that we'll use an if statement to check
use an if statement to check that if num of dice is greater than zero
that if num of dice is greater than zero then we'll roll some
then we'll roll some dice we'll get to that
dice we'll get to that momentarily else we will print the
following let's say number of dice must be greater than
dice must be greater than zero within our if statement let's say
zero within our if statement let's say just
just temporarily you
temporarily you roll the dice okay we're doing a test
roll the dice okay we're doing a test run enter the number of dice to roll
run enter the number of dice to roll let's say I try and roll zero dice
let's say I try and roll zero dice number of dice must be greater than zero
number of dice must be greater than zero let's try this again let's say I roll
let's try this again let's say I roll three
three Dice and then we're just printing a test
Dice and then we're just printing a test message
message you rolled the dice okay we know that
you rolled the dice okay we know that that works we can delete this print
that works we can delete this print statement we no longer need it we were
statement we no longer need it we were just testing
just testing it now we actually need to roll all the
it now we actually need to roll all the dice we'll take care of that within our
dice we'll take care of that within our if statement if the number of dice is
if statement if the number of dice is greater than zero then we will roll the
greater than zero then we will roll the dice we're going to create a for Loop
dice we're going to create a for Loop that will iterate once based on the
that will iterate once based on the number of dice we have so let's create a
number of dice we have so let's create a for
for Loop for in I will be our index in I
Loop for in I will be our index in I equals z we will continue as long as I
equals z we will continue as long as I is less than our number of
is less than our number of dice then increment our index of I by
dice then increment our index of I by One during each
One during each cycle within this for loop we're going
cycle within this for loop we're going to generate a random number I will
to generate a random number I will create a local variable of r r will
create a local variable of r r will equal now we'll use a random object to
equal now we'll use a random object to generate a random number a random number
generate a random number a random number between 1 and six we will use the next
between 1 and six we will use the next int method of our random object
int method of our random object we will specify our range 1 through 7
we will specify our range 1 through 7 the first number is inclusive the second
the first number is inclusive the second number is exclusive this will give us a
number is exclusive this will give us a random number between 1 and six
random number between 1 and six then once we have our roll let's print
then once we have our roll let's print it
it temporarily let's print you rolled colon
temporarily let's print you rolled colon space plus our local variable of Ro
let's say we would like to roll four dice you rolled five you rolled five you
dice you rolled five you rolled five you rolled one you rolled two then we'll add
rolled one you rolled two then we'll add these numbers together for a sum or
these numbers together for a sum or total let's take our
total let's take our total total equals our total plus our
total total equals our total plus our roll and this is within the for Loop so
roll and this is within the for Loop so Java does want us to initialize this
Java does want us to initialize this variable so set total equal to zero when
variable so set total equal to zero when you declare it so total equals total
you declare it so total equals total whatever it currently is in this case
whatever it currently is in this case zero plus roll we can shorten this too
zero plus roll we can shorten this too we could just say total plus equals roll
we could just say total plus equals roll we'll use the augmented assignment
we'll use the augmented assignment operator for
operator for addition then when we escape the for
addition then when we escape the for Loop we will print the
Loop we will print the total let's say total colon space plus
total let's say total colon space plus our variable of total let's do a test
our variable of total let's do a test run I Will Roll three dice we have 3 2 2
run I Will Roll three dice we have 3 2 2 for a total of seven 3 5 7 okay we know
for a total of seven 3 5 7 okay we know that that
that that works we have rolled all the dice and
works we have rolled all the dice and get the
get the total now here comes the hard part we're
total now here comes the hard part we're going to display some ASI art based on
going to display some ASI art based on the result of each die that is
the result of each die that is rolled so we're going to declare a
rolled so we're going to declare a method to take care of that for
method to take care of that for us let's do so outside of the main
us let's do so outside of the main method
method we will create a static method that's
we will create a static method that's not going to return anything the return
not going to return anything the return type is void let's name this method
type is void let's name this method print
print D D is the singular version of the word
D D is the singular version of the word dice we're going to set up one parameter
dice we're going to set up one parameter int roll what did we roll we're going to
int roll what did we roll we're going to call this method before we display the
call this method before we display the output of you rolled whatever the RO
output of you rolled whatever the RO is we will call the method of printing
is we will call the method of printing die and pass in our
die and pass in our roll it's going to be a number between 1
roll it's going to be a number between 1 and
and six let's head back to our print die
six let's head back to our print die method within the print die method we're
method within the print die method we're going to create some asky art the asky
going to create some asky art the asky art is going to be made of strings let's
art is going to be made of strings let's create a string of dice one equals now
create a string of dice one equals now instead of a standard string that takes
instead of a standard string that takes up one line we're going to create a
up one line we're going to create a multi-line string we need a triple set
multi-line string we need a triple set of double quotes
anything between these two lines is a multi-line string it's within here that
multi-line string it's within here that we're going to create some dice some asy
we're going to create some dice some asy art of dice so this will be an art
art of dice so this will be an art lesson today let's start with seven
lesson today let's start with seven dashes on the next line we'll create a
dashes on the next line we'll create a vertical bar and on the other side we
vertical bar and on the other side we need a vertical bar
need a vertical bar too I'm going to shift these dashes over
too I'm going to shift these dashes over by one same thing with the vertical bar
by one same thing with the vertical bar we need a another set of vertical
we need a another set of vertical bars another
bars another set and then we can copy our dashes
set and then we can copy our dashes again so we should have a shape like
again so we should have a shape like this right in the middle we're going to
this right in the middle we're going to add a bullet point the easiest way to do
add a bullet point the easiest way to do this is to pull up the charm map
this is to pull up the charm map application so if you hold windows and
application so if you hold windows and type R you can look up charm map hit
type R you can look up charm map hit enter if you scroll all the way down to
enter if you scroll all the way down to the bottom and up a little bit
it there should be a bullet point let's select it copy it close
point let's select it copy it close character
character map and paste that bullet point or
map and paste that bullet point or otherwise you can find it from someplace
otherwise you can find it from someplace else online let's print it just
else online let's print it just once I'm just going to print dice
once I'm just going to print dice one let's do a test run I'm just going
one let's do a test run I'm just going to roll one dice and this isn't going to
to roll one dice and this isn't going to be accurate right away
be accurate right away but we do have an asky art of a
but we do have an asky art of a one-sided
dice then we need dice two really we can copy everything for dice one paste it
copy everything for dice one paste it change dice one to dice two and move
change dice one to dice two and move this bullet point
this bullet point around so this is Dice two then we need
around so this is Dice two then we need dice
dice three dice
three dice three there will be a bullet right in
three there will be a bullet right in the middle
the middle dice
four we need the bullets in each corner and none in the center that's
corner and none in the center that's dice
dice four dice
five we'll have a bullet point right in the middle along with the corners and
the middle along with the corners and dice
six we have two rows of bullet points and those are the dice that we
and those are the dice that we need now we'll create an enhanced
switch what are we examining so going back to our
examining so going back to our parameters right here we're examining
parameters right here we're examining the role that we pass in it's going to
the role that we pass in it's going to be a number 1 through six we'll examine
be a number 1 through six we'll examine our role against matching
our role against matching cases if roll matches a case of one
cases if roll matches a case of one we'll do this
we'll do this we will print rather than print
we will print rather than print line dice
string if roll matches a case of two we will print dice
will print dice two if Case is three we will print dice
two if Case is three we will print dice three four if Case is four print dice
three four if Case is four print dice four
five print dice five and six print dice
six print dice six and a default case we might as well
six and a default case we might as well add
add one if there are no matches we'll print
one if there are no matches we'll print the
the following we'll say invalid
following we'll say invalid roll all right and that's it let's run
roll all right and that's it let's run this enter the number of dice to roll
this enter the number of dice to roll I'll roll three
I'll roll three Dice and here's what we got I rolled a
Dice and here's what we got I rolled a six a two and a
six a two and a six all right everybody so that is a
six all right everybody so that is a dice rolling program that you can make
dice rolling program that you can make using
Java what is going on everybody in this video I'm going to discuss arrays in
video I'm going to discuss arrays in Java an array is a collection of values
Java an array is a collection of values of the same data type as a beginner it
of the same data type as a beginner it might be helpful to think of an array as
might be helpful to think of an array as a variable that can store more than one
a variable that can store more than one value it's a little more complicated
value it's a little more complicated than that but that might be a good way
than that but that might be a good way to think of it let me give you a
to think of it let me give you a demonstration suppose we have a string
demonstration suppose we have a string variable a fruit pick a fruit I will
variable a fruit pick a fruit I will pick an
pick an apple and then you know we can print our
apple and then you know we can print our variable of
variable of fruit which would give me an
fruit which would give me an Apple well what if I told you that this
Apple well what if I told you that this variable can store more than one value
variable can store more than one value if we were to turn it into an array
if we were to turn it into an array here's how after the data type of our
here's how after the data type of our variable add a set of straight brackets
variable add a set of straight brackets enclose any values within a set of curly
enclose any values within a set of curly braces and there we go we now have an
braces and there we go we now have an array we have an array of
array we have an array of strings this array can store more than
strings this array can store more than one value but they all have to be the
one value but they all have to be the same data type in this case strings
same data type in this case strings let's add some more fruit let's add an
let's add some more fruit let's add an orange a
orange a banana and a coconut
banana and a coconut the name of your array should be
the name of your array should be descriptive of what it contains let's
descriptive of what it contains let's say fruits instead of
say fruits instead of fruit technically in the English
fruit technically in the English language fruit would still be plural but
language fruit would still be plural but by adding an S it's more descriptive
by adding an S it's more descriptive that it contains more than one value I
that it contains more than one value I know English is a weird language at
know English is a weird language at times if I was to print my array of
times if I was to print my array of fruits here's the
fruits here's the result while we get a memory address
result while we get a memory address arrays fall under the category of a
arrays fall under the category of a reference data type if we access the
reference data type if we access the name of our array we're given a memory
name of our array we're given a memory address each value within an array is
address each value within an array is known as an element to access an element
known as an element to access an element we have to indicate an index number
we have to indicate an index number after our array name let's add a set of
after our array name let's add a set of straight brackets and then an index
straight brackets and then an index number as is the case with many things
number as is the case with many things in programming toxis the first of
in programming toxis the first of something it usually has an index of
something it usually has an index of zero that applies to arrays as well
zero that applies to arrays as well print our array of fruits at index of
print our array of fruits at index of zero that's going to give you the first
zero that's going to give you the first element of Apple for the next element
element of Apple for the next element that would be an index of
that would be an index of one which is
one which is orange
orange two would be
two would be banana
banana three coconut if we attempt to access an
three coconut if we attempt to access an element that doesn't exist here's what
element that doesn't exist here's what happens we get an exception an exception
happens we get an exception an exception is similar to an error we have an array
is similar to an error we have an array in index out of bounds
in index out of bounds exception this error message appears
exception this error message appears when you try and access an element that
when you try and access an element that doesn't exist within an array there is
doesn't exist within an array there is no index of four there's only 0 1 2 3 in
no index of four there's only 0 1 2 3 in this case now you do have the capability
this case now you do have the capability to change the value at a given
to change the value at a given index to do so we will take the name of
index to do so we will take the name of our array in this case fruits specify an
our array in this case fruits specify an index using the set of straight brackets
index using the set of straight brackets at index of zero let's set that equal to
at index of zero let's set that equal to a string of pineapple rather than
a string of pineapple rather than Apple and then we'll print it print our
Apple and then we'll print it print our array of fruits at index of
array of fruits at index of zero that would give us a pineapple
zero that would give us a pineapple rather than an apple by specifying the
rather than an apple by specifying the index you can change any element so
index you can change any element so fruits at index of one is now a
pineapple if at any time you need the length of an array there's a built-in
length of an array there's a built-in property for that let's say say we have
property for that let's say say we have an integer variable of
an integer variable of num of fruits meaning number of
num of fruits meaning number of fruits to access the length of an array
fruits to access the length of an array take our array in this case
take our array in this case fruits use dot which is the axis
fruits use dot which is the axis modifier then type
modifier then type length give me the length of my array of
length give me the length of my array of fruits how many elements are within this
fruits how many elements are within this array take a
array take a guess four
guess four there's four elements within this array
there's four elements within this array 1 2 3 4 if you ever need the length of
1 2 3 4 if you ever need the length of an array use the length property of your
an array use the length property of your array this will return an integer which
array this will return an integer which you can assign to a variable if you
you can assign to a variable if you would like if you need to print all of
would like if you need to print all of the elements of an array you could use a
the elements of an array you could use a for Loop here's
how well declare for Loop we'll create an index of I equal to
Loop we'll create an index of I equal to zero
zero how many times do we want to iterate
how many times do we want to iterate this Loop let's continue as long as I is
this Loop let's continue as long as I is less than we need to determine the
less than we need to determine the length of this array well we can use
length of this array well we can use that length property that we discussed
that length property that we discussed take our array of fruits access the
take our array of fruits access the length property this should return the
length property this should return the number four continue as long as I is
number four continue as long as I is less than four then we will increment
less than four then we will increment our index of I so our for Loop in this
our index of I so our for Loop in this case is going to iterate four times
case is going to iterate four times let's perform a test run if I was to
let's perform a test run if I was to print my array of fruits at index of
print my array of fruits at index of zero this is what happens
zero this is what happens exactly it's going to print fruits at
exactly it's going to print fruits at index zero four times apple apple apple
index zero four times apple apple apple apple what I need is to print each
apple what I need is to print each element of this array we could use our
element of this array we could use our index V for that so replace zero with i
index V for that so replace zero with i i is going to change during each
i is going to change during each iteration of this loop we're increasing
iteration of this loop we're increasing it by one after we complete each cycle
it by one after we complete each cycle of the loop so here's what happens now
of the loop so here's what happens now we get all the elements of our array
we get all the elements of our array Apple orange banana
Apple orange banana coconut this index of I is going to
coconut this index of I is going to increase after each cycle of this Loop
increase after each cycle of this Loop each
each iteration alternatively rather than
iteration alternatively rather than printing each fruit on a new line we
printing each fruit on a new line we could use
could use print then after printing each element
print then after printing each element we could add a space
we could add a space character that would print each element
character that would print each element and separate each with a space if you so
and separate each with a space if you so choose there's something called an
choose there's something called an enhanced for Loop an enhanced for Loop
enhanced for Loop an enhanced for Loop will cycle once for each element within
will cycle once for each element within an
an array we'll start with a normal for Loop
array we'll start with a normal for Loop to create an enhanced for Loop within
to create an enhanced for Loop within the set of parentheses we will list the
the set of parentheses we will list the data type of each element of the array
data type of each element of the array in this case
in this case strings now we need a unique identifier
strings now we need a unique identifier for each element within the Sur array
for each element within the Sur array since we're working with an array of
since we're working with an array of fruits let's say fruit
fruits let's say fruit singular then we need a colon then our
singular then we need a colon then our array that we're iterating through in
array that we're iterating through in this case
this case fruits basically we're saying for every
fruits basically we're saying for every fruit in my array of fruits do
fruit in my array of fruits do this let's print each
this let's print each fruit fruit will be the current element
fruit fruit will be the current element we're cycling
we're cycling through here's what happens we print
through here's what happens we print each fruit we have all the elements of
each fruit we have all the elements of our array of fruits Apple orange banana
our array of fruits Apple orange banana coconut this is an enhanced for Loop
coconut this is an enhanced for Loop also known as a 4 each Loop it
also known as a 4 each Loop it simplifies iterating through a
simplifies iterating through a collection such as an
collection such as an array if you need to sort your array
array if you need to sort your array there's a built-in sort method we're
there's a built-in sort method we're going to access the class of arrays you
going to access the class of arrays you may need to import it import class
may need to import it import class arrays so make sure you have this import
arrays so make sure you have this import import
import java.util.arrays
java.util.arrays this class provides a lot of
this class provides a lot of functionality when working with arrays
functionality when working with arrays there's a built-in sort
there's a built-in sort method we're going to pass in our array
method we're going to pass in our array of fruits to this method we'll end up
of fruits to this method we'll end up sorting the elements in this array
alphabetically originally the order of our elements was Apple orange banana
our elements was Apple orange banana coconut but after sorting there they're
coconut but after sorting there they're now apple banana coconut orange they're
now apple banana coconut orange they're all arranged alphabetically or if these
all arranged alphabetically or if these were numbers they would be arranged in
were numbers they would be arranged in ascending
ascending order there's also a fill method with
order there's also a fill method with arrays we can fill all the elements of
arrays we can fill all the elements of an array with a given value again we're
an array with a given value again we're going to access the arrays class called
going to access the arrays class called The Fill
The Fill method pass in our array comma the value
method pass in our array comma the value we're going to fill the array with let's
we're going to fill the array with let's fill our array with pineapples
then we'll use a for each Loop to print each
each element and here's our new array we have
element and here's our new array we have filled our array of fruits with the
filled our array of fruits with the value of
value of pineapple all right everybody that's an
pineapple all right everybody that's an introduction to arrays think of an array
introduction to arrays think of an array as a variable but it can store more than
as a variable but it can store more than one value and well everybody those are
one value and well everybody those are arrays in
Java what is going on everybody in this video I'm going to show you how we can
video I'm going to show you how we can enter in user input into an array so
enter in user input into an array so let's get started before assigning
let's get started before assigning values into an array our compiler needs
values into an array our compiler needs to know the size of the array beforehand
to know the size of the array beforehand we have to first allocate space for the
we have to first allocate space for the array let's begin by creating an array
array let's begin by creating an array of strings we'll create an array of
of strings we'll create an array of strings we'll enter in some food I will
strings we'll enter in some food I will name this array Foods equals add a set
name this array Foods equals add a set of krly braces and then within this
of krly braces and then within this array you can enter in some values pick
array you can enter in some values pick some food that you like I'll enter in a
some food that you like I'll enter in a pizza
pizza taco and and
hamburger the size of this array is three
three elements once you set a size for an
elements once you set a size for an array normally you can't change it this
array normally you can't change it this array will have three elements however
array will have three elements however all the elements are already filled with
all the elements are already filled with values to create an empty array you
values to create an empty array you don't want a set of empty curly braces
don't want a set of empty curly braces then we're creating an array of no
then we're creating an array of no elements just to demonstrate that I'm
elements just to demonstrate that I'm going to print the length of our array
going to print the length of our array Foods foods. length
Foods foods. length this is going to give us
this is going to give us zero and we can't assign any values even
zero and we can't assign any values even if I attempt to let's say Foods at index
if I attempt to let's say Foods at index zero equals a string of pizza here's
zero equals a string of pizza here's what
happens well we have an exception and array index out of bounds exception
array index out of bounds exception before assigning values we'll want to be
before assigning values we'll want to be sure that we're setting a size of the
sure that we're setting a size of the array even if it is empty instead of
array even if it is empty instead of assigning a set of values we'll create
assigning a set of values we'll create an empty array we'll set our array equal
an empty array we'll set our array equal to use the new keyword type the data
to use the new keyword type the data type of our array straight brackets and
type of our array straight brackets and within the straight brackets we'll set a
within the straight brackets we'll set a size a number so let's say three we're
size a number so let's say three we're creating an empty array that has space
creating an empty array that has space for three elements three values let's
for three elements three values let's try this
try this again the length of our array is three
again the length of our array is three and we can assign the values so let's
and we can assign the values so let's say Foods at index
say Foods at index one equals a
one equals a taco Foods at index 2 will be a
hamburger I'll print all the foods in this array we can use an enhanced for
this array we can use an enhanced for Loop list the data type we're working
Loop list the data type we're working with an array of strings for every food
with an array of strings for every food in our array of
in our array of foods we will print each
foods we will print each food that would give us pizza Taco
food that would give us pizza Taco hamburger we have declared and
hamburger we have declared and instantiated an empty array and filled
instantiated an empty array and filled in the values
in the values later let's modify this program so a
later let's modify this program so a user can type in some values let's
user can type in some values let's delete these lines if we're accepting
delete these lines if we're accepting user input we will need a scanner we'll
user input we will need a scanner we'll declare that and instantiate it scanner
declare that and instantiate it scanner scanner equals new
scanner equals new scanner within the set of parentheses
scanner within the set of parentheses typ
typ system.in import the class for
system.in import the class for scanner import java.util.scanner and
scanner import java.util.scanner and close the scanner when you're done
close the scanner when you're done because I sometimes forget to do that
because I sometimes forget to do that still scanner.
still scanner. close so we have an empty array of three
close so we have an empty array of three elements we'll create a for Loop to
elements we'll create a for Loop to iterate over the length of our array of
iterate over the length of our array of foods so four we'll create a counter of
foods so four we'll create a counter of in I equals z will continue as long as I
in I equals z will continue as long as I is less
is less than our array of foods length property
than our array of foods length property which returns three because there's
which returns three because there's three elements then increment I by One
three elements then increment I by One during each iteration of this Loop let's
during each iteration of this Loop let's do the
do the following we'll output the following
following we'll output the following prompt enter a
prompt enter a food I'll use print instead of print
food I'll use print instead of print line because I prefer
line because I prefer that we'll assign our array of foods at
that we'll assign our array of foods at index of I I changes during each cycle
index of I I changes during each cycle at first it's zero then 1 then two then
at first it's zero then 1 then two then three we'll set that equal to use our
three we'll set that equal to use our scanner to accept some user input call
scanner to accept some user input call the next line
the next line method okay let's perform a test run
method okay let's perform a test run currently we have an array with three
currently we have an array with three empty elements we'll cycle this loop
empty elements we'll cycle this loop three times because the length property
three times because the length property of the array is three then print all the
of the array is three then print all the elements when we're done
elements when we're done here's what happens exactly enter a food
here's what happens exactly enter a food pizza Taco
pizza Taco hamburger here are the elements within
hamburger here are the elements within our array of food pizza Taco
our array of food pizza Taco hamburger let's say that we change the
hamburger let's say that we change the size of the array let's say for this
size of the array let's say for this time Pizza Taco
time Pizza Taco hamburger hot
hamburger hot dog Pizza Taco hamburger hot dog
dog Pizza Taco hamburger hot dog we're going to make a few changes
we're going to make a few changes instead of setting a static size for the
instead of setting a static size for the array we'll have a user enter in the
array we'll have a user enter in the number of food they would like to enter
number of food they would like to enter we'll replace this number with a
we'll replace this number with a variable to determine the size what
variable to determine the size what we'll do now is we will declare our
we'll do now is we will declare our string array of foods but instantiate it
string array of foods but instantiate it later once we know the
later once we know the size we'll
size we'll output what number of food do you want
I'll use print instead of print line I'll also create an integer
line I'll also create an integer variable of size I'll declare it but not
variable of size I'll declare it but not yet fill it in until after our
yet fill it in until after our prompt let's set the size the size of
prompt let's set the size the size of the array that is equal to use our
the array that is equal to use our scanner and call the next int method we
scanner and call the next int method we are accepting an
are accepting an integer once we know the size of the
integer once we know the size of the array we can finish instantiating it
array we can finish instantiating it let's take our array of foods that we've
let's take our array of foods that we've declared but have not yet assigned and
declared but have not yet assigned and we'll assign it our array is made up of
we'll assign it our array is made up of strings we'll use the new keyword new
strings we'll use the new keyword new list the data type
list the data type string it's an array so we need a set of
string it's an array so we need a set of straight
straight brackets and instead of a number we're
brackets and instead of a number we're going to use our variable the user is
going to use our variable the user is going to determine what this number is
going to determine what this number is going to
going to be there's one final step this is
be there's one final step this is specific for scanners since we're
specific for scanners since we're accepting an integer and then we're
accepting an integer and then we're accepting a string for our user input we
accepting a string for our user input we have to clear the input buffer next
have to clear the input buffer next integer isn't going to pick up the new
integer isn't going to pick up the new line character at the end so just to
line character at the end so just to demonstrate
demonstrate that let's say we want one food
that let's say we want one food item there's still that new line
item there's still that new line character within the input buffer we
character within the input buffer we didn't get the opportunity to enter in a
didn't get the opportunity to enter in a food we are just going to clear our
food we are just going to clear our scanner by using scanner. next line and
scanner by using scanner. next line and that will clear it
that will clear it up all right let's try this again
what number of food do you want I want five five food items enter in some food
five five food items enter in some food pizza
pizza Taco
Taco hamburger hot dog and
hamburger hot dog and Sushi and here's our food pizza Taco
Sushi and here's our food pizza Taco hamburger hot dog
hamburger hot dog sushi in summary to enter values into an
sushi in summary to enter values into an array you'll likely want to create an
array you'll likely want to create an empty array but you need to know the
empty array but you need to know the size of the array first
size of the array first if the size of the array is
if the size of the array is predetermined you can always set that to
predetermined you can always set that to be a number otherwise if one way or
be a number otherwise if one way or another if a user is going to determine
another if a user is going to determine the size of the array you'll have to get
the size of the array you'll have to get that from the user and you can set the
that from the user and you can set the size of the array to whatever the user
size of the array to whatever the user types in just be sure to do that before
types in just be sure to do that before filling in the values if you would like
filling in the values if you would like a copy of this code you can look in the
a copy of this code you can look in the comment section down below be sure that
comment section down below be sure that you're looking in the playlist and well
you're looking in the playlist and well everybody that is how to enter and user
everybody that is how to enter and user data into an array using
Java what is is going on everybody in this video I'm going to show you how we
this video I'm going to show you how we can search through the elements of an
can search through the elements of an array let's begin we'll need an array to
array let's begin we'll need an array to work with to keep the simple let's
work with to keep the simple let's create an array of integers we'll create
create an array of integers we'll create an array of integers named numbers
an array of integers named numbers equals make up some numbers to put
equals make up some numbers to put within this array I'll just type
within this array I'll just type whatever comes to
mind good enough we'll also need a Target what number are we searching for
Target what number are we searching for let's say I'm searching for the number
let's say I'm searching for the number number two I will create an integer
number two I will create an integer variable of Target set it equal to
variable of Target set it equal to two in data structures and algorithms
two in data structures and algorithms we'll be performing what is known as a
we'll be performing what is known as a linear search we're going to use a for
linear search we're going to use a for Loop to iterate through these elements
Loop to iterate through these elements and then see if there's a match we'll
and then see if there's a match we'll create a for Loop create an index of I I
create a for Loop create an index of I I will equal zero we'll continue as long
will equal zero we'll continue as long as I is less than R array of numbers
as I is less than R array of numbers access the length property that will
access the length property that will return the length as a number then
return the length as a number then increment I by
increment I by One I will check using an if
One I will check using an if statement if our
statement if our Target is
Target is equal to our array at the current index
equal to our array at the current index of I at first I will be zero and then we
of I at first I will be zero and then we increment it during each cycle of this
increment it during each cycle of this Loop if our Target equals the current
Loop if our Target equals the current element let's print the following
let's say element found at index plus I that's our
index plus I that's our index in case we find the target for
index in case we find the target for example two we don't need to search
example two we don't need to search through the rest of the array we could
through the rest of the array we could add what is known as a break statement
add what is known as a break statement to break out of the
to break out of the loop if we find the target break out of
loop if we find the target break out of the loop let's perform a test run we're
the loop let's perform a test run we're searching for the number two
searching for the number two and we'll be given the index element
and we'll be given the index element found at index
found at index 2 let's look for
2 let's look for one one is found at index
one one is found at index zero four which is near the end is found
zero four which is near the end is found at index 6 0 1 2 3 4 5 6 what if we
at index 6 0 1 2 3 4 5 6 what if we don't find our Target I don't have the
don't find our Target I don't have the number seven in
here well there's no output since this if statement is never true
since this if statement is never true once we reach the end of the array we
once we reach the end of the array we don't do anything so let's add a Boolean
don't do anything so let's add a Boolean variable of is
variable of is found and set it to be
found and set it to be false we'll check if is found is false
false we'll check if is found is false if that is the case we'll output a
if that is the case we'll output a message that element wasn't found in the
message that element wasn't found in the array so if we do find our Target we'll
array so if we do find our Target we'll take our Boolean variable of is found
take our Boolean variable of is found and set it to be true we have found our
and set it to be true we have found our Target that we're looking
for if we exit the for Loop and never find our Target we can check
find our Target we can check that we'll say is
that we'll say is found but we'll use the not logical
found but we'll use the not logical operator the not logical operator gives
operator the not logical operator gives you the inverse of a Boolean value or
you the inverse of a Boolean value or variable if is found is false if
variable if is found is false if something isn't true if we don't find
something isn't true if we don't find the target then we execute this if
the target then we execute this if statement where we will print the
statement where we will print the following let's say something such as
following let's say something such as element not found in the
element not found in the array all right we are looking for the
array all right we are looking for the number seven which does not exist within
number seven which does not exist within this
this array that would give us this message
array that would give us this message element not found in the array because
element not found in the array because is found was false we could never find
is found was false we could never find it within this for
it within this for Loop so we're checking if is found is
Loop so we're checking if is found is not
not true what if we have an array of strings
true what if we have an array of strings and we're searching for an element well
and we're searching for an element well instead of using the comparison operator
instead of using the comparison operator we have to use the equals method of
we have to use the equals method of strings because strings are a reference
strings because strings are a reference data type so this time let's say we have
data type so this time let's say we have an array of
an array of strings named fruits think of some
strings named fruits think of some fruit I will pick an apple
fruit I will pick an apple an
an orange and a
orange and a banana the target this time will be a
orange will iterate through our array of fruits the condition for the for Loop
fruits the condition for the for Loop will be I is less than the length of our
will be I is less than the length of our array of fruits now we can't necessarily
array of fruits now we can't necessarily say is our Target equal to
say is our Target equal to fruits at index of
fruits at index of I we're comparing two strings and since
I we're comparing two strings and since strings are reference data types we
strings are reference data types we would end up comparing the memory
would end up comparing the memory addresses of two different strings we
addresses of two different strings we would be saying are these two memory
would be saying are these two memory addresses the same are they at the same
addresses the same are they at the same location which isn't the case if we're
location which isn't the case if we're comparing the value of strings we'll use
comparing the value of strings we'll use the equals
the equals method let's take fruits at index of I
method let's take fruits at index of I call the built-in equals method of
call the built-in equals method of strings and pass in our Target as an
strings and pass in our Target as an argument now this should work we are
argument now this should work we are searching for an
orange element found at index one what about a
pineapple element not found in the array there was no pineapple let's modify this
there was no pineapple let's modify this program slightly we'll accept some user
program slightly we'll accept some user input but we'll need a scanner
import the class java.util.scanner and close your
class java.util.scanner and close your scanner when you're done with it
scanner when you're done with it scanner.
scanner. close instead of assigning our Target
close instead of assigning our Target we'll accept user input we'll use our
we'll accept user input we'll use our scanner use the next line
scanner use the next line method and we will also need a
method and we will also need a prompt let's print the following
prompt let's print the following enter a fruit to search
for just to make this a little more clean I'm going to move this variable of
clean I'm going to move this variable of is found to the top
is found to the top here I'll declare our string of Target
here I'll declare our string of Target but not assign it and then after the
but not assign it and then after the prompt I'll assign our name of Target
prompt I'll assign our name of Target this is just how I like to arrange
this is just how I like to arrange things but it all works the same now we
things but it all works the same now we can search for an element after acting
can search for an element after acting user input and I will convert this to be
user input and I will convert this to be a print statement instead of print line
a print statement instead of print line all right let's search for some fruit is
all right let's search for some fruit is there a coconut element not found in the
array perhaps a banana element found at index 2 0 1 2 all right everybody so
index 2 0 1 2 all right everybody so that's how to search through an array
that's how to search through an array using
Java hello everybody in this video I'm going to explain variable arguments also
going to explain variable arguments also known as VAR args in Java variable
known as VAR args in Java variable arguments allow a method to accept a
arguments allow a method to accept a varying number of arguments they make
varying number of arguments they make methods more flexible and there's no
methods more flexible and there's no need for overloaded methods overloaded
need for overloaded methods overloaded methods are methods that share the same
methods are methods that share the same name but have different
name but have different parameters in this example I have
parameters in this example I have several add methods they each have
several add methods they each have different amounts of parameters if I was
different amounts of parameters if I was to add a few numbers together for
to add a few numbers together for example I'll add 1 + 2 + 3 well then I
example I'll add 1 + 2 + 3 well then I would use this method what if I told you
would use this method what if I told you instead of creating several different
instead of creating several different methods that basically do the same thing
methods that basically do the same thing we could instead create one method that
we could instead create one method that accepts any number of
accepts any number of arguments we'll only need to declare one
arguments we'll only need to declare one method we will create one add method
method we will create one add method that accepts a varying amount of
that accepts a varying amount of arguments so let's create a method the
arguments so let's create a method the return type let's say is an integer
return type let's say is an integer we'll create a method of add our method
we'll create a method of add our method will have one parameter what is the data
will have one parameter what is the data type of the values we're sending this
type of the values we're sending this method in this case
method in this case integers we're going to follow the data
integers we're going to follow the data type with three dots and
type with three dots and ellipses how this works is that the Java
ellipses how this works is that the Java compiler is going to pack the arguments
compiler is going to pack the arguments we send it into an array we'll need a
we send it into an array we'll need a name for this array let's say
name for this array let's say numbers just to demonstrate this
numbers just to demonstrate this temporarily I'm going to print my array
temporarily I'm going to print my array of
numbers when we call the add method we can send any number of arguments for
can send any number of arguments for example 1 2 3 4 and they're going to be
example 1 2 3 4 and they're going to be packed into an
packed into an array within this method we're now
array within this method we're now working with an array let's perform a
working with an array let's perform a test
test run let's return void
actually so we're given a memory address of this array now let's actually add
of this array now let's actually add these numbers
these numbers together we need to cycle through the
together we need to cycle through the elements of this array we can use a for
elements of this array we can use a for Loop or an enhanced for Loop for that so
Loop or an enhanced for Loop for that so let's return an integer in this
let's return an integer in this case let's declare a local variable of
case let's declare a local variable of sum I will set that to be
zero let's create an enhanced for Loop the data type will be int for every
Loop the data type will be int for every number in my array of numbers
number in my array of numbers let's take our sum and add the current
let's take our sum and add the current number sum plus equals
number sum plus equals number then at the end we will return
number then at the end we will return our
our sum and there we go and then we need to
sum and there we go and then we need to print the output I'm going to cut this
print the output I'm going to cut this and paste it within a print
and paste it within a print statement let's perform a test run the
statement let's perform a test run the sum when we add these four numbers
sum when we add these four numbers together the sum is 10 and we can pass
together the sum is 10 and we can pass in any number of
arguments the result is now 21 basically the Java compiler is
21 basically the Java compiler is packing all of these arguments into an
packing all of these arguments into an array when we send them to a method then
array when we send them to a method then within the context of this method we
within the context of this method we would just need to work with this array
would just need to work with this array one way or another but it's a lot easier
one way or another but it's a lot easier than having several different overloaded
than having several different overloaded methods okay this time let's create a
methods okay this time let's create a new method we'll create a method of
new method we'll create a method of average average will find the average
average average will find the average value of whatever we send it so we will
value of whatever we send it so we will create a static method that's going to
create a static method that's going to return a double this time the method
return a double this time the method name will be
name will be average what is the data type of what
average what is the data type of what we're sending let's say double then we
we're sending let's say double then we need the ellipses the three dots then a
need the ellipses the three dots then a unique name for this array let's say
unique name for this array let's say numbers so to find the average we can
numbers so to find the average we can perform the following
perform the following code let's say we have
code let's say we have double sum
double sum I will set that equal to
I will set that equal to zero we will create an enhanced for Loop
zero we will create an enhanced for Loop the data type is double for every number
the data type is double for every number in my array of numbers do the following
in my array of numbers do the following we will take our
we will take our sum and add the current number sum plus
sum and add the current number sum plus equals
equals number then at the end we will return
number then at the end we will return sum divided by now since we're working
sum divided by now since we're working with an array there is a built-in length
with an array there is a built-in length property numbers. length to find the
property numbers. length to find the average you take all the numbers add
average you take all the numbers add them together then divide it by the
them together then divide it by the amount of numbers that you
amount of numbers that you have let's perform a test
have let's perform a test run I'm going to
run I'm going to print call the average
print call the average method let's find the average of a few
method let's find the average of a few numbers I don't know what that's going
numbers I don't know what that's going to be so the average of these four
to be so the average of these four numbers is 2.5
numbers is 2.5 I can pass in any number of
I can pass in any number of arguments so the average of these
arguments so the average of these numbers is four
numbers is four 4.0 you can even pass in no arguments if
4.0 you can even pass in no arguments if you so
you so choose but with this method that we have
choose but with this method that we have created here's what
created here's what happens we're actually dividing by zero
happens we're actually dividing by zero because the length of our array is zero
because the length of our array is zero there's no elements that we're passing
there's no elements that we're passing in in this specific example let's create
in in this specific example let's create an if
an if statement if our array of
statement if our array of numbers if the length of it we can
numbers if the length of it we can access the length property is equal to
access the length property is equal to zero let's return zero instead of
zero let's return zero instead of receiving noted number we're calling the
receiving noted number we're calling the average method but passing in no
average method but passing in no arguments this
arguments this time that would give us zero because the
time that would give us zero because the length of our array is zero because
length of our array is zero because we're passing in no arguments I already
we're passing in no arguments I already everybody so those are variable
everybody so those are variable arguments they allow a method to accept
arguments they allow a method to accept a varying number of arguments it makes
a varying number of arguments it makes methods more flexible and there's no
methods more flexible and there's no need for overloaded methods the Java
need for overloaded methods the Java compiler will pack the arguments into an
compiler will pack the arguments into an array when setting up the parameters of
array when setting up the parameters of a method declare the data type and add a
a method declare the data type and add a suffix of an ellipsis Three Dots and
suffix of an ellipsis Three Dots and well everybody those are variable
well everybody those are variable arguments in
Java hey there everybody so today I'm going to explain 2D arrays in Java also
going to explain 2D arrays in Java also known as multi-dimensional arrays a
known as multi-dimensional arrays a two-dimensional array is an array where
two-dimensional array is an array where each element is an array it's useful for
each element is an array it's useful for storing a matrix of data let me give you
storing a matrix of data let me give you an example let's say we have some basic
an example let's say we have some basic one-dimensional arrays I will create a
one-dimensional arrays I will create a string array of
string array of fruits think of some
fruits think of some fruit I'll add an
fruit I'll add an apple an orange and a
apple an orange and a banana then I'll create another separate
banana then I'll create another separate array let's create a string array of
array let's create a string array of vegetables think of some
vegetables think of some vegetables I will add a
vegetables I will add a potato an
potato an onion and a
onion and a carrot let's create one more I will
carrot let's create one more I will create a string array of
create a string array of meats I will add
meats I will add chicken pork
fish these three arrays are all separate one-dimensional arrays well what if I
one-dimensional arrays well what if I told you we can make an array made of
told you we can make an array made of arrays where each element is an array
arrays where each element is an array here's how we're going to combine all
here's how we're going to combine all these arrays together into a grid or
these arrays together into a grid or Matrix I will create a two-dimensional
Matrix I will create a two-dimensional array of strings we will need two sets
array of strings we will need two sets of straight brackets I will name this
of straight brackets I will name this two-dimensional array
groceries and then we need our curly braces this two-dimensional array each
braces this two-dimensional array each element within this two-dimensional
element within this two-dimensional array is going to be an array we have
array is going to be an array we have fruits
fruits vegetables and
meats let's attempt to display these elements you can use a for Loop or an
elements you can use a for Loop or an enhanced for Loop
enhanced for Loop within this for Loop what is the data
within this for Loop what is the data type of each element well each element
type of each element well each element is a string
is a string array so we need to list the data type
array so we need to list the data type as a string array let's give a nickname
as a string array let's give a nickname of each element as
of each element as Foods in our two-dimensional array of
Foods in our two-dimensional array of groceries let me show you what happens
groceries let me show you what happens if I print each element within our
if I print each element within our two-dimensional array of
two-dimensional array of groceries I will print each array of
groceries I will print each array of foods here's what we got
foods here's what we got well we get a bunch of memory addresses
well we get a bunch of memory addresses because arrays are a reference data type
because arrays are a reference data type we're referring to some place in
we're referring to some place in memory we'll need to use a nested
Loop an enhanced for Loop would be good for this with each of these arrays what
for this with each of these arrays what is the data type of each element within
is the data type of each element within each well we're working with strings so
each well we're working with strings so the data type is going to be string
the data type is going to be string let's give a nickname of each element as
let's give a nickname of each element as food
food in our array of
in our array of foods during each cycle of this Loop
foods during each cycle of this Loop let's print not print line each food and
let's print not print line each food and then I'll add a
currently we have our first array and our second then
our second then third after finishing each array I'm
third after finishing each array I'm going to add a new line
going to add a new line character we can use a print line
character we can use a print line statement for that
here's what we got now what we have is a grid or Matrix of data you can say that
grid or Matrix of data you can say that there's
there's columns and
array now when initializing an array you don't necessarily needed names let's
don't necessarily needed names let's remove
remove fruits copy the elements of this array
fruits copy the elements of this array including the curly braces and paste
including the curly braces and paste them within this two-dimensional array
them within this two-dimensional array just for readability I'm going to place
just for readability I'm going to place each row on a new
line let's replace vegetables with the elements including the curly
elements including the curly braces same thing applies with
meats and we can delete all this this would work the
this this would work the same groceries is a matrix of data a gri
same groceries is a matrix of data a gri let's print
let's print this and that works the
this and that works the same if you ever need to access or
same if you ever need to access or change an element you'll need to use two
change an element you'll need to use two indices for example let's replace apple
indices for example let's replace apple with the pineapple we will take our
with the pineapple we will take our two-dimensional array of groceries and
two-dimensional array of groceries and list two
list two indices the first index applies to the
indices the first index applies to the row the second index applies to the
row the second index applies to the column so we're saying at row 0 column
column so we're saying at row 0 column 0 we can change it or access it let's
0 we can change it or access it let's say that row 0 column 0 is now a
say that row 0 column 0 is now a pineapple rather than an apple then we
pineapple rather than an apple then we have pineapple orange
have pineapple orange banana let's replace our potato with
banana let's replace our potato with something
something else that would be Row one column 0 Row
else that would be Row one column 0 Row one column 0 is now
carrot let's replace the carrot with celery then that would be Row one column
celery then that would be Row one column 2 0 1 2 Row one column
2 0 1 2 Row one column 2 potato onion
2 potato onion celery let's replace pork with eggs that
celery let's replace pork with eggs that would be row two 0 1 2 column 1 0 1
would be row two 0 1 2 column 1 0 1 row two column one is now
eggs we have chicken eggs beef fish to access or modify an element
fish to access or modify an element within a 2d array you need to list two
within a 2d array you need to list two indices the first for the row the second
indices the first for the row the second for the
for the column okay now we're going to create a
column okay now we're going to create a mini
mini project we'll create a two-dimensional
project we'll create a two-dimensional array that resembles a telephone number
array that resembles a telephone number pad this two-dimensional array will be
pad this two-dimensional array will be made up of characters
made up of characters the data type is Char and then we have
the data type is Char and then we have two sets of straight brackets let's name
two sets of straight brackets let's name this two-dimensional array telephone
this two-dimensional array telephone equals we have an array of arrays we'll
equals we have an array of arrays we'll have four
rows and just for readability I'm going to place each of these on a new
to place each of these on a new line just so it resembles a grid or
line just so it resembles a grid or Matrix for the first row we'll have one
two three and these are all characters not strings we're using single quotes
not strings we're using single quotes not double quotes for the second row
not double quotes for the second row we'll have
we'll have four
four 5
5 6 the third row will be
6 the third row will be 7
7 8
8 9 now for the last row we'll have an
9 now for the last row we'll have an asterisk
asterisk character Zero
and pound or hashtag as I like to call it so here's our Matrix our grid of
it so here's our Matrix our grid of characters we have an array of arrays it
characters we have an array of arrays it has rows and
columns now let's display our data we'll need nested Loops for
this our outer for Loop is going to be in charge of the rows what is the data
in charge of the rows what is the data type of each element within this
type of each element within this two-dimensional array well each row is
two-dimensional array well each row is an array of characters that's going to
an array of characters that's going to be the data type of the outer for Loop
be the data type of the outer for Loop we have an array of characters let's
we have an array of characters let's give a nickname of each inner array as a
give a nickname of each inner array as a row in our two-dimensional array of
row in our two-dimensional array of telephone for every Row in our telephone
telephone for every Row in our telephone do this then we'll need a nested
do this then we'll need a nested Loop what is the data type of each
Loop what is the data type of each element within each array their
element within each array their characters the data type will be
characters the data type will be Char let's say for every number
Char let's say for every number in each array of row we'll print the
in each array of row we'll print the following we'll use print rather than
following we'll use print rather than print
print line we'll print each number and I'll
line we'll print each number and I'll add a space
add a space character let's do a test
character let's do a test run after each row I'm going to print a
run after each row I'm going to print a new line character
new line character so when we escape the inner four Loop
so when we escape the inner four Loop I'll add an empty print line
I'll add an empty print line statement and here's our telephone we
statement and here's our telephone we have
have rows and
rows and columns it's a two-dimensional array of
columns it's a two-dimensional array of characters so those are two-dimensional
characters so those are two-dimensional arrays they're an array where each
arrays they're an array where each element is an array it's useful for
element is an array it's useful for storing a matrix of data we probably
storing a matrix of data we probably won't be using 2D arrays too often but
won't be using 2D arrays too often but you should still be familiar with them
you should still be familiar with them and well everybody those are two
and well everybody those are two dimensional arrays in
Java hello everybody in this video we're going to create an interactive quiz game
going to create an interactive quiz game using Java for this project you'll
using Java for this project you'll create an array of your own custom
create an array of your own custom questions and a two-dimensional array of
questions and a two-dimensional array of all the different options for answers
all the different options for answers that we have you'll type in a number 1
that we have you'll type in a number 1 through four depending on your guess
through four depending on your guess after all of the questions are answered
after all of the questions are answered we will display a final score depending
we will display a final score depending on the amount of correct guesses that
on the amount of correct guesses that you have so let's begin as a beginner it
you have so let's begin as a beginner it might be helpful to you to break down
might be helpful to you to break down your project into different steps as
your project into different steps as comments we'll list all of the different
comments we'll list all of the different steps we need to take to get this
steps we need to take to get this program up and running the first thing
program up and running the first thing that we need is an array of questions
that we need is an array of questions questions will be an
questions will be an array we will also need
array we will also need options options will be a
options options will be a two-dimensional
two-dimensional array we will declare our
array we will declare our variables we'll need a welcome message
we will list each question using a loop I'll just write in parenthesis that
loop I'll just write in parenthesis that we will use a loop now within this loop
we will use a loop now within this loop we're going to do a few things we will
we're going to do a few things we will list our
list our options then get guess from
options then get guess from user then check our guess to see if it's
user then check our guess to see if it's correct at the end of this program we
correct at the end of this program we will display find fin
score so here's a rough outline of our project we'll fill this project in one
project we'll fill this project in one step at a time let's begin with creating
step at a time let's begin with creating an array of questions we'll ask the
an array of questions we'll ask the user the data type will be a string
user the data type will be a string array of
questions here's where you're going to ask all of your questions in this
ask all of your questions in this project we'll have five
project we'll have five questions they're all going to be very
questions they're all going to be very long strings
for our first question you don't need to type in the same questions that I do
type in the same questions that I do feel free to come up with your own
feel free to come up with your own here's a few that I've looked up online
here's a few that I've looked up online my first question will be what is the
my first question will be what is the main function of a
main function of a router that'll be the first question
router that'll be the first question I'll put each of these questions on a
I'll put each of these questions on a new line just for
new line just for readability the second question will be
readability the second question will be which part of the
which part of the computer is
considered the brain then I'll go to a new
launched who is known as the father of computers then for my last
question what was the first programming
first programming language all right here are the
language all right here are the questions questions is an array of
questions questions is an array of strings a one-dimensional array now
strings a one-dimensional array now we'll create a two-dimensional array of
we'll create a two-dimensional array of options we will create a two-dimensional
options we will create a two-dimensional array of strings named options
we have five questions that means we need five arrays one array for each
question I'll Place each of these on a new line for
readability our first array within our 2D array of options will hold all of the
2D array of options will hold all of the options for our first question each
options for our first question each value within this first array is going
value within this first array is going to be strings and I'm going to zoom in a
to be strings and I'm going to zoom in a little so we can both read it what is
little so we can both read it what is the main function of a router here's
the main function of a router here's where you're going to list all of the
where you're going to list all of the different possible answers but only one
different possible answers but only one of them is going to be correct I'll say
of them is going to be correct I'll say one. space storing
one. space storing files for option two that will be
files for option two that will be encrypting
data option three will be
three will be for
for directing internet traffic this will be
directing internet traffic this will be the correct answer number three number
the correct answer number three number four will
four will be managing
be managing passwords this will be my first array
passwords this will be my first array all the options for question one now for
all the options for question one now for question
options honestly I'm just going to copy these and then paste them within each
these and then paste them within each array just to speed things up what part
array just to speed things up what part of the computer is considered the
of the computer is considered the brain here's the different options
brain here's the different options option one will be CPU that's going to
option one will be CPU that's going to be the correct answer the central
be the correct answer the central processing unit two hard
processing unit two hard drive three
drive three Ram four
Ram four GPU question three what year was
GPU question three what year was Facebook
Facebook launched option one will be 2000 option
launched option one will be 2000 option two 2004 and that's the correct
two 2004 and that's the correct answer
answer 2006 or 2008
2006 or 2008 who is known as the father of
who is known as the father of computers let's say Steve
Jobs Bill Gates Allan
Gates Allan Turing or Charles Babbage and that's the
Turing or Charles Babbage and that's the correct
answer what was the first programming language either
language either cobal C
cobal C for
for Tran or
Tran or assembly the correct answer is actually
assembly the correct answer is actually Fortran it's the first commercially
Fortran it's the first commercially available programming language one more
available programming language one more thing we're going to create a
thing we're going to create a one-dimensional array what are the
one-dimensional array what are the correct answers we'll need some sort of
correct answers we'll need some sort of key we could include this with our
key we could include this with our declare variable
declare variable step we will create an integer array of
step we will create an integer array of answers we will list the correct answers
answers we will list the correct answers as integers the correct answer to
as integers the correct answer to question one is directing internet
question one is directing internet traffic so we will list three for the
traffic so we will list three for the next question what part of the computer
next question what part of the computer is considered the brain that is the CPU
is considered the brain that is the CPU option
option one Facebook was launched in the year
one Facebook was launched in the year 2004 that's
2004 that's two who is the father of computers that
two who is the father of computers that is Charles
is Charles Babbage that's
Babbage that's four and the first commercially
four and the first commercially available program ining language is for
available program ining language is for Tran that is three here are the correct
Tran that is three here are the correct answers are key there's a few more
answers are key there's a few more variables we'll need we will create an
variables we'll need we will create an integer variable of score we can set
integer variable of score we can set that to be zero if we would like and an
that to be zero if we would like and an integer of guess guess is going to store
integer of guess guess is going to store whatever the user types in 1 through
whatever the user types in 1 through four so it's going to be an integer we
four so it's going to be an integer we will also need a scanner to accept user
will also need a scanner to accept user input scanner scanner equals new scanner
input scanner scanner equals new scanner it doesn't really matter where we
it doesn't really matter where we declare it just as long as we declare it
declare it just as long as we declare it before we use it system.in and then we
before we use it system.in and then we will import this
will import this class import java.util.scanner and then
class import java.util.scanner and then close our scanner at the end of our
close our scanner at the end of our program when we're done with it scanner.
close all right here are the variables we'll need including our options and our
we'll need including our options and our questions our next step is to create a
questions our next step is to create a welcome message
welcome message let's output the
let's output the following let's say welcome to the Java
following let's say welcome to the Java quiz
game and then I'll add some separators a bunch of asterisks because
separators a bunch of asterisks because I think it'll look cool
mostly we have our welcome message and I'll just perform a test run it's a good
I'll just perform a test run it's a good idea to test your code as you're coding
idea to test your code as you're coding it just sure that everything is working
it just sure that everything is working fine and that is our welcome
fine and that is our welcome message now we'll Loop through all of
message now we'll Loop through all of the questions that we
have we'll probably want to use a for Loop we will create an index of I in I
Loop we will create an index of I in I equals z we'll continue this loop as
equals z we'll continue this loop as long as I is less
long as I is less than the length of our array of
than the length of our array of questions questions access the length
questions questions access the length property
property which will return a number in this case
which will return a number in this case five because there's five questions we
five because there's five questions we will increment I by
will increment I by one as a test let's print our
one as a test let's print our questions at index of I I will start at
questions at index of I I will start at zero so we're returning the first
zero so we're returning the first question at index
question at index zero then during each iteration of this
zero then during each iteration of this Loop we will display each question let's
Loop we will display each question let's do a test
do a test run so here are the five questions
run so here are the five questions we're displaying each element of our
we're displaying each element of our array of
array of questions after each question we have to
questions after each question we have to list all of the different
list all of the different options that's the next
options that's the next step we'll display a question then
step we'll display a question then create a nested Loop to display all of
create a nested Loop to display all of the
the options I'm going to use an enhanced for
options I'm going to use an enhanced for Loop for this what is the data type of
Loop for this what is the data type of each value within each array within
each value within each array within options
options well we're working with
well we're working with strings the inner for Loop is going to
strings the inner for Loop is going to be an enhanced for Loop the data type of
be an enhanced for Loop the data type of each value is a
each value is a string string option colon meaning
string string option colon meaning in rray of options at index of
in rray of options at index of i options is a two-dimensional array if
i options is a two-dimensional array if we retrieve a value at a given index
we retrieve a value at a given index will be given an array display every
will be given an array display every option in each inner array
option in each inner array so to demonstrate that let's print each
option so here's what we have after printing each question we will Loop
printing each question we will Loop through and print all of the
options now before moving on to the next question we have to get some user input
question we have to get some user input we don't want to display all the
we don't want to display all the questions right away just one at a time
questions right away just one at a time so we will do this within the outer for
so we will do this within the outer for loop after printing all of the options
loop after printing all of the options this is where we will get the guess from
this is where we will get the guess from the
user we will create a prompt to enter your guests and I will use print instead
your guests and I will use print instead of print line because I like the user
of print line because I like the user input on the same
input on the same line we will assign our variable of
line we will assign our variable of guess guess equal
guess guess equal scanner. next int the user going to type
scanner. next int the user going to type in a number 1 through
in a number 1 through 4 then we have to check our guess is it
4 then we have to check our guess is it correct or
correct or not we can do the
not we can do the following we'll use an if statement if
following we'll use an if statement if our guess is equal to our array of
our guess is equal to our array of answers it's a one-dimensional
answers it's a one-dimensional array at index of I we're using the
array at index of I we're using the index of I because we're still within
index of I because we're still within our for Loop during the first iteration
our for Loop during the first iteration of this Loop I will be zero so is our
of this Loop I will be zero so is our guess equal to answers at index zero if
guess equal to answers at index zero if that is correct let's print the
that is correct let's print the following let's say correct and for fun
following let's say correct and for fun I'll add some text decoration some of
I'll add some text decoration some of those
separators again it's not necessary I just think it'll look
cool else if our guest doesn't equal our answer well we can check that with an
answer well we can check that with an lse statement if we don't have the
lse statement if we don't have the correct answer that means we have the
correct answer that means we have the wrong answer and I will output
wrong answer and I will output wrong and I will just space this out a
wrong and I will just space this out a little
little bit all right let's do a test
bit all right let's do a test run for the first question the correct
run for the first question the correct answer is three I'll type in three then
answer is three I'll type in three then we print
we print correct which part of the computer is
correct which part of the computer is considered the brain I will
considered the brain I will intentionally get this wrong let's say
intentionally get this wrong let's say the
the GPU
GPU wrong and I'll guess the others
wrong and I'll guess the others wrong
wrong wrong wrong then we have to calculate a
wrong wrong then we have to calculate a final
final score okay then we have to display the
score okay then we have to display the final score so after we get the correct
final score so after we get the correct answer we will increment our score by
answer we will increment our score by one score
one score Plus+ then we will display the final
score your final score is I'll use string catnation to keep this simple
string catnation to keep this simple we'll add our score variable plus the
we'll add our score variable plus the words out
words out of plus we're going to get the length of
of plus we're going to get the length of our questions questions is an
our questions questions is an array questions. length
array questions. length property I'm just going to add a space
property I'm just going to add a space right before out because I'm forgetting
right before out because I'm forgetting that let's run this one last
that let's run this one last time what is the main function of a
time what is the main function of a router that that is three directing
router that that is three directing internet traffic which part of the
internet traffic which part of the computer is considered the brain that is
computer is considered the brain that is the
the CPU what year was Facebook launched I'm
CPU what year was Facebook launched I'm going to get this one wrong
going to get this one wrong intentionally I'm going to say 2000 and
intentionally I'm going to say 2000 and that is wrong who is known as the father
that is wrong who is known as the father of computers that is Charles babage
of computers that is Charles babage 4 what was the first programming
4 what was the first programming language well the first commercially
language well the first commercially available programming language that
available programming language that would be three for
would be three for Tran correct your final score is four
Tran correct your final score is four out of five
out of five all right everybody so that is an
all right everybody so that is an interactive quiz game that you can
interactive quiz game that you can create using
Java what is going on everybody in this video we're going to create a game of
video we're going to create a game of rock paper scissors for beginners so
rock paper scissors for beginners so let's get started as a beginner when
let's get started as a beginner when creating a project it could be helpful
creating a project it could be helpful to you to break down a project into
to you to break down a project into smaller steps just as comments I'm going
smaller steps just as comments I'm going to list the different steps that we'll
to list the different steps that we'll need to take so let's say first we will
need to take so let's say first we will declare our
declare our variables then then get a choice from
variables then then get a choice from the
the user get random choice for the
user get random choice for the computer check win conditions who
won ask to play again then at the end we will display a
again then at the end we will display a goodbye
message it may be helpful to you as a beginner to list the different steps
beginner to list the different steps that your program is going to take just
that your program is going to take just for more organization all right let's
for more organization all right let's work on step one we will declare our
work on step one we will declare our variables we'll need a scanner because
variables we'll need a scanner because we're accepting user input scanner
we're accepting user input scanner scanner equals new
scanner equals new scanner within the set of parentheses we
scanner within the set of parentheses we will type system.
will type system. in import the class for scanners import
in import the class for scanners import java.util.scanner and then we will close
java.util.scanner and then we will close our scanner when we're done with it
our scanner when we're done with it scanner. close because we don't want to
scanner. close because we don't want to leave any resources open we will be
leave any resources open we will be generating random numbers we will need
generating random numbers we will need to create a random object random random
to create a random object random random equals new
equals new random and then import this class as
random and then import this class as well import
well import java.util
java.util random we're going to create an array of
random we're going to create an array of choices they will be strings rock paper
choices they will be strings rock paper or scissors we will create a string
or scissors we will create a string array named
array named choices equals an array this will be an
choices equals an array this will be an array of
array of strings at the first index we'll have
strings at the first index we'll have Rock then
Rock then paper then
scissors we'll store our choice within a variable this will be a string we'll
variable this will be a string we'll name this variable player
name this variable player choice I will declare this variable but
choice I will declare this variable but not yet assign it and the computer's
not yet assign it and the computer's Choice string computer choice
Choice string computer choice we're going to create a while loop that
we're going to create a while loop that will ask the user to play again when
will ask the user to play again when they reach the end we'll create a string
they reach the end we'll create a string variable of play again and I will set
variable of play again and I will set this to be
this to be yes basically while play again is yes
yes basically while play again is yes continue the
continue the game let's work on our next step get the
game let's work on our next step get the choice from the
choice from the user we need to prompt the
user we need to prompt the user we'll use a print line statement
user we'll use a print line statement and say
and say enter your move I'll add a set of
enter your move I'll add a set of parentheses that says rock paper
parentheses that says rock paper scissors just so the user knows what to
scissors just so the user knows what to type in I'll use print instead of print
type in I'll use print instead of print line because I prefer user input on the
line because I prefer user input on the same
same line once we have our prompt we're going
line once we have our prompt we're going to assign our player choice variable
to assign our player choice variable player choice equals we will use our
player choice equals we will use our scanner to get some user input we need
scanner to get some user input we need to accept a string so we can use the
to accept a string so we can use the next
next line
line method to accept a line of text in case
method to accept a line of text in case a user types in any uppercase characters
a user types in any uppercase characters for example Rock we could follow this
for example Rock we could follow this with the two lowercase method just to
with the two lowercase method just to make it all lowercase whatever the user
make it all lowercase whatever the user types
types in accept the next line of user input
in accept the next line of user input then make it lowercase just for
then make it lowercase just for consistency now we should have our
consistency now we should have our player
player choice we need a way to determine to see
choice we need a way to determine to see if this user input is valid did the user
if this user input is valid did the user pick rock paper or scissors or something
pick rock paper or scissors or something else entirely well we could use an if
else entirely well we could use an if statement for
that we're going to be checking to see if our player choice doesn't equal Rock
if our player choice doesn't equal Rock and doesn't equal paper and doesn't
and doesn't equal paper and doesn't equal scissors so we can write the
equal scissors so we can write the following statement we're going to use
following statement we're going to use the not logical operator first not will
the not logical operator first not will give you the opposite the
give you the opposite the inverse if player choice use the equals
inverse if player choice use the equals method pass in a string of rock if the
method pass in a string of rock if the Player's Choice doesn't equal Rock then
Player's Choice doesn't equal Rock then we'll use the and logical
we'll use the and logical operator and the Player's
operator and the Player's Choice doesn't again I'm using the not
Choice doesn't again I'm using the not logical
logical operator
operator equals
equals paper again we're going to use the and
paper again we're going to use the and logical
logical operator and just to help with
operator and just to help with readability cuz we're going to have one
readability cuz we're going to have one really long line I'm going to place
really long line I'm going to place these conditions on a new line each this
these conditions on a new line each this will help with
readability and take our player choice not
equals scissors we're linking three conditions
scissors we're linking three conditions together
together if our player choice doesn't equal Rock
if our player choice doesn't equal Rock and our player choice doesn't equal
and our player choice doesn't equal paper and our player choice doesn't
paper and our player choice doesn't equal
equal scissors if all of these conditions are
scissors if all of these conditions are true that means a user didn't type in
true that means a user didn't type in something that's valid so let's do the
something that's valid so let's do the following again I'm within my set of
following again I'm within my set of curly
curly braces we'll output the
braces we'll output the following we'll say something like
following we'll say something like invalid choice
run enter your move rock paper scissors let's choose Rock nothing happens that's
let's choose Rock nothing happens that's good paper nothing
good paper nothing happens
happens scissors nothing happens all right I'm
scissors nothing happens all right I'm going to type in something that's not
going to type in something that's not rock paper or scissors uh I choose the
rock paper or scissors uh I choose the gun invalid
gun invalid Choice that's good that's what we
Choice that's good that's what we want we're picking something that's not
want we're picking something that's not rock and is not paper and is not
rock and is not paper and is not scissors so we execute this if statement
scissors so we execute this if statement if that's the
if that's the case now for the next step we have to
case now for the next step we have to get a random choice for the
get a random choice for the computer we don't need user input this
computer we don't need user input this time we will assign our variable of
time we will assign our variable of computer
computer Choice equals access our array of
Choice equals access our array of choices
choices at a given
at a given index zero would be Rock because it's
index zero would be Rock because it's the first value in our
the first value in our array one would be paper two would be
array one would be paper two would be scissors well why don't we use our
scissors well why don't we use our random object random and call the next
random object random and call the next int
int method then pass in
method then pass in three this method of a random object
three this method of a random object would return a random number between 0
would return a random number between 0 and two zero for rock one for p paper
and two zero for rock one for p paper two for
two for scissors then we'll output it using a
scissors then we'll output it using a print line
print line statement let's say computer Choice col
statement let's say computer Choice col in space then add our variable of
in space then add our variable of computer
computer Choice let's do a test
Choice let's do a test run I'll type in rock the computer picks
paper I will pick paper the computer picks
picks scissors I will will pick
scissors I will will pick scissors the computer picks scissors as
scissors the computer picks scissors as well all right we know that that
well all right we know that that works using this method of a random
works using this method of a random object we're generating a random number
object we're generating a random number as the
as the index now here's the tricky part we have
index now here's the tricky part we have to check all the win
to check all the win conditions I feel like the best way to
conditions I feel like the best way to handle this would be to create an if
handle this would be to create an if statement followed by an else if
statement followed by an else if statement followed by an else
statement followed by an else statement within our if statement this
statement within our if statement this will be for a tie let's output the
will be for a tie let's output the following it's a
following it's a tie our Eli statement will be used if
tie our Eli statement will be used if you win we'll
you win we'll output you
output you win else will be used for you
win else will be used for you lose you
lose you lose if we have a tie that means the
lose if we have a tie that means the Player's Choice is equal to the
Player's Choice is equal to the computer's
computer's Choice that's how you get a tie within
Choice that's how you get a tie within the of statement we can check the
the of statement we can check the following condition if our player choice
following condition if our player choice variable use the equals method of
variable use the equals method of strings then pass in the variable of
strings then pass in the variable of computer
computer choice we're comparing two strings
choice we're comparing two strings the're reference data types so we're
the're reference data types so we're going to use the equals method you can't
going to use the equals method you can't use double equals because then you're
use double equals because then you're comparing memory addresses of two
comparing memory addresses of two different strings we're going to be
different strings we're going to be using equals the equals method if these
using equals the equals method if these two strings are equal will print it's a
two strings are equal will print it's a tie now for the wi conditions within
tie now for the wi conditions within this LF statement this is where things
this LF statement this is where things are going to get kind of tricky we're
are going to get kind of tricky we're going to list all of the different win
going to list all of the different win conditions within our LF statement first
conditions within our LF statement first we'll check if the player picks Rock and
we'll check if the player picks Rock and the computer picks scissors if our
the computer picks scissors if our player
player choice use the equals
choice use the equals method if the player picks Rock a string
method if the player picks Rock a string of
Choice equals let me zoom out a little bit scissors that means we
bit scissors that means we win within our condition of our LF
win within our condition of our LF statement we'll be adding the different
statement we'll be adding the different win conditions but temporarily I'm going
win conditions but temporarily I'm going to add a few else if statements just to
to add a few else if statements just to help me explain this so if we pick Rock
help me explain this so if we pick Rock and the computer pick scissors that
and the computer pick scissors that means we win but we will also win if the
means we win but we will also win if the player
player pick
pick paper and the
paper and the computer let's add that right
computer let's add that right here picks rock that means we also
here picks rock that means we also win and then temporarily I'll add
win and then temporarily I'll add another LF
another LF statement else if the player picks
paper that also means we win we could condense all of these LF
we could condense all of these LF statements into one but we'll do that in
statements into one but we'll do that in a moment I just want to be sure that it
a moment I just want to be sure that it all works first let's do a test run I
all works first let's do a test run I will pick Rock the computer picks
will pick Rock the computer picks scissors that means we
scissors that means we win I will pick paper the computer picks
win I will pick paper the computer picks paper it's a
paper it's a tie I'll keep playing until I lose I
tie I'll keep playing until I lose I will pick scissors the computer picks
will pick scissors the computer picks paper we win let's try scissors again
paper we win let's try scissors again the computer picks Rock we lose we know
the computer picks Rock we lose we know that these different wi conditions are
that these different wi conditions are working this is fairly readable but if
working this is fairly readable but if you prefer we can condense all of these
you prefer we can condense all of these steps down together into one else if
steps down together into one else if statement optionally what you could do
statement optionally what you could do with our first win condition let's
with our first win condition let's enclose them within a set of
parentheses then I will use the or logical Operator Let Me zoom in so you
logical Operator Let Me zoom in so you can see
can see it I'm adding or to the
it I'm adding or to the end
or let's take the entire condition within our LS if statement then paste it
within our LS if statement then paste it after the or logical
after the or logical operator and these do need to be
operator and these do need to be enclosed within a set of
parentheses and we can delete this LF statement We'll add the or logical
statement We'll add the or logical operator to the end
cut this condition for the next LF statement and delete this LF
statement and delete this LF statement and paste
statement and paste it so here's our LF statement there is a
it so here's our LF statement there is a lot going on here this should work too
lot going on here this should work too but if you prefer to keep it the other
but if you prefer to keep it the other way just for readability feel free to do
way just for readability feel free to do so if you like to condense some of the
so if you like to condense some of the code here's how you could do that so let
code here's how you could do that so let me just be sure that everything's
me just be sure that everything's working fine
working fine I will pick Rock computer picks Rock
I will pick Rock computer picks Rock it's a
it's a tie I will pick paper computer picks
tie I will pick paper computer picks scissors you
scissors you lose I will pick scissors computer picks
lose I will pick scissors computer picks paper you win all right this LF
paper you win all right this LF statement does work again if you would
statement does work again if you would prefer to add more LF statements feel
prefer to add more LF statements feel free to keep it the other way now we
free to keep it the other way now we need to ask the user if they want to
need to ask the user if they want to play
play again after displaying either it's a tie
again after displaying either it's a tie you win or you lose We'll add a prompt I
you win or you lose We'll add a prompt I will use print instead of print
will use print instead of print line I'll ask play
line I'll ask play again yes slash
no we have one variable we haven't used yet our play again variable and
yet our play again variable and currently it's
currently it's yes play again equals use our scanner
yes play again equals use our scanner use the next line
use the next line method and I will take the user's input
method and I will take the user's input and make it lowercase right away to
and make it lowercase right away to lowercase
lowercase method we're going to enclose all of our
method we're going to enclose all of our code right before the variables within a
code right before the variables within a loop a do while loop so we'll say do all
loop a do while loop so we'll say do all this code while some condition remains
this code while some condition remains true let's cut all of our
code cut it and then paste it within this do while
loop so with the do while loop we do all of this code once
of this code once and then check the condition at the
and then check the condition at the end what's our condition going to be
end what's our condition going to be we'll continue playing while our play
we'll continue playing while our play again variable equals a string of yes
again variable equals a string of yes play again equals
play again equals yes one more change we're going to
yes one more change we're going to make if the user picks something that
make if the user picks something that isn't valid we're going to skip the
isn't valid we're going to skip the current iteration of this Loop we can
current iteration of this Loop we can use continue for that
use continue for that we want to go back to the beginning if a
we want to go back to the beginning if a user types in something that is
user types in something that is invalid then the last step is to create
invalid then the last step is to create a goodbye message we're doing this
a goodbye message we're doing this outside of the while loop cuz when we're
outside of the while loop cuz when we're outside of the while loop that means
outside of the while loop that means we're no longer playing let's print the
we're no longer playing let's print the following thanks for
following thanks for playing all right let's run this one
playing all right let's run this one last
last time I will pick Rock computer pick
time I will pick Rock computer pick scissors you win play again again I'm
scissors you win play again again I'm going to type yes enter your move I will
going to type yes enter your move I will pick paper computer picks rock you win I
pick paper computer picks rock you win I will play again I will pick
will play again I will pick scissors the computer picks Rock You
scissors the computer picks Rock You Lose I'm going to type no to play again
Lose I'm going to type no to play again and we escape that Doh Loop thanks for
and we escape that Doh Loop thanks for playing all right everybody so that is a
playing all right everybody so that is a game of rock paper scissors you can make
game of rock paper scissors you can make using
Java hello everybody in this video we're going to create a slot machine program
going to create a slot machine program using Java a user is going to bet an
using Java a user is going to bet an amount for the symbols of our slot
amount for the symbols of our slot machine we'll be using emojis if a user
machine we'll be using emojis if a user gets any matching symbols they'll
gets any matching symbols they'll receive a payout then at the end we'll
receive a payout then at the end we'll give a final balance if that sounds good
give a final balance if that sounds good to you let's get started all right
to you let's get started all right everybody when working on a project it
everybody when working on a project it might be helpful to you to tackle your
might be helpful to you to tackle your project one step at a time as comments
project one step at a time as comments we'll list the different steps that our
we'll list the different steps that our program is going to take this will give
program is going to take this will give us a rough outline of our project the
us a rough outline of our project the first thing we'll do is declare our
first thing we'll do is declare our variables then display a welcome message
variables then display a welcome message display welcome
display welcome message we will play if our balance
message we will play if our balance meaning the money that we have is
meaning the money that we have is greater than
greater than zero if we don't have any money we can't
zero if we don't have any money we can't play it is a slot machine after all a
play it is a slot machine after all a user is going to enter bet amount then
user is going to enter bet amount then I'll write a few Subs steps underneath
I'll write a few Subs steps underneath here we need to
here we need to verify if the bet is greater than the
verify if the bet is greater than the balance you can't bet money that you
balance you can't bet money that you don't
don't have then
have then verify if bet is greater than zero you
verify if bet is greater than zero you can't bet negative money so we'll need
can't bet negative money so we'll need to check
to check that then subtract bet from our balance
that then subtract bet from our balance once we subtract the BET from the
once we subtract the BET from the balance then we will spin our
balance then we will spin our row our row is going to contain emojis
row our row is going to contain emojis but we'll need to display it we'll
but we'll need to display it we'll create a method to print our row of
create a method to print our row of emojis once we display our row we need
emojis once we display our row we need to get a payout if we win something if
to get a payout if we win something if we have any
we have any matches then ask to play
matches then ask to play again if the user doesn't want to play
again if the user doesn't want to play we will display an exit message display
we will display an exit message display exit message so here's a rough outline
exit message so here's a rough outline of our project we will Begin by
of our project we will Begin by declaring our
declaring our variables we will be accepting user
variables we will be accepting user input we'll need a scanner for that
input we'll need a scanner for that scanner scanner equals new
scanner scanner equals new scanner type system.in within the set of
scanner type system.in within the set of parentheses import this class import
parentheses import this class import java.util.scanner then when we're done
java.util.scanner then when we're done with our scanner we'll want want to
with our scanner we'll want want to close it scanner.
close we'll need a balance how much money do we have I will set that to be
money do we have I will set that to be 100 100 as in
100 100 as in $100 this could also be done with other
$100 this could also be done with other units of currency we'll need an amount
units of currency we'll need an amount for our bet int bet how much are we
for our bet int bet how much are we betting how much are we
betting how much are we risking int
risking int payout how much money do we win we'll be
payout how much money do we win we'll be adding our pay pay out to our balance if
adding our pay pay out to our balance if we
we win and a string array named
win and a string array named row our row is going to contain our
row our row is going to contain our symbols our emojis that will display to
symbols our emojis that will display to the output window that's why we're
the output window that's why we're creating a string array to store all of
creating a string array to store all of them here are the variables we'll need
them here are the variables we'll need we'll move on to the next step our next
we'll move on to the next step our next step is to display a welcome
step is to display a welcome message let's say something like this
message let's say something like this I'll use a print line statement we'll
I'll use a print line statement we'll say welcome to
say welcome to Java
Java slots underneath this line we'll add
slots underneath this line we'll add another print line statement I will
another print line statement I will print the word symbols and here we'll
print the word symbols and here we'll list all the different symbols we would
list all the different symbols we would like to use within our program I'll be
like to use within our program I'll be using emojis to pull up the Emoji menu
using emojis to pull up the Emoji menu if you're on Windows hold on the window
if you're on Windows hold on the window key then hit the semicolon
key then hit the semicolon button so pick some emojis that you like
button so pick some emojis that you like here's a few that I typically see
here's a few that I typically see cherries watermelon
cherries watermelon lemons bells and
lemons bells and stars if you would like to stick to a
stars if you would like to stick to a certain theme feel free to change
certain theme feel free to change these but these are a few symbols you
these but these are a few symbols you may see on a slot
may see on a slot machine and I'm just going to work on
machine and I'm just going to work on the spacing a little bit that looks
the spacing a little bit that looks pretty
pretty good just to make this a little more
good just to make this a little more fancy I'm going to add a bunch of
fancy I'm going to add a bunch of asterisks as separators before and after
asterisks as separators before and after not necessary I just think it looks cool
not necessary I just think it looks cool and that's a good enough
and that's a good enough reason let's perform a test run just to
reason let's perform a test run just to be sure that this looks
be sure that this looks fine I think that looks pretty good all
fine I think that looks pretty good all right we have our welcome
right we have our welcome message our next step is to play our
message our next step is to play our game if our balance is greater than zero
game if our balance is greater than zero this can be done with the while
this can be done with the while loop while our balance is greater than
loop while our balance is greater than zero we will continue
zero we will continue playing then we have to enter the BET
playing then we have to enter the BET amount that's the next step
amount that's the next step first we'll display our current
first we'll display our current balance current balance colon
balance current balance colon space pick unit of currency I'll pick
space pick unit of currency I'll pick American
American dollars plus we will display our balance
dollars plus we will display our balance variable we will ask a user for some
variable we will ask a user for some input place your bet
input place your bet amount I'll use print rather than print
amount I'll use print rather than print line because I like the user input on
line because I like the user input on the same line we will assign our bet
the same line we will assign our bet variable use our scanner to accept some
variable use our scanner to accept some input let's say next int we won't deal
input let's say next int we won't deal with cents we'll just bet whole
with cents we'll just bet whole dollars then we have a couple substeps
dollars then we have a couple substeps we have to verify if our bet is greater
we have to verify if our bet is greater than our
balance we'll write an if statement if bet is greater than our
statement if bet is greater than our balance we'll output the following
balance we'll output the following let's say insufficient
let's say insufficient funds we'll want to skip the current
funds we'll want to skip the current cycle of this Loop we'll use continue to
cycle of this Loop we'll use continue to go back to the
go back to the beginning then we'll verify if the bet
beginning then we'll verify if the bet is greater than
is greater than zero we don't want a user to bet
zero we don't want a user to bet negative
negative money else
if our bet let's say less than or equal to zero we don't want to use our betting
to zero we don't want to use our betting no
money bet must be greater than zero else we have to subtract the BET
zero else we have to subtract the BET from the
from the balance we could say balance equals
balance we could say balance equals balance minus bet but we can shorten
balance minus bet but we can shorten this using the augmented assignment
this using the augmented assignment operator we can say balance minus equals
operator we can say balance minus equals bet Within our LF statement we're going
bet Within our LF statement we're going to use the continue keyword to skip the
to use the continue keyword to skip the current iteration of this Loop so
current iteration of this Loop so temporarily within my else statement I'm
temporarily within my else statement I'm just going to print our balance right
after just to be sure that it's all working let's do a test
working let's do a test run okay welcome to Java slots current
run okay welcome to Java slots current balance $100 place your bet amount I
balance $100 place your bet amount I will bet money that I don't have one1
will bet money that I don't have one1 kajillion dollars insufficient funds
kajillion dollars insufficient funds current balance $100 place your bet
current balance $100 place your bet amount we can't bet negative money I'll
amount we can't bet negative money I'll bet1 bet must be greater than zero then
bet1 bet must be greater than zero then we're brought back to the beginning I
we're brought back to the beginning I will bet
will bet $10 and our new balance is
$10 and our new balance is $90 all right we know that that
$90 all right we know that that works we can delete this print line
works we can delete this print line statement we no longer need it we were
statement we no longer need it we were just testing something our next step is
just testing something our next step is that we're going to spin our row of
that we're going to spin our row of symbols our
emojis after we subtract our bet from our balance it's here that we'll spin
our balance it's here that we'll spin our Row first I'll print the following
our Row first I'll print the following message let's say the word
message let's say the word spinning then we will call a method to
spinning then we will call a method to spin our row but we will need to declare
spin our row but we will need to declare this method we will do that outside of
this method we will do that outside of the main
the main method this will be a static method the
method this will be a static method the return type is going to be an array of
return type is going to be an array of strings
strings string array and the name of the method
string array and the name of the method will be spin
row we'll be creating a few local variables within this method but first
variables within this method but first we do need to return
we do need to return something because we promised that we're
something because we promised that we're going to return a string array in order
going to return a string array in order for this program to run a compile fine I
for this program to run a compile fine I will add The Following return statement
will add The Following return statement return a new empty array of strings
return a new empty array of strings we'll be replacing this later but we do
we'll be replacing this later but we do have to return something in order for
have to return something in order for this method to at least work we'll be
this method to at least work we'll be creating a few local variables the first
creating a few local variables the first is a string
is a string array named
array named symbols equals then within a set of cly
symbols equals then within a set of cly braces we need our emojis let's go back
braces we need our emojis let's go back to the
to the beginning copy our
beginning copy our emojis then place them within this array
emojis then place them within this array they do need to be surrounded with a set
they do need to be surrounded with a set of double quotes because this is an
of double quotes because this is an array of strings
array of strings so let's take a moment to take care of
that all right that is good we will declare a string array named row our row
declare a string array named row our row is going to be empty it's going to be a
is going to be empty it's going to be a new string array that can hold three
new string array that can hold three elements row is an empty array that can
elements row is an empty array that can hold three strings which will be picked
hold three strings which will be picked at random
we will be generating random numbers we need a random object random random
need a random object random random equals new
equals new random then import this
random then import this class at the top import java.util
random temporarily there's something I'm going to demonstrate let's display our
going to demonstrate let's display our aray of symbols at index of zero that
aray of symbols at index of zero that should output this first Emoji a cherry
should output this first Emoji a cherry I'll just bet a dollar doesn't matter
I'll just bet a dollar doesn't matter and we have our
watermelon watermelon then four should be our
star star we need to choose a random number
star we need to choose a random number between zero and four when we select our
between zero and four when we select our array of symbols within the straight
array of symbols within the straight brackets where we list an index we will
brackets where we list an index we will take our random object call the next int
take our random object call the next int method we will generate a random number
method we will generate a random number between zero and
between zero and five the first number is inclusive the
five the first number is inclusive the second number is exclusive if your range
second number is exclusive if your range starts with zero you don't technically
starts with zero you don't technically need this first number you could just
need this first number you could just say
say five let's run this a few times just to
five let's run this a few times just to see what
see what happens so that time I got a bell
cherry and a watermelon if we have more or less
watermelon if we have more or less emojis we would need to change this
emojis we would need to change this number why don't we use the length of
number why don't we use the length of our symbols instead symbols then give me
our symbols instead symbols then give me the length property of this
the length property of this array if we were to add more or less
array if we were to add more or less symbols our length is going to change
symbols our length is going to change automatically when we run and compile
automatically when we run and compile this
this program so we'll do a test run again
program so we'll do a test run again again and that seems to
work you're getting a random symbol each time let's delete the print line
time let's delete the print line statement portion of
statement portion of this we need to generate three random
this we need to generate three random symbols we can use a for Loop for that
symbols we can use a for Loop for that for in I equals 0 we will continue as
for in I equals 0 we will continue as long as I is less than three then
long as I is less than three then increment I by One
increment I by One we will take our row at index of I in
we will take our row at index of I in the beginning I is going to equal zero
the beginning I is going to equal zero then one then two then the four Loop
then one then two then the four Loop ends we will assign row at index of I
ends we will assign row at index of I equal to cut this line of
equal to cut this line of code we're picking a random symbol from
code we're picking a random symbol from our array of strings our array of
our array of strings our array of emojis at the end we will return our row
emojis at the end we will return our row we're returning our array of strings
we're returning our array of strings just to test it I'm going to Output
just to test it I'm going to Output using print row at index
one plus row at index 2 I just want to be sure that we get three random
symbols there we go we get three random symbols we'll format the output later so
symbols we'll format the output later so don't
don't wor we can delete this statement we were
wor we can delete this statement we were just testing
just testing something now this method is complete we
something now this method is complete we can close
can close it we're returning a string array back
it we're returning a string array back to the place in which we called this
to the place in which we called this method we can assign this
method we can assign this array back to the beginning we will
array back to the beginning we will assign our string array of
row our row equals call the spin row method and this will return a string
method and this will return a string array which we're assigning to row once
array which we're assigning to row once we have our row we're going to print our
we have our row we're going to print our row we'll need to create another method
row we'll need to create another method for that we will create a static method
for that we will create a static method it's not going to return anything the
it's not going to return anything the return type is void the name will be
return type is void the name will be print
print row there will be one parameter we
row there will be one parameter we accept a string array which we will name
accept a string array which we will name row after assigning our row we will call
row after assigning our row we will call call the print row
call the print row method but we have to pass in our
method but we have to pass in our row because we have one parameter we
row because we have one parameter we have to pass in a string array which we
have to pass in a string array which we are so here's where we'll print and
are so here's where we'll print and display our row of emojis let's output
display our row of emojis let's output the following I will display a space
the following I will display a space character plus now the string class has
character plus now the string class has a few useful methods type string with a
a few useful methods type string with a capital s dot call the join method
capital s dot call the join method for each character within a string we
for each character within a string we can join them together with another
can join them together with another character I will join them by a space a
character I will join them by a space a vertical bar then a space comma
vertical bar then a space comma Row for every string in my string array
Row for every string in my string array of row we're going to join them with the
of row we're going to join them with the vertical bar along with a space before
vertical bar along with a space before and after here's the output
and after here's the output currently I'll just bet a dollar here's
currently I'll just bet a dollar here's what we have we have three
what we have we have three emojis each separated with the IAL
emojis each separated with the IAL bar I'll add some of those separators
bar I'll add some of those separators too those
too those asterisks 14 Aster risks should be
enough all right let's take another look I'll bet
I'll bet $10 that looks pretty good I'm happy
$10 that looks pretty good I'm happy with that our next step is to get a
with that our next step is to get a payout if there's any
payout if there's any matches we can collapse this method we
matches we can collapse this method we no longer need
no longer need it now we need to get our
it now we need to get our payout after printing our row we will
payout after printing our row we will call a method of get payout which we
call a method of get payout which we still need to
still need to declare we'll pass in two things our
declare we'll pass in two things our string array of row and our bet how much
string array of row and our bet how much money did we
money did we bet we need to declare this
bet we need to declare this method after the print row method we
method after the print row method we will declare a static method this method
will declare a static method this method is going to return an integer our payout
is going to return an integer our payout the method name will be get
the method name will be get payout we have to set up the parameters
payout we have to set up the parameters we're accepting a string
we're accepting a string array we will name the string array
array we will name the string array row and a bet our bet is an integer int
row and a bet our bet is an integer int bet we do need to return something just
bet we do need to return something just temporarily at the end I'm going to
temporarily at the end I'm going to return
return zero we need to check to see if we have
zero we need to check to see if we have any
any matches what we could do first is check
matches what we could do first is check to see if all three elements match are
to see if all three elements match are all these strings the same symbol here's
all these strings the same symbol here's how we can do
how we can do that let's write an if
that let's write an if statement if our
statement if our row at index of zero that's the first
row at index of zero that's the first symbol now you can't use the comparison
symbol now you can't use the comparison operator for Strings cuz they're
operator for Strings cuz they're reference data
reference data types you would think you could say if
types you would think you could say if row at index 0 is equal to row at index
row at index 0 is equal to row at index one but you actually need to use
one but you actually need to use equals if row at index
equals if row at index zero equals row at index
one if the first two symbols match row at index0 and row at index one well then
at index0 and row at index one well then the first two symbols match but not only
the first two symbols match but not only that we have to compare row at index one
that we have to compare row at index one and row at index 2 do those match as
and row at index 2 do those match as well we're checking to see if all three
well we're checking to see if all three symbols match we will use the and
symbols match we will use the and logical operator and we can copy this
logical operator and we can copy this check paste it and if row at index one
check paste it and if row at index one equals row at index 2 if all three
equals row at index 2 if all three symbols match then we execute this if
symbols match then we execute this if statement why don't we use an enhanced
statement why don't we use an enhanced switch a switch can return something
switch a switch can return something we'll use the return
we'll use the return keyword create a switch within the
keyword create a switch within the switch where are we examining let's
switch where are we examining let's examine one of these symbols we can just
examine one of these symbols we can just pick any I'll just pick the first
pick any I'll just pick the first one we are examining our row at index
one we are examining our row at index zero all three symbols are going to be
zero all three symbols are going to be the same so it doesn't matter which one
the same so it doesn't matter which one you pick we'll examine this value this
you pick we'll examine this value this Emoji against any matching cases the
Emoji against any matching cases the first case will be our first symbol of a
first case will be our first symbol of a cherry if these two values match we'll
cherry if these two values match we'll do the following we'll write an arrow
do the following we'll write an arrow and we're going to be returning
and we're going to be returning something let's return our bet times
something let's return our bet times three let's
three let's say we get a payout of three times what
say we get a payout of three times what we bet for our next
we bet for our next case that was a
case that was a watermelon the payout will be
lemon let's set the payout to be five a
Bell three matching Bells will be worth 10 three stars let's say is
20 bet times 20 We'll add a default case too in case
20 We'll add a default case too in case there's no
there's no matches default Arrow return
zero looks like I'm missing a semicolon at the end if all three symbols match
at the end if all three symbols match return our bet times a certain amount
return our bet times a certain amount depending on which symbols
depending on which symbols match the get payout method is going to
match the get payout method is going to return an
return an integer we will assign our variable of
integer we will assign our variable of payout equal to get
payout if our payout is greater than zero we'll do the following that means
zero we'll do the following that means we won something if that's the case
we won something if that's the case let's let's output U1 pick a unit of
let's let's output U1 pick a unit of currency plus our payout whatever we
currency plus our payout whatever we win then we will add that to our balance
win then we will add that to our balance balance equals balance plus our payout
balance equals balance plus our payout but we can shorten this using the
but we can shorten this using the augmented assignment operator for
augmented assignment operator for addition balance plus equals our
payout else if we don't get a payout if our payout is zero that means we didn't
our payout is zero that means we didn't win anything we'll
win anything we'll output sorry you lost this round okay
output sorry you lost this round okay let's do a few test runs I'm going to
let's do a few test runs I'm going to keep on running this until we get three
keep on running this until we get three matching symbols just to be sure that it
matching symbols just to be sure that it all works I will bet a
all works I will bet a dollar our message is sorry you lost
dollar our message is sorry you lost this round and the current balance is
this round and the current balance is $99 I'll bet another dollar you lost you
$99 I'll bet another dollar you lost you lost you
lost you lost it's hard to get three matching
lost it's hard to get three matching symbols here we go I have three matching
symbols here we go I have three matching cherries you won $3 and my current
cherries you won $3 and my current balance is
balance is $86 now if you would like to check to
$86 now if you would like to check to see if the first two symbols match or
see if the first two symbols match or the second two you can add the following
the second two you can add the following code let's copy our if
code let's copy our if statement paste it change if to be else
statement paste it change if to be else if we'll only be checking the first two
if we'll only be checking the first two symbols we can delete the second
symbols we can delete the second condition
condition if the first two symbols match we'll
if the first two symbols match we'll give a reduced payout let's say for two
give a reduced payout let's say for two matching cherries that will be two for
matching cherries that will be two for watermelon that will be three
watermelon that will be three 4 5 and then
4 5 and then 10 if the second symbol matches the
10 if the second symbol matches the third
third one we'll write another L
one we'll write another L statement index one and index two will
statement index one and index two will give the same
give the same payout hello this is from the future
payout hello this is from the future there's just one bug that I need to fix
there's just one bug that I need to fix the else if statement where we check if
the else if statement where we check if our second symbol matches the third
our second symbol matches the third within our switch we have to examine one
within our switch we have to examine one of these two symbols I forgot to change
of these two symbols I forgot to change that originally both these symbols
that originally both these symbols should be the same so it doesn't matter
should be the same so it doesn't matter which one we pick I'll just pick the
which one we pick I'll just pick the index at one back to the previous LF
index at one back to the previous LF statement index zero is fine because the
statement index zero is fine because the first two symbols should match I just
first two symbols should match I just needed to fix that that is all let's
needed to fix that that is all let's check to be sure that works I'll bet a
check to be sure that works I'll bet a dollar so my first two symbols match we
dollar so my first two symbols match we have a reduced payout of $3 but if it
have a reduced payout of $3 but if it was three watermelons we would win $4
instead we can close this get payout method we're done with
method we're done with it here we'll ask the user to play again
it here we'll ask the user to play again if they would like to
continue we'll create a prompt do you want to play again I'll
prompt do you want to play again I'll use print rather than print
use print rather than print line there's one more variable we'll
line there's one more variable we'll need that I'm
need that I'm forgetting let's create a string
forgetting let's create a string variable of play
again we will assign play again equal to use our scanner call the next line
use our scanner call the next line method
method we'll want a user to type in either
we'll want a user to type in either capital y or capital N after accepting
capital y or capital N after accepting user input we'll make it uppercase using
user input we'll make it uppercase using the two uppercase
method using an if statement we'll check we'll check if play again doesn't
equal for comparing strings we use equals if play again doesn't equal a
equals if play again doesn't equal a capital Y then we will break to break
capital Y then we will break to break out of the loop that we're
out of the loop that we're in then go to the exit the exit
in then go to the exit the exit message one more thing we need to add
message one more thing we need to add though I'm going to play a
though I'm going to play a bet we get that prompt to play again but
bet we get that prompt to play again but the program exits after typing in a
the program exits after typing in a number there's still a new line
number there's still a new line character within the input
character within the input buffer because we're using next int next
buffer because we're using next int next integer we need to clear that input
integer we need to clear that input buffer
buffer after this line of codee where we call
after this line of codee where we call the next int method we can take our
the next int method we can take our scanner called the next line method to
scanner called the next line method to get rid of that new line character and
get rid of that new line character and that should
that should work I'll bet a dollar then we can play
work I'll bet a dollar then we can play again if we type in
again if we type in y we display our current balance we can
y we display our current balance we can place another
place another bet hey $50 that time I'll type n to not
bet hey $50 that time I'll type n to not play again then we exit
play again then we exit the last thing we're going to do is
the last thing we're going to do is display an exit
display an exit message we'll take care of that right
message we'll take care of that right here once we're out of the
here once we're out of the loop let's output the
loop let's output the following game
following game over your final
over your final balance is pick unit of
balance is pick unit of currency then I will add our variable of
currency then I will add our variable of balance okay let's run this one last
balance okay let's run this one last time welcome to Java slots I'll bet a
time welcome to Java slots I'll bet a dollar sorry you lost would you like to
dollar sorry you lost would you like to play again I will type y for yes current
play again I will type y for yes current balance $99 I will bet a dollar
balance $99 I will bet a dollar again I
again I lost I'll just keep playing till I win
lost I'll just keep playing till I win hey I won $10 we have two matching Stars
hey I won $10 we have two matching Stars I'll play one more time I will bet
I'll play one more time I will bet $10 and I won 20 we have two matching
$10 and I won 20 we have two matching symbols I will type in no to not play
symbols I will type in no to not play again and we get our game over message
again and we get our game over message your final balance is
your final balance is $117 so we came out ahead all right
$117 so we came out ahead all right everybody that is a slot machine game
everybody that is a slot machine game you can create using
Java yo we have finally made it to object-oriented programming in Java so
object-oriented programming in Java so what is an object exactly look around
what is an object exactly look around wherever you're sitting right now you
wherever you're sitting right now you are surrounded by different objects for
are surrounded by different objects for example next to me I have my phone a cup
example next to me I have my phone a cup of coffee and a microphone in
of coffee and a microphone in programming an object can represent a
programming an object can represent a real world entity they can do one of a
real world entity they can do one of a few things objects can hold data and
few things objects can hold data and they can perform actions the data they
they can perform actions the data they hold are known as attributes the actions
hold are known as attributes the actions that they can perform are known as
that they can perform are known as methods objects can have things and they
methods objects can have things and they can do things some attributes that a
can do things some attributes that a person may have would be a name their
person may have would be a name their age their height and their weight a few
age their height and their weight a few methods meaning actions that a human
methods meaning actions that a human could do a person well they could eat
could do a person well they could eat and they could sleep objects are
and they could sleep objects are reference data types we store the data
reference data types we store the data for an object in a location known as the
for an object in a location known as the Heap in this demonstration we're going
Heap in this demonstration we're going to be creating some car objects but
to be creating some car objects but we'll need a Class A Class can serve as
we'll need a Class A Class can serve as a blueprint to create objects so what
a blueprint to create objects so what we're going to do is create a new Java
we're going to do is create a new Java class we will create a class of car
class we will create a class of car we have two classes our main class and
we have two classes our main class and our car
our car Class A Class can behave as a blueprint
Class A Class can behave as a blueprint for creating objects we'll start by
for creating objects we'll start by listing the different attributes that a
listing the different attributes that a car may have so what does a car have
car may have so what does a car have exactly well a car could have a make
exactly well a car could have a make that would be a
that would be a string we can assign it if we would like
string we can assign it if we would like think of a car you'd like or a car you
think of a car you'd like or a car you drive I'll pick my favorite car the make
drive I'll pick my favorite car the make will be Ford another attribute could be
will be Ford another attribute could be a
a model and I will pick a
model and I will pick a Mustang cars could have a year that
Mustang cars could have a year that would be an integer into Year I'll pick
would be an integer into Year I'll pick the year
the year 2025 a price that could be a double
2025 a price that could be a double double price
double price equals let's say
equals let's say $58,000
$58,000 99 a car's engine could be running that
99 a car's engine could be running that could be a Boolean Boolean is running I
could be a Boolean Boolean is running I will set that to be true
will set that to be true or false if the car is turned off things
or false if the car is turned off things that an object has in this case car
that an object has in this case car these are known as attributes they are
these are known as attributes they are things that an object
things that an object has now heading back to our main class
has now heading back to our main class we will create a car
we will create a car object we're already a little familiar
object we're already a little familiar with working with objects for example a
with working with objects for example a scanner is an object to create a scanner
scanner is an object to create a scanner we would type scanner scanner equals new
scanner then you type system.in or with random objects we
system.in or with random objects we would type random random equals new
random Now to create a car object we're going to be utilizing this
going to be utilizing this class we'll type car then think of a
class we'll type car then think of a name for this car we'll just say car all
name for this car we'll just say car all lowercase equals new car we're following
lowercase equals new car we're following a similar
a similar pattern car car equals new
pattern car car equals new car we don't need the scanner or the
car we don't need the scanner or the random object I was just demonstrating
random object I was just demonstrating something we now have a car object that
something we now have a car object that we can use our car object has these
we can use our car object has these attributes these
things if I was to print my car object here's what we can
here's what we can see well since objects are a reference
see well since objects are a reference data type if you were to print your car
data type if you were to print your car directly you get a memory
address if you need to access one of these attributes
these attributes you have to follow the object name with
you have to follow the object name with a DOT a DOT is known as the dot operator
a DOT a DOT is known as the dot operator it allows you to access things within an
it allows you to access things within an object if I need the model of my car I
object if I need the model of my car I would take my object name use the dot
would take my object name use the dot operator followed by the attribute name
operator followed by the attribute name if I was to print the model of my
if I was to print the model of my car that would output
car that would output Mustang let's print some of the other
Mustang let's print some of the other attributes car. make who manufactures
attributes car. make who manufactures the
the car
car Ford what is the year of my car car.
price $58,000 and
$58,000 and 99 is my car running or not car do is
99 is my car running or not car do is running
false the car is not currently running you can modify and change these
you can modify and change these attributes too with our car object let's
attributes too with our car object let's access the is running attribute I will
access the is running attribute I will set that to be true like we're turning
set that to be true like we're turning the car
the car on is running is now true because we
on is running is now true because we changed the attribute of is
changed the attribute of is running not only do objects have the
running not only do objects have the capability to hold data meaning
capability to hold data meaning attributes they can perform actions they
attributes they can perform actions they can have their own methods going back to
can have their own methods going back to our car class we'll Define a few
our car class we'll Define a few methods what sorts of actions can a car
methods what sorts of actions can a car take well we could start a car within
take well we could start a car within this class we will Define a method we
this class we will Define a method we don't need that static keyword this time
don't need that static keyword this time we need a return type we'll say void
we need a return type we'll say void we're not returning anything we will
we're not returning anything we will Define a method of
Define a method of start let's do the following let's
start let's do the following let's output
output you start the
you start the engine we'll create another
engine we'll create another method
method void
stop let's say you stop the engine so now with our
engine so now with our car we can delete these print line
car we can delete these print line statements we'll take our car object use
statements we'll take our car object use the dot operator call the start method
the dot operator call the start method method this should output you start the
method this should output you start the engine or we can stop car.
stop you start the engine you stop the engine not only that Within These
engine not only that Within These methods let's change one of these
methods let's change one of these variables one of these
variables one of these attributes within our start method let's
attributes within our start method let's take is running set that to be
take is running set that to be true within the stop method we'll take
true within the stop method we'll take is running set that to be
false going back to our main class before starting the car let's
class before starting the car let's output car do is
output car do is running after starting the car let's
running after starting the car let's output car dot is running and then
output car dot is running and then stopping the car will output car dot is
stopping the car will output car dot is running the car is currently not running
running the car is currently not running that's false you start the engine the
that's false you start the engine the car is now running that's set to true
car is now running that's set to true you stop the engine the car is no longer
you stop the engine the car is no longer running that is
running that is false let's add two more methods we can
false let's add two more methods we can start we can stop we can drive we'll
start we can stop we can drive we'll create a method to drive void
Drive let's output you drive the I'm going to use string concatenation we'll
going to use string concatenation we'll concatenate the model of the
concatenate the model of the car so my car is a Mustang
car so my car is a Mustang we will create a method to
break you break the plus our model variable
you break the plus our model variable our model
our model attribute we can delete these lines of
attribute we can delete these lines of code let's drive the car car.
code let's drive the car car. drive you drive the Mustang and here's
drive you drive the Mustang and here's the model of the car and we can break
the model of the car and we can break car. break
you drive the Mustang you break the Mustang there's one issue with this
Mustang there's one issue with this though with our class of car every car
though with our class of car every car that we make has the same attributes and
that we make has the same attributes and methods we can only create 225 Ford
Mustangs if I was to create another car object let's say car car 2
object let's say car car 2 equals new
equals new car we'll rename the first car as car
car we'll rename the first car as car 1 and I'll output some of their
1 and I'll output some of their attributes Car
attributes Car 1make Plus a
1make Plus a space plus car
space plus car 1 model we'll do this with our second
1 model we'll do this with our second car object too Car 2 car 2. make car 2.
car object too Car 2 car 2. make car 2. model these cars have the same
model these cars have the same attributes it would be nice if we had a
attributes it would be nice if we had a way to customize them so that each car
way to customize them so that each car is unique because currently they're all
is unique because currently they're all the same they're different cars but they
the same they're different cars but they have the same attributes and methods
have the same attributes and methods which is kind of lame that's why in the
which is kind of lame that's why in the next video we're going to discuss
next video we're going to discuss Constructors by passing in arguments we
Constructors by passing in arguments we can create unique objects in summary an
can create unique objects in summary an object is an entity that holds data it
object is an entity that holds data it has attributes and they can perform
has attributes and they can perform actions they can perform
actions they can perform methods they have things and they can do
methods they have things and they can do things and and well everybody those are
things and and well everybody those are objects in
Java hey yeah today we're talking about Constructors in Java a Constructor is
Constructors in Java a Constructor is just a special method within a class
just a special method within a class it's used to initialize objects by using
it's used to initialize objects by using a Constructor we can create objects with
a Constructor we can create objects with unique values when you create an object
unique values when you create an object you can pass arguments to a Constructor
you can pass arguments to a Constructor to set up the initial values here's a
to set up the initial values here's a demonstration what we're going to do is
demonstration what we're going to do is create a new class let's go to file new
create a new class let's go to file new Java
Java class let's create a class of students
class let's create a class of students this will be the student
this will be the student class what are some attributes that a
class what are some attributes that a student should have they should have a
student should have they should have a name let me zoom in a little so you can
name let me zoom in a little so you can read it NH AG int
read it NH AG int ag ag GPA meaning grade point
ag ag GPA meaning grade point average let's create a Boolean of is
average let's create a Boolean of is enrolled
enrolled that is good enough for now there's one
that is good enough for now there's one issue with this let's say that all
issue with this let's say that all students that I create using this class
students that I create using this class they're all going to be named
they're all going to be named SpongeBob going back to my Java file
SpongeBob going back to my Java file I'll create a few
I'll create a few students we type the name of the class
students we type the name of the class and name for this object let's say
and name for this object let's say student one equals new student the name
student one equals new student the name of the class
of the class again then we'll create a second
again then we'll create a second student student two
student student two I'm going to Output student one's name
I'm going to Output student one's name student 1. name as well as student 2's
name the issue that we have is that all students that we create all student
students that we create all student objects they're all named
objects they're all named SpongeBob what if we would like to give
SpongeBob what if we would like to give each object a unique name well we can do
each object a unique name well we can do that with the help of a Constructor a
that with the help of a Constructor a Constructor is just a special method
Constructor is just a special method within a class
within a class to set up a Constructor we type the name
to set up a Constructor we type the name of the class in this case student you
of the class in this case student you need a set of parentheses then a set of
need a set of parentheses then a set of curly
curly braces we automatically call this
braces we automatically call this Constructor when we instantiate an
Constructor when we instantiate an object of that class when we say new
object of that class when we say new then the name of the class
then the name of the class parenthesis behind the scenes we're
parenthesis behind the scenes we're calling this
calling this Constructor and we can pass in
Constructor and we can pass in arguments within the set of parentheses
arguments within the set of parentheses we can pass in arguments so let's pass
we can pass in arguments so let's pass in what are we missing a name age GPA is
in what are we missing a name age GPA is enrolled as well but we'll take care of
enrolled as well but we'll take care of that momentarily let's pass in a name
that momentarily let's pass in a name age and
age and GPA student one's name will be
GPA student one's name will be SpongeBob SpongeBob's age will be let's
SpongeBob SpongeBob's age will be let's say 30 he seems about 30 SpongeBob's GPA
say 30 he seems about 30 SpongeBob's GPA can be 3.2 that's pretty
can be 3.2 that's pretty good we have a warning our Constructor
good we have a warning our Constructor isn't set up to take these arguments
isn't set up to take these arguments going back to our Constructor since
going back to our Constructor since we're receiving arguments we need a
we're receiving arguments we need a matching set of parameters just like any
matching set of parameters just like any other method we have a string for name
other method we have a string for name integer of age double GPA we'll take
integer of age double GPA we'll take care of these three first we have string
care of these three first we have string name int age double
name int age double GPA to assign some of these attributes
GPA to assign some of these attributes we're going to use the this keyword this
we're going to use the this keyword this dot the name of the attribute this do
dot the name of the attribute this do name equals our parameter of
name equals our parameter of name this. AG equals the age that we
name this. AG equals the age that we receive this. GPA equals the GPA that we
receive this. GPA equals the GPA that we receive going back to our Java file we
receive going back to our Java file we can now construct an object if I attempt
can now construct an object if I attempt to run this currently we are receiving a
to run this currently we are receiving a warning our Constructor expects three
warning our Constructor expects three arguments but we don't pass in any zero
arguments but we don't pass in any zero are found if I were to run
are found if I were to run this we get this error message actual
this we get this error message actual and formal argument lists differ in
and formal argument lists differ in length in order for us to create a scent
length in order for us to create a scent object we have to pass in these three
object we have to pass in these three things a string for the name an integer
things a string for the name an integer for the age and a double for the
for the age and a double for the GPA if we are missing these three we
GPA if we are missing these three we can't construct an object but previously
can't construct an object but previously we could with without the Constructor
we could with without the Constructor for our second student let's pass in a
for our second student let's pass in a name of Patrick Patrick will be
name of Patrick Patrick will be 34 Patrick's GPA isn't too good it's a
1.5 all right let's test this we're printing student one's name and student
printing student one's name and student 2's
2's name we get SpongeBob and
name we get SpongeBob and Patrick let's display some of the other
attributes we have name age
name age GPA we'll do this with student 2 as well
GPA we'll do this with student 2 as well student 2.age student 2.
GPA SpongeBob SpongeBob is 30 years old SpongeBob's GPA is
SpongeBob's GPA is 3.2 these are all the unique attributes
3.2 these are all the unique attributes of our student object student
of our student object student one student 2's attributes are Patrick
one student 2's attributes are Patrick age is 34 GPA is 1.5
with the this keyword this refers to the object we're currently constructing or
object we're currently constructing or otherwise working with imagine that when
otherwise working with imagine that when we construct student
we construct student one imagine we replace the this keyword
one imagine we replace the this keyword with the name of the object we're
with the name of the object we're assigning student one's name equal to
assigning student one's name equal to the name that we receive same thing
the name that we receive same thing applies with our age and our
applies with our age and our GPA the same thing would apply with
GPA the same thing would apply with student 2 when we construct student 2
student 2 when we construct student 2 imagine during the process we replace
imagine during the process we replace this with student
this with student 2 this refers to the object we're
2 this refers to the object we're currently working with or
currently working with or constructing with these parameter names
constructing with these parameter names they don't necessarily need to be the
they don't necessarily need to be the same as your attribute names just to
same as your attribute names just to demonstrate let's rename name as a age
demonstrate let's rename name as a age as B GPA as C this.name equals a this.
as B GPA as C this.name equals a this. age equals B this. GPA equals c
age equals B this. GPA equals c this should work
this should work too each object still has their unique
attributes but I like to keep the parameter names the same as the
parameter names the same as the attributes it makes the code easier to
attributes it makes the code easier to read and understand we haven't assigned
read and understand we haven't assigned to this attribute of is
to this attribute of is enrolled each object that we create
enrolled each object that we create using this Constructor let's assign this
using this Constructor let's assign this objects is enrolled attribute equal to
objects is enrolled attribute equal to you don't always necessarily need to
you don't always necessarily need to assign arguments to these attributes for
assign arguments to these attributes for example let's just say that when you
example let's just say that when you become a student you are enrolled that
become a student you are enrolled that is true we don't necessarily need to
is true we don't necessarily need to pass in an argument for that going back
pass in an argument for that going back to our main class let's print take
to our main class let's print take student ones is enrolled attribute and
student ones is enrolled attribute and then print it we'll do the same thing
then print it we'll do the same thing with student two
Patrick when we create a student object we're automatically setting is a
we're automatically setting is a enrolled to be true they are enrolled in
enrolled to be true they are enrolled in classes and that applies to Patrick as
classes and that applies to Patrick as well student to Let's create another
well student to Let's create another student object just so that we get the
student object just so that we get the hang of this repetition is going to help
hang of this repetition is going to help you remember let's create student 3
you remember let's create student 3 student 3 is an object
student 3 is an object new
new student to create a student we have to
student to create a student we have to pass in three things a string for the
pass in three things a string for the name an integer for the age and a double
name an integer for the age and a double for the
for the GPA student 3 will be be
GPA student 3 will be be Sandy Sandy is 27 let's say Sandy is
Sandy Sandy is 27 let's say Sandy is smart she'll have a 4.0
smart she'll have a 4.0 GPA and then we'll print student 3's
GPA and then we'll print student 3's attributes student 3. name student 3's
attributes student 3. name student 3's age student 3's GPA student 3 is
age student 3's GPA student 3 is enrolled our object of student 3 has
enrolled our object of student 3 has these attributes Sandy 27 4.0 and
these attributes Sandy 27 4.0 and true if if your class has any methods
true if if your class has any methods for example all students have the method
for example all students have the method to
study void study I'll just output the following let's take our name
following let's take our name attribute but I'm going to use
attribute but I'm going to use this.name plus the text of is
this.name plus the text of is studying let's delete these print line
studying let's delete these print line statements we'll take student one call
statements we'll take student one call the study method
the study method then we'll do this with student two and
then we'll do this with student two and student
3 SpongeBob is studying Patrick is studying Sandy is
studying after assigning values to your attributes using a Constructor you can
attributes using a Constructor you can use them within methods too or change
use them within methods too or change them this refers to the object we're
them this refers to the object we're currently working with if student 3
currently working with if student 3 meaning Sandy was to call her study
meaning Sandy was to call her study method imagine we're replacing this with
method imagine we're replacing this with student 3 student 3's name
student 3 student 3's name attribute all right everybody those are
attribute all right everybody those are Constructors they're a special method
Constructors they're a special method found within a class to initialize
found within a class to initialize objects you can pass arguments to a
objects you can pass arguments to a Constructor when you initialize them
Constructor when you initialize them they're used to set up the initial
they're used to set up the initial values when you construct an object a
values when you construct an object a Constructor is automatically called when
Constructor is automatically called when you create a new object but you need a
you create a new object but you need a matching set of arguments if there's any
matching set of arguments if there's any parameter setup just like any other
parameter setup just like any other method by using a Constructor we can
method by using a Constructor we can create objects with unique values and
create objects with unique values and well everybody those are Constructors in
Java what is going on people today I'm going to explain overloaded Constructors
going to explain overloaded Constructors overloaded Constructors allow a class to
overloaded Constructors allow a class to have multiple Constructors with
have multiple Constructors with different parameter lists much like
different parameter lists much like overloaded methods they enable an object
overloaded methods they enable an object to be initialized in various ways here's
to be initialized in various ways here's a demonstration we are going to create a
a demonstration we are going to create a new class let's go to file new Java
new class let's go to file new Java class we will create a class for users
class we will create a class for users we will create a user
we will create a user class let's say that users have three
class let's say that users have three things they will have a string of
things they will have a string of username a string of
username a string of email and an integer in
email and an integer in age let's say that when we create a user
age let's say that when we create a user object these three fields are optional
object these three fields are optional if these three attributes are optional
if these three attributes are optional we may or may not receive them when we
we may or may not receive them when we construct a user object so let's do this
construct a user object so let's do this let's create a Constructor if somebody
let's create a Constructor if somebody were to create a user object with just a
were to create a user object with just a username to create a Constructor we type
username to create a Constructor we type the name of the class in this case
the name of the class in this case user we need to set up a parameter for
user we need to set up a parameter for our username we will receive a string of
our username we will receive a string of username we will assign this St user
username we will assign this St user usern name equal to the username that we
usern name equal to the username that we receive as an argument let's go back to
receive as an argument let's go back to our main Java
our main Java file we will create a new
file we will create a new user let's say user user one equals new
user let's say user user one equals new user we're receiving a warning
user we're receiving a warning though in order to create a user object
though in order to create a user object we have to pass in a string of
we have to pass in a string of username let's say that our user is
username let's say that our user is going to be SpongeBob because that's the
going to be SpongeBob because that's the first thing that came to mind for
first thing that came to mind for me we'll use this Constructor where we
me we'll use this Constructor where we have a username we can also set up the
have a username we can also set up the default values for our attributes too
default values for our attributes too let's say this. email equals a string of
let's say this. email equals a string of not
provided this. AG equals 0 going back to user
0 going back to user one I will output the
one I will output the following user one dot
username user one's email user 1's age here's what we got
here's what we got currently username is SpongeBob email is
currently username is SpongeBob email is not provided age is
not provided age is zero these attributes were optional when
zero these attributes were optional when we construct this object we're just
we construct this object we're just assigning them to some default values
assigning them to some default values what if we create a user that has an
what if we create a user that has an email well we could create another
email well we could create another Constructor with the same
Constructor with the same name but we need a different set of
name but we need a different set of parameters this is very similar to
parameters this is very similar to Method overloading you can have methods
Method overloading you can have methods with the same name but they need
with the same name but they need different
different parameters not only do we have a string
parameters not only do we have a string of username we'll have a string of
of username we'll have a string of email our email attribute equals the
email our email attribute equals the email that we receive we can use either
email that we receive we can use either of these Constructors depending on the
of these Constructors depending on the arguments that are passed in
arguments that are passed in let's create a second user user user 2
let's create a second user user user 2 equals new
equals new user the username will be
user the username will be Patrick Patrick's email is let's say
Patrick Patrick's email is let's say p Patrick is probably still using AOL
p Patrick is probably still using AOL for some reason let's say
for some reason let's say aol.com then we'll print user 2's
aol.com then we'll print user 2's attributes user 2. username user two.
attributes user 2. username user two. email user 2.age
email user 2.age here's what we got we have all the
here's what we got we have all the attributes for user one and user two
attributes for user one and user two Patrick P star
Patrick P star aol.com our age is still
aol.com our age is still zero we can create different objects
zero we can create different objects with a varying number of
with a varying number of arguments let's create a third
arguments let's create a third user this time we'll have a parameter
user this time we'll have a parameter for our age
for our age attribute I'm just going to copy this
attribute I'm just going to copy this cuz I'm lazy we'll have an INT age we
cuz I'm lazy we'll have an INT age we will assign our age variable
will assign our age variable with the age argument we
with the age argument we receive we'll create user
receive we'll create user 3 user user 3 equals new
user username will be Sandy email will be S
Sandy email will be S cheeks
cheeks gmail.com then an age let's say
gmail.com then an age let's say 27 then I'll print user 3's attributes
27 then I'll print user 3's attributes user 3. username email then
user 3. username email then age here is all of sy's attributes
age here is all of sy's attributes username email
age let's set up a Constructor that accepts no
arguments this will be kind of an anonymous
anonymous profile this. username will equal guest
profile this. username will equal guest or a guest
or a guest profile this . email
profile this . email equals not
provided this. AG equals z now we could create a user object then
z now we could create a user object then pass in no arguments user user 4 equals
pass in no arguments user user 4 equals new user this time we don't have any
new user this time we don't have any arguments then I'll display user Force
email age here's what we got username guessed
age here's what we got username guessed email not provided age is
email not provided age is zero in a way by creating an object and
zero in a way by creating an object and passing in no arguments you can set up
passing in no arguments you can set up some default
some default values all right everybody those are
values all right everybody those are overloaded Constructors they allow a
overloaded Constructors they allow a class to have multiple Constructors they
class to have multiple Constructors they just need different parameter lists they
just need different parameter lists they enable objects to be initialized in
enable objects to be initialized in various Ways by passing in a varying
various Ways by passing in a varying amount of
amount of arguments this would be great in a
arguments this would be great in a situation where some fields are optional
situation where some fields are optional when creating an object and well
when creating an object and well everybody those are overloaded
everybody those are overloaded Constructors in
Java hey everybody in this video I'm going to show you how we can create an
going to show you how we can create an array of objects using Java it's pretty
array of objects using Java it's pretty useful at times and you should probably
useful at times and you should probably know how to do it we'll Begin by
know how to do it we'll Begin by creating a new class let's go to file
creating a new class let's go to file new class we will create a car
new class we will create a car class let's say that cars have the
class let's say that cars have the following
following attributes we'll just pick two to keep
attributes we'll just pick two to keep it simple a string of model and a string
it simple a string of model and a string of color we'll need a car
of color we'll need a car Constructor we will pass in a string of
Constructor we will pass in a string of model and a string of color we will
model and a string of color we will assign this. model equals the model we
assign this. model equals the model we receive this. color equals the color
receive this. color equals the color that we receive we'll add one method
that we receive we'll add one method void drive all cars can drive well I'll
void drive all cars can drive well I'll put the following using a print line
put the following using a print line statement you drive
statement you drive the plus this. color plus a space plus
the plus this. color plus a space plus this. model okay we are done with the
this. model okay we are done with the car
car class we'll construct a few car objects
class we'll construct a few car objects let's start with car one car car 1
let's start with car one car car 1 equals a new car we have to pass in a
equals a new car we have to pass in a model and a
model and a color think of some cars that you like I
color think of some cars that you like I will pick a red Mustang for one car
will pick a red Mustang for one car let's create Car 2 Car 2 equals a new
let's create Car 2 Car 2 equals a new car I will pick a
car I will pick a Corvette that is blue one more car car 3
Corvette that is blue one more car car 3 car car 3 equals a new
car car 3 equals a new car a yellow
charger all right we have our three car objects we can create an array but for
objects we can create an array but for an array you have to list the data type
an array you have to list the data type of what you're storing we're going to be
of what you're storing we're going to be storing car objects the data type of the
storing car objects the data type of the array is going to be car objects car
array is going to be car objects car then for an array we need a set of
then for an array we need a set of straight
straight brackets what is the name of this array
brackets what is the name of this array going to be well I think cars would be
going to be well I think cars would be appropriate cars equals if you're
appropriate cars equals if you're creating an empty array you're going to
creating an empty array you're going to use the new keyword list the data type
use the new keyword list the data type of
of car within the straight brackets specify
car within the straight brackets specify the size of this array let's say three
the size of this array let's say three elements Max or we could go ahead and
elements Max or we could go ahead and just assign these right away too using a
just assign these right away too using a set of cly braces let's Place car 1 Car
set of cly braces let's Place car 1 Car 2 and car 3 within this array we'll
2 and car 3 within this array we'll place these three car objects within
place these three car objects within this array of cars now you could use a
this array of cars now you could use a for Loop to iterate through this array
for Loop to iterate through this array here's how we'll start with the standard
here's how we'll start with the standard for Loop we'll need an index in I equals
for Loop we'll need an index in I equals z we'll continue as long as I is less
z we'll continue as long as I is less than our cars length property then
than our cars length property then increment I by one we'll access our
increment I by one we'll access our array of cars at index of I which is
array of cars at index of I which is going to increase each time but it
going to increase each time but it starts at zero we will call the drive
starts at zero we will call the drive method and let's see what
happens you drive the red Mustang you drive the blue Corvette you drive the
drive the blue Corvette you drive the yellow
yellow charger now an enhanced for Loop would
charger now an enhanced for Loop would probably be more appropriate for
this if you want to use an enhanced for Loop type four parentheses curly
Loop type four parentheses curly braces what is the data type of each
braces what is the data type of each element within this array car objects
element within this array car objects we'll need a nickname for each element
we'll need a nickname for each element within this array let's say car colon
within this array let's say car colon think of colon as in then our array of
think of colon as in then our array of cars for every car object in our array
cars for every car object in our array of cars do the following we'll take each
of cars do the following we'll take each car object call the drive
car object call the drive method and that's going to do the same
method and that's going to do the same thing you drive the red Mustang you
thing you drive the red Mustang you drive the blue Corvette you drive the
drive the blue Corvette you drive the yellow
yellow charger another thing you can do to when
charger another thing you can do to when creating an array of objects you can
creating an array of objects you can pass in Anonymous objects rather than
pass in Anonymous objects rather than first instantiating the objects then
first instantiating the objects then assigning them to the array here's how
assigning them to the array here's how you can do
you can do that for each element we're going to
that for each element we're going to call the car Constructor with the new
call the car Constructor with the new keyword call the car Constructor then
keyword call the car Constructor then pass in the details for each car the
pass in the details for each car the necessary arguments we'll pass in our
necessary arguments we'll pass in our Mustang that's red that's the first
Mustang that's red that's the first element I'll just copy it to save some
element I'll just copy it to save some time then we're creating a new car but
time then we're creating a new car but this will be a
this will be a Corvette that's
Corvette that's blue and I'll put each of these on a new
blue and I'll put each of these on a new line just for readability
and then we have our charger that's
yellow and this will do the same thing too we have our three
too we have our three cars constructing a new object without
cars constructing a new object without giving the object a unique identifier
giving the object a unique identifier like car 1 Car 2 or car 3 these are
like car 1 Car 2 or car 3 these are known as Anonymous
known as Anonymous objects So within an array you can
objects So within an array you can create Anonymous objects if you would
create Anonymous objects if you would rather not give each of the car is a
rather not give each of the car is a unique identifier another thing you can
unique identifier another thing you can do too with an array of objects is let's
do too with an array of objects is let's change the color of each car using our
change the color of each car using our enhanced for Loop car do
enhanced for Loop car do color let's change the color to be black
color let's change the color to be black for each
for each car we'll use another enhanced for Loop
car we'll use another enhanced for Loop to display each car car die
drive you drive the black Mustang you drive the black Corvette you drive the
drive the black Corvette you drive the black
black charger all all right everybody those
charger all all right everybody those are a few things you can do with an
are a few things you can do with an array of objects in
Java hello everybody today I'm going to explain the static keyword using Java
explain the static keyword using Java static is a keyword it modifies a
static is a keyword it modifies a variable or method so that it belongs to
variable or method so that it belongs to the class rather than any specific
the class rather than any specific object we see the static keyword within
object we see the static keyword within the main method when you modify a
the main method when you modify a variable or method with the static
variable or method with the static keyword static is used to create utility
keyword static is used to create utility methods or other shared resources let me
methods or other shared resources let me give you a demonstration we're going to
give you a demonstration we're going to create a new class let's go to file new
create a new class let's go to file new class we'll create a front class we will
class we'll create a front class we will create some friend objects because
create some friend objects because you're
you're lonely let's say that all friends will
lonely let's say that all friends will have a name attribute string
have a name attribute string name we need a Constructor it's the same
name we need a Constructor it's the same as the class name parenthesis curly
as the class name parenthesis curly braces when we construct a friend object
braces when we construct a friend object we have to pass in a string of name we
we have to pass in a string of name we will assign this object's name attribute
will assign this object's name attribute equal to the name parameter that we
equal to the name parameter that we receive let's construct two friends
receive let's construct two friends we'll say friend friend one equals new
we'll say friend friend one equals new friend but we have to pass in a name
friend but we have to pass in a name pick a name my default is SpongeBob
pick a name my default is SpongeBob because most people know who SpongeBob
because most people know who SpongeBob is if I was to Output friend one's name
is if I was to Output friend one's name then it should be SpongeBob we just want
then it should be SpongeBob we just want to be sure that it
to be sure that it works yes it does SpongeBob
works yes it does SpongeBob now going back to our friend class let's
now going back to our friend class let's say we would like to keep track of how
say we would like to keep track of how many friend objects we create well that
many friend objects we create well that could be an attribute let's say we have
could be an attribute let's say we have an integer of num of friends meaning
an integer of num of friends meaning number of friends whenever we create a
number of friends whenever we create a friend object we will increment number
friend object we will increment number of friends by one num of friends
of friends by one num of friends Plus+ so going back let's output friend
Plus+ so going back let's output friend On's number of friends attribute num of
On's number of friends attribute num of friends so this should be one yep num
friends so this should be one yep num friends is one we have one friend but
friends is one we have one friend but what if we create a second friend object
what if we create a second friend object I'll just copy this line of code paste
I'll just copy this line of code paste it change friend one to friend two we'll
it change friend one to friend two we'll pass in a new name let's say
pass in a new name let's say Patrick we'll print friend One's number
Patrick we'll print friend One's number of friends and friend two's number of
of friends and friend two's number of friends how many friend objects have we
friends how many friend objects have we created we have created two but what's
created we have created two but what's the out
the out put well it's one for
put well it's one for both here's why each friend object has
both here's why each friend object has their own copy of the number of friends
their own copy of the number of friends variable we're incrementing each copy of
variable we're incrementing each copy of number of friends by one when we create
number of friends by one when we create the object of friend one we're
the object of friend one we're incrementing its attribute of number of
incrementing its attribute of number of friends by one same thing applies with
friends by one same thing applies with friend two when we create friend two
friend two when we create friend two friend 2's number of friends is zero and
friend 2's number of friends is zero and we're incrementing it by one what if we
we're incrementing it by one what if we would like to keep track of the total
would like to keep track of the total amount of friends that we created and
amount of friends that we created and store it within one variable well there
store it within one variable well there is a way we can do that and that is with
is a way we can do that and that is with the static
the static modifier so going back to our friend
modifier so going back to our friend class we're going to precede the data
class we're going to precede the data type of this attribute with the static
type of this attribute with the static modifier static int number of friends
modifier static int number of friends rather than all objects all friend
rather than all objects all friend objects having their own copy of number
objects having their own copy of number of friends they're all going to share
of friends they're all going to share one so going back let's print a number
one so going back let's print a number of friends now
of friends now it's two we have two total friends if I
it's two we have two total friends if I was to create a third friend friend
was to create a third friend friend three friend three will be
Squidward and then I'll output friend 3's number of
3's number of friends we have three total friends we
friends we have three total friends we are receiving a suggestion when
are receiving a suggestion when accessing a static variable or calling a
accessing a static variable or calling a static method it's actually best to do
static method it's actually best to do so through the class itself
so through the class itself rather than any object created from that
rather than any object created from that class instead of saying you know friend
class instead of saying you know friend one then accessing the static member we
one then accessing the static member we will instead use the name of the class
will instead use the name of the class in this case friend it's better for
in this case friend it's better for clarity to access a static member by the
clarity to access a static member by the name of the class itself rather than any
name of the class itself rather than any object because you and other developers
object because you and other developers will know that this is a static
will know that this is a static attribute or method to display the
attribute or method to display the static variable we would want to access
static variable we would want to access it by the class name then access that
it by the class name then access that static attribute how many friends do we
static attribute how many friends do we have now three let's create a fourth
have now three let's create a fourth friend friend four will be Sandy then
friend friend four will be Sandy then display the number of friends we
display the number of friends we have now we have four friends going back
have now we have four friends going back to the friend class it's as if all these
to the friend class it's as if all these objects are sharing the same variable
objects are sharing the same variable but rather than any one object having
but rather than any one object having ownership of this variable rather the
ownership of this variable rather the friend class owns it and all objects
friend class owns it and all objects have access to it methods can also be
have access to it methods can also be modified by the static
modified by the static keyword we will create a static method
keyword we will create a static method that doesn't return anything the return
that doesn't return anything the return type is void this method will be the
type is void this method will be the show Friends method we'll just output
show Friends method we'll just output the following we'll output you
the following we'll output you have
have plus normally when you access an
plus normally when you access an attribute you type this dot the name of
attribute you type this dot the name of the attribute such as you know name if
the attribute such as you know name if you're working with the static attribute
you're working with the static attribute you don't need this
you don't need this for example this. number of friends you
for example this. number of friends you don't need this we even have a warning
don't need this we even have a warning here that friends. this cannot be
here that friends. this cannot be referenced from a static context if
referenced from a static context if you're working with a static attribute
you're working with a static attribute you don't need this this refers to the
you don't need this this refers to the object you're currently working with but
object you're currently working with but since this attribute belongs to the
since this attribute belongs to the class we don't need this you have your
class we don't need this you have your static attribute of number of friends
static attribute of number of friends then the words total friends
to call a static method type the name of the class in this case friend dot the
the class in this case friend dot the name of the method show
friends you have four total friends let's create another friend friend
five friend five will be Gary friend. show friends you have five
Gary friend. show friends you have five total
total friends another place in which you see
friends another place in which you see static members is through the math class
static members is through the math class for example let's say you would like to
for example let's say you would like to round a number you would type the name
round a number you would type the name of the math class math. round and you
of the math class math. round and you can round a
can round a number round is a utility method we
number round is a utility method we access it through the class name of math
access it through the class name of math you don't need to go ahead and create a
you don't need to go ahead and create a math object such as math math 1 equals
math object such as math math 1 equals new math and then access it through this
new math and then access it through this object that would be
object that would be silly round is a static method it
silly round is a static method it behaves as a utility method we can
behaves as a utility method we can access it through the class name and we
access it through the class name and we don't need to create any math objects
don't need to create any math objects because that's stupid and to prove this
because that's stupid and to prove this let's go to the math class I'm going to
let's go to the math class I'm going to hover over math jump to
Source here's the math class and let's find the round method I'm going to do a
find the round method I'm going to do a search for
search for it here's the round
it here's the round method so round is a method and we have
method so round is a method and we have that static keyword round is a utility
that static keyword round is a utility method for the math class we can access
method for the math class we can access it through the name of the class all
it through the name of the class all right everybody so that is the static
right everybody so that is the static keyword it modifies a variable or method
keyword it modifies a variable or method so that it belongs to the class rather
so that it belongs to the class rather than any specific object it's commonly
than any specific object it's commonly used for utility methods or shared
used for utility methods or shared resources among objects created from
resources among objects created from that class such as the number of friends
that class such as the number of friends all those friend objects share the same
all those friend objects share the same attribute rather than each of them
attribute rather than each of them having their own copy and and well
having their own copy and and well everybody that is the static keyword in
everybody that is the static keyword in Java what is going on people today we
Java what is going on people today we got a very important topic to discuss
got a very important topic to discuss today and that is inheritance
today and that is inheritance inheritance is where one class inherits
inheritance is where one class inherits the attributes and methods from another
the attributes and methods from another class much like how a child can inherit
class much like how a child can inherit traits from A parent well in programming
traits from A parent well in programming we could do something similar one class
we could do something similar one class a child's class can inherit traits from
a child's class can inherit traits from A parent here's an example we're going
A parent here's an example we're going to create a few classes but we'll start
to create a few classes but we'll start with a new class of animal let's go to
with a new class of animal let's go to new class I will create an animal
new class I will create an animal class what do animals have let's say
class what do animals have let's say that all animals are alive they will
that all animals are alive they will start by being alive is
start by being alive is alive let's create a Constructor of
alive let's create a Constructor of animal I will set is alive to be true
animal I will set is alive to be true when we construct a new animal object
when we construct a new animal object but not only are all animals alive all
but not only are all animals alive all animals can eat they will have an eat
animals can eat they will have an eat method void eat we'll print something
method void eat we'll print something like the
like the following the animal is eating easting
following the animal is eating easting eating that is good enough for this
eating that is good enough for this class so what we're going to do is
class so what we're going to do is create two more classes file new class
create two more classes file new class we will create a dog
we will create a dog class and a cat
class dog and cats are types of animals our animal class will be the parent the
our animal class will be the parent the dog and cat class will be its children
dog and cat class will be its children in order for a class to inherit all the
in order for a class to inherit all the attributes and methods from another
attributes and methods from another class after the class name you will use
class after the class name you will use the extend
the extend keyword then specify the parent class
keyword then specify the parent class dog extends animal our dog class will
dog extends animal our dog class will inherit all these traits these
inherit all these traits these attributes and methods from the animal
attributes and methods from the animal class the cat and dog class don't have
class the cat and dog class don't have any anything within them let's see if
any anything within them let's see if they actually do have these attributes
they actually do have these attributes and methods even though there's nothing
and methods even though there's nothing within them let's create a dog object
within them let's create a dog object dog dog equals new dog and a cat cat cat
dog dog equals new dog and a cat cat cat equals new
cat let's print our dogs is alive variable is my dog alive I sure hope
variable is my dog alive I sure hope so cat do is
so cat do is alive look at that they're both
alive look at that they're both true they should also be able to eat
true they should also be able to eat dog. eat method cat. eat
method the animal is eating the animal is
is eating even though these classes of dog
eating even though these classes of dog and cat don't have anything within them
and cat don't have anything within them since they extend to the animal class
since they extend to the animal class we're specifying that the animal class
we're specifying that the animal class is the parent the cat and dog classes
is the parent the cat and dog classes are the children of the animal class
are the children of the animal class they inherit all these attributes and
they inherit all these attributes and methods from its parent of animal even
methods from its parent of animal even though they don't have anything within
though they don't have anything within them this isn't as useful if you only
them this isn't as useful if you only have a few classes such as two because
have a few classes such as two because you know you could just copy and paste
you know you could just copy and paste all this code within
all this code within each and then just change the
each and then just change the Constructor but imagine if you had
Constructor but imagine if you had hundreds of classes hundreds of children
hundreds of classes hundreds of children you'd have to do that for hundreds of
you'd have to do that for hundreds of classes but not only that if you have to
classes but not only that if you have to make any changes to say you know this
make any changes to say you know this animal is eating
animal is eating you'd have to make that change for
you'd have to make that change for hundreds of classes and we are repeating
hundreds of classes and we are repeating ourselves a lot it'd be a lot easier if
ourselves a lot it'd be a lot easier if we can just make that change in one
we can just make that change in one place if we have to change the to this
place if we have to change the to this all of the children classes will inherit
all of the children classes will inherit this updated method we're following the
this updated method we're following the dry principle don't repeat yourself
dry principle don't repeat yourself we're writing the code once and just
we're writing the code once and just reusing it all the children classes will
reusing it all the children classes will inherit this updated method but not only
inherit this updated method but not only that each child class can have their own
that each child class can have their own unique attributes and methods too let's
unique attributes and methods too let's say that all dogs will have one life int
say that all dogs will have one life int lives equals 1 they will also have their
lives equals 1 they will also have their own unique speak method void
own unique speak method void speak when our dog uses the speak method
speak when our dog uses the speak method let's output the following let's say the
let's output the following let's say the dog goes
dog goes woof then within the cat
woof then within the cat class cats will have have nine
class cats will have have nine lives and they can speak but they will
lives and they can speak but they will say something different when they speak
say something different when they speak let's output the cat goes
let's output the cat goes meow going
meow going back let's output our dog objects lives
back let's output our dog objects lives how many lives does our dog have same
how many lives does our dog have same thing applies with our cat cat.
thing applies with our cat cat. lives our dog has one life our cat has
lives our dog has one life our cat has nine
nine lives they also have their own unique
lives they also have their own unique speak methods dog
speak methods dog dope cat
dope the dog goes woof the cat goes meow there's also the concept of
meow there's also the concept of multi-level inheritance we'll create a
multi-level inheritance we'll create a new class to serve as a sort of
new class to serve as a sort of grandparent a child class will inherit
grandparent a child class will inherit from a parent a parent will inherit from
from a parent a parent will inherit from a grandparent so let's change this
a grandparent so let's change this program around a little bit we're going
program around a little bit we're going to create a new class file new Java
to create a new class file new Java class we will create a class of
organism animals will extend the organism
organism class let's cut our is aive variable and
class let's cut our is aive variable and the
the Constructor if you inherit from the
Constructor if you inherit from the animal class you will get an eat
animal class you will get an eat method if you inherit from the organism
method if you inherit from the organism class you are alive and that's it but we
class you are alive and that's it but we need to change the
need to change the Constructor animal inherits from
Constructor animal inherits from organism dog and cat inherit from the
organism dog and cat inherit from the animal class so from the perspective of
animal class so from the perspective of our dog and cat class the organism class
our dog and cat class the organism class is you could say a grandparent going
is you could say a grandparent going back to our main Java file let's take a
back to our main Java file let's take a look at our is alive variables dog. is
look at our is alive variables dog. is alive same thing with our cat
alive same thing with our cat cat dot is
alive yes our dog is alive and our cat is alive let's take this a step
is alive let's take this a step further let's create a class of plant
further let's create a class of plant plant is going to inherit from the
plant is going to inherit from the organism class because plants are a type
organism class because plants are a type of organism but they're not related to
of organism but they're not related to animals let's create a new class of
plant let's say that if you're a plant you get a method to well plants don't
you get a method to well plants don't eat but they can
eat but they can photosynthesize
photosynthesize photosynthesize I think I spelled that
photosynthesize I think I spelled that right probably not but who
right probably not but who cares if you're a plant and you
cares if you're a plant and you photosynthesize then the
photosynthesize then the plant absorbs
plant absorbs sunlight hey this is bro from the future
sunlight hey this is bro from the future I forgot to extend the organism class so
I forgot to extend the organism class so let's take care of that heading back to
let's take care of that heading back to our main Java file let's create a plant
our main Java file let's create a plant object plant plant equals new
plant our plant object should have an is alive attribute is alive which it
alive attribute is alive which it inherits from the organism class that's
inherits from the organism class that's true and plants can
true and plants can photosynthesize plant
photosynthesize plant do photosynthesize
the plant absorbs sunlight it's kind of like we have a
sunlight it's kind of like we have a whole family tree dog and cat inherit
whole family tree dog and cat inherit from animal animal inherits from
from animal animal inherits from organism and plant inherits from
organism and plant inherits from organism but animals and plants aren't
organism but animals and plants aren't related they're siblings but they're not
related they're siblings but they're not the same going back to our main Java
the same going back to our main Java file let's see if our dog has a
file let's see if our dog has a photosynthesize method dog.
photosynthesize method dog. photosynthesize
looks like they can't we do not have a photosynthesize method for dogs they do
photosynthesize method for dogs they do not inherit this method because they're
not inherit this method because they're not related to
not related to plants all right everybody so that's
plants all right everybody so that's inheritance it's where one class
inheritance it's where one class inherits the attributes and methods from
inherits the attributes and methods from another class A Child class will inherit
another class A Child class will inherit all the attributes and methods from a
all the attributes and methods from a parent class parents can also be
parent class parents can also be considered children too and inherit it
considered children too and inherit it from a let's say grandparent class you
from a let's say grandparent class you just have to use the extends keyword and
just have to use the extends keyword and well everybody that's inheritance in
well everybody that's inheritance in Java yo so let's get started today I got
Java yo so let's get started today I got to discuss the super keyword super just
to discuss the super keyword super just refers to the parent class when using
refers to the parent class when using inheritance a child class is also known
inheritance a child class is also known as the sub class the parent class is
as the sub class the parent class is also known as the super class super just
also known as the super class super just means parent for all intents and
means parent for all intents and purposes the super keyword is used
purposes the super keyword is used within Constructors and Method
within Constructors and Method overwriting method overwriting is a
overwriting method overwriting is a whole another topic that we'll discuss
whole another topic that we'll discuss we're more focused on Constructors in
we're more focused on Constructors in this topic we use the super keyword to
this topic we use the super keyword to call the parent Constructor to
call the parent Constructor to initialize attributes let me give you an
initialize attributes let me give you an example we'll be creating a few
example we'll be creating a few different classes let's go to file new
different classes let's go to file new class we will Begin by creating a class
class we will Begin by creating a class of
of person person will be the parent the
person person will be the parent the super
super class let's say that any person object
class let's say that any person object has the following attributes they will
has the following attributes they will have a string of first meaning first
have a string of first meaning first name then string last meaning last name
name then string last meaning last name we'll need a Constructor it's going to
we'll need a Constructor it's going to be the same as the class name Person
be the same as the class name Person parentheses curly braces when we
parentheses curly braces when we construct a person object we will need
construct a person object we will need to pass in the following arguments a
to pass in the following arguments a string for first name first and a string
string for first name first and a string for last name last this objects first
for last name last this objects first name attribute this. first
name attribute this. first equals the argument that we receive for
equals the argument that we receive for first same thing applies with last this.
first same thing applies with last this. last equals the argument we receive for
last equals the argument we receive for last and then we'll create one method in
last and then we'll create one method in this demonstration this method won't
this demonstration this method won't return anything we will name the method
return anything we will name the method show
show name all we'll do is output the
name all we'll do is output the following this do first plus a space
following this do first plus a space plus this. last okay let's test this
plus this. last okay let's test this class
class out person person equals new
out person person equals new person but we do have to pass in a first
person but we do have to pass in a first and last name I've already used
and last name I've already used SpongeBob for too many examples so let's
SpongeBob for too many examples so let's mix it up this time I'll pick Harry
mix it up this time I'll pick Harry Potter or feel free to pick a different
Potter or feel free to pick a different franchise that you like so one person
franchise that you like so one person from Harry Potter is
from Harry Potter is Tom Riddle
Tom Riddle we have a person object with this first
we have a person object with this first name and this last name first
name and this last name first last our person is going to have a show
last our person is going to have a show name method show name then call
name method show name then call it there we go there's our person
it there we go there's our person objects first and last name Tom
objects first and last name Tom Riddle our person class will be the
Riddle our person class will be the parent class we'll create a few other
parent class we'll create a few other classes to inherit from this person
classes to inherit from this person class we're going to create a class of
class we're going to create a class of student that's going to inherit from the
student that's going to inherit from the person class the student class will
person class the student class will inherit these attributes and
inherit these attributes and methods let's create a new class of
student student will extends the parent or super class
will extends the parent or super class of
of person since student is inheriting from
person since student is inheriting from person student is going to have a first
person student is going to have a first and last name already and a show name
and last name already and a show name method what other attributes does a
method what other attributes does a student have that a person might not
student have that a person might not well students have a GPA a grade point
well students have a GPA a grade point average we'll declare that as an
average we'll declare that as an attribute double
attribute double GPA we're going to create a student
GPA we're going to create a student Constructor let's say that when we
Constructor let's say that when we create a student we need to pass in a
create a student we need to pass in a string for first name String
string for first name String first string
first string last and double GPA what's their grade
last and double GPA what's their grade point average now rather than assigning
point average now rather than assigning our first and last name within this
our first and last name within this Constructor such as this. first equals
Constructor such as this. first equals first this. last equals
first this. last equals last and this. GPA equals GPA we are
last and this. GPA equals GPA we are receiving a
receiving a warning there is no parameterless
warning there is no parameterless Constructor available in person we're
Constructor available in person we're not able to assign these attributes of
not able to assign these attributes of first and last within the Constructor
first and last within the Constructor for student this is because student
for student this is because student inherits from the person class since the
inherits from the person class since the Constructor of our parent requires a
Constructor of our parent requires a first and last name we have to pass
first and last name we have to pass these arguments to its parent of person
these arguments to its parent of person how we can do that going back to the
how we can do that going back to the child class we're going to be using the
child class we're going to be using the super keyword any arguments that the
super keyword any arguments that the parent requires we have to send the
parent requires we have to send the parent these arguments from the child
parent these arguments from the child Constructor and how we can do that is
Constructor and how we can do that is use the super keyword
use the super keyword and then pass in those arguments of
and then pass in those arguments of first and last and now Java is
first and last and now Java is Happy super just refers to the parent
Happy super just refers to the parent imagine that we replace the super
imagine that we replace the super keyword with
keyword with person think of it like that and now
person think of it like that and now this should
this should work going back to our main file we
work going back to our main file we should be able to create a student
should be able to create a student object student student equals new
object student student equals new student
student we have to pass in a first name first
we have to pass in a first name first name will be
name will be Harry last name will be
Harry last name will be Potter then we have to pass in a GPA
Potter then we have to pass in a GPA because our student Constructor requires
because our student Constructor requires it Harry Potter has a
it Harry Potter has a 3.25 GPA let's say our student object
3.25 GPA let's say our student object should have these attributes this
should have these attributes this method and this attribute from the
method and this attribute from the student class of GPA
student class of GPA Let's test it student. show
Let's test it student. show name this student's name is Harry
name this student's name is Harry Potter and they should have a
Potter and they should have a GPA let's print students GPA
GPA let's print students GPA attribute
attribute 3.25 but not only that let's create a
3.25 but not only that let's create a method to display their GPA within the
method to display their GPA within the student class we will create a method
student class we will create a method that doesn't return anything it will be
that doesn't return anything it will be show GPA
show GPA we will output the
we will output the following let's say this.
following let's say this. first plus a string apostrophe s so
first plus a string apostrophe s so Harry's
Harry's GPA
GPA is plus this.
GPA let's take our student object call the show GPA method that we have
the show GPA method that we have declared
Harry's GPA is 3.25 let's create one more class we will
3.25 let's create one more class we will create an employee
create an employee class class
employee employee will inherit from the person
person class employee extends
person since employees aren't studying they're not students they instead get a
they're not students they instead get a salary we will create an integer
salary we will create an integer attribute of
attribute of salary and then we need that Constructor
salary and then we need that Constructor for our employee
object all employees will require the following
following arguments a string for first name String
arguments a string for first name String first a string for last name String last
first a string for last name String last and an integer for our employee salary I
and an integer for our employee salary I will attempt to assign these attributes
will attempt to assign these attributes for our employee again it's not going to
for our employee again it's not going to work but let's try it this. first equals
work but let's try it this. first equals first this. last equals
first this. last equals last this do
last this do salary equals
salary equals salary again we're receiving that
salary again we're receiving that warning there is no parameter list
warning there is no parameter list Constructor available in
Constructor available in person since employee extends person and
person since employee extends person and our person Constructor requires a first
our person Constructor requires a first name and a last name we have to send our
name and a last name we have to send our person Constructor these arguments first
person Constructor these arguments first and last so again going back to our
and last so again going back to our employee
employee class we will call the Constructor of
class we will call the Constructor of our parent using the super keyword and
our parent using the super keyword and then passing in those arguments first
then passing in those arguments first and
and last let's create a method within our
last let's create a method within our employee class void Show
salary let's output the following we'll say this. first this person's first
say this. first this person's first name apostrophe yes we'll create the
name apostrophe yes we'll create the employee of Hagrid their
employee of Hagrid their salary is pick unit of currency I'll
salary is pick unit of currency I'll pick American dollars plus this do
pick American dollars plus this do salary now we'll need to construct an
salary now we'll need to construct an employee
object employee
employee employee equals new
employee equals new employee we have to pass in a first name
employee we have to pass in a first name a last name and a salary in order to
a last name and a salary in order to construct an employee object we're going
construct an employee object we're going to pick Hagrid Hagrid's first name is
to pick Hagrid Hagrid's first name is actually
actually rubius last name
rubius last name Hagrid Hagrid's salary will be
Hagrid Hagrid's salary will be $50,000 let's
$50,000 let's say all right let's take our
say all right let's take our employee call its Show salary
method and there we go rubius ALS also known as Hagrid rubi's salary is
known as Hagrid rubi's salary is $50,000 in conclusion super refers to
$50,000 in conclusion super refers to the parent class student and employee
the parent class student and employee inherit from person since the
inherit from person since the Constructor of the parent of person
Constructor of the parent of person requires a first name and a last name
requires a first name and a last name any children objects that we create we
any children objects that we create we have to call the Constructor of the
have to call the Constructor of the parent and pass in those arguments to
parent and pass in those arguments to satisfy Java if the parent didn't
satisfy Java if the parent didn't require these
require these arguments then you wouldn't need to
and well everybody that is the super keyword in Java what's going on people
keyword in Java what's going on people today I'm going to discuss method
today I'm going to discuss method overwriting using Java method
overwriting using Java method overwriting is when a subass provides
overwriting is when a subass provides its own implementation of a method
its own implementation of a method rather than use one that's inherited
rather than use one that's inherited from a parent it allows for code
from a parent it allows for code reusability and you can give specific
reusability and you can give specific implementations of a method let me give
implementations of a method let me give you a demonstration we'll be creating a
you a demonstration we'll be creating a few classes file new class we will Begin
few classes file new class we will Begin by creating a class of
by creating a class of animal then a new
animal then a new class of
class of dog a
dog a class of
class of cat then finally a class of
cat then finally a class of fish dog cat and fish are going to
fish dog cat and fish are going to extend the animal class after the class
extend the animal class after the class name type extends
name type extends animal so let's do the this with cat and
animal so let's do the this with cat and fish the dog cat and fish classes are
fish the dog cat and fish classes are all children of the animal class animal
all children of the animal class animal class is the parent class there's not a
class is the parent class there's not a lot we have to write with this example
lot we have to write with this example if a child class inherits from the
if a child class inherits from the animal parent class they will inherit a
animal parent class they will inherit a method to move let's define a method of
method to move let's define a method of move all we'll say is this animal is
move all we'll say is this animal is running we can keep the dog cat and fish
running we can keep the dog cat and fish class is empty for now so going back to
class is empty for now so going back to our main Java file let's construct a dog
our main Java file let's construct a dog object dog dog equals new dog a cat
object dog dog equals new dog a cat object cat cat equals new cat and a fish
object cat cat equals new cat and a fish fish fish equals new
fish fish equals new fish all three of these animal objects
fish all three of these animal objects dog cat and fish should have a move
dog cat and fish should have a move method let's take our dog call its move
method let's take our dog call its move method say same thing with the cat and
method say same thing with the cat and the
the fish cat. move method fish. move method
fish cat. move method fish. move method currently when we run this program we
currently when we run this program we get the following
get the following output our dog is running our cat is
output our dog is running our cat is running and our fish is running but fish
running and our fish is running but fish don't have legs though they can only
don't have legs though they can only swim the move method that the fish class
swim the move method that the fish class inherits isn't appropriate for that
inherits isn't appropriate for that class this animal is swimming would be
class this animal is swimming would be more appropriate so why don't we do this
more appropriate so why don't we do this within the fish class why don't we do
within the fish class why don't we do some method overwriting specifically for
some method overwriting specifically for the fish class we will create a unique
the fish class we will create a unique move method only for this class we will
move method only for this class we will Define a new move
Define a new move method where we will
method where we will say this animal is
say this animal is swimming however it is good practice to
swimming however it is good practice to add this annotation of at override so
add this annotation of at override so that you and other Developers know that
that you and other Developers know that this method is being overridden our fish
this method is being overridden our fish class does inherit a move method from
class does inherit a move method from its parent of animal if you have the
its parent of animal if you have the same named method defined in a child
same named method defined in a child class you'll use that one first it has
class you'll use that one first it has precedence going back to our main Java
precedence going back to our main Java file let's call the move method for our
file let's call the move method for our fish our dog is running our cat is
fish our dog is running our cat is running but our fish is swimming within
running but our fish is swimming within the fish class we have overridden the
the fish class we have overridden the move method we have given a specific
move method we have given a specific implementation for this method just for
implementation for this method just for this one class the cat and dog classes
this one class the cat and dog classes will use what's inherited from their
will use what's inherited from their parent not only is a good practice to
parent not only is a good practice to add this annotation of at override but
add this annotation of at override but let's say that you misspell this
let's say that you misspell this overwritten method rather than move
overwritten method rather than move let's say moves even though it should be
let's say moves even though it should be move we're receiving a warning that this
move we're receiving a warning that this method does not override the method from
method does not override the method from its super class it's parent if you
its super class it's parent if you didn't have this annotation you may not
didn't have this annotation you may not notice that you misspelled this method
notice that you misspelled this method and you're not actually overwriting
and you're not actually overwriting it adding the at override annotation
it adding the at override annotation provides a system of checks and balances
provides a system of checks and balances when overwriting method this error will
when overwriting method this error will go away once we actually are overwriting
go away once we actually are overwriting a
a method all right everybody so that is
method all right everybody so that is Method overwriting it's when a subass
Method overwriting it's when a subass provides its own implementation of a
provides its own implementation of a method rather than use one that's
method rather than use one that's already defined it allows for code
already defined it allows for code reusability and you can give specific
reusability and you can give specific implementations of a method we'll be
implementations of a method we'll be seeing method overwriting again with the
seeing method overwriting again with the two string method coming up in a future
two string method coming up in a future topic and well everybody that is method
topic and well everybody that is method overwriting in Java hello everybody
overwriting in Java hello everybody today I got to explain the two- string
today I got to explain the two- string method using Java the two- string method
method using Java the two- string method is inherited from the object class
is inherited from the object class whenever you create an object behind the
whenever you create an object behind the scenes the object class is a super class
scenes the object class is a super class the two-ring method is used to return a
the two-ring method is used to return a string representation of an object if
string representation of an object if you were to Output it directly using
you were to Output it directly using system.out print line the default
system.out print line the default behavior of the two- string method is
behavior of the two- string method is that it returns a hash code as a unique
that it returns a hash code as a unique identifier for that object but it can be
identifier for that object but it can be overridden to provide meaningful details
overridden to provide meaningful details which is why we've learned about method
which is why we've learned about method overriding in the last video in this
overriding in the last video in this demonstration let's create a new class
demonstration let's create a new class file new class we will create a car
file new class we will create a car class let's say that all cars should
class let's say that all cars should have the following attributes a string
have the following attributes a string of make who manufactures the car a
of make who manufactures the car a string of model what's the model of the
string of model what's the model of the car int year for the year and string
car int year for the year and string color for the color we'll need a
color for the color we'll need a Constructor and then we'll assign these
Constructor and then we'll assign these attributes we have a string of make a
attributes we have a string of make a string of model an INT of year and a
string of model an INT of year and a string of color then we'll assign these
string of color then we'll assign these attributes this St make equals make this
attributes this St make equals make this St model equals model
St model equals model this.e equals
this.e equals year this. color equals
year this. color equals color that looks good enough for now
color that looks good enough for now going back to our main Java file we'll
going back to our main Java file we'll construct a car object car car equals
construct a car object car car equals new car but we have to pass in the
new car but we have to pass in the details for our car Constructor our car
details for our car Constructor our car Constructor requires a make a model a
Constructor requires a make a model a year and a color so pick a car that you
year and a color so pick a car that you like I like Ford Mustang I'll pick a
like I like Ford Mustang I'll pick a Ford Mustang the make will be Ford Model
Ford Mustang the make will be Ford Model will be
will be Mustang I need a year 2025 and a color
Mustang I need a year 2025 and a color I'll pick the color
I'll pick the color red car is an object if I were to Output
red car is an object if I were to Output my car object directly using
my car object directly using system.out.print line here's what you'll
system.out.print line here's what you'll see if you output your card directly
see if you output your card directly technically you'll be given a hash code
technically you'll be given a hash code a unique identifier for that car object
a unique identifier for that car object hashing is kind of an advanced topic
hashing is kind of an advanced topic that I don't want to introduce right now
that I don't want to introduce right now but typically with hashing it's a unique
but typically with hashing it's a unique identifier that uses the object's memory
identifier that uses the object's memory address to calculate a hash you don't
address to calculate a hash you don't need to know any more than that right
need to know any more than that right now but wouldn't it be useful if we were
now but wouldn't it be useful if we were to print our car object directly we were
to print our car object directly we were given the details of the car normally
given the details of the car normally what we would have to do is output
what we would have to do is output something like this this is if we wanted
something like this this is if we wanted to Output the details of the car we
to Output the details of the car we could say something such as car. color
could say something such as car. color that would would be first plus a space
that would would be first plus a space character plus car do which should be
character plus car do which should be next let's say the year color year then
next let's say the year color year then make and
make and model car. make plus a
model car. make plus a space plus car.
space plus car. model this print line statement is
model this print line statement is giving us meaningful details of this car
giving us meaningful details of this car object this is the
object this is the output red 2025 Ford Mustang it would be
output red 2025 Ford Mustang it would be nice if we were to print our car object
nice if we were to print our car object directly using print or print line we
directly using print or print line we could be given these details instead
could be given these details instead well we can do that with method
well we can do that with method overwriting going to our car
overwriting going to our car class we will be overriding a method we
class we will be overriding a method we need the at override
need the at override annotation we do need this keyword of
annotation we do need this keyword of public this is a publicly accessible
public this is a publicly accessible method the return type is string the
method the return type is string the name of the method is to string
everything within this print line statement we're going to cut and delete
statement we're going to cut and delete this print line
this print line statement going to our car class within
statement going to our car class within the two string method we have to return
the two string method we have to return a string because we set the return type
a string because we set the return type to be a string we promised that we would
to be a string we promised that we would return a string let's paste all the
return a string let's paste all the details of that car we'll need to
details of that car we'll need to replace car with
replace car with this this refers to the object we're
this this refers to the object we're currently working with that and add a
currently working with that and add a semicolon to the end if we were to print
semicolon to the end if we were to print our car object directly using this print
our car object directly using this print line statement or a print statement or
line statement or a print statement or even printf instead of that hash
even printf instead of that hash code we're instead given meaningful
code we're instead given meaningful details of that car that we've
details of that car that we've customized the cars color year make and
customized the cars color year make and model we have overridden the two- string
model we have overridden the two- string method that's normally available to all
method that's normally available to all objects let's construct another car
objects let's construct another car object let's rename car is car one we'll
object let's rename car is car one we'll have car car 2 equals new
have car car 2 equals new car pick some different details for a
car pick some different details for a car I will pick a
car I will pick a Chevrolet
Chevrolet Corvette the year will be
Corvette the year will be 2026 and the color will be blue I'll
2026 and the color will be blue I'll print car
print car one then print Car
2 here's car one and car two Car 2 is a blue 2026 Chevrolet
blue 2026 Chevrolet Corvette all right everybody so that is
Corvette all right everybody so that is the two-ring method objects inherit from
the two-ring method objects inherit from the object class the object class does
the object class the object class does have a two string method but it can be
have a two string method but it can be overridden so that when you print an
overridden so that when you print an object directly you can display
object directly you can display meaningful details such as the details
meaningful details such as the details of that object instead of displaying a
of that object instead of displaying a hash code if you were to print the
hash code if you were to print the object it's pretty useful at times and
object it's pretty useful at times and well everybody that is the two string
well everybody that is the two string method in Java
method in Java all right everybody it's about time we
all right everybody it's about time we get into abstraction overall abstraction
get into abstraction overall abstraction is the process of hiding implementation
is the process of hiding implementation details and showing only the essential
details and showing only the essential features think of it like this if I'm
features think of it like this if I'm teaching somebody how to drive I'm not
teaching somebody how to drive I'm not going to open up the hood of the car and
going to open up the hood of the car and explain how the engine works I'm instead
explain how the engine works I'm instead going to tell the user that the gas
going to tell the user that the gas pedal is to drive and the brake is to
pedal is to drive and the brake is to stop the car abstraction is the process
stop the car abstraction is the process of hiding implementation details a user
of hiding implementation details a user just needs to know what the gas pedal is
just needs to know what the gas pedal is and what the brake is we can make
and what the brake is we can make classes and methods abstract by using
classes and methods abstract by using this abstract keyword this provides a
this abstract keyword this provides a few benefits abstract classes can't be
few benefits abstract classes can't be instantiated directly abstract classes
instantiated directly abstract classes can also contain abstract methods which
can also contain abstract methods which must be implemented they can also
must be implemented they can also contain concrete methods which are the
contain concrete methods which are the opposite these are real and physical
opposite these are real and physical methods you could say concrete methods
methods you could say concrete methods are inherited so I know that's a lot let
are inherited so I know that's a lot let me give you an example we're going to be
me give you an example we're going to be creating an abstract class that can't be
creating an abstract class that can't be instantiated directly meaning we can't
instantiated directly meaning we can't create any objects from this class in
create any objects from this class in this demonstration we're going to create
this demonstration we're going to create some shape objects shape is going to be
some shape objects shape is going to be the parent then we'll have circle
the parent then we'll have circle triangle and rectangle classes as its
triangle and rectangle classes as its children so we're going to go to new
children so we're going to go to new Java class we will create a shape
Java class we will create a shape class then a class for
rectangle our shape class is going to be abstract we can't create any shape
abstract we can't create any shape objects before the word of class we will
objects before the word of class we will add this keyword of abstract we can't
add this keyword of abstract we can't create any shape objects it's an
create any shape objects it's an abstract class now circle triangle and
abstract class now circle triangle and rectangle are going to extend the shape
rectangle are going to extend the shape class Circle extends shape circles are
class Circle extends shape circles are type of shape same thing applies with
type of shape same thing applies with triangle and
triangle and rectangle let's attempt to create a
rectangle let's attempt to create a shape object shape shape equals new
shape object shape shape equals new shape and we get an error message shape
shape and we get an error message shape is abstract it cannot be
is abstract it cannot be instantiated since shape is an abstract
instantiated since shape is an abstract class we can't create any objects from
class we can't create any objects from this class it adds a little bit of
this class it adds a little bit of security to our program we don't want
security to our program we don't want anybody creating any generic shape
anybody creating any generic shape objects
objects we want them to create a certain kind of
we want them to create a certain kind of shape a circle a triangle or a rectangle
shape a circle a triangle or a rectangle but we can create some circles triangles
but we can create some circles triangles and rectangles so let's do so circle
and rectangles so let's do so circle circle equals new
circle equals new circle triangle
circle triangle triangle equals new
triangle equals new triangle
triangle rectangle
rectangle rectangle equals new rectangle
we can create circle triangle and rectangle objects just not shape because
rectangle objects just not shape because it's an abstract
it's an abstract class that's good though because we
class that's good though because we don't want people creating any shape
don't want people creating any shape objects it's too generic we want a user
objects it's too generic we want a user to pick a certain kind of shape abstract
to pick a certain kind of shape abstract classes can contain abstract methods and
classes can contain abstract methods and concrete methods an abstract method is a
concrete methods an abstract method is a method which must be implemented by its
method which must be implemented by its children within our shape class
children within our shape class we will define an abstract method use
we will define an abstract method use the abstract keyword let's list a return
the abstract keyword let's list a return type of double every child class of the
type of double every child class of the shape class needs an area method I'll
shape class needs an area method I'll add a comment that this is an abstract
add a comment that this is an abstract method
method abstract So within our Circle class we
abstract So within our Circle class we get an error
get an error message Circle must either be declared
message Circle must either be declared abstract or implement the abstract
abstract or implement the abstract method of area circle is going to
method of area circle is going to inherit this abstract method of area
inherit this abstract method of area from its parent of shape we need to
from its parent of shape we need to implement this method so let's do
implement this method so let's do so this is going to be an overridden
so this is going to be an overridden method we need The annotation of
method we need The annotation of override we need to define a method of
override we need to define a method of area but we'll fill it in momentarily
area but we'll fill it in momentarily just for now I'm going to return zero
just for now I'm going to return zero and now that error message goes away
and now that error message goes away since we inherit from the shape class
since we inherit from the shape class and there's an abstract method of area
and there's an abstract method of area we need to implement this method this
we need to implement this method this helps to ensure consistency among the
helps to ensure consistency among the children classes you can see that we're
children classes you can see that we're missing that same method with triangle
missing that same method with triangle and rectangle so why don't we copy this
and rectangle so why don't we copy this code where we override the area method
code where we override the area method and paste
and paste it we'll be filling these in
later going back to our shape class abstract classes can contain abstract
abstract classes can contain abstract methods and concrete methods which are
methods and concrete methods which are kind of the opposite concrete methods
kind of the opposite concrete methods are defined and inherited within an
are defined and inherited within an abstract class let's define a method of
abstract class let's define a method of display this method doesn't return
display this method doesn't return anything the return type is void we'll
anything the return type is void we'll just output the
just output the following this is a shape I'll add a
following this is a shape I'll add a comment that this is a concrete method
comment that this is a concrete method in an abstract class a concrete method
in an abstract class a concrete method is
is inherited within our circle triangle and
inherited within our circle triangle and rectangle classes we don't need to
rectangle classes we don't need to implement it we don't need to override
implement it we don't need to override this method it's
this method it's inherited going back to our main Java
inherited going back to our main Java file if I was to take my circle object
file if I was to take my circle object call the display method we get the
call the display method we get the following
following output this is a shape and that applies
output this is a shape and that applies with triangle and rectangle to triangle.
with triangle and rectangle to triangle. display rectangle.
display this is a shape this is a shape this is a a
this is a a shape this concrete method of display
shape this concrete method of display was inherited from the shape class their
was inherited from the shape class their parent now we'll Define the area methods
parent now we'll Define the area methods area is an abstract method that means
area is an abstract method that means that the children classes have to Define
that the children classes have to Define it to calculate the area of a circle
it to calculate the area of a circle we'll need a radius we'll Define that as
we'll need a radius we'll Define that as an attribute all circles will have a
an attribute all circles will have a radius attribute Double Radius and we'll
radius attribute Double Radius and we'll need a Constructor a circle Constructor
need a Constructor a circle Constructor when we construct a circle object we
when we construct a circle object we have to pass in a double for the
have to pass in a double for the radius this. rius equals the radius we
radius this. rius equals the radius we receive now the formula to calculate the
receive now the formula to calculate the area of a circle will be we're going to
area of a circle will be we're going to return access the math class access the
return access the math class access the constant of Pi from the math class times
constant of Pi from the math class times radius time
radius that's how to calculate the area of a circle
of a circle now for our triangle we need the
now for our triangle we need the following a double for base a double for
following a double for base a double for height we need a
Constructor parameter 1 will be double base parameter 2 will be double
base parameter 2 will be double height this.
height this. base equals
base equals base this do height equals height
base this do height equals height for the area we will
for the area we will return
return 0.5 time base time
0.5 time base time height then we have a
rectangle double length double
length double width we need our Constructor of
rectangle parameter 1 will be double length parameter 2 will be double
length parameter 2 will be double width this do length equals
width this do length equals length this. width equals
length this. width equals width
width return length time width within the area
return length time width within the area method and we're good let's go back to
method and we're good let's go back to our main class we're missing those
our main class we're missing those arguments we have to pass them in for
arguments we have to pass them in for our Circle object let's say the radius
our Circle object let's say the radius is three for the triangle the base and
is three for the triangle the base and height will be 4 and 5 the rectangle the
height will be 4 and 5 the rectangle the length and width will be 6 and
length and width will be 6 and 7 we are going to Output using
7 we are going to Output using system.out.print line take our circle
system.out.print line take our circle called the area
called the area method then do this with triangle and
rectangle here's the area of each of our shapes our Circle our triangle and a
shapes our Circle our triangle and a rectangle so that's the abstract keyword
rectangle so that's the abstract keyword abstraction is the process of hiding
abstraction is the process of hiding implementation details from a user and
implementation details from a user and showing only the essential features
showing only the essential features that's why we've created a shape class
that's why we've created a shape class that's abstract we can't directly create
that's abstract we can't directly create any shape objects we want a user to
any shape objects we want a user to create a certain kind of shape whether
create a certain kind of shape whether it's a circle a triangle or a rectangle
it's a circle a triangle or a rectangle a shape is too generic an abstract class
a shape is too generic an abstract class can contain abstract methods which need
can contain abstract methods which need to be implemented by the children
to be implemented by the children classes or concrete methods which are
classes or concrete methods which are inherited and the children classes will
inherited and the children classes will have access to it all right everybody so
have access to it all right everybody so that is abstraction and the of the
that is abstraction and the of the abstract keyword in Java all right
abstract keyword in Java all right what's going on everybody in this video
what's going on everybody in this video I got to explain interfaces using Java
I got to explain interfaces using Java an interface is very similar to an
an interface is very similar to an abstract class in fact there's a lot of
abstract class in fact there's a lot of overlap where you could use either one
overlap where you could use either one but there's a few key differences an
but there's a few key differences an interface is a blueprint for a class it
interface is a blueprint for a class it specifies a set of abstract methods that
specifies a set of abstract methods that any implementing classes must Define one
any implementing classes must Define one key difference is that by using
key difference is that by using interfaces we can achieve multiple
interfaces we can achieve multiple inheritance like Behavior normally with
inheritance like Behavior normally with inheritance a class can only have a
inheritance a class can only have a single parent but by using interfaces a
single parent but by using interfaces a class can have multiple parents like two
class can have multiple parents like two three or more so in this demonstration
three or more so in this demonstration we're going to create two interfaces
we're going to create two interfaces let's go to file new Java class rather
let's go to file new Java class rather than creating a class we're going to
than creating a class we're going to create an interface we will create an
create an interface we will create an interface of prey and the other for
interface of prey and the other for predator file new Java class
predator file new Java class interface
interface Predator we're going to be declaring
Predator we're going to be declaring some methods but not defining them if a
some methods but not defining them if a class inherits from the prey interface
class inherits from the prey interface they will have to finish defining a
they will have to finish defining a method of flea the return type will be
method of flea the return type will be void if you're considered prey you need
void if you're considered prey you need a flea method to run away if you're a
a flea method to run away if you're a predator you need to define a method to
predator you need to define a method to hunt cuz you're a predator now we'll be
hunt cuz you're a predator now we'll be creating three classes file new Java
creating three classes file new Java class the first class will be rabbit
then fish we'll create a fish class and
Hawk going to our rabbit class rabbits are typically considered prey not
are typically considered prey not Predators unless you count that one
Predators unless you count that one rabbit from Monty Python and the Holy
rabbit from Monty Python and the Holy Grail that's the exception our rabbit
Grail that's the exception our rabbit class is going to
class is going to implements the prey interface we get a
implements the prey interface we get a warning message class rabbit must either
warning message class rabbit must either declare abstract or Implement abstract
declare abstract or Implement abstract method flee since the rabbit class is
method flee since the rabbit class is implementing the prey interface we have
implementing the prey interface we have to finish defining this method that's
to finish defining this method that's declared within the prey interface it's
declared within the prey interface it's kind of like a contract the prey
kind of like a contract the prey interface is telling the rabbit class
interface is telling the rabbit class hey if you're going to implement me you
hey if you're going to implement me you need to Define this method a flea we'll
need to Define this method a flea we'll need to do that in order to create rabid
need to do that in order to create rabid objects we're going to be overwriting
objects we're going to be overwriting this method using the override
this method using the override annotation this method will be flee void
annotation this method will be flee void flee and we'll want to add this axis
flee and we'll want to add this axis modifier of public it's a publicly
modifier of public it's a publicly accessible method in this method we're
accessible method in this method we're going to Output the following let's say
going to Output the following let's say the rabbit is running
the rabbit is running away and that error should go away let's
away and that error should go away let's go back to our main class we'll create a
go back to our main class we'll create a rabbit object and test it rabbit rabbit
rabbit object and test it rabbit rabbit equals new rabbit let's take our rabbit
equals new rabbit let's take our rabbit object have it call the flea
object have it call the flea method and this should
method and this should work yes the rabbit is running away now
work yes the rabbit is running away now let's go to our Hawk class Hawk will
let's go to our Hawk class Hawk will implement the Predator
implement the Predator interface but we have to override this
interface but we have to override this method of hunt because with The Predator
method of hunt because with The Predator interface it's kind of like we're
interface it's kind of like we're signing a contract if Hawk is going to
signing a contract if Hawk is going to implement the Predator interface then we
implement the Predator interface then we have to finish defining this method we
have to finish defining this method we will add the at override
will add the at override annotation and Define this method and
annotation and Define this method and then again we do need an axis modifier
then again we do need an axis modifier we'll pick
we'll pick public let's output the
public let's output the following the hawk is
following the hawk is hunting let's create a hawk
hunting let's create a hawk object Hawk Hawk equals New
object Hawk Hawk equals New Hawk our rabbit is fleeing let's take
Hawk our rabbit is fleeing let's take our Hawk object use the hunt method
okay we have the rabbit is running away the hawk is
the hawk is hunting now rabbits don't have a hunt
hunting now rabbits don't have a hunt method and Hawks don't have a flea
method now one key difference with interfaces compared to abstract classes
interfaces compared to abstract classes is that you can Implement more than one
is that you can Implement more than one interface so fish they eat smaller fish
interface so fish they eat smaller fish and they flee larger fish they could be
and they flee larger fish they could be considered both prey and
considered both prey and predators we will implement two
predators we will implement two interfaces Implement prey comma Predator
interfaces Implement prey comma Predator then we need both of these methods we
then we need both of these methods we have to finish defining both again we're
have to finish defining both again we're going to use the at override
going to use the at override annotation we will create a publicly
annotation we will create a publicly accessible method a flea where we will
accessible method a flea where we will print the fish is
print the fish is swimming away and we need a hunt method
too add the at override annotation this is a public method of hunt where we will
is a public method of hunt where we will print the fish is hunting let's say all
print the fish is hunting let's say all right let's test it we will create a
right let's test it we will create a fish object fish fish equals new
fish object fish fish equals new fish our fish can
fish our fish can flee and our fish can
hunt the fish is swimming away the fish is hunting our fish object implements
is hunting our fish object implements both the prey and Predator interfaces it
both the prey and Predator interfaces it has to Define these two methods so
has to Define these two methods so that's one key difference with
that's one key difference with interfaces compared to abstract classes
interfaces compared to abstract classes a class can inherit more than one
a class can inherit more than one interface normally with inheritance you
interface normally with inheritance you can only have one parent but this is a
can only have one parent but this is a way around that using interfaces fish
way around that using interfaces fish are considered both prey and predators
are considered both prey and predators all right everybody so that is a quick
all right everybody so that is a quick introduction to interfaces an interface
introduction to interfaces an interface is a blueprint for a class that's
is a blueprint for a class that's specifies a set of abstract methods that
specifies a set of abstract methods that implementing classes must Define and it
implementing classes must Define and it supports multiple inheritance like
supports multiple inheritance like Behavior there's a lot of overlap where
Behavior there's a lot of overlap where you can use abstract classes or
you can use abstract classes or interfaces you should be familiar with
interfaces you should be familiar with both and well everybody that's a quick
both and well everybody that's a quick introduction to interfaces using Java so
introduction to interfaces using Java so yeah it's about time I explain
yeah it's about time I explain polymorphism using Java polymorphism is
polymorphism using Java polymorphism is a Greek word poly means many morph means
a Greek word poly means many morph means shape together you get the concept of
shape together you get the concept of many shapes or forms it's a general
many shapes or forms it's a general programming concept objects can identify
programming concept objects can identify as other objects objects of different
as other objects objects of different types objects can be treated as objects
types objects can be treated as objects of a common super Class A dog identifies
of a common super Class A dog identifies as a dog but it can also identify as an
as a dog but it can also identify as an animal it can also identify as an
animal it can also identify as an organism it can also identify as an
organism it can also identify as an object it can identify as more than one
object it can identify as more than one thing in this topic we're going to
thing in this topic we're going to create a few vehicle objects let's
create a few vehicle objects let's create a few classes file new Java class
create a few classes file new Java class we will create a super class of vehicle
we will create a super class of vehicle iicle this class doesn't have to be
iicle this class doesn't have to be abstract but let's make it abstract we
abstract but let's make it abstract we can't create any vehicle
can't create any vehicle objects we will declare an abstract
objects we will declare an abstract method that doesn't return anything the
method that doesn't return anything the return type is void if you're a vehicle
return type is void if you're a vehicle you need a go method so what we're going
you need a go method so what we're going to be doing is creating a few different
to be doing is creating a few different types of vehicles a car bike and boat
types of vehicles a car bike and boat class which will inherit from the class
class which will inherit from the class of vehicle so let's create these classes
of vehicle so let's create these classes file new Java class we will create a car
file new Java class we will create a car class that extends the vehicle class but
class that extends the vehicle class but there is an abstract method of go that
there is an abstract method of go that we need to
we need to Define we will use the at override
Define we will use the at override annotation the method will be return
annotation the method will be return type of void go all we'll do is output
type of void go all we'll do is output you drive the car all right let's do
you drive the car all right let's do this with a few other classes I'll just
this with a few other classes I'll just copy this method because we'll reuse it
copy this method because we'll reuse it we'll create a bike class
we'll create a bike class bike bike extends
bike bike extends vehicle and we need that method of go
vehicle and we need that method of go you ride the
you ride the bike and a boat class file new Java
bike and a boat class file new Java class
class Boat Boat extends
that is good enough for now going back to our main Java file let's create these
to our main Java file let's create these objects starting with our car car car
objects starting with our car car car equals new
equals new car bike bike equals new
car bike bike equals new bike Boat Boat equals new
boat each of these objects has a go method for example let's have our car
method for example let's have our car object use its go method followed by
object use its go method followed by bike bike Dogo method and Boat Boat Dogo
bike bike Dogo method and Boat Boat Dogo method you drive the car you ride the
method you drive the car you ride the bike you sail the boat so let's say we
bike you sail the boat so let's say we would like to have a
would like to have a race we're going to place all of these
race we're going to place all of these objects within an array our car bike and
objects within an array our car bike and boat objects so what should the data
boat objects so what should the data type of the array be let's attempt to
type of the array be let's attempt to create an array of car objects and place
create an array of car objects and place our bike and boat objects within that
our bike and boat objects within that array and we'll just see what happens
array and we'll just see what happens exactly for learning purposes I will
exactly for learning purposes I will create an array of
create an array of cars the data type is car it's an array
cars the data type is car it's an array named cars equals curly braces let's
named cars equals curly braces let's stick our car bike and boat objects
stick our car bike and boat objects within here we're already getting a few
within here we're already getting a few error
messages incompatible types bike cannot be converted to car bikes and boats
be converted to car bikes and boats don't identify as cars cars identify as
don't identify as cars cars identify as cars s that's one of the shapes that
cars s that's one of the shapes that bikes and boats don't have they don't
bikes and boats don't have they don't identify as cars if this were an array
identify as cars if this were an array of
of bikes bike bikes equals R array of
bikes bike bikes equals R array of objects well then we have another a
objects well then we have another a message car cannot be converted to a
message car cannot be converted to a bike and you can assume the same thing
bike and you can assume the same thing applies with
applies with boats cars and bikes don't identify as
boats cars and bikes don't identify as boats what we could do is declare our
boats what we could do is declare our array of what they have in common well
array of what they have in common well our car bike and boat they all extend
our car bike and boat they all extend the vehicle class you could say they
the vehicle class you could say they also identify as Vehicles we're going to
also identify as Vehicles we're going to change the data type of our array to
change the data type of our array to hold Vehicles we have an array of
hold Vehicles we have an array of vehicle
vehicle objects and then let's change our array
objects and then let's change our array name to be Vehicles cars identifies cars
name to be Vehicles cars identifies cars but also Vehicles bikes identifies bikes
but also Vehicles bikes identifies bikes but also Vehicles boats identify as
but also Vehicles boats identify as boats but also Vehicles that's the one
boats but also Vehicles that's the one thing they have in common they're all
thing they have in common they're all extending the vehicle super class
extending the vehicle super class they're also considered Vehicles that's
they're also considered Vehicles that's another one of their forms they shapes
another one of their forms they shapes for every object within this array I
for every object within this array I would like to have each object use its
would like to have each object use its go method like we're
go method like we're racing well what we could do is use a
racing well what we could do is use a for each
Loop what's the data type of the array well it's vehicle we have an array of
well it's vehicle we have an array of vehicles we will give a nickname of each
vehicles we will give a nickname of each vehicle
vehicle as vehicle in my array of
as vehicle in my array of vehicles for every vehicle in this array
vehicles for every vehicle in this array of vehicles let's take each
of vehicles let's take each vehicle call the go method take every
vehicle call the go method take every vehicle object call its go method here's
vehicle object call its go method here's the result you drive the car you ride
the result you drive the car you ride the bike you sail the
the bike you sail the boat oh and another thing I'm forgetting
boat oh and another thing I'm forgetting polymorphism can also be achieved
polymorphism can also be achieved through using interfaces let's delete
through using interfaces let's delete our vehicle
class we'll create a new Java class this will be an interface a
vehicle rather than extending the vehicle class we will implements the
vehicle class we will implements the vehicle
interface we will declare a method of go that doesn't return
that doesn't return anything these methods do need an access
anything these methods do need an access modifier let's just say
public so polymorphism can be achieved this way too through using interfaces if
this way too through using interfaces if you prefer interfaces in summary
you prefer interfaces in summary polymorphism means many shapes it's
polymorphism means many shapes it's where objects can identify as themselves
where objects can identify as themselves but also other objects objects can be
but also other objects objects can be treated as objects of a common super
treated as objects of a common super class and well everybody that is an
class and well everybody that is an introduction to polymorphism using jav
introduction to polymorphism using jav Ava what's going on people today I got
Ava what's going on people today I got to explain a runtime polymorphism also
to explain a runtime polymorphism also known as Dynamic polymorphism how I
known as Dynamic polymorphism how I would explain it in a single sentence is
would explain it in a single sentence is when the method that gets executed is
when the method that gets executed is decided at runtime based on the actual
decided at runtime based on the actual type of the object in this demonstration
type of the object in this demonstration a user is going to pick a type of animal
a user is going to pick a type of animal they want as a pet a dog or a cat but
they want as a pet a dog or a cat but that's going to be determined at runtime
that's going to be determined at runtime after the program is already running
after the program is already running we'll create a total of three classes
we'll create a total of three classes first we'll create an animal class which
first we'll create an animal class which will be a parent class we will create a
will be a parent class we will create a class of animal we might as well make
class of animal we might as well make this an abstract class for good practice
this an abstract class for good practice we don't want anybody creating any
we don't want anybody creating any animal objects we will have an abstract
animal objects we will have an abstract method the return type is void this
method the return type is void this method will be speak when an animal
method will be speak when an animal speaks they'll say something
speaks they'll say something unique we'll create a dog class file new
unique we'll create a dog class file new Java class we will create a class of dog
Java class we will create a class of dog that
that extends the animal class but we do need
extends the animal class but we do need a speak method we will use method
a speak method we will use method overwriting the return type is void with
overwriting the return type is void with our speak
our speak method we will output the
method we will output the following the dog goes woof all right
following the dog goes woof all right then we need a cat class file new Java
then we need a cat class file new Java class we will create a class of
class we will create a class of cat cat extends
cat cat extends animal and we'll just copy the speak
animal and we'll just copy the speak method just to save a little bit of
method just to save a little bit of time when the cat speaks we'll output
time when the cat speaks we'll output the cat goes meow that's good enough for
the cat goes meow that's good enough for this
this example since animal is an abstract
example since animal is an abstract class we can't create any animal objects
class we can't create any animal objects I'll attempt to do so animal animal
I'll attempt to do so animal animal equals new
equals new animal and we get an error message
animal and we get an error message animal is abstract can be instantiated
animal is abstract can be instantiated that's good though animals are too
that's good though animals are too generic we would rather have a user
generic we would rather have a user create a certain kind of animal either a
create a certain kind of animal either a dog or a cat in this demonstration we're
dog or a cat in this demonstration we're going to have a user pick if they want a
going to have a user pick if they want a dog or a cat but we don't know which one
dog or a cat but we don't know which one they're going to pick so why don't we do
they're going to pick so why don't we do this let's declare an animal object but
this let's declare an animal object but not instantiate it we will assign our
not instantiate it we will assign our animal equal to a new dog or a new cat
animal equal to a new dog or a new cat based on the user input so animal animal
based on the user input so animal animal this will either be animal equals a new
this will either be animal equals a new dog or animal equals a new cat based on
dog or animal equals a new cat based on the user
the user input we will declare an object that's
input we will declare an object that's at least an animal we'll accept some
at least an animal we'll accept some user input we'll need a scanner scanner
user input we'll need a scanner scanner scanner equals new
scanner equals new scanner we will pass in
scanner we will pass in system.in and import this class
system.in and import this class java.util.scanner
java.util.scanner we'll need a prompt
would you like a dog or a cat we'll say 1 equals dog 2 equals
cat we'll say 1 equals dog 2 equals cat I'll use print rather than print
cat I'll use print rather than print line because I like the input on the
line because I like the input on the same line let's declare a variable of
same line let's declare a variable of choice this will be an integer we'll use
choice this will be an integer we'll use our scanner called the next int method
our scanner called the next int method and then we'll do the
and then we'll do the following we'll examine if our choice
following we'll examine if our choice variable is equal to one if it is we'll
variable is equal to one if it is we'll finish instantiating our animal object
finish instantiating our animal object but we'll assign it to be a new dog
but we'll assign it to be a new dog object then we will have our animal use
object then we will have our animal use its speak
its speak method so if it's a dog it should go
choice is equal to two then we will instantiate our animal object as a new C
instantiate our animal object as a new C and have our animal use its speak
method you could add an else Clause but it's not really
it's not really necessary this is good enough for
necessary this is good enough for now before running the program we don't
now before running the program we don't know what kind of animal we're going to
know what kind of animal we're going to create it's either going to be a dog or
create it's either going to be a dog or a cat
if I select one we get a dog the dog goes
goes woof if I select two we get a cat the
woof if I select two we get a cat the cat goes meow the actual method that we
cat goes meow the actual method that we call is determined at runtime after the
call is determined at runtime after the program is already
program is already running before we run the program we
running before we run the program we know that we're going to use a speak
know that we're going to use a speak method we're just not sure which one so
method we're just not sure which one so that's runtime polymorphism it's when
that's runtime polymorphism it's when the method that gets executed is decided
the method that gets executed is decided at runtime based on the actual type of
at runtime based on the actual type of object that we create and well everybody
object that we create and well everybody that is an introduction to runtime
that is an introduction to runtime polymorphism using
polymorphism using Java all right everybody today I'm going
Java all right everybody today I'm going to be explaining getter and Setter
to be explaining getter and Setter methods using Java getter and Setter
methods using Java getter and Setter methods help protect object data and
methods help protect object data and they add rules for accessing or
they add rules for accessing or modifying that data here's a
modifying that data here's a demonstration we're going to create a
demonstration we're going to create a class of car file new class we will
class of car file new class we will create a car
create a car Class A few attributes that cars could
Class A few attributes that cars could have include a string of model A String
have include a string of model A String of color and an INT let's say price then
of color and an INT let's say price then we'll need a
we'll need a Constructor we'll have three
Constructor we'll have three parameters a string of model A String of
parameters a string of model A String of color and an inch of price we will
color and an inch of price we will assign this do
assign this do model equals
model equals model this do color equals color
model this do color equals color this St price equals price let's
this St price equals price let's construct a car
object car car equals new car pick a model a year and a price I've
car pick a model a year and a price I've already used red Mustangs for too many
already used red Mustangs for too many examples I'll pick something else let's
examples I'll pick something else let's say a
say a charger that is yellow and the price
charger that is yellow and the price will be
will be $10,000 but I don't know if that's good
$10,000 but I don't know if that's good or not we don't even know the year of
or not we don't even know the year of the car anyways so we have our car
the car anyways so we have our car object and then let's output these
object and then let's output these attributes just to test them car. color
attributes just to test them car. color I'll add a space character to plus car.
I'll add a space character to plus car. model plus a space
model plus a space character plus car. price I'm
character plus car. price I'm intentionally not adding a unit of
intentionally not adding a unit of currency so here's our
currency so here's our car I have a yellow charger and the
car I have a yellow charger and the price is 10,000 10,000 of a unit of
price is 10,000 10,000 of a unit of currency that you choose but that's not
currency that you choose but that's not important
important with our car object its attributes are
with our car object its attributes are publicly accessible meaning we can view
publicly accessible meaning we can view and change them
and change them easily to demonstrate let's say that the
easily to demonstrate let's say that the model of our car is now a
Corvette we have a yellow Corvette that is
is $10,000 we don't want the model of our
$10,000 we don't want the model of our car to magically become a Corvette once
car to magically become a Corvette once we assign its model to be charger we
we assign its model to be charger we don't want it to change what we could do
don't want it to change what we could do when to declaring these attributes is
when to declaring these attributes is add this access modifier of private
add this access modifier of private preceding the data type private string
preceding the data type private string model private string color private and
model private string color private and price we can't access them and let's
price we can't access them and let's test that you can see that the font
test that you can see that the font color already changed to
color already changed to Red I will attempt to print the car's
Red I will attempt to print the car's color model and
price color has private access and car model has private ACC access in car and
model has private ACC access in car and price has private access in
price has private access in car since these attributes are private
car since these attributes are private we can't normally access them outside of
we can't normally access them outside of the car class but there is a way around
the car class but there is a way around that and that is by using getter and
that and that is by using getter and Setter methods getter methods make a
Setter methods getter methods make a field readable Setter methods make a
field readable Setter methods make a field writable use get to read set to
field writable use get to read set to write we'll set up some getter methods
write we'll set up some getter methods first I would like the car's color model
first I would like the car's color model and price
and price here's how we can do that within the car
here's how we can do that within the car class we will create a method we'll
class we will create a method we'll start with the model the return type
start with the model the return type will be string because our model is a
will be string because our model is a string data type we'll create a getter
string data type we'll create a getter method following this naming convention
method following this naming convention get then the name of the attribute
get then the name of the attribute model all we're going to do is return
model all we're going to do is return this.
this. model and then we'll do this with the
model and then we'll do this with the color and the price and I'll just copy
color and the price and I'll just copy this method because I'm I'm feeling a
this method because I'm I'm feeling a little lazy we have get
little lazy we have get model get color return this.
model get color return this. color and get
color and get price return this.
price return this. price oh and this returns an integer not
price oh and this returns an integer not a string because our price is an integer
a string because our price is an integer let's go back to our main Java file
let's go back to our main Java file rather than accessing these attributes
rather than accessing these attributes directly because we can't we're going to
directly because we can't we're going to call these getter methods get model if
call these getter methods get model if you need the model get color if you need
you need the model get color if you need the color get price if you need the
the color get price if you need the price replace car. color with car do get
price replace car. color with car do get color and this is a method car. getet
color and this is a method car. getet model and car. getet price and that
model and car. getet price and that should
should work yep we can now read those
work yep we can now read those attributes we have a yellow charger and
attributes we have a yellow charger and the price is
the price is 10,000 another thing you can do too with
10,000 another thing you can do too with getter methods you can add additional
getter methods you can add additional logic so with our get price method let's
logic so with our get price method let's instead return a string we will return a
instead return a string we will return a unit of currency I'll pick American
unit of currency I'll pick American dollars plus the price let's see how
dollars plus the price let's see how that
that changes again we are calling the get
changes again we are calling the get price
$110,000 getter methods make a field readable and you can add additional
readable and you can add additional logic when retrieving one of these
logic when retrieving one of these attributes and in this demonstration I
attributes and in this demonstration I just added a dollar sign just to keep it
just added a dollar sign just to keep it simple then we have Setter methods
simple then we have Setter methods Setter methods make a field writable
Setter methods make a field writable going to our car class we have model
going to our car class we have model color and price I don't want the model
color and price I don't want the model attribute to be writable once we've
attribute to be writable once we've declared the model of our car we don't
declared the model of our car we don't want to change it our charger can't
want to change it our charger can't magically become a Corvette even though
magically become a Corvette even though that'd be pretty cool but the color you
that'd be pretty cool but the color you could change you can paint your car and
could change you can paint your car and the price you can sell your car for a
the price you can sell your car for a different price we'll declare Setter
different price we'll declare Setter methods for our color and price but not
methods for our color and price but not the model because we don't want this
the model because we don't want this attribute to be
attribute to be writable so let's scroll down to the
writable so let's scroll down to the bottom following a similar pattern we're
bottom following a similar pattern we're going to create a method the return type
going to create a method the return type is void this will be set
is void this will be set color we have one parameter a string of
color we have one parameter a string of color we will assign this do color equal
color we will assign this do color equal to the new color that we
to the new color that we receive we'll do this with our price
receive we'll do this with our price too void set
too void set price we'll have one parameter and int
price we'll have one parameter and int of
of price this. price equals price the new
price this. price equals price the new price that we receive okay let's test
price that we receive okay let's test these
things I'll attempt to access our color directly car. color equals I don't know
directly car. color equals I don't know blue that's the first thing that came to
blue that's the first thing that came to mind and car. price equals you know what
mind and car. price equals you know what the car's on sale it's
the car's on sale it's $5,000 well I can't change these we
$5,000 well I can't change these we still have that red text for color and
still have that red text for color and price because the color and price
price because the color and price attributes are still
attributes are still private instead we're going to call
private instead we're going to call these Setter
these Setter methods we will set the color and then
methods we will set the color and then pass in the new
pass in the new color rather than assign it directly set
color rather than assign it directly set color pass in a new
color pass in a new color set price passing a new price
color set price passing a new price 5,000 then using our Getters we should
5,000 then using our Getters we should be able to print these
be able to print these attributes yes we now have a blue
attributes yes we now have a blue charger and the price is
charger and the price is $5,000 we don't have a Setter method set
$5,000 we don't have a Setter method set up for the model that's good though we
up for the model that's good though we don't want the model to
don't want the model to change we only have set
change we only have set and set price if I attempt to access a
and set price if I attempt to access a set model
set model method we shouldn't be able to change
it because we never declared a set model method it doesn't exist but if you did
method it doesn't exist but if you did want to change the model if you want
want to change the model if you want this attribute to be writable well then
this attribute to be writable well then you could add a Setter
you could add a Setter method void set
method void set model we'll pass in a string for the new
model we'll pass in a string for the new model this model equals
model this model equals model and then you could change
model and then you could change it we have a blue corvet for $5,000
it we have a blue corvet for $5,000 which is really
which is really cheap but you know what I don't want the
cheap but you know what I don't want the model to be writable just
model to be writable just readable if you don't want an attribute
readable if you don't want an attribute to be writable when you declare it you
to be writable when you declare it you can also add this keyword a final that
can also add this keyword a final that adds an extra security
measure one last thing we should do with the price let's add some additional
the price let's add some additional logic so with our price let's do the
logic so with our price let's do the following let's add a
following let's add a check if our price is less than zero
check if our price is less than zero then let's output the
then let's output the following price can't be less than
following price can't be less than zero else if everything checks out if
zero else if everything checks out if our price is zero or above then we'll
our price is zero or above then we'll assign this do price equals the price
assign this do price equals the price that we receive as an argument Let's
that we receive as an argument Let's test it
test it I'll change the color of my car to be
I'll change the color of my car to be blue but the price is going to
be100 we get that message price can't be less than zero the color changed but not
less than zero the color changed but not the price it stayed the same at
the price it stayed the same at $10,000 so those are getter and Setter
$10,000 so those are getter and Setter methods they help protect object data
methods they help protect object data and add rules for accessing or modifying
and add rules for accessing or modifying that data getter methods make a field
that data getter methods make a field readable Setter methods make a a field
readable Setter methods make a a field writable depending on your object's
writable depending on your object's attributes you may want some to be
attributes you may want some to be readable or writable or both it's up to
readable or writable or both it's up to you and well everybody those are getter
you and well everybody those are getter and Setter methods using Java all right
and Setter methods using Java all right let's do this today I got to talk about
let's do this today I got to talk about aggregation in programming aggregation
aggregation in programming aggregation represents a has a relationship between
represents a has a relationship between objects one object contains another
objects one object contains another object as part of its structure but the
object as part of its structure but the contained object or objects can exist
contained object or objects can exist independently B basically speaking an
independently B basically speaking an object can contain another object but
object can contain another object but those objects can exist independently
those objects can exist independently what we'll do for this demonstration is
what we'll do for this demonstration is create some book objects then we'll
create some book objects then we'll create a library object to contain the
create a library object to contain the book objects the books and the library
book objects the books and the library can exist independently that's
can exist independently that's aggregation the library object will have
aggregation the library object will have book objects we'll create a new class of
book objects we'll create a new class of book file new class
book file new class book and a class for Library file new
book and a class for Library file new class
class Library let's design our book
Library let's design our book objects let's say that books have a
objects let's say that books have a string of title and an integer for Pages
string of title and an integer for Pages you could include an author too if you
you could include an author too if you would like but I don't want this example
would like but I don't want this example to be too big we'll need a Constructor
to be too big we'll need a Constructor for our book
for our book objects we'll set up the parameters we
objects we'll set up the parameters we need a string of title and an integer
need a string of title and an integer for
for Pages this. tile equals title
Pages this. tile equals title this. Pages equals Pages if you would
this. Pages equals Pages if you would like you can set these attributes to be
like you can set these attributes to be private but that might be overkill for
private but that might be overkill for this lesson why don't we create a method
this lesson why don't we create a method to display the book's info this method
to display the book's info this method will return a string we'll Define a
will return a string we'll Define a method to display info we will display
method to display info we will display the info of this book Let's return the
the info of this book Let's return the following let's return this.
following let's return this. tile plus a space character
tile plus a space character plus this.
plus this. pages and a string of the word
pages and I think I'm going to enclose the number of pages within a set of
the number of pages within a set of parenthesis you can also use a print F
parenthesis you can also use a print F statement if that's easier for you but I
statement if that's easier for you but I want to try and keep this beginner
want to try and keep this beginner friendly okay that's good enough for the
friendly okay that's good enough for the book class let's create a few book
book class let's create a few book objects we'll start with book one book
objects we'll start with book one book book one equals a new book but to
book one equals a new book but to construct a book we have to pass in at
construct a book we have to pass in at least the following a title and a number
least the following a title and a number of pages so I've picked out a few books
of pages so I've picked out a few books already feel free to choose your own if
already feel free to choose your own if you would rather choose different books
you would rather choose different books for the first book that I'll pick I will
for the first book that I'll pick I will pick the Fellowship of the Ring this
pick the Fellowship of the Ring this will be all one
will be all one string and the number of pages at least
string and the number of pages at least according to wekipedia is
according to wekipedia is 423 then we'll create another book
423 then we'll create another book another book object this will be book
another book object this will be book two book two will be the two towers the
two book two will be the two towers the number of pages will be
number of pages will be 352 and then book
352 and then book three book three will be the Return of
three book three will be the Return of the
the King the number of pages will be
King the number of pages will be 416 all right we have our independent
416 all right we have our independent book objects then what we'll do is stick
book objects then what we'll do is stick them all within an array we'll create an
them all within an array we'll create an array of book objects named books equals
array of book objects named books equals then within a set of curly braces we can
then within a set of curly braces we can place our book objects within here book
place our book objects within here book one book two book three we have an array
one book two book three we have an array of book objects before moving on let's
of book objects before moving on let's test the display info method of each of
test the display info method of each of these books so we'll need a print
these books so we'll need a print statement book one. display
statement book one. display info so we should get book one The
info so we should get book one The Fellowship of the Ring 423 Pages I'm
Fellowship of the Ring 423 Pages I'm just going to make one
just going to make one change I'll put the right parentheses at
change I'll put the right parentheses at the
end that's better let's display book
better let's display book two the two towers 352
two the two towers 352 Pages book
Pages book three the Return of the King 46
three the Return of the King 46 Pages you could also Loop through this
Pages you could also Loop through this array using an enhanced for for
array using an enhanced for for Loop the data type of each element in my
Loop the data type of each element in my array is book for every book in my array
array is book for every book in my array of
of books will print take each book call the
books will print take each book call the display info
method and here's all the books that I have in my array The Fellowship of the
have in my array The Fellowship of the Ring The Two Towers The Return of the
Ring The Two Towers The Return of the King and we can delete this for Loop we
King and we can delete this for Loop we no longer need it
no longer need it now we're going to create a library
now we're going to create a library object our library object will contain
object our library object will contain our array of book objects because
our array of book objects because libraries contain books going to our
libraries contain books going to our library
library class what should libraries have let's
class what should libraries have let's say that our library should have a name
say that our library should have a name what's the name of the library maybe a
what's the name of the library maybe a year in which the library was
year in which the library was established in year and libraries should
established in year and libraries should contain book objects we will create an
contain book objects we will create an array of book objects named
array of book objects named books we'll need to instructor for the
books we'll need to instructor for the library
library class we'll need the following a string
class we'll need the following a string for the name of the
for the name of the library an integer for the year of the
library an integer for the year of the library when was the library built and
library when was the library built and an array of book
an array of book objects this St name equals
objects this St name equals name this doe equals
name this doe equals year this. books equals the books that
year this. books equals the books that we receive this array
we receive this array all right going back to our main Java
all right going back to our main Java file this is where aggregation is going
file this is where aggregation is going to come
to come in we will create a library
in we will create a library object
object library
library library equals new
library equals new library but we have to pass in the
library but we have to pass in the following as arguments to the
following as arguments to the Constructor a name for the library a
Constructor a name for the library a year for the library and an array of
year for the library and an array of book
book objects so for the library I'm going to
objects so for the library I'm going to say the NYC the New York
say the NYC the New York City public
City public library after a quick Google search this
library after a quick Google search this library was built in the year
library was built in the year 1897 then we also need an array of book
1897 then we also need an array of book objects I will pass in my array of book
objects I will pass in my array of book objects named
objects named books this is
books this is aggregation our library object has book
aggregation our library object has book objects within the library class let's
objects within the library class let's also create a display info method for
also create a display info method for the library we'll make it a little bit
the library we'll make it a little bit different this method won't return
different this method won't return anything let's say the return type is
anything let's say the return type is void we'll name this method display info
void we'll name this method display info we'll display the following information
we'll display the following information about this Library let's output the
about this Library let's output the following
following the this.e of the
the this.e of the library plus a space
library plus a space character plus
character plus this.name you can also also use a printf
this.name you can also also use a printf statement if you would prefer to use
statement if you would prefer to use that I'm trying to keep this as beginner
that I'm trying to keep this as beginner friendly as possible so let's test
friendly as possible so let's test this we will take our library object
this we will take our library object call it display info
method the 1897 New York City public
1897 New York City public library then within this method of
library then within this method of display info for the library let's also
display info for the library let's also list all the books that it has this
list all the books that it has this Library
Library has aggregated a whole bunch of book
has aggregated a whole bunch of book objects so then we can display them or
objects so then we can display them or use them for something let's output the
use them for something let's output the following let's output
following let's output books
books available then we'll use an enhanced for
available then we'll use an enhanced for Loop the data type of what we're
Loop the data type of what we're iterating through is book objects for
iterating through is book objects for every book in my array of books take
every book in my array of books take each book call the books display in
method and then we do have to print it using a print line statement because
using a print line statement because this method returns a
this method returns a string there we go let's test
string there we go let's test it so after calling the display info
it so after calling the display info method of the
method of the library we should display the
library we should display the information of the library including its
information of the library including its books the 1897 New York City public
books the 1897 New York City public library and we display the books
library and we display the books available which are the array of books
available which are the array of books that we have created
that we have created so that's aggregation it represents a
so that's aggregation it represents a has a relationship between objects our
has a relationship between objects our library object has book objects within
library object has book objects within it there's another similar concept
it there's another similar concept called composition with aggregation if
called composition with aggregation if you were to delete this Library class
you were to delete this Library class for example I'll delete
for example I'll delete it well these book objects can exist
it well these book objects can exist independently outside of the library the
independently outside of the library the books aren't built into the library so
books aren't built into the library so they can exist independently which is a
they can exist independently which is a key compared to composition which is the
key compared to composition which is the next topic we'll cover and well
next topic we'll cover and well everybody that is aggregation using Java
everybody that is aggregation using Java hey everybody in this video I'm going to
hey everybody in this video I'm going to explain composition to you in
explain composition to you in programming composition represents a
programming composition represents a part of relationship between objects for
part of relationship between objects for example an engine is part of a car an
example an engine is part of a car an object can be part of another object
object can be part of another object this allows for complex objects to be
this allows for complex objects to be constructed from smaller objects in this
constructed from smaller objects in this demonstration we're going to create a
demonstration we're going to create a car object
car object the car object is composed of an engine
the car object is composed of an engine object we will create a class of car and
object we will create a class of car and a class of
engine we'll begin with our class of car what sorts of attributes should cars
what sorts of attributes should cars have let's say a string of
have let's say a string of model an INT of year and an engine
model an INT of year and an engine object engine engine
object engine engine we'll need a
we'll need a Constructor we'll pass in a string for
Constructor we'll pass in a string for the
the model an INT for the
model an INT for the year now for the engine we're not going
year now for the engine we're not going to be passing in an engine object let's
to be passing in an engine object let's say that when we construct a car object
say that when we construct a car object we have to pass in a string for the
we have to pass in a string for the engine
engine type is it an inline engine is it a V6
type is it an inline engine is it a V6 that sort of thing we will assign this
that sort of thing we will assign this St model equals the model that we
St model equals the model that we receive
receive this. year equals the year that we
this. year equals the year that we receive now with our engine this. engine
receive now with our engine this. engine we're going to call the Constructor for
we're going to call the Constructor for a new engine
a new engine object and then we can pass in our
object and then we can pass in our engine
engine type but we still however have to set up
type but we still however have to set up the Constructor for our engine class
the Constructor for our engine class when constructing a car object we will
when constructing a car object we will also be constructing a new engine object
also be constructing a new engine object so let's go to our engine
so let's go to our engine class let's say that engine
class let's say that engine have a
have a string of type you could say engine type
string of type you could say engine type but that would be redundant I would say
but that would be redundant I would say let's just say type then we need a
let's just say type then we need a Constructor for our engine class we will
Constructor for our engine class we will need a string of type to pass
need a string of type to pass in this.type equals
in this.type equals type so going back to our car class when
type so going back to our car class when we pass in a string for the engine type
we pass in a string for the engine type you could say that this is
you could say that this is type this term is kind of ambiguous
type this term is kind of ambiguous though because a user is going to think
though because a user is going to think that the type is for the car type rather
that the type is for the car type rather than the engine type so when you pass
than the engine type so when you pass arguments your parameter names can be
arguments your parameter names can be different from the argument names that
different from the argument names that you pass in we simply rename them when
you pass in we simply rename them when this Constructor receives that argument
this Constructor receives that argument but type refers to the engine type all
but type refers to the engine type all right so this is a basic demonstration
right so this is a basic demonstration of composition now we'll construct a car
of composition now we'll construct a car object car car equals new
object car car equals new car and then we have to pass in the
car and then we have to pass in the following a string for the model an inch
following a string for the model an inch for the year and a string for the engine
for the year and a string for the engine type pick a card that you like this time
type pick a card that you like this time I will pick a
I will pick a Corvette the year will be
Corvette the year will be 20125 and for the engine I will pick a
20125 and for the engine I will pick a V8
V8 engine then let's see if we have these
engine then let's see if we have these details I'm going to Output my car
details I'm going to Output my car objects model and these attributes I did
objects model and these attributes I did not set to private but you can set them
not set to private but you can set them to private and use Getters and Setters
to private and use Getters and Setters if you would like so we have
if you would like so we have model
object here's what we have we have our model Corvette year 2025 now for the
model Corvette year 2025 now for the engine our engine is an object it's a
engine our engine is an object it's a reference data type so if you you output
reference data type so if you you output it directly you're given a hash ID to
it directly you're given a hash ID to represent that engine object so if we
represent that engine object so if we need the type of engine we're going to
need the type of engine we're going to access our engine object then get the
access our engine object then get the type so following our engine object we
type so following our engine object we will use that access modifier that
will use that access modifier that dot then access the type the
dot then access the type the attribute so the engine type is a
attribute so the engine type is a V8 so it's like we have an object that's
V8 so it's like we have an object that's composed with another object our n
composed with another object our n is part of our car you know what let's
is part of our car you know what let's create a method for the engine we'll
create a method for the engine we'll create a start
create a start method void
method void start we'll output the following let's
start we'll output the following let's say using a print line
say using a print line statement you start
statement you start the plus this. type meaning type of the
the plus this. type meaning type of the engine plus the word engine then going
engine plus the word engine then going to our car class let's create a start
to our car class let's create a start method for the car class
method for the car class void
void start when we start the car we also
start when we start the car we also start the engine let's take this.
start the engine let's take this. engine call it start
engine call it start method and then we can output something
method and then we can output something else too if we would like let's
else too if we would like let's output the plus this do
output the plus this do model plus the words is
model plus the words is running now if we start the car let's
running now if we start the car let's take our car call it start
take our car call it start method and we should get the following
method and we should get the following you start the V8 engine the Corvette is
you start the V8 engine the Corvette is running now a key difference with
running now a key difference with composition is that if we delete our car
composition is that if we delete our car object that should also delete our
object that should also delete our engine cuz our engine is part of our car
engine cuz our engine is part of our car so to demonstrate that I'm going to
so to demonstrate that I'm going to delete our car object
engine all right everybody that is composition it represents a part of
composition it represents a part of relationship between objects for example
relationship between objects for example an engine is part of a car this allows
an engine is part of a car this allows for complex objects to be constructed
for complex objects to be constructed from smaller objects and well everybody
from smaller objects and well everybody that is composition using Java well look
that is composition using Java well look who showed up today I got to talk about
who showed up today I got to talk about rapper classes rapper classes allow
rapper classes rapper classes allow primitive values you know such as as
primitive values you know such as as integers characters doubles booleans
integers characters doubles booleans those sorts of things rapper classes
those sorts of things rapper classes allow these primitive values to be
allow these primitive values to be treated as objects or basically wrapping
treated as objects or basically wrapping primitive values within an object kind
primitive values within an object kind of like a Christmas present generally
of like a Christmas present generally you don't need to wrap Primitives unless
you don't need to wrap Primitives unless you need an object for some reason like
you need an object for some reason like if you're using a collections framework
if you're using a collections framework in Java and rapper classes also give you
in Java and rapper classes also give you access to a lot of useful static utility
access to a lot of useful static utility methods so let me give you a
methods so let me give you a demonstration of rapper
demonstration of rapper classes the method of creating rapper
classes the method of creating rapper classes I'm about about to show you is
classes I'm about about to show you is actually depreciated but it's going to
actually depreciated but it's going to help you visualize how this works
help you visualize how this works wrapping A Primitive within an object
wrapping A Primitive within an object the modern approach is using a technique
the modern approach is using a technique called autoboxing but the method I'm
called autoboxing but the method I'm about to show you is a good way to
about to show you is a good way to visualize this whole thing so let's say
visualize this whole thing so let's say we have an INT of a variable a a equal
we have an INT of a variable a a equal 123 we can treat this primitive as an
123 we can treat this primitive as an object by using a wrapper class here's
object by using a wrapper class here's how rather than declaring this variable
how rather than declaring this variable as an INT
as an INT we will use the rapper class of integer
we will use the rapper class of integer integer variable a equals a new integer
integer variable a equals a new integer and then we're going to pass in that
and then we're going to pass in that number that integer as an argument a is
number that integer as an argument a is an object we're passing in that
an object we're passing in that primitive data type that int as an
primitive data type that int as an argument to the integer class so a is an
argument to the integer class so a is an object but it does contain A Primitive
object but it does contain A Primitive value again this is depreciated as a
value again this is depreciated as a version 9 so you shouldn't do it this
version 9 so you shouldn't do it this way but this is a good way to visualize
way but this is a good way to visualize it then if you need a double we'll use
it then if you need a double we'll use the wrapper class of double let's say
the wrapper class of double let's say variable b equals a new double then
variable b equals a new double then we'll pass in a double 3.14 is
we'll pass in a double 3.14 is good then we have char which is
good then we have char which is character that's the rapper class
character that's the rapper class character C equals a new character then
character C equals a new character then pass in a character I'll pass in a
pass in a character I'll pass in a dollar
dollar sign We'll add one more let's say a
sign We'll add one more let's say a Boolean we will use the wrapper class of
Boolean we will use the wrapper class of Boolean Boolean D equals a new boan then
Boolean Boolean D equals a new boan then pass in a Boolean
pass in a Boolean value here's just a few examples these
value here's just a few examples these are all objects a b c and d by wrapping
are all objects a b c and d by wrapping these Primitives within an object that
these Primitives within an object that allows us to use these primitive values
allows us to use these primitive values within collections Frameworks such as
within collections Frameworks such as array lists which we'll talk about in
array lists which we'll talk about in the next topic the modern way to use
the next topic the modern way to use rapper classes is actually just to
rapper classes is actually just to assign them directly to their primitive
assign them directly to their primitive values the class of integer a equals
values the class of integer a equals 123 doubleb equal
123 doubleb equal 3.14 character C equals a dollar sign
3.14 character C equals a dollar sign character and then D equals
character and then D equals true this technique is called
true this technique is called autoboxing We're directly assigning
autoboxing We're directly assigning these Primitives into an object using a
these Primitives into an object using a rapper class now this is very similar to
rapper class now this is very similar to how we declare and assign strings to
how we declare and assign strings to create a string you would say string
create a string you would say string let's say E equals a string of
let's say E equals a string of characters such as the word Pizza you
characters such as the word Pizza you can see that there's a similar pattern
can see that there's a similar pattern we have always created strings this way
we have always created strings this way but with autoboxing it's a similar
but with autoboxing it's a similar process these are all reference data
process these are all reference data types they're a type of
types they're a type of object there's also a technique called
object there's also a technique called unboxing to convert a rapper class back
unboxing to convert a rapper class back to its primitive this is
to its primitive this is unboxing so let's say we would like to
unboxing so let's say we would like to convert our object of a it's an integer
convert our object of a it's an integer object back to its primitive let's say
object back to its primitive let's say int x equals all you got to do is set it
int x equals all you got to do is set it equal to your object in this case our
equal to your object in this case our integer object of a this is unboxing
integer object of a this is unboxing we're taking a primitive that's wrapped
we're taking a primitive that's wrapped in an object and unboxing it we
in an object and unboxing it we unwrapping it and setting it back to its
unwrapping it and setting it back to its primitive if we were unboxing a double
primitive if we were unboxing a double we would say double some variable equals
we would say double some variable equals b or chars Char x
b or chars Char x equals our character object of c and
equals our character object of c and then Boolean Boolean x equals D again
then Boolean Boolean x equals D again this is autoboxing we're wrapping up a
this is autoboxing we're wrapping up a Christmas present we're wrapping up a
Christmas present we're wrapping up a primitive within an object and then
primitive within an object and then unboxing is removing it we're opening
unboxing is removing it we're opening the Christmas present now these rapper
the Christmas present now these rapper classes themselves do have some pretty
classes themselves do have some pretty useful utility methods that are static
useful utility methods that are static let me demonstrate a few you might be
let me demonstrate a few you might be interested in but there would be too
interested in but there would be too many to cover in just this one video if
many to cover in just this one video if you ever need to convert a primitive
you ever need to convert a primitive data type into a string there's a two-
data type into a string there's a two- string method of these utility classes
string method of these utility classes so let's say we have string
so let's say we have string a string
a string B string
B string C and string
D I can convert an integer into a string using the integer wrapper class it's ACC
using the integer wrapper class it's ACC statically so we type the name of the
statically so we type the name of the class integer called the two string
class integer called the two string method which is static and then pass it
method which is static and then pass it an integer like
an integer like 123 so let's do this with the
123 so let's do this with the double we will access the double wrapper
double we will access the double wrapper class called the two string method and
class called the two string method and then pass in a double
then pass in a double 3.14 then to convert a character to a
3.14 then to convert a character to a string we would use the character
string we would use the character wrapper class character to string and
wrapper class character to string and then pass in a character
then pass in a character and then
and then Boolean we will access the Boolean
Boolean we will access the Boolean wrapper class called the two string
wrapper class called the two string method and then pass in a
method and then pass in a Boolean so strings can be concatenated
Boolean so strings can be concatenated together we should be able to do the
together we should be able to do the following let's say string X = A + B + C
following let's say string X = A + B + C +
+ D and then we'll output whatever our
D and then we'll output whatever our variable X is
we get 1 123 3.14 at false it's all one long string it's because we use these
long string it's because we use these rapper classes to convert these
rapper classes to convert these primitive data types into Strings if you
primitive data types into Strings if you ever need to convert a primitive to a
ever need to convert a primitive to a string then use that primitive data
string then use that primitive data types rapper class and call the two
types rapper class and call the two string method then you just need to pass
string method then you just need to pass that value in as an argument then it's
that value in as an argument then it's going to spit out a string for you now
going to spit out a string for you now on the other hand to convert a string to
on the other hand to convert a string to a primitive data type there's another
a primitive data type there's another useful utility method of wrapper classes
useful utility method of wrapper classes so what we'll do is
so what we'll do is parsing we will have an INT of
parsing we will have an INT of a a double of
a a double of B A Char of
B A Char of c and a Boolean of
D int a will equal we're going to call the integer wrapper class call a static
the integer wrapper class call a static method of parse int we can convert a
method of parse int we can convert a string to an integer I will convert a
string to an integer I will convert a string of 123 to an
string of 123 to an integer now with doubles you will call
integer now with doubles you will call the double wrapper class and we will
the double wrapper class and we will parse a
parse a double we'll pass in a string of
double we'll pass in a string of 3.14 now characters don't have a parse
3.14 now characters don't have a parse method what you could do instead is with
method what you could do instead is with any string let's say we have a string of
any string let's say we have a string of pizza strings do have built-in methods
pizza strings do have built-in methods one of which is the Char at
one of which is the Char at method return the character the first
method return the character the first position where index is zero again
position where index is zero again character doesn't have a parse character
character doesn't have a parse character method so you would have to use charart
method so you would have to use charart at which is unrelated to wrapper
at which is unrelated to wrapper classes so then with the
classes so then with the Boolean we would access the Boolean
Boolean we would access the Boolean wrapper class called the parse Boolean
wrapper class called the parse Boolean method and we can convert a string
method and we can convert a string representation of a Boolean such as true
representation of a Boolean such as true into an actual Boolean and then let's
into an actual Boolean and then let's output them now we shouldn't be able to
output them now we shouldn't be able to add these together much like what we did
add these together much like what we did when we used the two string method for
when we used the two string method for example string X = A + B + C + D this
example string X = A + B + C + D this isn't going to work because we're mixing
isn't going to work because we're mixing and matching different data types and
and matching different data types and then if I was to Output
X that would give us a compilation error to convert a string to its primitive
to convert a string to its primitive data type there is various parse methods
data type there is various parse methods to handle that within our rapper classes
to handle that within our rapper classes it depends on the data type you're
it depends on the data type you're working with
working with there's a couple other miscellaneous
there's a couple other miscellaneous utility methods within rapper classes
utility methods within rapper classes I'll just cover two more so let's say we
I'll just cover two more so let's say we have a Char of letter pick a
have a Char of letter pick a letter I will pick the letter lowercase
letter I will pick the letter lowercase B I'm going to use a print line
B I'm going to use a print line statement we can check to see if our
statement we can check to see if our letter actually is a letter we can
letter actually is a letter we can access the character wrapper class call
access the character wrapper class call the is letter method and then pass in
the is letter method and then pass in our letter
our letter this returns a Boolean true or false is
this returns a Boolean true or false is this character a
this character a letter that is
letter that is true this would be useful for verifying
true this would be useful for verifying user input what if this was a dollar
user input what if this was a dollar sign is this a letter well this returns
sign is this a letter well this returns false that is not a
false that is not a letter I'll switch this back to
letter I'll switch this back to lowercase b there's also a built-in
lowercase b there's also a built-in method to check to see if this letter is
method to check to see if this letter is uppercase or not there's a built-in
uppercase or not there's a built-in utility method of the character rapper
utility method of the character rapper class class to check to see if this is
class class to check to see if this is uppercase or
uppercase or not
not character is uppercase and then pass in
character is uppercase and then pass in our letter is it uppercase currently it
our letter is it uppercase currently it isn't that is
isn't that is false but if it were
false but if it were uppercase that returns
uppercase that returns true some of these utility methods of
true some of these utility methods of the character rapper class would be
the character rapper class would be great for verifying user input like a
great for verifying user input like a username or a password all right
username or a password all right everybody so those are wrapper classes
everybody so those are wrapper classes we're basically taking a primitive and
we're basically taking a primitive and wrapping it in an object kind of like a
wrapping it in an object kind of like a Christmas present in the next topic
Christmas present in the next topic we're going to be working with array
we're going to be working with array lists and array lists only work with
lists and array lists only work with objects so we need to utilize these
objects so we need to utilize these rapper classes in order to work with
rapper classes in order to work with array lists and wrapper classes do
array lists and wrapper classes do provide some useful static utility
provide some useful static utility methods that you can always access all
methods that you can always access all right everybody and those are wrapper
right everybody and those are wrapper classes and in the next video we're
classes and in the next video we're going to cover array lists all right
going to cover array lists all right people it's about time we get to array
people it's about time we get to array lists and Java an array list is a
lists and Java an array list is a resizable array that stores objects you
resizable array that stores objects you can store Primitives if so you'll be
can store Primitives if so you'll be using autoboxing which we learned about
using autoboxing which we learned about in the last topic on rapper classes
in the last topic on rapper classes arrays are fixed in size but array lists
arrays are fixed in size but array lists can change they're Dynamic here's how to
can change they're Dynamic here's how to create an array list first we'll follow
create an array list first we'll follow our similar pattern with creating many
our similar pattern with creating many objects in Java array list let's say
objects in Java array list let's say list equals new array list we will need
list equals new array list we will need to make One Import import java. u.
to make One Import import java. u. arraylist following the type of array
arraylist following the type of array list we're going to use the diamond
list we're going to use the diamond operator this has to deal with generics
operator this has to deal with generics which is a future topic but for now
which is a future topic but for now we're going to specify what type of
we're going to specify what type of object we're going to be storing within
object we're going to be storing within our array list and you can always use
our array list and you can always use the appropriate wrapper class to store
the appropriate wrapper class to store Primitives for example if you need to
Primitives for example if you need to store integers you can say integer and
store integers you can say integer and then we do need that diamond operator
then we do need that diamond operator after the second array list
after the second array list you don't also need to specify the data
you don't also need to specify the data type within the second Diamond operator
type within the second Diamond operator Java can infer that you're going to
Java can infer that you're going to follow this pattern to create an array
follow this pattern to create an array list this array list can store integers
list this array list can store integers you just have to specify that type so
you just have to specify that type so for example let's take our list and add
for example let's take our list and add a few
a few numbers
two and then we can print our list our list I will print our
list I will print our list and we have three numbers
list and we have three numbers 312 now if you were storing doubles you
312 now if you were storing doubles you would set the type to be double and use
would set the type to be double and use the double wrapper class 3.14 1.99
the double wrapper class 3.14 1.99 2.01 I'm just making up numbers
2.01 I'm just making up numbers here there we go so let's store
here there we go so let's store strings let's create an array list named
strings let's create an array list named fruits we will store the names of some
fruits we will store the names of some fruit so the array name is going to be
fruit so the array name is going to be fruits and then we will print our array
fruits and then we will print our array list of fruits think of some fruit I
list of fruits think of some fruit I will add an
apple an orange a
orange a banana and a coconut that should be good
banana and a coconut that should be good enough for this
example and now we have an array list of strings named fruits Apple Orange banana
strings named fruits Apple Orange banana coconut to add an element to an array
coconut to add an element to an array list you can use the add method add is a
list you can use the add method add is a built-in method of array lists to remove
built-in method of array lists to remove an element you can use the remove method
an element you can use the remove method then specify an index so let's take
then specify an index so let's take fruits and remove the element at index
fruits and remove the element at index zero that should get rid of our
Apple then we have orange banana coconut if we were to remove the element
coconut if we were to remove the element at index one that should get rid of our
at index one that should get rid of our orange apple banana Coco
orange apple banana Coco nut there's also the set method take our
nut there's also the set method take our Ray list of fruits called the set method
Ray list of fruits called the set method add a certain index let's say zero we
add a certain index let's say zero we can set that element to be something
can set that element to be something else let's replace apple with
else let's replace apple with pineapple replace the element at index
pineapple replace the element at index zero with
zero with pineapple then we have pineapple orange
pineapple then we have pineapple orange banana coconut or index
banana coconut or index one would be apple pineapple banana
one would be apple pineapple banana coconut
coconut that's the set
that's the set method with an array list to get an
method with an array list to get an element at a certain index you can use
element at a certain index you can use the get method then specify the element
the get method then specify the element number get the element at index zero
number get the element at index zero that's going to return
that's going to return Apple get the element at index one would
Apple get the element at index one would be
be orange
orange two
two banana
banana 3
3 coconut you can also get the size of an
coconut you can also get the size of an array list take your array list call the
array list take your array list call the size method that will return the total
size method that will return the total amount of elements within your array
amount of elements within your array list so my array list has four
list so my array list has four elements to sort your array list you
elements to sort your array list you will use the collections framework call
will use the collections framework call the sort method and then pass in your
the sort method and then pass in your array list our array list is named
array list our array list is named fruits and then you do need to import
fruits and then you do need to import this
this class java.util doc collections
class java.util doc collections after sorting our array list let's print
after sorting our array list let's print it print my array list of
it print my array list of fruits so these all should be in
fruits so these all should be in alphabetical order starting with a for
alphabetical order starting with a for apple b for banana C for coconut o for
apple b for banana C for coconut o for orange so that's how to sort an array
orange so that's how to sort an array list you can use the collections
list you can use the collections framework you could use an enhanced for
framework you could use an enhanced for Loop to iterate through all the elements
Loop to iterate through all the elements of an array list so the data type of my
of an array list so the data type of my aray list is strings we specified that
aray list is strings we specified that type for every fruit in my array list of
type for every fruit in my array list of fruits let's print each
fruit and here they are apple banana coconut
coconut orange all right so now we're going to
orange all right so now we're going to cover an
exercise we'll create an array and accept user input a user will enter in
accept user input a user will enter in all the food that they want within this
all the food that they want within this array list so to help us with this
array list so to help us with this exercise we will need a scanner scanner
exercise we will need a scanner scanner scanner equals new scanner
scanner equals new scanner pass in
pass in system.in import this class and then be
system.in import this class and then be sure to close your scanner at the end
sure to close your scanner at the end because I tend to forget scanner.
because I tend to forget scanner. close we'll need an array
close we'll need an array list again we'll follow a similar
list again we'll follow a similar pattern with creating objects array list
pattern with creating objects array list let's say list equals new array
let's say list equals new array list using the diamond operator we're
list using the diamond operator we're going to specify the type of what we're
going to specify the type of what we're storing within this array list we'll
storing within this array list we'll stick with
strings let's rename our list as Foods we'll be storing some food well at least
we'll be storing some food well at least the name of
the name of food we'll create a prompt we'll ask a
food we'll create a prompt we'll ask a user enter the number of food they would
user enter the number of food they would like to
like to store enter the number of food you would
store enter the number of food you would like and I'll use print rather than
like and I'll use print rather than print line for the user input
print line for the user input we'll create a variable of num of food
we'll create a variable of num of food to store the number of food that we're
to store the number of food that we're going to store equals take our scanner
going to store equals take our scanner call the next int method to get the next
call the next int method to get the next integer from the
integer from the user once we accept an integer we should
user once we accept an integer we should clear the input buffer because there's
clear the input buffer because there's going to be a new line character within
going to be a new line character within there take our scanner call the next
there take our scanner call the next line method to clear it let's do a test
line method to clear it let's do a test run and enter the number of food you
run and enter the number of food you would like I'll just say three and that
would like I'll just say three and that seems to work for now we have the number
seems to work for now we have the number of food we're going to store within this
of food we're going to store within this array list in my example let's say I
array list in my example let's say I would like to enter three food items
would like to enter three food items well we could use a for Loop to iterate
well we could use a for Loop to iterate three times we will ask your user to
three times we will ask your user to enter in a food three times then so we
enter in a food three times then so we can use a for Loop for that within our
can use a for Loop for that within our for loop we're going to create a counter
for loop we're going to create a counter of I meaning index we can set that to be
of I meaning index we can set that to be zero or one let's stick with one we'll
zero or one let's stick with one we'll continue this for loop as long as I is
continue this for loop as long as I is less than or equal to our number of food
less than or equal to our number of food variable if I would like to enter in
variable if I would like to enter in four food items this would be four so we
four food items this would be four so we should iterate this Loop four times we
should iterate this Loop four times we will increment I by One during each
will increment I by One during each cycle of this
cycle of this Loop during each iteration of this Loop
Loop during each iteration of this Loop we will ask for a food item I'll use
we will ask for a food item I'll use print rather than print line we will ask
print rather than print line we will ask a user to enter food number
a user to enter food number then I'll add plus our index of I so
then I'll add plus our index of I so during the first cycle I is going to be
during the first cycle I is going to be one then 2 3 four so on and so
one then 2 3 four so on and so forth then I'll add a colon then a
forth then I'll add a colon then a space we'll create a local variable of
space we'll create a local variable of food this will be of the string data
food this will be of the string data type we will set this equal to use our
type we will set this equal to use our scanner called the next line method to
scanner called the next line method to get a line of text from the
get a line of text from the user once we have our string of food
user once we have our string of food we're going to add it to our array list
we're going to add it to our array list of Foods so take your array list of
of Foods so take your array list of foods call the ad method to add an
foods call the ad method to add an element we will add our string of food
element we will add our string of food to our array list of
to our array list of foods and then once we're done let's
foods and then once we're done let's print our array list using a print line
print our array list using a print line statement we will print our Ray list of
statement we will print our Ray list of foods all right let's test
foods all right let's test it enter the number of food you would
it enter the number of food you would like I'll say four so we should ask for
like I'll say four so we should ask for four food items enter food number one
four food items enter food number one I'll say
I'll say pizza hot
pizza hot dog hamburger and then
dog hamburger and then Taco and here's my array list of food
Taco and here's my array list of food pizza hot dog hamburger
pizza hot dog hamburger taco all right everybody those are array
taco all right everybody those are array lists an array list is a resizable array
lists an array list is a resizable array that stores objects you can store
that stores objects you can store Primitives you're just going to use
Primitives you're just going to use Java's autoboxing feature if that's the
Java's autoboxing feature if that's the case once you have your array list
case once you have your array list there's various methods to add remove
there's various methods to add remove move or set elements and well everybody
move or set elements and well everybody those are array lists in Java today I'm
those are array lists in Java today I'm going to talk about exceptions using
going to talk about exceptions using Java an exception is an event that
Java an exception is an event that interrupts the normal flow of a program
interrupts the normal flow of a program these exceptions pop up if you do things
these exceptions pop up if you do things like divide by zero you can't find a
like divide by zero you can't find a resource for some reason or if there's a
resource for some reason or if there's a mismatch with the input type let's say
mismatch with the input type let's say the program asks for a number and you
the program asks for a number and you type in a string of characters these
type in a string of characters these sorts of events interrupt your program
sorts of events interrupt your program they're called exceptions there's a way
they're called exceptions there's a way that we can handle them and that is by
that we can handle them and that is by using a few blocks of code try catch and
using a few blocks of code try catch and optionally finally so any code that's
optionally finally so any code that's considered dangerous where it might
considered dangerous where it might interrupt your program you can surround
interrupt your program you can surround with a tri block here's an example so
with a tri block here's an example so let's say I'm going to take the number
let's say I'm going to take the number one and divide it by zero mathematically
one and divide it by zero mathematically speaking you can't divide by
zero that causes an exception more specifically and arithmetic exception
specifically and arithmetic exception I'm actually just going to copy this and
I'm actually just going to copy this and save
save it this code is dangerous it's
it this code is dangerous it's interrupting our program by causing an
interrupting our program by causing an exception we can gracefully handle this
exception we can gracefully handle this exception so that it doesn't interrupt
exception so that it doesn't interrupt the normal flow of our program any
the normal flow of our program any dangerous code we're going to surround
dangerous code we're going to surround with a tri block try and a set of curly
braces there we go however if we have a Tri block we also need a catch
Tri block we also need a catch block we will catch any
block we will catch any exceptions but we're going to list the
exceptions but we're going to list the specific kind of exception we're going
specific kind of exception we're going to catch well let's catch that one
to catch well let's catch that one exception that arithmetic
exception that arithmetic exception this is the type we're setting
exception this is the type we're setting up a parameter here arithmetic exception
up a parameter here arithmetic exception is the type we will give this exception
is the type we will give this exception a name of e for a
a name of e for a nickname if we encounter this exception
nickname if we encounter this exception we can take a different course of action
we can take a different course of action instead of interrup the program so let's
instead of interrup the program so let's do the
do the following let's
following let's output you can't divide by zero idiot so
output you can't divide by zero idiot so if we run this again it shouldn't
if we run this again it shouldn't interrupt our
interrupt our program we catch this exception and
program we catch this exception and output this text
output this text instead so any code that's dangerous
instead so any code that's dangerous where it might cause an exception you
where it might cause an exception you can surround with the tri block you can
can surround with the tri block you can add more than one catch block to catch
add more than one catch block to catch and handle spefic specific exceptions so
and handle spefic specific exceptions so this time we're going to accept some
this time we're going to accept some user input we'll need a scanner for now
user input we'll need a scanner for now I'm going to write the scanner outside
I'm going to write the scanner outside of the tri Block near the end of this
of the tri Block near the end of this video there's a feature called used with
video there's a feature called used with resources I'll show you how to do that
resources I'll show you how to do that later scanner scanner equals new scanner
later scanner scanner equals new scanner type
type system.in and then import this
system.in and then import this class import java.util.scanner
class import java.util.scanner anytime you accept user input it's
anytime you accept user input it's almost always d dangerous code because a
almost always d dangerous code because a user can type in
user can type in anything this time let's prompt a user
anything this time let's prompt a user to enter a
to enter a number and I will use
number and I will use print let's create a local variable of
print let's create a local variable of int number equals use our scanner called
int number equals use our scanner called the next int method to accept an integer
the next int method to accept an integer and then we'll just output our
number and enter a number uh how about no I'm going to type in the word Pizza
no I'm going to type in the word Pizza instead well we get an exception an
instead well we get an exception an input mismatch exception Java was
input mismatch exception Java was expecting an integer but we typed in a
expecting an integer but we typed in a string instead we can handle these
string instead we can handle these exceptions too and I'm just going to
exceptions too and I'm just going to copy the name of this exception because
copy the name of this exception because we'll reuse it let's catch the following
we'll reuse it let's catch the following let's
let's catch any input mismatch
catch any input mismatch exceptions this is the type we will give
exceptions this is the type we will give this exception a nickname of e so this
this exception a nickname of e so this exception we actually do have to
exception we actually do have to import import java.util do input
import import java.util do input mismatch exception in case there's a
mismatch exception in case there's a mismatch with the data type we're asking
mismatch with the data type we're asking the user for a number but they type in a
the user for a number but they type in a string Let's help with the following
string Let's help with the following let's
let's say that wasn't a
say that wasn't a number let's try it
number let's try it again enter a number uh I'll type in the
again enter a number uh I'll type in the word I already did pizza let's do Taco
word I already did pizza let's do Taco that wasn't a
that wasn't a number and our program finished with no
number and our program finished with no problems you can catch and handle more
problems you can catch and handle more than one exception there is a catch all
than one exception there is a catch all statement that you could
add you could catch all exceptions exception e using this by itself isn't
exception e using this by itself isn't good
good practice you want to let a user know
practice you want to let a user know exactly what went wrong if all else
exactly what went wrong if all else fails and there's an exception that you
fails and there's an exception that you don't anticipate you could just say okay
don't anticipate you could just say okay something went
something went wrong you could technically use this by
itself enter a number for example I'll type in hot dog something went wrong
type in hot dog something went wrong this does prevent our program from being
this does prevent our program from being interrupted it is good practice to let
interrupted it is good practice to let the user know what went wrong exactly
the user know what went wrong exactly I'm looking at you Microsoft catching
I'm looking at you Microsoft catching all exceptions acts as some sort of
all exceptions acts as some sort of safety net you should only do it at the
safety net you should only do it at the end in case there's something you don't
end in case there's something you don't anticipate it is better to catch and
anticipate it is better to catch and handle specific types of exceptions
handle specific types of exceptions because you can let the user know what
because you can let the user know what went wrong
went wrong exactly now there's also the finally
exactly now there's also the finally block this is
block this is optional finally will always execute
optional finally will always execute whether there's an exception or not this
whether there's an exception or not this is where you might clean up any
is where you might clean up any resources for example with my scanner I
resources for example with my scanner I forgot to close it we can actually close
forgot to close it we can actually close it within the final
it within the final block when we're done with our scanner
block when we're done with our scanner let's close it
let's close it because if we encounter an exception we
because if we encounter an exception we might not close the scanner other times
might not close the scanner other times finally might be useful is if you open a
finally might be useful is if you open a file within a tri
file within a tri block then you'll want to close the file
block then you'll want to close the file when you're done with it you can do that
when you're done with it you can do that within the finally block for testing
within the finally block for testing purposes I'm just going to add this
purposes I'm just going to add this always
always executes all right let's do a test
executes all right let's do a test run enter a number I'll type in 12 three
run enter a number I'll type in 12 three and then we output 123 see that finally
and then we output 123 see that finally block does execute this always
block does execute this always executes if we encounter an exception
executes if we encounter an exception enter a number I will type in
enter a number I will type in Taco we get our exception message for
Taco we get our exception message for input mismatch and then that finally
input mismatch and then that finally block does
block does execute finally is quite often used for
execute finally is quite often used for cleanup cleaning up your program when
cleanup cleaning up your program when you're done with it when you open a file
you're done with it when you open a file or resource you want to close it we'll
or resource you want to close it we'll have more practice with this on the next
have more practice with this on the next topic of file handling now there's also
topic of file handling now there's also try with
try with resources and actually Java is
resources and actually Java is recommending this rather than declaring
recommending this rather than declaring our scanner outside of the tri block we
our scanner outside of the tri block we can place within a set of parentheses
can place within a set of parentheses and then Java is automatically going to
and then Java is automatically going to close those resources when it's done
close those resources when it's done opening them so this works
opening them so this works too so enter a number
123 enter a number Pizza that wasn't a number
Pizza that wasn't a number all right everybody so those are
all right everybody so those are exceptions they're events that interrupt
exceptions they're events that interrupt the normal flow of a program exceptions
the normal flow of a program exceptions occur when you divide by zero you can't
occur when you divide by zero you can't locate a resource or there's a mismatch
locate a resource or there's a mismatch of the input type that a user types in
of the input type that a user types in you'll want to surround any dangerous
you'll want to surround any dangerous code with a tri block anytime you accept
code with a tri block anytime you accept user input or try and locate an external
user input or try and locate an external resource that's almost always dangerous
resource that's almost always dangerous code try any dangerous code catch any
code try any dangerous code catch any exceptions and optionally you can add
exceptions and optionally you can add finally to do any resource cleanup and
finally to do any resource cleanup and well everybody those are exceptions in
well everybody those are exceptions in Java all right everybody in this video
Java all right everybody in this video I'm going to show you how you can write
I'm going to show you how you can write a file using Java after doing some
a file using Java after doing some research I've encountered four popular
research I've encountered four popular options the first way I'm about to show
options the first way I'm about to show you is the most simple and is what I'll
you is the most simple and is what I'll be demonstrating in this topic we'll be
be demonstrating in this topic we'll be using a file writer object it's good for
using a file writer object it's good for writing small or medium-sized text files
writing small or medium-sized text files there's also buffered writer this has
there's also buffered writer this has better performance for large amounts of
better performance for large amounts of text print writer is best for structure
text print writer is best for structure data like reports or logs then there's
data like reports or logs then there's file output stream which is best for
file output stream which is best for binary files such as images or audio
binary files such as images or audio files files of that nature in this topic
files files of that nature in this topic I'm going to cover file writer just so
I'm going to cover file writer just so we get the hang of the basics I might
we get the hang of the basics I might make videos on the other writers but I
make videos on the other writers but I haven't decided yet here's how we can
haven't decided yet here's how we can write a basic file using Java we'll need
write a basic file using Java we'll need a file writer object file writer I'll
a file writer object file writer I'll name this file writer just writer for
name this file writer just writer for short equals new file
short equals new file writer then we need to pass in a file
writer then we need to pass in a file path or a file name let's create a file
path or a file name let's create a file named test and include a file extension
named test and include a file extension let's say it's a txt file a plain text
let's say it's a txt file a plain text file now you could include an absolute
file now you could include an absolute file path I'll show you how to do that
file path I'll show you how to do that later our plain text file a test is
later our plain text file a test is going to appear in our source folder
going to appear in our source folder reading or writing files is kind of
reading or writing files is kind of unpredictable you could consider that
unpredictable you could consider that dangerous code any dangerous code we
dangerous code any dangerous code we want to enclose within a tri block try
want to enclose within a tri block try this dangerous code catch any exceptions
this dangerous code catch any exceptions that might interrupt our
that might interrupt our program with modern Java you can try and
program with modern Java you can try and open up some resource add a set of
open up some resource add a set of parentheses after try we will try to
parentheses after try we will try to open up a file writer
object so file writer writer equals new file writer then we have our file name
file writer then we have our file name including the
including the extension now we do have to import this
extension now we do have to import this class import
class import java. file writer
java. file writer if for some reason we can't write this
if for some reason we can't write this file we might encounter an exception we
file we might encounter an exception we will catch any IO exceptions IO meaning
will catch any IO exceptions IO meaning input output catch any input output
input output catch any input output exceptions that's the type we will give
exceptions that's the type we will give this exception a nickname of
this exception a nickname of e then we do have to import this class
e then we do have to import this class too in order to work with IO exceptions
too in order to work with IO exceptions java.io doio
java.io doio exception in case there's a problem
exception in case there's a problem writing this file we'll catch this
writing this file we'll catch this exception if it comes up this acts as
exception if it comes up this acts as more of a safety net if we encounter
more of a safety net if we encounter this exception we can say something
this exception we can say something generic such as could not write file but
generic such as could not write file but it is best practice to handle specific
it is best practice to handle specific kind of exceptions first momentarily
kind of exceptions first momentarily we're going to add a catch clause for a
we're going to add a catch clause for a file not found exception in case we
file not found exception in case we can't locate a file path but we'll take
can't locate a file path but we'll take care of that in a moment within the tri
care of that in a moment within the tri Block in order to write a file using
Block in order to write a file using Java using file writer we will take our
Java using file writer we will take our file writer which we named
file writer which we named writer called the write method and then
writer called the write method and then pass in a
pass in a string let's say I like then pick your
string let's say I like then pick your favorite food as you know my favorite
favorite food as you know my favorite food is
food is pizza then after writing this file if we
pizza then after writing this file if we don't encounter any exceptions we'll
don't encounter any exceptions we'll print a confirmation
print a confirmation message let's say the
message let's say the following file has been
following file has been written all right let's test this
written since we didn't specify a file path your file is likely going to be
path your file is likely going to be within your Source folder and here's
within your Source folder and here's mine test.txt and it says the following
mine test.txt and it says the following I like
I like pizza now you could pick a different
pizza now you could pick a different location for example you could use an
location for example you could use an absolute file path so let's say I would
absolute file path so let's say I would like to write this file to my desktop so
like to write this file to my desktop so what I could do I'm going to go to my
what I could do I'm going to go to my desktop I'm going to get the file
desktop I'm going to get the file location my desktop I'll just right
location my desktop I'll just right click on one of these
click on one of these folders go to properties copy this
folders go to properties copy this location then I'm going to paste that
location then I'm going to paste that file
path you'll likely need to use double forward slashes Java interprets a single
forward slashes Java interprets a single forward slash as an escape sequence so
forward slash as an escape sequence so you may need to use double slashes when
you may need to use double slashes when I write this file it should be at this
I write this file it should be at this location this absolute file path Let's
location this absolute file path Let's test it
test it file has been written let's go to my
file has been written let's go to my desktop and here's that
desktop and here's that file
file test it says I like
pizza let's say that we get the file path wrong instead of desktop I'll
path wrong instead of desktop I'll misspell this as
misspell this as deskto run this again we counter that
deskto run this again we counter that exception could not write file that's
exception could not write file that's because Java couldn't locate this file
because Java couldn't locate this file path I misspelled it now when handling
path I misspelled it now when handling exceptions it is best practice to catch
exceptions it is best practice to catch specific types of exceptions first here
specific types of exceptions first here we're relying solely on our safety net
we're relying solely on our safety net that catches all input output exceptions
that catches all input output exceptions another kind of exception that we can
another kind of exception that we can catch is the
catch is the following file not
following file not found exception we will give this a
found exception we will give this a nickname of e then we do need to import
nickname of e then we do need to import this class
this class java.io file not found
java.io file not found exception this this is if we can't
exception this this is if we can't locate a file or a file path is
locate a file or a file path is invalid so let's output the
invalid so let's output the following could not locate file location
following could not locate file location let's try that again remember that my
let's try that again remember that my file path is
file path is misspelled could not locate file
misspelled could not locate file location let's spell this correctly this
location let's spell this correctly this time I'm going to delete this
time I'm going to delete this file maybe I'll add another line of text
file maybe I'll add another line of text I like
I like pizza it's really good okay let's try
pizza it's really good okay let's try that
that again file has been written going to my
again file has been written going to my desktop here's that file and it says I
desktop here's that file and it says I like pizza it's really
like pizza it's really good for better organization what you
good for better organization what you could do is create a string a file path
could do is create a string a file path and set that equal to a
and set that equal to a string we're going to cut everything
string we're going to cut everything within our file
within our file writer and paste it within the string
writer and paste it within the string we're going to assign the string of text
we're going to assign the string of text equal to a string variable a file path
equal to a string variable a file path then we'll pass in the string variable
then we'll pass in the string variable to the file
to the file writer and instead of passing in a
writer and instead of passing in a string literal to the right method of a
string literal to the right method of a file writer for better organization
file writer for better organization let's create a string of let's say text
let's create a string of let's say text content equals and then we'll cut our
text and then pass in the text content let's see I'll add another line
content let's see I'll add another line I like pizza it's really
I like pizza it's really good buy me
good buy me pizza okay let's run this
pizza okay let's run this again file has been written go to our
again file has been written go to our test file and here's our test file I
test file and here's our test file I like pizza it's really good buy me pizza
like pizza it's really good buy me pizza if you have a string that takes up
if you have a string that takes up multiple lines another option is to
multiple lines another option is to write a multi-line string by using a
write a multi-line string by using a triple set of double quotes So This is
triple set of double quotes So This is if you have a lot of
if you have a lot of text this time I'm going to write a
text this time I'm going to write a poem roses are
poem roses are red violets are
red violets are blue booty booty
blue booty booty booty rocking everywhere
booty rocking everywhere all right so this is a multi-line string
all right so this is a multi-line string you use a triple set of double
you use a triple set of double quotes that's if you have a lot of text
quotes that's if you have a lot of text to write okay let's test it
to write okay let's test it again file has been written let's go to
again file has been written let's go to our desktop open this file and here's
our desktop open this file and here's our poem roses are red violets are blue
our poem roses are red violets are blue booty booty booty rocking
booty booty booty rocking everywhere all right everybody so that
everywhere all right everybody so that is how to write a file using Java to
is how to write a file using Java to write small or mediumsized textt files
write small or mediumsized textt files you can use a file right writer but you
you can use a file right writer but you will need a try and catch block and well
will need a try and catch block and well everybody that's how to write a file
everybody that's how to write a file using Java hey everybody in this video
using Java hey everybody in this video I'm going to show you how we can read a
I'm going to show you how we can read a file using Java after doing some
file using Java after doing some research there's three popular options
research there's three popular options the first and which I'll demonstrate in
the first and which I'll demonstrate in this video is to combine a buffered
this video is to combine a buffered reader and a file reader both together
reader and a file reader both together this technique is best for reading text
this technique is best for reading text files line by line buffered reader can't
files line by line buffered reader can't read a file by itself you can say that
read a file by itself you can say that it acts as a middleman between the
it acts as a middleman between the program and the file system it helps us
program and the file system it helps us read files more efficiently and a file
read files more efficiently and a file reader is what actually reads the file
reader is what actually reads the file so we'll be using these two together
so we'll be using these two together which I will demonstrate momentarily
which I will demonstrate momentarily another technique is to use a file input
another technique is to use a file input stream which is best for binary files
stream which is best for binary files such as images and audio files then
such as images and audio files then there's also Random Access file that's
there's also Random Access file that's best for reading or writing specific
best for reading or writing specific portions of a large file so use this if
portions of a large file so use this if you need to read something specific from
you need to read something specific from a big file in today's video we're going
a big file in today's video we're going to combine a buffered reader and a file
to combine a buffered reader and a file reader together but first we need a file
reader together but first we need a file to work with pick a location where you
to work with pick a location where you would like to read this file from for me
would like to read this file from for me I'm going to create a file on my desktop
I'm going to create a file on my desktop I will create a new text document I'll
I will create a new text document I'll name this
name this test and what should our file say think
test and what should our file say think of something to write so there's a poem
of something to write so there's a poem that I like to use roses are
that I like to use roses are red violets are
red violets are blue booty booty
blue booty booty booty rocking
everywhere we will need the name of this file including the file extension I'm
file including the file extension I'm going to right click go to
going to right click go to properties this file is a plain text
properties this file is a plain text file a txt file I'm going to copy this
location I will create a string variable named file path equals then within a set
named file path equals then within a set of quotes cuz we're working with strings
of quotes cuz we're working with strings I will paste that file path and include
I will paste that file path and include the file name including the extension
the file name including the extension test.txt
test.txt now we're going to be combining a
now we're going to be combining a buffered reader and a file reader
buffered reader and a file reader together first we will create a buffered
together first we will create a buffered reader
reader object
object buffered reader we'll name this reader
buffered reader we'll name this reader equals new buffer
reader we will need to import this class import
class import java.io buffered reader
java.io buffered reader we can't create a buffered reader object
we can't create a buffered reader object without first passing in a reader object
without first passing in a reader object which is why we'll be combining this
which is why we'll be combining this with a file reader object within the
with a file reader object within the Constructor we'll be passing in an
Constructor we'll be passing in an object a new file reader
object a new file reader object and then we do need to import
object and then we do need to import this class
this class too import java.io file reader within
too import java.io file reader within the Constructor of our file reader we're
the Constructor of our file reader we're going to pass in that file path that
going to pass in that file path that string
string when reading and writing files you'll
when reading and writing files you'll need try and catch blocks you can see
need try and catch blocks you can see that Java is already giving us a warning
that Java is already giving us a warning when working with files it's considered
when working with files it's considered dangerous code because you don't know if
dangerous code because you don't know if you'll actually locate that file or not
you'll actually locate that file or not or reading or writing that file might be
or reading or writing that file might be unsuccessful for some reason we will use
unsuccessful for some reason we will use a try and catch block try this dangerous
a try and catch block try this dangerous code catch any
code catch any exceptions with modern Java you can use
exceptions with modern Java you can use with
with resources we will add a set of
resources we will add a set of parentheses after
parentheses after try copy the snippet of code where we
try copy the snippet of code where we create a buffered reader
create a buffered reader object and then paste it within that set
object and then paste it within that set of parentheses remove the semicolon when
of parentheses remove the semicolon when using try with resources you'll
using try with resources you'll automatically close this reader when
automatically close this reader when you're done with it we're going to catch
you're done with it we're going to catch any file not found exceptions within the
any file not found exceptions within the catch
catch block so catch file not found exception
block so catch file not found exception that's the type we will give this
that's the type we will give this exception a nickname of e within the
exception a nickname of e within the parameter and we do need to import this
parameter and we do need to import this class as well import java.io file not
class as well import java.io file not found
found exception if for some reason we can't
exception if for some reason we can't locate this file at this file location
locate this file at this file location let's output the
let's output the following could not locate
following could not locate file to catch all other input output
file to catch all other input output exceptions We'll add another catch block
exceptions We'll add another catch block this will act as a safety
this will act as a safety net we will catch any
net we will catch any IO exceptions IO exception we will give
IO exceptions IO exception we will give it a nickname name of
it a nickname name of e this is where we'll say something went
e this is where we'll say something went wrong and import this class as
wrong and import this class as well just temporarily within our Tri
well just temporarily within our Tri block I'm going to Output that file
block I'm going to Output that file exists so let's test
exists so let's test it that file
it that file exists so that file is at this file
exists so that file is at this file location on my
location on my desktop for some reason if we can't
desktop for some reason if we can't locate that file let's say that I
locate that file let's say that I misspell desktop as deskto run this
misspell desktop as deskto run this again well we get that exception that
again well we get that exception that file not found exception could not
file not found exception could not locate
locate file let's make sure the file path is
file let's make sure the file path is correct now here's how to actually read
correct now here's how to actually read the file within our Tri block let's
the file within our Tri block let's create a local variable of line we'll be
create a local variable of line we'll be reading our file line by
line since we're reading the file line by line we'll be using a while
by line we'll be using a while loop during each cycle of the while loop
loop during each cycle of the while loop we're going to write the following
we're going to write the following within a set of parentheses we're going
within a set of parentheses we're going to set our string of line equal to use
to set our string of line equal to use our buffered reader object call the read
our buffered reader object call the read line method we're taking our reader
line method we're taking our reader reading the current line this will
reading the current line this will return a string which we're assigning to
return a string which we're assigning to the string variable of line after
the string variable of line after reading one line our reader is going to
reading one line our reader is going to point to the next line however if we run
point to the next line however if we run out of lines the readline method is
out of lines the readline method is going to return null so we're going to
going to return null so we're going to continue reading lines while line does
continue reading lines while line does not equal a value of null use the reader
not equal a value of null use the reader read each line assign it to this
read each line assign it to this variable of line if we run out of lines
variable of line if we run out of lines if this is null we'll escape the while
if this is null we'll escape the while loop during each cycle of the while loop
loop during each cycle of the while loop we'll output each line it's going to be
we'll output each line it's going to be a string and now this should work let's
a string and now this should work let's test it
and here's our poem roses are red violets are blue booty booty booty
violets are blue booty booty booty rocking everywhere so that's one way in
rocking everywhere so that's one way in which you can read a file using Java you
which you can read a file using Java you can combine a buffered reader and a file
can combine a buffered reader and a file reader it's best for reading text files
reader it's best for reading text files line by line but there's other methods
line by line but there's other methods you should be aware of too such as file
you should be aware of too such as file input stream and random access file I'm
input stream and random access file I'm not sure if I'll make videos on these
not sure if I'll make videos on these yet and well everybody that's how to
yet and well everybody that's how to read a file using Java hey everybody in
read a file using Java hey everybody in this video we're going to create an
this video we're going to create an audio player using
audio player using [Music]
[Music] Java let's get started all right let's
Java let's get started all right let's get started everybody now in this
get started everybody now in this following project what I'm about to show
following project what I'm about to show you isn't compatible with MP3 files but
you isn't compatible with MP3 files but you could easily convert an MP3 file to
you could easily convert an MP3 file to a wave file you can do that online
a wave file you can do that online otherwise to play an MP3 file you'll
otherwise to play an MP3 file you'll need an external library or framework
need an external library or framework such as Java FX and I do have another
such as Java FX and I do have another video on that if you need some sample of
video on that if you need some sample of music you can always use YouTube's audio
music you can always use YouTube's audio library these songs are free to use as
library these songs are free to use as long as they're within the context of
long as they're within the context of YouTube you could search for songs find
YouTube you could search for songs find one that you like and download
one that you like and download it this is the song I picked it's
it this is the song I picked it's currently an MP3 file I'll need to
currently an MP3 file I'll need to convert it to a wave file you can easily
convert it to a wave file you can easily look up an mp3 to wave
look up an mp3 to wave converter select a
file convert to wave convert
download for convenience I'm going to put this on my
put this on my desktop I'll delete the MP3
desktop I'll delete the MP3 file and we now have a wave file to make
file and we now have a wave file to make this even more convenient I'll place
this even more convenient I'll place this wave file within my source
folder so that I don't need to use an absolute file path so we're ready to
absolute file path so we're ready to begin once we have a wave file we're
begin once we have a wave file we're going to create a string for our file
going to create a string for our file path
path you can use an absolute file path or
you can use an absolute file path or relative file path since this wave file
relative file path since this wave file is right next to my main Java file I can
is right next to my main Java file I can use a relative file path easily we're
use a relative file path easily we're going to copy the name of this file
going to copy the name of this file we're going to copy path file name and
we're going to copy path file name and then paste it within the string the song
then paste it within the string the song that I picked is a caring friend and
that I picked is a caring friend and this is a wave file be sure to include
this is a wave file be sure to include the extension too once we have our file
the extension too once we have our file path we'll create a file object but we
path we'll create a file object but we have to pass in our file file path as an
have to pass in our file file path as an argument to create a file object file
argument to create a file object file file equals new
file equals new file then within the Constructor we will
file then within the Constructor we will pass in our file path to the file
pass in our file path to the file Constructor then be sure to import this
Constructor then be sure to import this class for
class for file when handling files it's considered
file when handling files it's considered dangerous code because accessing files
dangerous code because accessing files can be unpredictable we'll use a try and
can be unpredictable we'll use a try and catch
catch block try this dangerous code catch any
block try this dangerous code catch any exceptions one exception that we may run
exceptions one exception that we may run into
into is an IO exception we'll give it a
is an IO exception we'll give it a nickname of e then be sure to import
nickname of e then be sure to import this
this class this catch statement will act as a
class this catch statement will act as a safety net to catch any unexpected IO
safety net to catch any unexpected IO exceptions here we'll output something
exceptions here we'll output something went wrong it is better to handle
went wrong it is better to handle specific kinds of exceptions first we
specific kinds of exceptions first we will do that momentarily within the tri
will do that momentarily within the tri block we will create an audio input
block we will create an audio input stream object that's the first step to
stream object that's the first step to playing audio the type of object is
playing audio the type of object is audio input
audio input stream let's name this object just audio
stream let's name this object just audio stream
stream equals we will access the audio system
equals we will access the audio system class we're accessing it statically so
class we're accessing it statically so we type the name of the class call the
we type the name of the class call the get audio let me zoom out a little get
get audio let me zoom out a little get audio input stream
audio input stream method and then we will we'll pass in
method and then we will we'll pass in our file
our file object be sure to import this class too
object be sure to import this class too we'll be doing a lot of importing so get
we'll be doing a lot of importing so get used to it now with the get audio input
used to it now with the get audio input stream method we have to add a catch
stream method we have to add a catch clause for any unsupported audio file
clause for any unsupported audio file exceptions well we can write a catch
exceptions well we can write a catch block for
block for that catch the following exception type
that catch the following exception type where the type is unsupported audio file
where the type is unsupported audio file exception this is if somebody tries to
exception this is if somebody tries to use an audio file that's not imported
use an audio file that's not imported not one of the following we will give
not one of the following we will give this a nickname of e import this class
this a nickname of e import this class then we'll output the
then we'll output the following audio file is not
supported be sure to import the audio input stream class
too now when you open this audio stream you do want to close it so in modern
you do want to close it so in modern Java you can use try with resources add
Java you can use try with resources add a of parentheses after try we will cut
a of parentheses after try we will cut the snippet of
the snippet of code and paste it within the set of
code and paste it within the set of parentheses delete the
parentheses delete the semicolon if you use triy with resources
semicolon if you use triy with resources you'll automatically close this object
you'll automatically close this object when you're done with it you don't need
when you're done with it you don't need that finally Clause so now we're going
that finally Clause so now we're going to create a clip
to create a clip object clip clip equals access the audio
object clip clip equals access the audio system class we're doing it
system class we're doing it statically call the get clip method
statically call the get clip method import this class for clip in simple
import this class for clip in simple terms a clip is like a music or Sound
terms a clip is like a music or Sound Player it allows you to load an audio
Player it allows you to load an audio file and then play pause stop or reset
file and then play pause stop or reset the audio so it gives you some
the audio so it gives you some controls and we do need a catch clause
controls and we do need a catch clause for this too for any line unavailable
for this too for any line unavailable exceptions so let's add that catch
exceptions so let's add that catch clause in case we encounter a line
clause in case we encounter a line unavailable exception
unavailable exception which we will nickname e you might
which we will nickname e you might encounter this exception if another
encounter this exception if another resource is trying to access that audio
resource is trying to access that audio file or if it's unplayable for some
file or if it's unplayable for some reason it's
reason it's unavailable we could output something
unavailable we could output something such
such as unable to access audio
as unable to access audio resource then import this class as well
resource then import this class as well there we
there we go once we have our clip it gives us
go once we have our clip it gives us some controls but we do have to use it
some controls but we do have to use it to open the audio stream
to open the audio stream object we will take our clip object call
object we will take our clip object call the open method and then pass in our
the open method and then pass in our audio stream
audio stream object the clip object which is our
object the clip object which is our player is going to open our audio
player is going to open our audio stream now we're not going to play it
stream now we're not going to play it quite yet before we actually do play it
quite yet before we actually do play it I'm going to add another catch
I'm going to add another catch Clause we're going to catch any file not
Clause we're going to catch any file not found exceptions if we can't locate our
found exceptions if we can't locate our audio file file not
audio file file not found exception of
found exception of e will
e will output could not
output could not locate file import this class
locate file import this class two so we have four catch blocks the
two so we have four catch blocks the last one acts as a safety net now let's
last one acts as a safety net now let's be sure that we can locate this file
be sure that we can locate this file first so
first so temporarily let's output no problems
temporarily let's output no problems detected I'm going to run this
detected I'm going to run this program could not locate
program could not locate file if that's the case with our
file if that's the case with our relative file path we're going to access
relative file path we're going to access the source folder then access that audio
the source folder then access that audio file there it is no problems
file there it is no problems detected if this file is unsupported
detected if this file is unsupported let's say it's MP3 I'll bring back my
let's say it's MP3 I'll bring back my MP3 file move it to my source folder
then I'll switch this to MP3 then we should get an unsupported
MP3 then we should get an unsupported audio file exception if that's the
audio file exception if that's the case yes audio file is not supported
case yes audio file is not supported because we're trying to use an MP3 file
because we're trying to use an MP3 file so let's switch that back to wave or
so let's switch that back to wave or whatever yours was
whatever yours was originally and delete our MP3 file we
originally and delete our MP3 file we were just testing it all right now we're
were just testing it all right now we're actually going to play the clip
actually going to play the clip now one last thing that I'm going to add
now one last thing that I'm going to add it's optional I'm going to add a finally
it's optional I'm going to add a finally block once we're done with this program
block once we're done with this program we can output the following let's just
we can output the following let's just say
say by this will make sense in just a moment
by this will make sense in just a moment why I'm doing this there's one problem
why I'm doing this there's one problem we're going to encounter when we play
we're going to encounter when we play our audio now to actually play the audio
our audio now to actually play the audio we're going to take our clip
we're going to take our clip object call the start method to start
object call the start method to start the
the audio here's what happens when I run
audio here's what happens when I run this currently
the music may play for just a brief second we print by then exit the program
second we print by then exit the program right away the issue that we're running
right away the issue that we're running into is that our program doesn't wait
into is that our program doesn't wait for the audio to finish once we start
for the audio to finish once we start the clip we immediately end the
the clip we immediately end the program so we need some way to keep the
program so we need some way to keep the clip open and there's a bunch of
clip open and there's a bunch of different options you could use
different options you could use threading within a while loop to check
threading within a while loop to check to see if the clip is still running but
to see if the clip is still running but I haven't taught that yet so here's
I haven't taught that yet so here's another option we create a prompt for
another option we create a prompt for the user to play stop reset or quit the
the user to play stop reset or quit the audio program the audio will continue
audio program the audio will continue playing unless the user decides to stop
playing unless the user decides to stop or quit the program so we'll need a
or quit the program so we'll need a scanner to work with to accept user
scanner to work with to accept user input scanner scanner equals new scanner
input scanner scanner equals new scanner pass in
system.in import this class now if you open a scanner you do
class now if you open a scanner you do want to close it when you're done with
want to close it when you're done with it you can do that within the final
it you can do that within the final finally block like this scanner.
finally block like this scanner. close with modern Java you can use try
close with modern Java you can use try with resources which will automatically
with resources which will automatically close any resources and we can do that
close any resources and we can do that with our scanner too let's cut our
with our scanner too let's cut our scanner paste it within the tri block
scanner paste it within the tri block now be sure to include the
now be sure to include the semicolon our scanner is going to
semicolon our scanner is going to automatically close when we're done with
automatically close when we're done with this program because we're using try
this program because we're using try with resources you can use try with
with resources you can use try with resources if an object implements the
resources if an object implements the autoc closable interface scanner and
autoc closable interface scanner and audio stream both do clip doesn't so
audio stream both do clip doesn't so we'll keep that within the tri block
we'll keep that within the tri block rather than start our clip let's create
rather than start our clip let's create a string variable of
a string variable of response we'll create a while
response we'll create a while loop while our
loop while our response
response equals let's say capital Q now we want
equals let's say capital Q now we want to say while our response doesn't equal
to say while our response doesn't equal capital Q we'll use the Notch logical
capital Q we'll use the Notch logical operator and to make our while loop
operator and to make our while loop happy we do have to initialize our
happy we do have to initialize our response we'll set that to be an empty
response we'll set that to be an empty string so a user is going to type in a
string so a user is going to type in a response as long as it's not Q meaning
response as long as it's not Q meaning quit we'll continue the
quit we'll continue the program within the while loop we'll give
program within the while loop we'll give a user a few
a user a few options let's output the
options let's output the following let's say p equals
following let's say p equals play Let's copy this print line
play Let's copy this print line statement s equals
statement s equals stop R is to
quit then we will ask a user to enter your choice I'll use print rather than
your choice I'll use print rather than print line to keep the user input on the
print line to keep the user input on the same
same line we'll take our response which is a
line we'll take our response which is a string set it equal to use our scanner
string set it equal to use our scanner get the next character by calling the
get the next character by calling the next method in case a user types in a
next method in case a user types in a lowercase character we can make it
lowercase character we can make it uppercase by Method chaining the two
uppercase by Method chaining the two uppercase
uppercase method all right we'll do a test run and
method all right we'll do a test run and let's be sure that we start the clip
let's be sure that we start the clip just temporarily clip.art method what's
just temporarily clip.art method what's likely going to happen is that we'll
likely going to happen is that we'll start the audio clip and it won't stop
start the audio clip and it won't stop until we press Q to quit
so here's the audio hopefully you can hear me once I press Q the program's
hear me once I press Q the program's going to
going to stop it's because the program closes
stop it's because the program closes down and
down and exits now we want to give the user a few
exits now we want to give the user a few options after they type in their
options after they type in their response we can use an enhanced switch
response we can use an enhanced switch for this let's also be sure that we
for this let's also be sure that we delete the start method of our
clip we don't want the audio clip to start until the user presses p to play
start until the user presses p to play we will create a
we will create a switch we will examine our
switch we will examine our response does our response match any
response does our response match any cases if our response matches a case of
cases if our response matches a case of P we'll write an arrow to do the
P we'll write an arrow to do the following take our clip then call the
following take our clip then call the start
start method if our response matches a case of
method if our response matches a case of s that means stop take our clip object
s that means stop take our clip object called the stop method
called the stop method if our response matches a case of R do
if our response matches a case of R do the following take our clip to reset
the following take our clip to reset you're going to call the set
you're going to call the set micro
micro second
second position then pass in
position then pass in zero do pay attention to the
zero do pay attention to the capitalization s is a
capitalization s is a lowercase if our response matches a case
lowercase if our response matches a case of Q take our clip call the close method
of Q take our clip call the close method to close the clip
to close the clip then if there's no matching cases let's
then if there's no matching cases let's output the
output the following system.out.print line invalid
everything enter your choice just to be sure that the default case is working
sure that the default case is working I'm going to type
I'm going to type Taco invalid Choice we'll press P to
Taco invalid Choice we'll press P to play
s to stop P to play
stop P to play again R to
again R to reset and Q to
reset and Q to [Music]
[Music] quit all right everybody that is an
quit all right everybody that is an audio player that you can write using
audio player that you can write using Java what's up everybody in this video
Java what's up everybody in this video we're going to create a working game of
we're going to create a working game of hangman using Java a user is going to
hangman using Java a user is going to guess certain characters and we'll see
guess certain characters and we'll see if there's a match within a secret word
if there's a match within a secret word near the end of this video topic will be
near the end of this video topic will be importing a file of words and one of
importing a file of words and one of those words will be secretly selected so
those words will be secretly selected so let's get started all right let's get
let's get started all right let's get started everybody near the end of this
started everybody near the end of this video we'll have our program choose a
video we'll have our program choose a random word from a list of words but to
random word from a list of words but to keep this program simple in the
keep this program simple in the beginning for a testing purposes let's
beginning for a testing purposes let's create a string variable of word here
create a string variable of word here we'll select a word that we're going to
we'll select a word that we're going to use throughout the program just for
use throughout the program just for testing pick a word for me I'll say you
testing pick a word for me I'll say you know what let's go with pizza so this
know what let's go with pizza so this will be my word so we have our word
will be my word so we have our word we'll be accepting user input so we need
we'll be accepting user input so we need a scanner scanner scanner equals new
a scanner scanner scanner equals new scanner pass in
scanner pass in system.in import the scanner class and
system.in import the scanner class and close your scanner at the end of the
close your scanner at the end of the program scanner.
program scanner. close here's where we'll be working with
close here's where we'll be working with array lists we will create an array list
array lists we will create an array list of characters to do that we type array
of characters to do that we type array list then specify the type within a set
list then specify the type within a set of angle brackets we can't use
of angle brackets we can't use Primitives such as Char we'll have to
Primitives such as Char we'll have to use the rapper class of character to
use the rapper class of character to store characters I will name this array
store characters I will name this array list word State equals a
list word State equals a new array list use the diamond operator
new array list use the diamond operator set of parenthesis semicolon we'll need
set of parenthesis semicolon we'll need to import this
class now within the diamond operator you don't need to list character again
you don't need to list character again even though that does work Java can
even though that does work Java can infer what the type is in the beginning
infer what the type is in the beginning our word state is going to contain a
our word state is going to contain a bunch of underscores and we're going to
bunch of underscores and we're going to fill them in one letter at a time by
fill them in one letter at a time by guessing we'll also need a variable to
guessing we'll also need a variable to keep track of our wrong guesses int
keep track of our wrong guesses int wrong
wrong guesses this will initially be zero
guesses this will initially be zero we'll set that equal to be
we'll set that equal to be zero within our array of word State
zero within our array of word State we're going to add an underscore for
we're going to add an underscore for every letter within our word we'll
every letter within our word we'll create a for Loop that will cycle once
create a for Loop that will cycle once for every letter in our word here's how
for every letter in our word here's how we can do that
we can do that so we'll start with a basic for Loop
so we'll start with a basic for Loop create an INT of I for index equals 0
create an INT of I for index equals 0 we'll continue as long as I is less than
we'll continue as long as I is less than take our word and strings have a
take our word and strings have a built-in length method return the length
built-in length method return the length of this word so in this case it's going
of this word so in this case it's going to be five because there's five letters
to be five because there's five letters in this word then increment I by One
in this word then increment I by One during each cycle of this for loop we're
during each cycle of this for loop we're going to take our array of word State
going to take our array of word State and and add a character by using the add
and and add a character by using the add method we will pass in an underscore an
method we will pass in an underscore an underscore character be sure you're
underscore character be sure you're using single quotes not double quotes
using single quotes not double quotes because these are chars technically not
because these are chars technically not strings all right let's do a test run
strings all right let's do a test run I'm going to Output our word state to
I'm going to Output our word state to see what we have so we should get 5core
see what we have so we should get 5core characters and we do one 2 3 four five p
characters and we do one 2 3 four five p i z z a throughout this game by guessing
i z z a throughout this game by guessing letters we'll be filling in this word
letters we'll be filling in this word state by replacing the underscores if
state by replacing the underscores if there's a
there's a match let's change this word just so we
match let's change this word just so we know that everything's working I will
know that everything's working I will pick watermelon because that's the first
pick watermelon because that's the first thing that came to mind so watermelon
thing that came to mind so watermelon has 10
has 10 characters 1 2 3 4 5 6 7 8 9 10 all
characters 1 2 3 4 5 6 7 8 9 10 all right we know that that works I will
right we know that that works I will switch it back to Pizza delete this
switch it back to Pizza delete this print statement and we can move
print statement and we can move on word state is an array list made up
on word state is an array list made up of characters currently they're all
of characters currently they're all underscores but we'll be replacing each
underscores but we'll be replacing each with the character if we get the correct
with the character if we get the correct guess after the for Loop why don't we
guess after the for Loop why don't we create a welcome
create a welcome message let's say welcome to Java
message let's say welcome to Java hangman now you don't need to do this
hangman now you don't need to do this but I'm going to add some decorators
but I'm going to add some decorators just a bunch of asterisks before and
just a bunch of asterisks before and after again you don't need to but I
after again you don't need to but I think it looks
cool let's make sure everything looks okay welcome to Java
hangman for our hangman we're going to display some asky art outside of our
display some asky art outside of our main method we're going to declare
main method we're going to declare another method that's in charge of
another method that's in charge of returning asky art based on the number
returning asky art based on the number of wrong guesses that we have this will
of wrong guesses that we have this will be a static method it's going to return
be a static method it's going to return a string we'll name this method get
a string we'll name this method get hangman
hangman art we will have one parameter we have
art we will have one parameter we have to pass in how many wrong guesses we
to pass in how many wrong guesses we have then depending on the number of
have then depending on the number of wrong guesses we'll return a certain
wrong guesses we'll return a certain image represented as a
image represented as a string within our get hangman art method
string within our get hangman art method we'll be returning a string a string
we'll be returning a string a string representation of our asky art we can
representation of our asky art we can best do this with the switch now a
best do this with the switch now a switch can return something we'll use
switch can return something we'll use the return keyword create a
the return keyword create a switch end it with a semicolon within
switch end it with a semicolon within our switch what are we examining we're
our switch what are we examining we're examining the number of wrong guesses
examining the number of wrong guesses this will be a number 0 through 6 we'll
this will be a number 0 through 6 we'll need a case for each of those numbers
need a case for each of those numbers for each of those guesses depending on
for each of those guesses depending on how many wrong guesses the user has
how many wrong guesses the user has we'll display one of a few images so
we'll display one of a few images so here we'll be working on our art skills
here we'll be working on our art skills today too if we have a matching case
today too if we have a matching case where wrong guesses matches a case of
where wrong guesses matches a case of zero that means they have no wrong
zero that means they have no wrong guesses
guesses case0 Arrow meaning do this will return
case0 Arrow meaning do this will return the following in Java you can write a
the following in Java you can write a multi-line string but you have to use a
multi-line string but you have to use a triple set of double quotes and I'm just
triple set of double quotes and I'm just going to line these
going to line these up within this triple set of double
up within this triple set of double quotes I'll have three empty lines
quotes I'll have three empty lines between
between them we won't display anything if the
them we won't display anything if the number of wrong guesses is
number of wrong guesses is zero then for case one if a user has one
zero then for case one if a user has one wrong
wrong guess we'll display our man's
guess we'll display our man's head represented by an
head represented by an O if wrong guesses is two we can
O if wrong guesses is two we can represent that with case two we will
represent that with case two we will draw the man's
draw the man's body represented by a vertical
body represented by a vertical bar case three will be the left
arm for the left arm we'll use a forward slash for case four
that will be for the right arm we'll use a backslash in Java a backslash is
a backslash in Java a backslash is actually an escape sequence to display a
actually an escape sequence to display a backslash we have to use double back
backslash we have to use double back slashes case five will be for the left
leg it's kind of like we're assembling Exodia if you know the
Exodia if you know the reference and then k6 is for the right
reference and then k6 is for the right leg we'll need two backs
leg we'll need two backs slashes we'll want to a default case if
slashes we'll want to a default case if there's no matching
there's no matching cases we'll just return an empty string
cases we'll just return an empty string just to make Java happy all right and
just to make Java happy all right and this method is done based on the number
this method is done based on the number of wrong guesses we'll return one of a
of wrong guesses we'll return one of a few
strings Let's test it I'm going to use a print line
print line statement call our get hangman art
statement call our get hangman art method we'll start with zero zero wrong
method we'll start with zero zero wrong guesses we should end up displaying
guesses we should end up displaying three empty lines
if wrong guesses is one we should display The Hangman's
display The Hangman's head
head two two is for the
two two is for the body three is for the left
arm four is for the right
four is for the right arm five is for the left leg
body that's when we lose when wrong guesses is six all right we know that
guesses is six all right we know that the get hangman art method works I will
the get hangman art method works I will collapse it because we're done with it
collapse it because we're done with it to get the art for our hangman we just
to get the art for our hangman we just have to call this method then pass in
have to call this method then pass in the current number of wrong guesses
the current number of wrong guesses let's delete this print line statement
let's delete this print line statement we no longer need
we no longer need it now when we print our word
it now when we print our word State let me show you
State let me show you we get this ugly formatting where we
we get this ugly formatting where we have a set of straight brackets then all
have a set of straight brackets then all the underscores are comma separated we
the underscores are comma separated we can customize that so here's what we'll
can customize that so here's what we'll do after our welcome message we'll
do after our welcome message we'll output the
following we'll output the word word colon space I'll use print I want to
colon space I'll use print I want to stay on the same line we'll create a for
stay on the same line we'll create a for Loop an enhanced for Loop
Loop an enhanced for Loop for every character in our array list of
for every character in our array list of word State we're going to display an
word State we're going to display an underscore with no
underscore with no formatting using an enhanced for Loop we
formatting using an enhanced for Loop we have to list the data type of what we're
have to list the data type of what we're cycling through we're cycling through an
cycling through we're cycling through an array of characters Char a common
array of characters Char a common convention with enhanced for Loops is to
convention with enhanced for Loops is to name each letter C because we can't use
name each letter C because we can't use Char because that's a data
Char because that's a data type and character is kind of long so C
type and character is kind of long so C is short for character for every
is short for character for every character of C
character of C in our array list our array list is
in our array list our array list is named word
named word State we'll do the
State we'll do the following we will output our character
following we will output our character of C plus a
of C plus a space so then when we output
space so then when we output this oh let's use print rather than
this oh let's use print rather than print line because we want them all in
print line because we want them all in the same
line that's much better that output looks a lot nicer each letter letter is
looks a lot nicer each letter letter is an underscore they're all separated with
an underscore they're all separated with a space when we guess each letter we'll
a space when we guess each letter we'll be flipping these underscores to its
be flipping these underscores to its matching character if they do
matching character if they do match I'll add an empty print line just
match I'll add an empty print line just so we go down to the next
so we go down to the next line okay for the next part we'll have a
line okay for the next part we'll have a user guess a letter we'll need some user
user guess a letter we'll need some user input we'll need a
input we'll need a prompt guess a letter colon space I'll
prompt guess a letter colon space I'll use print not print line
use print not print line we'll create a variable of guess guess
we'll create a variable of guess guess will be a
will be a letter we'll need to accept user input
letter we'll need to accept user input we'll need to accept user input using
we'll need to accept user input using our scanner scanner. next next will get
our scanner scanner. next next will get the next
the next character now since we're working with
character now since we're working with lowercase characters we can method chain
lowercase characters we can method chain the two lowercase method just to make it
the two lowercase method just to make it lowercase if somebody types in an
lowercase if somebody types in an uppercase character to lower case
okay to lowercase method using next the user input is going to be a string not a
user input is going to be a string not a character we can easily convert that to
character we can easily convert that to a character by using the Char at
a character by using the Char at method but we have to pass it an index
method but we have to pass it an index we're only accepting a single character
we're only accepting a single character so we'll use Char at zero we're telling
so we'll use Char at zero we're telling Java with the string that the user types
Java with the string that the user types in give me just the first character and
in give me just the first character and convert it to be a Char so guess is
convert it to be a Char so guess is going to be a single letter it'll be of
going to be a single letter it'll be of the Char data type
the Char data type all right then let's test it I will
all right then let's test it I will output our
guess I will guess an uppercase P we'll end up outputting a lowercase p
P we'll end up outputting a lowercase p which is
which is good how about a z yep our guess is z if
good how about a z yep our guess is z if I were to type in a full word like
I were to type in a full word like pineapple we still end up with just the
pineapple we still end up with just the first character the first character in
first character the first character in our
our string which is good though let's delete
string which is good though let's delete this print line statement we no longer
this print line statement we no longer need it for this next part we're going
need it for this next part we're going to check to see if our guess matches any
to check to see if our guess matches any letters within our
letters within our word we'll use an if statement for
word we'll use an if statement for that if take our word it's a string in
that if take our word it's a string in this case Pizza we'll use the built-in
this case Pizza we'll use the built-in index of
index of method and then pass in our
method and then pass in our guess so basically with the index of
guess so basically with the index of method it's going to return the index
method it's going to return the index within the string of the first
within the string of the first occurrence of the specified
occurrence of the specified character for example let's say I guess
character for example let's say I guess the letter Z well Z is in the word Pizza
the letter Z well Z is in the word Pizza it's at index 2 that's the first
it's at index 2 that's the first occurrence if my guess was Z index of is
occurrence if my guess was Z index of is going to return the number two because
going to return the number two because that's the first occurrence of Z we will
that's the first occurrence of Z we will check if the first occurrence is greater
check if the first occurrence is greater than or equal to zero that means there's
than or equal to zero that means there's a matching letter if that's the
a matching letter if that's the case if there's a matching letter well
case if there's a matching letter well will
will output
output correct guess and then I'm just going to
correct guess and then I'm just going to add a new line character to the
add a new line character to the end all right let's do a test
end all right let's do a test run I will guess the letter Z that's a
run I will guess the letter Z that's a correct
correct guess but are there any
guess but are there any X's there is not so we don't output
X's there is not so we don't output correct
correct guess if it's the wrong guess we can
guess if it's the wrong guess we can output using an lse statement
output using an lse statement wrong guess then I'll add a new line
wrong guess then I'll add a new line character to the end let's try that
character to the end let's try that again I will guess an X wrong
again I will guess an X wrong guess there are no x's in the word
guess there are no x's in the word Pizza okay so within our if statement if
Pizza okay so within our if statement if we get the correct guess we're going to
we get the correct guess we're going to change our word state to reflect
change our word state to reflect it that's one less letter that the user
it that's one less letter that the user has to
has to guess we're going to cycle through the
guess we're going to cycle through the length of our word using a for Loop for
length of our word using a for Loop for in I equals 0 we'll continue as long as
in I equals 0 we'll continue as long as I is less than our words length by
I is less than our words length by calling the length method then increment
calling the length method then increment I by
I by one we have to see where there's a match
one we have to see where there's a match exactly which index within our word
exactly which index within our word we'll use an if
we'll use an if statement we will take our word in this
statement we will take our word in this case Pizza called the Char at method
case Pizza called the Char at method then pass in our index of I during each
then pass in our index of I during each cycle I is going to increment but during
cycle I is going to increment but during the first cycle it's going to be zero so
the first cycle it's going to be zero so we're saying take our word in this
we're saying take our word in this example Pizza give me the first
example Pizza give me the first character so for pizza that would be the
character so for pizza that would be the letter
letter P is that equal to using the comparison
P is that equal to using the comparison operator are
operator are guess so let's say I do guess P the
guess so let's say I do guess P the first character of my word is P that
first character of my word is P that means that they match we're going to
means that they match we're going to take our array list of word State and
take our array list of word State and we're going to update it by using the
we're going to update it by using the set
set method we have to pass in an index and a
method we have to pass in an index and a new value our
new value our guess let's test
guess let's test it so with the word Pizza are there any
it so with the word Pizza are there any z's correct guess oh then we have to
z's correct guess oh then we have to Output it
Output it too we're going to continue playing as
too we're going to continue playing as long as wrong guesses is less than six
long as wrong guesses is less than six once wrong guesses is six or greater
once wrong guesses is six or greater then the game
then the game ends so so let's cut this portion of
ends so so let's cut this portion of code cut it don't delete it we'll write
code cut it don't delete it we'll write a while
a while loop
loop while our wrong guesses variable wrong
while our wrong guesses variable wrong guesses is less than six we'll continue
guesses is less than six we'll continue playing this game within the while loop
playing this game within the while loop we'll paste all that code again let's do
we'll paste all that code again let's do a test
run guess a letter I'm going to guess Z so that should update our word to
so that should update our word to reflect two Z's because my word is pizza
reflect two Z's because my word is pizza but if there's no matching
but if there's no matching letters it doesn't get updated because
letters it doesn't get updated because there's no matches let me fill this in p
there's no matches let me fill this in p i ZZ a and we get the full word all
i ZZ a and we get the full word all right that's good so far so
right that's good so far so good so we'll need to keep track of
good so we'll need to keep track of wrong guesses within our else statement
wrong guesses within our else statement we're going to take our variable of
we're going to take our variable of wrong guesses incremented by one using
wrong guesses incremented by one using the increment operator
the increment operator then back to the beginning of the loop
then back to the beginning of the loop we're going to display our hangman art
we're going to display our hangman art by calling the get hangman art
by calling the get hangman art method this method will return a string
method this method will return a string so we can put that within a print
so we can put that within a print statement let's use print call the get
statement let's use print call the get hangman art method then pass in the
hangman art method then pass in the number of wrong
number of wrong guesses let's do another test
guesses let's do another test run we have three empty spaces because
run we have three empty spaces because we haven't displayed any parts of the
we haven't displayed any parts of the hangman yet I will guess the wrong
hangman yet I will guess the wrong letter X we get the head of the hangman
letter X we get the head of the hangman I'll guess some more wrong
I'll guess some more wrong letters
letters CV b n
m at the end we'll have to display the full hangman when we
full hangman when we lose let's display the right
lose let's display the right letters p i z
letters p i z a okay good what happens when we lose if
a okay good what happens when we lose if wrong guesses is six or
wrong guesses is six or greater so outside of the while loop our
greater so outside of the while loop our while loop ends right
while loop ends right here we'll write an if
here we'll write an if statement if our variable of wrong
statement if our variable of wrong guesses is greater than or equal to
guesses is greater than or equal to six okay we will again use a print
six okay we will again use a print statement called the get hangman art
statement called the get hangman art method and then pass in the number of
method and then pass in the number of wrong
wrong guesses we'll also display a game over
guesses we'll also display a game over message game
message game over then display the
over then display the word the word
word the word was colon space plus our original word
was colon space plus our original word of
of pizza let's do a test run
pizza let's do a test run again I'm going to guess the wrong
characters all right game over we display the the full hangman the word
display the the full hangman the word was
was pizza I think I'm going to make a few
pizza I think I'm going to make a few changes I'm going to remove these new
changes I'm going to remove these new line
line characters it's a little too much space
characters it's a little too much space I
I think all right we're
think all right we're good so how do we win let's add that
good so how do we win let's add that after the for
after the for Loop if we get a correct guess we'll
Loop if we get a correct guess we'll check to see if our word State doesn't
check to see if our word State doesn't contain any lowercase
contain any lowercase characters so take our array list of
characters so take our array list of word
word State call the contains
State call the contains method and then pass in an underscore
method and then pass in an underscore character but we want to check to see if
character but we want to check to see if our word State doesn't contain any
our word State doesn't contain any lowercase characters we can prefix this
lowercase characters we can prefix this with the not logical operator an
with the not logical operator an exclamation point if our word our word
exclamation point if our word our word State doesn't contain any lowercase
State doesn't contain any lowercase characters that means that we guessed
characters that means that we guessed all the letters and we
all the letters and we win if that's true let's display our
win if that's true let's display our hangman One Last Time
hangman One Last Time system.out.print get hangman art pass in
system.out.print get hangman art pass in the number of wrong guesses and we'll
the number of wrong guesses and we'll display you
again the word was colon space plus our word then we'll want to break out of
word then we'll want to break out of this Loop cuz we're stuck in a while
this Loop cuz we're stuck in a while loop we can use a break statement after
loop we can use a break statement after we win to break out of the
loop all right let's see what we're working
with I'll guess a few wrong letters x c v b n all right one more wrong guess and
v b n all right one more wrong guess and I lose game over the word was
I lose game over the word was pizza all right I'll actually win this
pizza all right I'll actually win this time but I'll guess a few wrong
time but I'll guess a few wrong characters q
characters q w t
w t I'll guess some correct characters a z i
I'll guess some correct characters a z i p you win and we display our current
p you win and we display our current score the current state of our hangman
score the current state of our hangman we display you win the word was
we display you win the word was pizza in this next part of this video
pizza in this next part of this video we're going to create a more advanced
we're going to create a more advanced version of this program by importing a
version of this program by importing a file of words a word is going to be
file of words a word is going to be randomly chosen from a file instead of
randomly chosen from a file instead of just setting one in the beginning okay
just setting one in the beginning okay everybody in this next section we're
everybody in this next section we're going to create a file that contains all
going to create a file that contains all the words that we can possibly use for
the words that we can possibly use for this Hangman game within our project
this Hangman game within our project folder why don't we create a new file
folder why don't we create a new file file new file I'm going to name this
file new file I'm going to name this file words and this will be a txt
file words and this will be a txt file for all the different possible
file for all the different possible words in this game place within this
words in this game place within this file you can copy and paste them from
file you can copy and paste them from somewhere online if you would like just
somewhere online if you would like just to make reading this file a simple as
to make reading this file a simple as possible I'm going to list all the words
possible I'm going to list all the words on a separate line so think of some
on a separate line so think of some words or like I said copying paste them
words or like I said copying paste them from somewhere I'll just add several
from somewhere I'll just add several Apple orange banana
Apple orange banana coconut
coconut pineapple grape lime lemon that's good
pineapple grape lime lemon that's good enough in my project folder I have this
enough in my project folder I have this file words.txt
file words.txt temporarily with my game I'm going to
temporarily with my game I'm going to write a multiline comment and just
write a multiline comment and just comment all of this out until we're
comment all of this out until we're ready to bring it back in
at the top of my Hangman game I will create a string named file
create a string named file path this will contain either a relative
path this will contain either a relative file path or an absolute file path since
file path or an absolute file path since this file is in my project folder I just
this file is in my project folder I just have to list the file name words.txt
we're going to read this file line by line we'll store each word in an array
line we'll store each word in an array list we'll create a new array list AR
list we'll create a new array list AR array list the data type is Going to Be
array list the data type is Going to Be Strings so string I will name this array
Strings so string I will name this array list words equals new array list Diamond
list words equals new array list Diamond operator parenthesis
operator parenthesis semicolon now we'll actually need to
semicolon now we'll actually need to read this file reading files is
read this file reading files is considered dangerous code because it's
considered dangerous code because it's highly likely that something can go
highly likely that something can go wrong we will write a try with resources
wrong we will write a try with resources block we need that set of parentheses
block we need that set of parentheses after try we will catch any except
after try we will catch any except options when you try with resources
options when you try with resources you'll automatically close any resources
you'll automatically close any resources listed within the set of parentheses
listed within the set of parentheses within the set of parentheses we will
within the set of parentheses we will create a buffered reader
create a buffered reader object buffered reader which we will
object buffered reader which we will name reader for short equals new
name reader for short equals new buffered
reader now a buffered reader by itself can't read files we do have to pass in a
can't read files we do have to pass in a file reader to the Constructor
file reader to the Constructor new file reader then within our file
new file reader then within our file reader Constructor we will pass in our
reader Constructor we will pass in our file path the location to that
file path the location to that file now our file reader object wants us
file now our file reader object wants us to catch any file not found
to catch any file not found exceptions we'll place that within our
exceptions we'll place that within our catch block file not found exception of
catch block file not found exception of e then we'll output if we can't find
e then we'll output if we can't find this
this file could not find
file could not find file We'll add another catch block just
file We'll add another catch block just as a safety net we'll catch any
as a safety net we'll catch any IO
IO exception e
exception e exceptions this is where we'll say
exceptions this is where we'll say something went wrong this just acts as a
something went wrong this just acts as a safety net if there's something we don't
safety net if there's something we don't anticipate so we have our reader object
anticipate so we have our reader object within the tri block we will create a
within the tri block we will create a local variable it's a string of
local variable it's a string of line we will read this file line by line
line we will read this file line by line using a while
using a while loop while within a set of parentheses
loop while within a set of parentheses assign our line equal to use our reader
assign our line equal to use our reader called the read line
called the read line method if we run out of lines this is
method if we run out of lines this is going to return null while the value
going to return null while the value that's returned does not equal null
that's returned does not equal null we'll continue reading this file reader
we'll continue reading this file reader is going to give us each of these words
is going to give us each of these words line by line we're going to assign them
line by line we're going to assign them to our array list of words take our
to our array list of words take our array list of words call the add method
array list of words call the add method we will add the current
we will add the current line if there's any white space after
line if there's any white space after these words this will pick that up and
these words this will pick that up and our program will consider them to be
our program will consider them to be characters we will use the trim method
characters we will use the trim method after line to trim that white
space let's perform a test run I'm going to Output our array list of words
to Output our array list of words yep and here's our words all within an
yep and here's our words all within an array
array list let's delete that line we're going
list let's delete that line we're going to choose one of these words at random
to choose one of these words at random we'll need a random object random random
we'll need a random object random random equals new
equals new random import the
random import the class here's where we're going to choose
class here's where we're going to choose our word I'm going to copy this from the
our word I'm going to copy this from the previous
previous code and paste
code and paste it rather than setting our word to be
it rather than setting our word to be hard-coded string we're going to take
hard-coded string we're going to take our array list of
words call the get method but we have to specify an
method but we have to specify an index with our array list return a
index with our array list return a string at a given index that index is
string at a given index that index is going to be randomly generated by using
going to be randomly generated by using this random object we will pass in a
this random object we will pass in a random object call the next int method
random object call the next int method to generate a random integer the range
to generate a random integer the range of random numbers is going to be
of random numbers is going to be dependent on the size of our array list
dependent on the size of our array list of
of words take our words call the size
words take our words call the size method so with our file I have let's see
method so with our file I have let's see how many words how many strings 1 2 3 4
how many words how many strings 1 2 3 4 5 6 7
5 6 7 8 the size method of words is going to
8 the size method of words is going to return the number eight just imagine
return the number eight just imagine that I'm replacing this with the number
that I'm replacing this with the number eight return a random index between 0
eight return a random index between 0 and 8 that's kind of how that works and
and 8 that's kind of how that works and then let's output our word for testing
then let's output our word for testing purposes
what is my word this time my word was pineapple but
word this time my word was pineapple but it's likely going to change every time
it's likely going to change every time you run it Apple lime Apple again
you run it Apple lime Apple again pineapple
pineapple grape it really likes pineapple for some
grape it really likes pineapple for some reason let's delete this print line
reason let's delete this print line statement we'll integrate our code back
statement we'll integrate our code back into the program again we can delete
into the program again we can delete that multi-line
comment and let's R this program one last time we should now have a randomly
last time we should now have a randomly chosen
chosen word I don't know what it's going to be
word I don't know what it's going to be for me it's six letters I'll guess some
for me it's six letters I'll guess some of the vowels a there's one a e i o
of the vowels a there's one a e i o u it's probably orange but I'm going to
u it's probably orange but I'm going to guess some more wrong letters for
guess some more wrong letters for testing
testing purposes okay game
purposes okay game over the word was Orange let's run it
over the word was Orange let's run it again
again this one is seven
this one is seven letters a e i o u it's
letters a e i o u it's coconut
coconut Co n u t you win the word was
Co n u t you win the word was coconut all right everybody that is a
coconut all right everybody that is a game of hangman that you can code using
game of hangman that you can code using Java hello there everybody in this video
Java hello there everybody in this video I'm going to show you how we can work
I'm going to show you how we can work with dates and times using Java this
with dates and times using Java this serves as more of an introduction we can
serves as more of an introduction we can work with local dates times date times
work with local dates times date times and UTC timestamps let's get the date
and UTC timestamps let's get the date right now using local date we will
right now using local date we will create an object of local date let's
create an object of local date let's name this date for short
name this date for short equals access the class of local
equals access the class of local date called the now
date called the now method if I was to Output our date
method if I was to Output our date object we'll print our date that's going
object we'll print our date that's going to give you the current date whatever it
to give you the current date whatever it is right now I'm filling this video
is right now I'm filling this video December 17th
December 17th 2024 post the date that you're watching
2024 post the date that you're watching this in the comment section down below
this in the comment section down below that is local date there's local time to
that is local date there's local time to get the time let's replace date with
get the time let's replace date with time local time.
time local time. now and rename this as time cuz that's
now and rename this as time cuz that's more
more appropriate print the time currently the
appropriate print the time currently the time for me is a little after 9:00 a.m.
time for me is a little after 9:00 a.m. 9 hours 29 minutes 52 seconds
9 hours 29 minutes 52 seconds and a bunch of
and a bunch of milliseconds to retrieve both the date
milliseconds to retrieve both the date and the time you can use date time local
and the time you can use date time local date
time local dat time.now method print the current date
current date time and currently for me it is December
time and currently for me it is December 17th 2024 at about 9:30 in the
17th 2024 at about 9:30 in the morning you can also use UTC time that's
morning you can also use UTC time that's a little different we will create a
a little different we will create a instant object instant instant equals
instant object instant instant equals access the class of instant called the
access the class of instant called the now
now method and print our instant
method and print our instant object which will give us the current
object which will give us the current date and time in
date and time in UTC December 17th 2024 in UTC time I
UTC December 17th 2024 in UTC time I think that's 300 p.m. it's in military
think that's 300 p.m. it's in military time that's how to get either the
time that's how to get either the current date time date time or UTC
current date time date time or UTC timestamp when you output the current
timestamp when you output the current date and/ or time it's kind of ugly and
date and/ or time it's kind of ugly and hard to read well we can write a custom
hard to read well we can write a custom format to display our date time here's
how here we'll create a custom format for our date time we will need the
for our date time we will need the current date
current date time local date
time local date time we will name this date time equals
time we will name this date time equals access the class of local date time
access the class of local date time called the now method
called the now method then we'll need to create a formatter
then we'll need to create a formatter object date time
object date time formatter we'll name this formatter
formatter we'll name this formatter equals date time formatter I'm just
equals date time formatter I'm just going to copy it call the of pattern
going to copy it call the of pattern method and then we're going to pass on a
method and then we're going to pass on a string let me move the cursor so you can
string let me move the cursor so you can see this within the string we will write
see this within the string we will write pattern letters what is the pattern in
pattern letters what is the pattern in which we would like to display our date
which we would like to display our date and our time if you go to the official
and our time if you go to the official Java documentation there's an extensive
Java documentation there's an extensive list here's a few beginner friendly ones
list here's a few beginner friendly ones for the day type 2DS dash for the month
for the day type 2DS dash for the month two Capital M's for the year Das y y y y
two Capital M's for the year Das y y y y four
four y's this will display the day the month
y's this will display the day the month and the year I'm an American so we
and the year I'm an American so we display the month first followed by the
display the month first followed by the day so I'm going to switch this around
day so I'm going to switch this around but you can keep it as it originally was
but you can keep it as it originally was if you prefer so that's how to display
if you prefer so that's how to display the date in that
the date in that format month day year now for the time
format month day year now for the time you can do the following for hours do
you can do the following for hours do two Capital H's colon minutes is two
two Capital H's colon minutes is two lowercase M's colon then for seconds
lowercase M's colon then for seconds it's two lowercase s's that is a good
it's two lowercase s's that is a good pattern we will create a new
pattern we will create a new string named new date
string named new date time equals take our current date time
time equals take our current date time it's an object call the format method
it's an object call the format method we are going to pass in our formatter to
we are going to pass in our formatter to format our date time to this
format our date time to this pattern once we have our new date time
pattern once we have our new date time we're going to print it let's output our
we're going to print it let's output our new date time and it should be in that
new date time and it should be in that format yeah that looks pretty good
format yeah that looks pretty good December 17th 2024 about 9:00 in the
December 17th 2024 about 9:00 in the morning 9:30 at least for me instead of
morning 9:30 at least for me instead of getting the time and date right now we
getting the time and date right now we can create a custom date time object
can create a custom date time object here's how so we'll start with a local
here's how so we'll start with a local date local date I'll name this object
date local date I'll name this object date equals local date we're accessing
date equals local date we're accessing the class statically we'll call the of
the class statically we'll call the of method depending on the date you would
method depending on the date you would like to create we'll pass them in as
like to create we'll pass them in as arguments let's say I would like to pick
arguments let's say I would like to pick Christmas of
Christmas of 2024 the first argument corresponds to
2024 the first argument corresponds to the year I will pick
the year I will pick 2024 the next is for the month 12
2024 the next is for the month 12 meaning
meaning December then the 25th 25th of December
December then the 25th 25th of December I'll type in
I'll type in 25 all right just to test it I'm going
25 all right just to test it I'm going to Output it let's print our
25th you can also use date time let's switch local date to local date
time we need a few more arguments ments so let's say noon on Christmas Day that
so let's say noon on Christmas Day that would be
would be 12 for the minutes 0o for the seconds
12 for the minutes 0o for the seconds zero then let's print this again let's
zero then let's print this again let's output our date well technically it
output our date well technically it should be date time but that still makes
should be date time but that still makes sense here's our date
sense here's our date time December 25th 2024 at noon 12:00
time December 25th 2024 at noon 12:00 p.m. you can also compare dates too
p.m. you can also compare dates too let's copy the snippet of code paste
let's copy the snippet of code paste it rename the first date as date one the
it rename the first date as date one the second date as date two for the second
second date as date two for the second date let's set that to New Year's Day
date let's set that to New Year's Day 2025 the month will be January the 1st
2025 the month will be January the 1st of
of January at midnight that would be
January at midnight that would be zero let's print date one and then date
two so we have Christmas December 25th 2024 and new
Christmas December 25th 2024 and new Year's Day January 1st
Year's Day January 1st 2025 all right now to compare dates we
2025 all right now to compare dates we can use the following we'll use an if
can use the following we'll use an if statement let's check if date
statement let's check if date one called the is before method dates
one called the is before method dates have a built-in is before method pass in
have a built-in is before method pass in date two is date one before date two and
date two is date one before date two and that is
that is true let's output date one plus a string
true let's output date one plus a string of is earlier than plus date 2 let's
of is earlier than plus date 2 let's check that our first date Christmas is
check that our first date Christmas is earlier than New Year's our second
date else if date
if date one let's just copy this date one is
one let's just copy this date one is after date two then we'll output
after date two then we'll output something
something different date one is later than date
different date one is later than date two so let's change date 1 to be January
two so let's change date 1 to be January 2nd of
2025 the second of January is later than New Year's Day our second
New Year's Day our second date you can also check if they're
date you can also check if they're equal let's add else
equal let's add else if let me scroll down date 1 is equal to
if let me scroll down date 1 is equal to date 2
date 2 and then we'll say that they're
and then we'll say that they're equal date 1 is equal
equal date 1 is equal to date
to date two let's set these to be the same New
two let's set these to be the same New Year's Day at
midnight New Year's Day at midnight is equal to New Year's Day at midnight this
equal to New Year's Day at midnight this could be good for some sort of alarm
could be good for some sort of alarm clock checking to see if two date times
clock checking to see if two date times are
are equal all right everybody so that is an
equal all right everybody so that is an introduction to working with dates and
introduction to working with dates and times using
times using Java well hello again friends today I
Java well hello again friends today I got to explain Anonymous classes in Java
got to explain Anonymous classes in Java so what is an anonymous class it's a
so what is an anonymous class it's a class that doesn't have a name meaning
class that doesn't have a name meaning it cannot be reused it's when you want
it cannot be reused it's when you want to add custom Behavior without having to
to add custom Behavior without having to create a new class because it can be
create a new class because it can be really inconvenient to create a new
really inconvenient to create a new class just for one object if that one
class just for one object if that one object is different from the rest in one
object is different from the rest in one way or another they're often used for
way or another they're often used for onetime uses when utilizing features
onetime uses when utilizing features such as timer task the runnable
such as timer task the runnable interface or callbacks these are more
interface or callbacks these are more advanced Java topics so let me
advanced Java topics so let me demonstrate why an anonymous class would
demonstrate why an anonymous class would be useful let's begin with this example
be useful let's begin with this example where we create a dog class file new
where we create a dog class file new Java class we will create a class of
Java class we will create a class of dog let's say that in this dog class
dog let's say that in this dog class there's a single method a speak
there's a single method a speak method void speak all we'll do is I'll
method void speak all we'll do is I'll put the following
put the following the dog goes woof and then let's create
the dog goes woof and then let's create a dog
a dog object dog dog equals new
object dog dog equals new dog we'll take our dog object have it
dog we'll take our dog object have it use its speak method which will
use its speak method which will output the dog goes wo so what if
output the dog goes wo so what if there's a unique kind of dog it's
there's a unique kind of dog it's different from the rest let's say it's
different from the rest let's say it's scoobydoo now
scoobydoo now Scooby-Doo he doesn't speak dog he
Scooby-Doo he doesn't speak dog he speaks English if I want Scooby be do to
speaks English if I want Scooby be do to say something else I'd have to override
say something else I'd have to override this method so one option would be to
this method so one option would be to create a new class again this is me not
create a new class again this is me not using Anonymous classes you'll see their
using Anonymous classes you'll see their usefulness in just a moment let's create
usefulness in just a moment let's create a new Java class let's create a talking
a new Java class let's create a talking dog class I know it's kind of a weird
dog class I know it's kind of a weird example so our talking dog class will
example so our talking dog class will extend the dog class and then we'll
extend the dog class and then we'll override the speak
override the speak method
method override void speak then we'll I'll put
override void speak then we'll I'll put the
the following Scooby Do says what's he
following Scooby Do says what's he usually say rut row or something rut row
usually say rut row or something rut row I think that's how you spell it but you
I think that's how you spell it but you get the idea going back to our main Java
get the idea going back to our main Java file I can create a talking dog object
file I can create a talking dog object talking dog talking dog equals new
talking dog talking dog equals new talking dog that's a lot to
talking dog that's a lot to type and then I can have my talking dog
type and then I can have my talking dog use its speak
method our dog goes woof and Scooby do our talking dog says rutro like uh- oh
our talking dog says rutro like uh- oh it is a lot of work to create a whole
it is a lot of work to create a whole new class just for one unique object our
new class just for one unique object our talking dog of Scooby-Doo is the
talking dog of Scooby-Doo is the exception so rather than creating an
exception so rather than creating an entirely new class just for this one
entirely new class just for this one object just for Scooby-Doo our talking
object just for Scooby-Doo our talking dog let's instead create an anonymous
dog let's instead create an anonymous class we'll take our our talking dog
class we'll take our our talking dog class and delete
it instead of creating a talking dog object let's create another dog object
object let's create another dog object but it's going to have some unique
but it's going to have some unique features that set it apart from other
features that set it apart from other dogs such as the ability to speak
dogs such as the ability to speak English let's rename dog is Dog one
English let's rename dog is Dog one we'll create another dog named dog 2
we'll create another dog named dog 2 equals new dog add aside a parenthesis
equals new dog add aside a parenthesis now to create an anonymous class you're
now to create an anonymous class you're going to add a set of curly
going to add a set of curly braces then make sure there's that
braces then make sure there's that semicolon at the end within the set of
semicolon at the end within the set of curly braces you can Define any unique
curly braces you can Define any unique features or override any methods dog 2
features or override any methods dog 2 is going to be different from all other
is going to be different from all other dogs with it speak method so let's
dogs with it speak method so let's override that method at override void
override that method at override void speak and then we'll
speak and then we'll say Scooby Do
say Scooby Do says rut
says rut row dog one is going to speak and dog
two the dog goes woof Scooby-Doo says rut
rut R so instead of creating an entirely new
R so instead of creating an entirely new class just for one dog Scooby-Doo we can
class just for one dog Scooby-Doo we can create a normal dog and just override
create a normal dog and just override one of the methods using an anonymous
one of the methods using an anonymous class so those are Anonymous classes
class so those are Anonymous classes it's a class that doesn't have a name
it's a class that doesn't have a name and it cannot be reused if you need to
and it cannot be reused if you need to reuse a class you're better off just
reuse a class you're better off just creating a new class it allows you to
creating a new class it allows you to add custom Behavior without having to
add custom Behavior without having to create a new class which is what we did
create a new class which is what we did with the speak method Anonymous classes
with the speak method Anonymous classes are often used with timer task which
are often used with timer task which we'll talk about in the next video the
we'll talk about in the next video the runnable interface and callbacks so it
runnable interface and callbacks so it is an important topic that you need to
is an important topic that you need to know going forward at least to create an
know going forward at least to create an anonymous class after you construct an
anonymous class after you construct an object add a set of curly braces within
object add a set of curly braces within that set of curly braces you can Define
that set of curly braces you can Define new behavior and well everybody those
new behavior and well everybody those are Anonymous classes in Java so uh yeah
are Anonymous classes in Java so uh yeah I got to talk about timers and timer
I got to talk about timers and timer tasks in Java timer is a class that
tasks in Java timer is a class that schedules tasks at specific times or
schedules tasks at specific times or periodically timer is useful for sending
periodically timer is useful for sending notifications scheduled updates or
notifications scheduled updates or repetitive actions when you need to
repetitive actions when you need to schedule a task at a specific time you
schedule a task at a specific time you can use the timer class now timer task
can use the timer class now timer task is the task that's going to execute cute
is the task that's going to execute cute when our timer says so in order to use
when our timer says so in order to use timer task you're going to extend the
timer task you're going to extend the timer task class and then Define your
timer task class and then Define your task and we're going to be doing this by
task and we're going to be doing this by using Anonymous classes which we learned
using Anonymous classes which we learned about in the last video we'll Begin by
about in the last video we'll Begin by creating a timer we need a timer to well
creating a timer we need a timer to well keep track of the time let's say timer
keep track of the time let's say timer timer equals new
timer equals new timer and then import these classes I'm
timer and then import these classes I'm pretty sure you're used to importing
pretty sure you're used to importing these by now
these by now we're going to select the timer from the
we're going to select the timer from the utility
utility package all right we have our timer then
package all right we have our timer then we need a timer task what are we going
we need a timer task what are we going to do when the timer is
up let's just say task timer task task equals new timer task import the
equals new timer task import the class all right so here's the
class all right so here's the situation with our timer class we have
situation with our timer class we have to implement the run method to override
to implement the run method to override the run method we could create a child
the run method we could create a child class from the timer task class but
class from the timer task class but here's a better option we're going to
here's a better option we're going to create an anonymous class after the set
create an anonymous class after the set of parentheses we will add a set of
of parentheses we will add a set of curly braces then add that semicolon to
curly braces then add that semicolon to the end within this Anonymous class we
the end within this Anonymous class we can update or change the behavior of our
can update or change the behavior of our timer task object what we'll do is
timer task object what we'll do is override the run
override the run method
method override to overrun this method
override to overrun this method this will be public void run it's the
this will be public void run it's the run
run method when we execute our task what
method when we execute our task what would we like to do let's output the
would we like to do let's output the following let's just say
following let's just say hello so our task is to print
hello so our task is to print hello but we have to do it when our
hello but we have to do it when our timer says so so they work
timer says so so they work together let's say I would like to say
together let's say I would like to say hello after 3 seconds to do that we're
hello after 3 seconds to do that we're going to take our timer
going to take our timer call the schedule
call the schedule method and then there's two arguments
method and then there's two arguments we're going to pass in our task what are
we're going to pass in our task what are we going to do that's the first argument
we going to do that's the first argument the next argument is the delay after how
the next argument is the delay after how many milliseconds will we execute this
many milliseconds will we execute this task I said 3 seconds let's say 3,000
task I said 3 seconds let's say 3,000 milliseconds then after a delay of 3
milliseconds then after a delay of 3 seconds 3,000 milliseconds do your task
seconds 3,000 milliseconds do your task that we're passing in so after 3 seconds
that we're passing in so after 3 seconds will
output hello or if this were 1,000 millisecs it
hello or if this were 1,000 millisecs it would only take a
would only take a second hello you can also schedule at a
second hello you can also schedule at a fixed rate our timer can do things
fixed rate our timer can do things periodically so let's repeat our task of
periodically so let's repeat our task of saying hello more than just once so we
saying hello more than just once so we have our delay you know what I'll set
have our delay you know what I'll set that to be zero the next argument is for
that to be zero the next argument is for the period what is the delay in
the period what is the delay in milliseconds between repetitions let's
milliseconds between repetitions let's say 1,000 milliseconds so 1
say 1,000 milliseconds so 1 second starting immediately 0
second starting immediately 0 milliseconds print hello every 1,000
milliseconds print hello every 1,000 milliseconds every second let's try
milliseconds every second let's try it hello hello hello hello I think you
it hello hello hello hello I think you get the idea or you could add a delay
get the idea or you could add a delay that's the second argument let's say
that's the second argument let's say after a delay delay of 3,000
after a delay delay of 3,000 milliseconds 3 seconds repeat this line
milliseconds 3 seconds repeat this line of code every 1,000 milliseconds 1
of code every 1,000 milliseconds 1 second so now there's going to be a
second so now there's going to be a delay of 3
delay of 3 seconds then we output hello every 1
seconds then we output hello every 1 second now how do you cancel this timer
second now how do you cancel this timer once it's started well you can use the
once it's started well you can use the cancel
cancel method where should we add that exactly
method where should we add that exactly well we can add that within our task
well we can add that within our task we'll need some sort of stopping
we'll need some sort of stopping condition kind of like a wild Loop so
condition kind of like a wild Loop so let's say this I would like to say hello
let's say this I would like to say hello three times I'll create a local variable
three times I'll create a local variable of count I'll set that to be
of count I'll set that to be three intellig wants me to make this
three intellig wants me to make this final you don't have to I'll keep it as
final you don't have to I'll keep it as is so again we are within our Anonymous
is so again we are within our Anonymous class we're declaring a variable to use
class we're declaring a variable to use within the context of our
within the context of our task within the run method we'll output
task within the run method we'll output hello decrement our count by one count
hello decrement our count by one count minus
minus minus then using an if statement this is
minus then using an if statement this is how we're going to escape if our count
how we're going to escape if our count is less than
is less than zero then let's
zero then let's say task
say task complete and then to cancel the timer we
complete and then to cancel the timer we will take our timer object called the
will take our timer object called the cancel
method all right let's try it I'll set the delay to be zero so it starts
the delay to be zero so it starts immediately every 1,000 milliseconds
immediately every 1,000 milliseconds print hello whoops it looks like that's
print hello whoops it looks like that's less than or equal to zero I fixed it
less than or equal to zero I fixed it all right so starting immediately the
all right so starting immediately the delay is zero every 1,000 milliseconds
delay is zero every 1,000 milliseconds print hello but only do it three times
print hello but only do it three times and then we cancel the timer to stop
and then we cancel the timer to stop because we don't want to say hello
because we don't want to say hello forever and here it
forever and here it is 1 2 3 task
is 1 2 3 task complete all right everybody so that is
complete all right everybody so that is timer and timer task timer is a class
timer and timer task timer is a class that schedules tasks at specific times
that schedules tasks at specific times or periodically it's useful for sending
or periodically it's useful for sending notifications scheduled updates or other
notifications scheduled updates or other repetitive actions timer task is the
repetitive actions timer task is the task you're going to perform when the
task you're going to perform when the timer says so in the next video we're
timer says so in the next video we're going to use timer and timer task to
going to use timer and timer task to create a countdown timer all right
create a countdown timer all right everybody so that is both timer and
everybody so that is both timer and timer task in
timer task in Java why hello there everybody in this
Java why hello there everybody in this video we're going to create a countdown
video we're going to create a countdown timer program using Java this is meant
timer program using Java this is meant to serve as more of a mini project to
to serve as more of a mini project to get us used to working with timer tasks
get us used to working with timer tasks let's begin we'll accept user input but
let's begin we'll accept user input but we're going to set that up near the end
we're going to set that up near the end it's going to be easier for us to
it's going to be easier for us to understand this program at first if we
understand this program at first if we set the countdown timer to be a raw
set the countdown timer to be a raw number like 10 to work with timer tasks
number like 10 to work with timer tasks we'll need a timer to keep track of the
we'll need a timer to keep track of the time timer timer equals new
time timer timer equals new timer we'll be importing our classes as
timer we'll be importing our classes as we go along long be sure to do that
we go along long be sure to do that import them from the Java utility
import them from the Java utility package then we'll need a timer task
package then we'll need a timer task timer task I'll name this task for short
timer task I'll name this task for short equals new timer task be sure to import
equals new timer task be sure to import this
this class now there's one issue though with
class now there's one issue though with our timer task object we have to
our timer task object we have to override the run method one option
override the run method one option although it's not the best is to create
although it's not the best is to create a new class and then inherit from the
a new class and then inherit from the timer task class so this would be the
timer task class so this would be the parent class and then we can override
parent class and then we can override the run method but since we don't plan
the run method but since we don't plan on reusing that class what we could do
on reusing that class what we could do instead is use an anonymous class after
instead is use an anonymous class after the set of parentheses add a set of
the set of parentheses add a set of curly braces then add that semicolon to
curly braces then add that semicolon to the end for a onetime use we can
the end for a onetime use we can override the run method of our timer
override the run method of our timer task object because we only plan on
task object because we only plan on using it once so we can write an
using it once so we can write an anonymous class rather than create a
anonymous class rather than create a whole new class that we're only going to
whole new class that we're only going to use once so we will
use once so we will override the run method
override the run method public void
public void run when our timer executes our task
run when our timer executes our task what would we like to do well we're
what would we like to do well we're going to Output a number the number for
going to Output a number the number for our countdown timer so within our
our countdown timer so within our Anonymous class let's create an integer
Anonymous class let's create an integer variable of count for the time being
variable of count for the time being let's set this to a low number like five
let's set this to a low number like five intelligent wants us to make this
intelligent wants us to make this variable final but we'll be accepting
variable final but we'll be accepting user input momentarily so you don't need
user input momentarily so you don't need to do that my IDE of intelligent is
to do that my IDE of intelligent is recommending that you can just ignore
recommending that you can just ignore that so let's say that our count is
that so let's say that our count is going to start at five and we'll
going to start at five and we'll decrement by one then display happy New
decrement by one then display happy New Year when count to zero so why don't we
Year when count to zero so why don't we do the following within our run method
do the following within our run method we'll output our count variable at first
we'll output our count variable at first it's going to be
it's going to be five then we'll decrement count by one
five then we'll decrement count by one count minus
count minus minus we'll need to escape the run
minus we'll need to escape the run method well we can do that with an if
method well we can do that with an if statement
statement we will check if our count is less than
we will check if our count is less than zero if it is let's output happy New
Year and then to stop our timer we'll take our timer object called the cancel
take our timer object called the cancel method now we have to set up our timer
method now we have to set up our timer we will do that outside the timer task
we will do that outside the timer task Anonymous
Anonymous class so right here is good we will take
class so right here is good we will take our timer called the schedule
our timer called the schedule method schedule will take a task our
method schedule will take a task our timer
timer task and execute it after a delay let's
task and execute it after a delay let's set the delay to be zero now this is
set the delay to be zero now this is only going to run once there's a better
only going to run once there's a better method for this let me just
method for this let me just demonstrate so we get the number five
demonstrate so we get the number five and our program
and our program stops so what we're going to use instead
stops so what we're going to use instead is schedule at fixed rate
is schedule at fixed rate the schedule at fixed rate method but
the schedule at fixed rate method but there's three arguments we have to pass
there's three arguments we have to pass in first is the task the delay and then
in first is the task the delay and then the
the period we have our task the delay is
period we have our task the delay is zero what is the period in between
zero what is the period in between executions let's set that to be 1,000
executions let's set that to be 1,000 milliseconds every 1 second 1,000
milliseconds every 1 second 1,000 milliseconds perform your task and our
milliseconds perform your task and our task is to display our countdown
task is to display our countdown whatever the count currently is
whatever the count currently is all right let's test this again we're
all right let's test this again we're setting our count to be five initially
setting our count to be five initially but we'll be accepting user input
but we'll be accepting user input momentarily we start at 5 and we're
momentarily we start at 5 and we're going to count down to zero then display
going to count down to zero then display happy New
happy New Year all right after zero we display
Year all right after zero we display happy New Year and our program exits
happy New Year and our program exits because we canceled the
because we canceled the timer now if we don't cancel the timer
timer now if we don't cancel the timer I'm just going to cut this momentarily
I'm just going to cut this momentarily it's going to continue forever
we keep on displaying happy New Year and we're going into negative
we're going into negative seconds so that's why we need to cancel
seconds so that's why we need to cancel the timer so that it stops all right now
the timer so that it stops all right now we'll accept user input because we want
we'll accept user input because we want a user to type in the number to
a user to type in the number to countdown from rather than us
countdown from rather than us programmers just typing in a random
programmers just typing in a random number so we will need a
scanner scanner scanner equals new scanner then pass in
scanner then pass in system.in import this class and then
system.in import this class and then we'll need a
we'll need a prompt let's output the
prompt let's output the following enter number of seconds to
following enter number of seconds to countdown
countdown from I'll use print rather than print
from I'll use print rather than print line let's create an integer variable of
line let's create an integer variable of response set that equal to use our
response set that equal to use our scanner call the next int method to get
scanner call the next int method to get the next integer from the user then we
the next integer from the user then we will set our count variable equal to the
will set our count variable equal to the response whatever the user types in so
response whatever the user types in so now the user can type in a number and we
now the user can type in a number and we can count down from that number rather
can count down from that number rather than just placing a random number here
than just placing a random number here all right let's test
all right let's test this enter number of seconds to count
this enter number of seconds to count down from let's say 10 we're going to
down from let's say 10 we're going to count down from 10 so we start at 10 and
count down from 10 so we start at 10 and we're going to count down to
zero zero happy New Year and then the program exits so you can type in any
program exits so you can type in any number you could even set this to a
number you could even set this to a higher number like
higher number like 60 but I'm not going to make you wait
60 but I'm not going to make you wait that
that long all right everybody that is a
long all right everybody that is a countdown timer program that you can
countdown timer program that you can write as a mini project using Java hello
write as a mini project using Java hello there every everybody in this video I
there every everybody in this video I got to cover generics in Java generics
got to cover generics in Java generics it's a concept it's where you can write
it's a concept it's where you can write a class interface or method and it's
a class interface or method and it's compatible with different data types
compatible with different data types there's two things we need a type
there's two things we need a type parameter and a type argument so with
parameter and a type argument so with type parameters it's a set of angle
type parameters it's a set of angle brackets with a letter inside for
brackets with a letter inside for example T basically this acts as a
example T basically this acts as a placeholder and it gets replaced with
placeholder and it gets replaced with the real type now on the other hand type
the real type now on the other hand type arguments with various objects and data
arguments with various objects and data structures you'll see a pair of angle
structures you'll see a pair of angle brackets with a type inside such as a
brackets with a type inside such as a string but it really can be anything it
string but it really can be anything it can be an integer or a
can be an integer or a Boolean really anything type arguments
Boolean really anything type arguments specify the type we send arguments to
specify the type we send arguments to parameters really our type parameter is
parameters really our type parameter is just acting as a placeholder anything
just acting as a placeholder anything that uses this type parameter it doesn't
that uses this type parameter it doesn't know the data type that it's going to
know the data type that it's going to receive it's set up to receive really
receive it's set up to receive really anything or a primitive using a rapper
anything or a primitive using a rapper class let me give you an example of
class let me give you an example of where you already see a gener being used
where you already see a gener being used for example array lists to create an
for example array lists to create an array list we add a set of angle
array list we add a set of angle brackets after array list and we have to
brackets after array list and we have to specify the type what is this array list
specify the type what is this array list going to store for example strings we
going to store for example strings we would write the data type of string
would write the data type of string let's say that this array list is named
let's say that this array list is named fruits fruits equals new array list and
fruits fruits equals new array list and then we need a set of angle brackets
then we need a set of angle brackets again parenthesis semicolon in modern
again parenthesis semicolon in modern Java within the second set of angle
Java within the second set of angle brackets you don't necessarily need to
brackets you don't necessarily need to type the data type again Java can infer
type the data type again Java can infer that so you can leave it empty this is
that so you can leave it empty this is the diamond
the diamond operator we have an array list that can
operator we have an array list that can store strings we have specified the type
store strings we have specified the type argument and now we can store some
argument and now we can store some strings within our array list so let's
strings within our array list so let's take our array list of fruits call the
take our array list of fruits call the ad method and add a few names of fruits
ad method and add a few names of fruits such as an
such as an apple let's do two
apple let's do two more Apple orange banana
more Apple orange banana currently the way that we set up this
currently the way that we set up this array list it's compatible with strings
array list it's compatible with strings because that's what we set the type
because that's what we set the type argument to be now if I set this to be
argument to be now if I set this to be integers well we can't store strings
integers well we can't store strings anymore but we could store numbers 1 2 3
anymore but we could store numbers 1 2 3 that's
that's fine let me change that back generally
fine let me change that back generally speaking an array data structure can
speaking an array data structure can store all sorts of different data types
store all sorts of different data types but when we create one we have to
but when we create one we have to specify what we're storing that's the
specify what we're storing that's the type argument it's because within the
type argument it's because within the array list class we have a type
array list class we have a type parameter set up a set of angle brackets
parameter set up a set of angle brackets with a letter inside in many cases
with a letter inside in many cases you'll see t meaning type for type
you'll see t meaning type for type parameter so let's actually take a look
parameter so let's actually take a look at our array list I am going to locate
at our array list I am going to locate array list jump to Source here's the
array list jump to Source here's the class for our array list there's a lot
class for our array list there's a lot of advanced Java in here don't worry
of advanced Java in here don't worry about that but what I want you to pay
about that but what I want you to pay attention to is the type parameter that
attention to is the type parameter that comes after after the array list class
comes after after the array list class name we have angle brackets and a letter
name we have angle brackets and a letter inside in this case e meaning element
inside in this case e meaning element because an array list has elements of
because an array list has elements of data by using this type parameter our
data by using this type parameter our array list is set up to store elements
array list is set up to store elements of various types we just have to specify
of various types we just have to specify what the type is going to be when we
what the type is going to be when we actually do store data and in my example
actually do store data and in my example we're using strings but like I said
we're using strings but like I said before we can change the data type of
before we can change the data type of what we're storing we just have to
what we're storing we just have to change the type argument I'll store
change the type argument I'll store booleans true
false true I don't know what that has to do
true I don't know what that has to do with fruits but I'm just trying to prove
with fruits but I'm just trying to prove a point
a point here so now what we're going to do is
here so now what we're going to do is actually use type parameters so let's
actually use type parameters so let's delete our array list using generics you
delete our array list using generics you can write some logic within a class
can write some logic within a class interface or method and it's compatible
interface or method and it's compatible with many different data types so what
with many different data types so what we're going to do in this example is
we're going to do in this example is create a class of box
create a class of box class
class box we'll be using a type parameter to
box we'll be using a type parameter to store all sorts of different things
store all sorts of different things within our box we can store a string
within our box we can store a string within our box an integer a double A
within our box an integer a double A Boolean even more complex objects so we
Boolean even more complex objects so we will set up a type parameter with a set
will set up a type parameter with a set of angle brackets then type t t is a
of angle brackets then type t t is a common convention meaning type let's say
common convention meaning type let's say that when we create a box object our box
that when we create a box object our box is going to act as a container we'll
is going to act as a container we'll store a value inside
store a value inside our box is going to be a reusable class
our box is going to be a reusable class we won't always know what the data type
we won't always know what the data type of what we're storing is going to be so
of what we're storing is going to be so what we could do is set the data type to
what we could do is set the data type to be T let's say that this variable is an
be T let's say that this variable is an item we're storing an item within a box
item we're storing an item within a box with t it does mean type but I like to
with t it does mean type but I like to think of it as thing we're storing a
think of it as thing we're storing a thing an item within our box we don't
thing an item within our box we don't know what this thing is going to be but
know what this thing is going to be but really it means type and that's not as
really it means type and that's not as fun T item we don't know what the data
fun T item we don't know what the data type is if it's always going to be a
type is if it's always going to be a string we could just set this to be a
string we could just set this to be a string but what if somebody is storing
string but what if somebody is storing an integer an INT or we can use the
an integer an INT or we can use the rapper class of integer we don't know
rapper class of integer we don't know what the type is going to be let's
what the type is going to be let's create a method where we will set our
create a method where we will set our item let's say that this is public void
item let's say that this is public void it's not going to return anything set
it's not going to return anything set item we'll have one parameter what's the
item we'll have one parameter what's the data type of what we're receiving well
data type of what we're receiving well we don't know so we're going to use our
we don't know so we're going to use our type parameter of
type parameter of t t is the data type it's generic we
t t is the data type it's generic we will receive an
will receive an item let's take this. item and set it to
item let's take this. item and set it to be the item that we
be the item that we receive we'll create a method to get our
receive we'll create a method to get our item public now we're going to be
item public now we're going to be returning an item the data type is T so
returning an item the data type is T so the return type is also going to be T
the return type is also going to be T we're returning a value of the T data
we're returning a value of the T data type we will create a method to get
item we will return this. item we can put things in our box and we can get
put things in our box and we can get things from our
things from our box all right this class is done our box
box all right this class is done our box class is set up to be reusable we can
class is set up to be reusable we can store all sorts of different things so
store all sorts of different things so to say within our box we will attempt to
to say within our box we will attempt to create a box object for now let's say
create a box object for now let's say box box equals new box but there's one
box box equals new box but there's one step that we're
step that we're missing we have a warning here raw use
missing we have a warning here raw use of parameterized class
of parameterized class box we need to set up a type argument
box we need to set up a type argument what are we going to be putting in our
what are we going to be putting in our box what's its data type our box class
box what's its data type our box class wants to know so we will use a type
wants to know so we will use a type argument after the class of box add a
argument after the class of box add a set of angle brackets then type what
set of angle brackets then type what we're going to store so let's say we're
we're going to store so let's say we're going to store strings within our box
going to store strings within our box values of the string data type and then
values of the string data type and then we do need the diamond operator after
we do need the diamond operator after the second box and we're good we now
the second box and we're good we now have a box object but it's set up to
have a box object but it's set up to store strings let's add some items to
store strings let's add some items to our box we've even created a few methods
our box we've even created a few methods for this set item let's take our box
for this set item let's take our box call set item but we have to pass in a
call set item but we have to pass in a string let's add a banana to our
string let's add a banana to our box and then we will get the banana from
box and then we will get the banana from the box using the get item method and
the box using the get item method and now I want to get the banana box. get
item here we go we have our banana we have successfully retrieved the banana
have successfully retrieved the banana from the
from the box our box class is compatible with all
box our box class is compatible with all sorts of different data types this time
sorts of different data types this time let's store an integer we will use the
let's store an integer we will use the wrapper class of integer but we can no
wrapper class of integer but we can no longer add a banana to the Box because
longer add a banana to the Box because it's a string I'll attempt to do so
it's a string I'll attempt to do so string cannot be converted to
string cannot be converted to integer unfortunately bananas are not
integer unfortunately bananas are not numbers but I can add the number three
numbers but I can add the number three to our
to our box we have the number three within our
box we have the number three within our box if I attempt to add a double like
box if I attempt to add a double like 3.14 we get a warning
incompatible types double cannot be converted to
converted to integer so I would have to set the type
integer so I would have to set the type argument to be double to add doubles to
argument to be double to add doubles to our
our box
box 3.14 basically with our box class we're
3.14 basically with our box class we're writing the logic of how a box works you
writing the logic of how a box works you put something in and you can take
put something in and you can take something out and it's compatible with
something out and it's compatible with different data
different data types we just have to use a type
types we just have to use a type argument when creating a box object we
argument when creating a box object we have to let Java know what we're storing
have to let Java know what we're storing within it exactly all right let me give
within it exactly all right let me give you another example now with type
you another example now with type parameters you can have more than one
parameters you can have more than one type we can have two or more different
type we can have two or more different types usually the common convention is
types usually the common convention is to use U after
to use U after T so we're going to create a new class
T so we're going to create a new class file new Java class we will create a
file new Java class we will create a class of
class of product here we're going to write the
product here we're going to write the logic of how a product works with a
logic of how a product works with a product you have an item and you have a
product you have an item and you have a price we will set up a type parameter
price we will set up a type parameter let me zoom in we'll have one type of t
let me zoom in we'll have one type of t and a common convention for the second
and a common convention for the second type is U because in the English
type is U because in the English alphabet the letter U comes after T if
alphabet the letter U comes after T if you had a third argument that would be V
you had a third argument that would be V by Common
by Common convention so we'll just stick with t
convention so we'll just stick with t and
and u we will have a generic type of
u we will have a generic type of item and another generic type of price
item and another generic type of price we don't know if our item is going to be
we don't know if our item is going to be a string or a more complex object our
a string or a more complex object our price could be an integer a floating
price could be an integer a floating Point number a double we don't know but
Point number a double we don't know but that's why we're setting it up this
that's why we're setting it up this way now we'll need a Constructor we will
way now we'll need a Constructor we will take our
take our product then set up some parameters the
product then set up some parameters the data type of our item is t t item but if
data type of our item is t t item but if we're creating a product we also need a
we're creating a product we also need a price the data type of our price is u
price the data type of our price is u U price this. item equals the item that
U price this. item equals the item that we
we receive this. price equals the price
receive this. price equals the price that we
that we receive okay let's do a test run let's
receive okay let's do a test run let's go to our main Java
go to our main Java file product product equals new
file product product equals new product and again we need those type
product and again we need those type arguments so this time we actually need
arguments so this time we actually need two because our class is set up to
two because our class is set up to receive two type arguments T and
receive two type arguments T and U for our product let's say that the
U for our product let's say that the first type is going to be a string
first type is going to be a string followed by a double and then we need
followed by a double and then we need the diamond operator after the second
the diamond operator after the second product all right now we have to pass in
product all right now we have to pass in arguments to the class because we have a
arguments to the class because we have a Constructor we have to pass in an item
Constructor we have to pass in an item and its
and its price and with our type arguments we set
price and with our type arguments we set that up to be a string and a double we
that up to be a string and a double we have to pass in those types for our
have to pass in those types for our product let's say that it's an apple and
product let's say that it's an apple and an apple is 50 Cents that's a
an apple is 50 Cents that's a double let's create two methods within
double let's create two methods within our product class we will create a
our product class we will create a method to get our item let's say public
method to get our item let's say public we're returning an item the data type is
we're returning an item the data type is T so we're going to return
T so we're going to return T get
T get item we will return this do
item we will return this do item then to return the
item then to return the price let's say public U cuz we're
price let's say public U cuz we're returning the price it has a type of
returning the price it has a type of U Get
U Get price return this do
price we have our product object I'm going to Output take our
object I'm going to Output take our product object called the get item
product object called the get item method and this is going to return are
method and this is going to return are apple or I could get the price get
apple or I could get the price get price and that is
price and that is 0.5 you can use string format but that
0.5 you can use string format but that might be overkill for this lesson all
might be overkill for this lesson all right let's create a second product so
right let's create a second product so we'll have product
we'll have product one and product
one and product two Now product two will use an integer
two Now product two will use an integer instead of a
instead of a double and let's say that these are
double and let's say that these are tickets like movie tickets ticket and
tickets like movie tickets ticket and the price will be $15 for
the price will be $15 for $15 let's take product
$15 let's take product two call the get item
ticket and we should have a price get price the price of a movie ticket is$ 15
price the price of a movie ticket is$ 15 $15 all right everybody so that is an
$15 all right everybody so that is an introduction to two generics it's a
introduction to two generics it's a concept where you can write a class
concept where you can write a class interface or method that is compatible
interface or method that is compatible with different data types basically
with different data types basically we're writing the logic of how this
we're writing the logic of how this class works and it's compatible with all
class works and it's compatible with all different types you just have to set up
different types you just have to set up a type parameter and then pass in type
a type parameter and then pass in type arguments and well everybody that is an
arguments and well everybody that is an introduction to generics in Java well
introduction to generics in Java well it's up everybody so today I got to
it's up everybody so today I got to explain hashmaps in Java hashmaps are a
explain hashmaps in Java hashmaps are a popular data structure
popular data structure they store a pair of values a key value
they store a pair of values a key value pair you have a key and a value
pair you have a key and a value associated with that key the keys have
associated with that key the keys have to be unique but the values can be
to be unique but the values can be duplicated hashmaps do not maintain any
duplicated hashmaps do not maintain any order but they are very memory efficient
order but they are very memory efficient when creating a hashmap we have to set
when creating a hashmap we have to set up type parameters we have to specify
up type parameters we have to specify what the data type of the key is and its
what the data type of the key is and its value here's how to create a hashmap we
value here's how to create a hashmap we will type hashmap let's say map for
will type hashmap let's say map for short
short hashmap map equals new hash
hashmap map equals new hash map we'll need to import this class it
map we'll need to import this class it looks like we're missing something let's
looks like we're missing something let's take a look raw use of parameterized
take a look raw use of parameterized class
class hashmap if we take a look at the hashmap
hashmap if we take a look at the hashmap class we have type parameter set up
class we have type parameter set up there's two values we learned about type
there's two values we learned about type parameters in the last video on generics
parameters in the last video on generics we can store any two types of values
we can store any two types of values within a hashmap we have a key and a
within a hashmap we have a key and a value represented by K and V we have to
value represented by K and V we have to send type arguments to the type
send type arguments to the type parameters when creating a hashmap we'll
parameters when creating a hashmap we'll have to set up some type arguments so
have to set up some type arguments so after our hashmap we have to list the
after our hashmap we have to list the data type of what we're storing these
data type of what we're storing these have to be reference data types so let's
have to be reference data types so let's say with our map we're going to have
say with our map we're going to have products an item and a price so for the
products an item and a price so for the item that could be a string a string
item that could be a string a string representation of our
representation of our item so for the price we could do an
item so for the price we could do an integer but I think a double would be
integer but I think a double would be better because you can have dollars and
better because you can have dollars and cents then we also need to use the
cents then we also need to use the diamond operator after the second
diamond operator after the second hashmap you don't need to State the data
hashmap you don't need to State the data types again even though you technically
types again even though you technically could Java can actually infer what the
could Java can actually infer what the data type is so after the second hashmap
data type is so after the second hashmap add the diamond operator and there we go
add the diamond operator and there we go we have our hashmap that we have named
we have our hashmap that we have named map the way that we've set this up is
map the way that we've set this up is that we've told the hashmap class we're
that we've told the hashmap class we're going to store a string as the key and a
going to store a string as the key and a double as the value so to put things in
double as the value so to put things in a hash map we're going to take our map
a hash map we're going to take our map called the put method we're going to put
called the put method we're going to put something in the hashmap we've specified
something in the hashmap we've specified that we're storing a string then a
that we're storing a string then a double a string for the key and a double
double a string for the key and a double for the value so let's say we have a
for the value so let's say we have a store and in our store we sell produce
store and in our store we sell produce we will have an apple and its price will
we will have an apple and its price will be 50 CS
be 50 CS 0.50 to put some something in a hashmap
0.50 to put some something in a hashmap you use the put method we have to pass
you use the put method we have to pass in two values as arguments all right
in two values as arguments all right let's add a few more
let's add a few more things we'll have an
things we'll have an orange an orange will be 75 cents let's
orange an orange will be 75 cents let's say then a banana bananas are pretty
say then a banana bananas are pretty cheap they will be 25 cents all right
cheap they will be 25 cents all right let's take a look at our hash map I'm
let's take a look at our hash map I'm going to show you what happens if we
going to show you what happens if we output our map directly system.out.print
output our map directly system.out.print line our map our hash
line our map our hash map and here's what we have we have all
map and here's what we have we have all the key value pairs printed within our
the key value pairs printed within our hash map we have a string and a double
hash map we have a string and a double string double string
string double string double now with hash Maps the keys have
double now with hash Maps the keys have to be unique for example let's say I try
to be unique for example let's say I try and put another orange within here we'll
and put another orange within here we'll attempt to add another orange and we'll
attempt to add another orange and we'll see what happens
see what happens exactly put another Orange
exactly put another Orange within our map and let's say that the
within our map and let's say that the price is 1
price is 1 million Venezuelan dollars yes oranges
million Venezuelan dollars yes oranges are very expensive in Venezuela because
are very expensive in Venezuela because of inflation so here's what happens if
of inflation so here's what happens if we have duplicate
we have duplicate Keys you actually overwrite the previous
Keys you actually overwrite the previous key value pair our orange is now worth 1
key value pair our orange is now worth 1 million Venezuelan dollars so do keep
million Venezuelan dollars so do keep that in mind hashmaps cannot have
that in mind hashmaps cannot have duplicate keys if you put another key
duplicate keys if you put another key value pair with than a hashmap and it
value pair with than a hashmap and it already exists you'll overwrite it but
already exists you'll overwrite it but that's also good if you want to change
that's also good if you want to change one of the key value pairs let's add one
one of the key value pairs let's add one more key value pair let's say a coconut
more key value pair let's say a coconut map. put we will put a coconut within
map. put we will put a coconut within our hash map coconuts are a little more
our hash map coconuts are a little more expensive they'll be
expensive they'll be $1 let's print our map to test
$1 let's print our map to test it there's our
it there's our coconut then we can remove an element to
coconut then we can remove an element to remove an element take your map call the
remove an element take your map call the remove
remove method here you're going to pass in a
method here you're going to pass in a key let's remove our
key let's remove our Apple then print our
Apple then print our map there the apple is gone we have
map there the apple is gone we have orange banana coconut but no apple so
orange banana coconut but no apple so I'm going to keep that in but turn it
I'm going to keep that in but turn it into a
into a comment to get the value associated with
comment to get the value associated with the key you can use the get method so
the key you can use the get method so let me delete this print line statement
let me delete this print line statement we will take our map called the get
we will take our map called the get method let's get the value with this
method let's get the value with this key give me the value where the key is
key give me the value where the key is Apple is what we're
Apple is what we're saying that would be
saying that would be 0.5 meaning
0.5 meaning 50 or we can get our
coconut the value associated with this key is one meaning
key is one meaning $1 all right you can also check to see
$1 all right you can also check to see if a key or a value exists here's
if a key or a value exists here's how we'll use the contains key method
how we'll use the contains key method take our map call the contains key
take our map call the contains key method and then pass in a key is there a
method and then pass in a key is there a key of
key of banana that returns a Boolean in this
banana that returns a Boolean in this case
case true is there a pineapple there is not
true is there a pineapple there is not so that returns
so that returns false you could use this with than an if
false you could use this with than an if statement here's
statement here's how we will check
how we will check if let me zoom in if our map call the
if let me zoom in if our map call the contains key
contains key method and then pass in a key does our
method and then pass in a key does our map contain any
map contain any apples contains key
apples contains key Apple if that returns true we'll
Apple if that returns true we'll output
output map. getet then we'll get our Apple
map. getet then we'll get our Apple this will give us the price else if
this will give us the price else if contains key is false then we'll output
contains key is false then we'll output something else we'll
output key not found all right let's test this so we do
found all right let's test this so we do have an apple we've set this up to
have an apple we've set this up to return the
return the price but let's say we are looking for a
price but let's say we are looking for a pineapple contains key
pineapple contains key pineapple if we do find a pineapple we
pineapple if we do find a pineapple we will get the price price currently
will get the price price currently there's no pineapples within our map key
there's no pineapples within our map key not found so that's how the contains key
not found so that's how the contains key method would be
method would be useful we also have the capability to
useful we also have the capability to check to see if a map contains a value
check to see if a map contains a value so we will take our map within a print
so we will take our map within a print line statement called the
line statement called the contains Value method and then pass in a
contains Value method and then pass in a value is there anything that's $1
value is there anything that's $1 1.0 this returns a Boolean and that's
1.0 this returns a Boolean and that's true our key of coconut has a value of
true our key of coconut has a value of 1.0 $1 and you do have to pay attention
1.0 $1 and you do have to pay attention to the data type too if I were to pass
to the data type too if I were to pass in an
in an integer this does return false you do
integer this does return false you do have to keep that in mind too that's how
have to keep that in mind too that's how to check to see if a map contains a key
to check to see if a map contains a key and a
value you can return the size of a map using map. size map dot called the size
using map. size map dot called the size method currently there's four key value
method currently there's four key value pairs within our map
pairs within our map this will return the number four to get
this will return the number four to get the size of a map call the size
the size of a map call the size method all right now the last thing that
method all right now the last thing that we're going to do if we were to print
we're going to do if we were to print our
our map we're given this ugly
map we're given this ugly formatting where we have a set of curly
formatting where we have a set of curly braces then all the key value pairs
braces then all the key value pairs comma
comma separated this time using a for loop
separated this time using a for loop we're going to cycle through all the key
we're going to cycle through all the key value pairs we will create an enhanced
value pairs we will create an enhanced for Loop
for Loop what we're going to iterate through is
what we're going to iterate through is every key and these have a string data
every key and these have a string data type because that's the way that we set
type because that's the way that we set them
them up the data type of each element is
up the data type of each element is going to be a string which we will name
going to be a string which we will name key colon think of it as in for every
key colon think of it as in for every key in now what we have to do is get all
key in now what we have to do is get all the keys from our map and there's
the keys from our map and there's actually a method for that a beginners
actually a method for that a beginners friendly way to get all the keys from
friendly way to get all the keys from our map what we can do is take our map
our map what we can do is take our map call the key set
call the key set method this will return all the keys
method this will return all the keys within our map and they're iterable so
within our map and they're iterable so we can use them within a for Loop for
we can use them within a for Loop for every key in our set of keys what do we
every key in our set of keys what do we want to do let's do the following within
want to do let's do the following within a print line statement let's print our
a print line statement let's print our key plus we'll list each product and its
key plus we'll list each product and its price key
price key plus maybe I'll add a colon space then
plus maybe I'll add a colon space then pick a unit of currency I'll pick
pick a unit of currency I'll pick American dollars for every key we need
American dollars for every key we need to get its value so we can use the get
to get its value so we can use the get method plus map. getet pass in our key
method plus map. getet pass in our key by using an enhanced for Loop we can
by using an enhanced for Loop we can customize the output of the key value
customize the output of the key value Pairs and I think this looks a lot
Pairs and I think this looks a lot better we have each product each piece
better we have each product each piece of fruit and its price laid out in this
of fruit and its price laid out in this format you could technically use print F
format you could technically use print F if you want to display two digits after
if you want to display two digits after the decimal
the decimal but that might be a little too much for
but that might be a little too much for this lesson I want to keep it as simple
this lesson I want to keep it as simple as possible all right everybody so those
as possible all right everybody so those are hashmaps it's a data structure that
are hashmaps it's a data structure that stores key value pairs the keys have to
stores key value pairs the keys have to be unique but the values can be
be unique but the values can be duplicated we have to specify the type
duplicated we have to specify the type for the key and its value and well
for the key and its value and well everybody those are hashmaps in
everybody those are hashmaps in Java all right let's do this thing
Java all right let's do this thing everybody today we're talking about
everybody today we're talking about enums en nums is short for enumerations
enums en nums is short for enumerations they're a special kind of class they
they're a special kind of class they represent a fixed set of constants by
represent a fixed set of constants by using enums they improve code
using enums they improve code readability and are easy to maintain one
readability and are easy to maintain one of the major benefits of enums is that
of the major benefits of enums is that they're more efficient with switches
they're more efficient with switches when comparing strings so basically an
when comparing strings so basically an enum is a special kind of class where we
enum is a special kind of class where we declare constants here's a demonstration
declare constants here's a demonstration we're going to create a new class file
we're going to create a new class file new Java class we're going to select
new Java class we're going to select enum enum is a special kind of class
enum enum is a special kind of class sort of like like how an interface is a
sort of like like how an interface is a special kind of
special kind of class we will create an enum of
class we will create an enum of day public enum Day within this Java
day public enum Day within this Java class we can declare some constants what
class we can declare some constants what we're going to write is enum constants a
we're going to write is enum constants a common convention for these constants is
common convention for these constants is that all the letters are uppercase so
that all the letters are uppercase so after the enum constant We'll add a set
after the enum constant We'll add a set of parentheses then associate this
of parentheses then associate this constant with the value so let's say
constant with the value so let's say that we're working with days of the week
that we're working with days of the week Sunday will be the the first day of the
Sunday will be the the first day of the week Sunday we'll have a value of one
week Sunday we'll have a value of one let's do this with the other days of the
let's do this with the other days of the week Monday parentheses then a value
week Monday parentheses then a value Monday will be the second day of the
Monday will be the second day of the week then we'll just follow this
pattern and all these constants with a semicolon all right we have our enum
semicolon all right we have our enum constants they have values 1 through 7
constants they have values 1 through 7 we're receiving some warnings here
we're receiving some warnings here expected zero arguments but one found
expected zero arguments but one found what we need to do is create a
what we need to do is create a Constructor a Constructor for our day
Constructor a Constructor for our day class when we Define these enum
class when we Define these enum constants we're automatically going to
constants we're automatically going to call the Constructor for this enum class
call the Constructor for this enum class and then pass in this value let's create
and then pass in this value let's create a field of day number for days of the
a field of day number for days of the week we'll make these values private
week we'll make these values private we'll use the private access modifier we
we'll use the private access modifier we don't want the ability to change them
don't want the ability to change them we'll make them final these are integers
we'll make them final these are integers that's the data type we'll name these
that's the data type we'll name these values day
values day number when we Define these enum
number when we Define these enum constants we're automatically going to
constants we're automatically going to call the Constructor and then pass in
call the Constructor and then pass in this value to the
this value to the Constructor for the parameters we'll
Constructor for the parameters we'll have int then our field of day
have int then our field of day number this day
number this day number equals the day day number that we
number equals the day day number that we receive if you would like you can add a
receive if you would like you can add a getter method to actually get the day
getter method to actually get the day number we'll use the public access
number we'll use the public access modifier we're returning an integer
modifier we're returning an integer we'll Define a method of get day
we'll Define a method of get day number and we will return our field of
number and we will return our field of this. day number all right and we have
this. day number all right and we have set up our enum class reading and
set up our enum class reading and understanding these enum constants is a
understanding these enum constants is a lot easier than these numbers if I was
lot easier than these numbers if I was looking at the number five I would have
looking at the number five I would have trouble understanding that that means
trouble understanding that that means Thursday now how do we work with these
Thursday now how do we work with these enum constants exactly here's how within
enum constants exactly here's how within our main Java
our main Java file we will create a day object by
file we will create a day object by using this enum
using this enum class let me delete
class let me delete this day day rather than saying new day
this day day rather than saying new day and then passing in a number like one
and then passing in a number like one there's a different approach
there's a different approach we will access the day class Dot and
we will access the day class Dot and then specify a constant a day of the
then specify a constant a day of the week let's say Sunday remember that this
week let's say Sunday remember that this is all caps our day is an object let's
is all caps our day is an object let's output our day and see what it
output our day and see what it outputs this will output Sunday all caps
outputs this will output Sunday all caps if you would rather get the day number
if you would rather get the day number the value that's associated with this
the value that's associated with this enum
enum constant then we can use that getter
constant then we can use that getter method
method day. get day
number so we have Sunday and one where this is really going to be helpful is
this is really going to be helpful is when working with
when working with switches here's a demonstration we will
switches here's a demonstration we will actually use an enhanced
actually use an enhanced switch what are we examining we're
switch what are we examining we're examining our day object if our day
examining our day object if our day matches a case of Monday now this isn't
matches a case of Monday now this isn't a string If This Were A String we would
a string If This Were A String we would enclose this within a set of quotes but
enclose this within a set of quotes but using enums within a switch is actually
using enums within a switch is actually faster than using
faster than using strings if it's Monday then we'll output
strings if it's Monday then we'll output the following we'll use an arrow because
the following we'll use an arrow because this is an enhanced switch then we'll
this is an enhanced switch then we'll output it is a
output it is a weekday then if we have a case of
weekday then if we have a case of Tuesday let me just copy
Tuesday let me just copy this Tuesday we'll also output it is a
this Tuesday we'll also output it is a weekday you can actually combine these
weekday you can actually combine these cases together too you just have to
cases together too you just have to comma separate them
comma separate them so case Monday comma Tuesday do
so case Monday comma Tuesday do this then let's do this with the other
this then let's do this with the other days of the week just for readability
days of the week just for readability I'll put these on new lines each of
I'll put these on new lines each of these
these cases so we have
Wednesday Thursday
Thursday Friday these are all the weekdays Monday
Friday these are all the weekdays Monday through
through Friday then if we have case Saturday
Friday then if we have case Saturday then it's the weekend case Saturday
then it's the weekend case Saturday today we'll do the following output it
today we'll do the following output it is the
is the weekend and we will also add a case for
weekend and we will also add a case for Sunday so currently our day is
Sunday so currently our day is Sunday that will output it is the
Sunday that will output it is the weekend if it were let's say
Wednesday then instead we output it is a weekday if we were comparing strings all
weekday if we were comparing strings all these cases would be enclosed within a
these cases would be enclosed within a set of double quotes kind of like
this but we don't need to do that it's actually more efficient to use
enums for some practice what we'll do this time is accept some user input
this time is accept some user input we'll need a
we'll need a scanner scanner scanner equals new
scanner scanner scanner equals new scanner pass it
scanner pass it system.in import this class be sure to
system.in import this class be sure to close your scanner because I tend to
close your scanner because I tend to forget scanner.
forget scanner. close then we'll need a prompt we will
close then we'll need a prompt we will output the following we'll use print
output the following we'll use print rather than print
rather than print Line enter a day of the
week we will create a string variable let's say response equals use our
let's say response equals use our scanner call the next line
scanner call the next line method all these constants are uppercase
method all these constants are uppercase we'll method chain the two uppercase
we'll method chain the two uppercase method to make our user input
method to make our user input uppercase when creating a day object by
uppercase when creating a day object by using the enum class we will use our
using the enum class we will use our response we will use the value of
response we will use the value of method and then pass in our response now
method and then pass in our response now we should be able to type in a
we should be able to type in a day enter a day of the week I will type
day enter a day of the week I will type Monday it is a weekday let's run this
Monday it is a weekday let's run this again I will type Sunday it is the
again I will type Sunday it is the weekend what if we type in a day that
weekend what if we type in a day that doesn't exist like pizza
doesn't exist like pizza day well we get an exception an illegal
day well we get an exception an illegal argument
argument exception we can catch that exception
exception we can catch that exception using a try and catch block any
using a try and catch block any dangerous code we're going to enclose
dangerous code we're going to enclose within a tri block we will try the
within a tri block we will try the dangerous
code and catch any exceptions we will catch that illegal
argument exception which we will name e if the user input doesn't match one of
if the user input doesn't match one of these e nums then we'll output the
these e nums then we'll output the following please enter a valid
following please enter a valid day let's try it
day let's try it again enter day of the week let's try
again enter day of the week let's try Tuesday it is a
Tuesday it is a weekday
weekday Saturday it is the weekend
Saturday it is the weekend Pizza day please enter a valid day Pizza
Pizza day please enter a valid day Pizza day is not one of our enums but if we
day is not one of our enums but if we wanted to change it so it was we can add
that pizza day will be the eighth day of the
the week at least it should
be we'll need a case for pizza day Pizza day will also be part of the
day Pizza day will also be part of the weekend that just makes sense to
weekend that just makes sense to me all right let's try that
me all right let's try that again enter day of the week Pizza day it
again enter day of the week Pizza day it is the weekend all right all right
is the weekend all right all right everybody so those are enums meaning
everybody so those are enums meaning enumerations they're a special kind of
enumerations they're a special kind of class kind of like how interfaces are a
class kind of like how interfaces are a special kind of class they represent a
special kind of class they represent a fixed set of constants they improve code
fixed set of constants they improve code readability and reliability and where
readability and reliability and where they're really useful is when working
they're really useful is when working with switches
with switches because when working with switches using
because when working with switches using enums is faster than strings if I wasn't
enums is faster than strings if I wasn't using enum constants I could use
using enum constants I could use integers which are also
efficient but as a programmer this is way less readable for me at first clance
way less readable for me at first clance I would have no idea what these numbers
I would have no idea what these numbers are but if they're enum constants this
are but if they're enum constants this is perfectly readable to me these are
is perfectly readable to me these are days of the week that makes sense and
days of the week that makes sense and well everybody those are enums in Java
well everybody those are enums in Java what's going on people in this video I'm
what's going on people in this video I'm going to teach you all about threading
going to teach you all about threading in Java threading allows a program to
in Java threading allows a program to run multiple tasks simultaneously it
run multiple tasks simultaneously it helps to improve performance with
helps to improve performance with timeconsuming
timeconsuming operations such as file input output
operations such as file input output network communications or any other
network communications or any other background tasks any code that is
background tasks any code that is considered timec consuming we can have
considered timec consuming we can have it run on a different thread so that it
it run on a different thread so that it doesn't inconvenience our main program
doesn't inconvenience our main program there's two options to creating a thread
there's two options to creating a thread option one is to extend the thread class
option one is to extend the thread class this is the simpler option but it's
this is the simpler option but it's limited option two is to implement the
limited option two is to implement the runnable interface this option tends to
runnable interface this option tends to be better because by extending the
be better because by extending the thread class we're limited to single
thread class we're limited to single inheritance but by implementing the
inheritance but by implementing the redible interface that's one way around
redible interface that's one way around that in this demonstration I'm going to
that in this demonstration I'm going to show you option two it's actually not
show you option two it's actually not that more difficult than option one and
that more difficult than option one and it gives you more possibilities I'll
it gives you more possibilities I'll give you a demonstration of why
give you a demonstration of why threading is useful in this program
threading is useful in this program where about to write let's say it's a
where about to write let's say it's a game or a quiz or something a user has
game or a quiz or something a user has 10 seconds to respond and if they don't
10 seconds to respond and if they don't times up currently we have one thread
times up currently we have one thread we're running our program on what is
we're running our program on what is known as the main thread without using
known as the main thread without using any other threads besides the main
any other threads besides the main thread I might write my program
thread I might write my program something like this we'll start with the
something like this we'll start with the scanner because we'll be accepting user
scanner because we'll be accepting user input scanner scanner equals new scanner
input scanner scanner equals new scanner pass in
pass in system.in import this class
system.in import this class and close your scanner when you're done
and close your scanner when you're done with it scanner.
close we're going to let a user know that they have let's say 5 Seconds to
that they have let's say 5 Seconds to enter their
enter their name you have 5 Seconds to enter your
name you have 5 Seconds to enter your name we will create a
name we will create a prompt enter your
prompt enter your name I'll use print rather than and
name I'll use print rather than and print
print line we will assign a string variable of
line we will assign a string variable of name use our scanner called the next
name use our scanner called the next line
line method and then once we have the name
method and then once we have the name we'll
we'll output hello plus the user's name hello
output hello plus the user's name hello plus name so let's do a test run
plus name so let's do a test run currently we don't have a timer
currently we don't have a timer setup you have 5 Seconds down to your
setup you have 5 Seconds down to your name I can type in a name hit enter we
name I can type in a name hit enter we display hello the name and then the
display hello the name and then the program exits processed finished with
program exits processed finished with exit Code Zero if we were creating some
exit Code Zero if we were creating some sort of timer we could do the
sort of timer we could do the following to make this simple we could
following to make this simple we could use a for Loop the for Loop is going to
use a for Loop the for Loop is going to cycle five times we will have an index
cycle five times we will have an index of I in I equals 1 that's where we'll
of I in I equals 1 that's where we'll start we'll continue as long as I is
start we'll continue as long as I is less than or equal to 5 and then
less than or equal to 5 and then increment I by One during each cycle of
increment I by One during each cycle of the for Loop to mimic waiting for one
the for Loop to mimic waiting for one second you can access the thread class
second you can access the thread class call the Sleep Method pass in 1,000
call the Sleep Method pass in 1,000 milliseconds when you use thread that
milliseconds when you use thread that refers to the current thread that we're
refers to the current thread that we're working with in this case the main
working with in this case the main thread which is what our main program
thread which is what our main program runs on but since our thread might be
runs on but since our thread might be interrupted we do need a try and catch
interrupted we do need a try and catch block because this is considered
block because this is considered dangerous code we will try this code
dangerous code we will try this code where we will have our main Java thread
where we will have our main Java thread sleep for 1,000 milliseconds
sleep for 1,000 milliseconds and we will catch the following
and we will catch the following exception an interrupted
exception an interrupted exception So within our catch block we
exception So within our catch block we will catch any interrupted exceptions
will catch any interrupted exceptions which we will name e if our thread is
which we will name e if our thread is interrupted we will
interrupted we will say thread was
interrupted in our imaginary timer we'll need an exit
need an exit condition let's say if our index of I is
condition let's say if our index of I is equal to 5
equal to 5 that means times up so we'll
that means times up so we'll output times up I'm going to show you
output times up I'm going to show you why this won't work the way that we
why this won't work the way that we think we have 5 Seconds to enter our
think we have 5 Seconds to enter our name but there's no prompt or
name but there's no prompt or anything then we get the message times
anything then we get the message times up and only after that Loop is complete
up and only after that Loop is complete are we allowed to enter our name and
are we allowed to enter our name and then we can type in our name we get the
then we can type in our name we get the output of hello our name and then the
output of hello our name and then the program exits so the problem that we're
program exits so the problem that we're running into is that all of this code is
running into is that all of this code is running on our main thread we have 5
running on our main thread we have 5 Seconds to enter our name but we can't
Seconds to enter our name but we can't reach that code until the 5 seconds are
reach that code until the 5 seconds are up because our main thread is waiting
up because our main thread is waiting for this Loop to finish so what we could
for this Loop to finish so what we could do is create a separate thread where
do is create a separate thread where we're counting to five and our main
we're counting to five and our main thread is going to be in charge of
thread is going to be in charge of accepting our user input so here's how
accepting our user input so here's how to create another thread we're going to
to create another thread we're going to extend the runable interface to create a
extend the runable interface to create a runnable object
runnable object let's go to file new Java class this
let's go to file new Java class this will be a class we'll name this class my
will be a class we'll name this class my runnable or something unique that's
runnable or something unique that's relevant to what you're
relevant to what you're creating my runnable is going to
creating my runnable is going to implements because we're working with
implements because we're working with interfaces the runnable
interfaces the runnable interface if you implement an interface
interface if you implement an interface it's kind of like you're signing a
it's kind of like you're signing a contract we have to override any
contract we have to override any required method me we need to override
required method me we need to override the run method we need the at override
the run method we need the at override annotation then we will override the run
annotation then we will override the run method public void
method public void run within this run method we're going
run within this run method we're going to add any code we want to run in the
to add any code we want to run in the background on a separate thread going
background on a separate thread going back to our main Java file we're going
back to our main Java file we're going to cut this
to cut this Loop and then paste it within the run
Loop and then paste it within the run method when we call this run method
method when we call this run method we'll have this countdown timer run
we'll have this countdown timer run running in the background on a separate
running in the background on a separate thread any code you want to run on a
thread any code you want to run on a separate thread place within the run
separate thread place within the run method all right going back to our main
method all right going back to our main Java file we'll tell the user they have
Java file we'll tell the user they have 5 Seconds to enter their
5 Seconds to enter their name we have our class of my runnable we
name we have our class of my runnable we will create a my runnable object or
will create a my runnable object or whatever it is that you named to this
whatever it is that you named to this class let's say my runnable will be the
class let's say my runnable will be the name of the object equals new my
name of the object equals new my runable we will take this runnable
runable we will take this runnable object pass it into the Constructor of
object pass it into the Constructor of the thread class here's where we're
the thread class here's where we're going to create a new thread thread
going to create a new thread thread thread equals new
thread equals new thread pass in your runnable object as
thread pass in your runnable object as an argument to the thread
an argument to the thread Constructor now we just need our thread
Constructor now we just need our thread to
to start you'll take your thread call the
start you'll take your thread call the start method and this should work let's
start method and this should work let's try
try it you have 5 Seconds to enter your name
it you have 5 Seconds to enter your name and we get that prompt of enter your
and we get that prompt of enter your name but I'm not going to type in
name but I'm not going to type in anything we get the message times up
anything we get the message times up because we ran out of
because we ran out of time let's try it again I'll type in my
time let's try it again I'll type in my name this
name this time there we go we get our output hello
time there we go we get our output hello bro then we get the message time is
bro then we get the message time is up both these threads are running at the
up both these threads are running at the same time the code within our run method
same time the code within our run method is running on a separate thread it's
is running on a separate thread it's running in the background while our main
running in the background while our main program is running running so that's why
program is running running so that's why threads are useful so let me extend this
threads are useful so let me extend this time let's say 10
time let's say 10 seconds if I is equal to 10 just to give
seconds if I is equal to 10 just to give us some more
us some more time you have 10 seconds to enter your
time you have 10 seconds to enter your name now check this
name now check this out you have 10 seconds to to your name
out you have 10 seconds to to your name I'll type in my name immediately we get
I'll type in my name immediately we get the output hello whatever your name is
the output hello whatever your name is but the program is still running because
but the program is still running because that second thread is still running in
that second thread is still running in the background
the background our program doesn't exit until all
our program doesn't exit until all threads are
threads are done if your main thread is done you can
done if your main thread is done you can end all other threads but you'll want to
end all other threads but you'll want to set those threads to be what is known as
set those threads to be what is known as Damon threads a Damon thread will end
Damon threads a Damon thread will end when the main thread is over we will
when the main thread is over we will take our thread call the set Damon
take our thread call the set Damon method pass and
method pass and true this thread is going to end as soon
true this thread is going to end as soon as our main thread is finished let's try
as our main thread is finished let's try it again you have 10 seconds then to
it again you have 10 seconds then to your name I'll type in my name we get
your name I'll type in my name we get our output and then our program exits
our output and then our program exits without saying time is up processed
without saying time is up processed finished with exit code
finished with exit code zero that's because we set our second
zero that's because we set our second thread to be a Damon thread it ends when
thread to be a Damon thread it ends when the main thread is over now on the other
the main thread is over now on the other hand let's say that we wait for time to
hand let's say that we wait for time to be up we wait the full 10
seconds time's up our program isn't over yet we're still waiting for user input
yet we're still waiting for user input and I can still type it
and I can still type it in hello bro process finished with exit
in hello bro process finished with exit Code Zero optionally what you could do
Code Zero optionally what you could do to get your program to exit go to your
to get your program to exit go to your runnable class wherever you would like
runnable class wherever you would like your program to exit when seconds equals
your program to exit when seconds equals 10 that's where I would like to exit to
10 that's where I would like to exit to exit the program prematurely I can
exit the program prematurely I can access system called the exit method
access system called the exit method pass in an exit code of zero that will
pass in an exit code of zero that will ENT the program all right let's try this
ENT the program all right let's try this again you have 10 seconds to end to your
again you have 10 seconds to end to your name I'm not going to type in anything
name I'm not going to type in anything I'm just going to wait for the full 10
seconds time's up and then our program exits but that's what we want though the
exits but that's what we want though the way that we've set up this program is
way that we've set up this program is that we want this program to exit either
that we want this program to exit either when we finish typing in our name or we
when we finish typing in our name or we run out of
run out of time all right everybody so that is an
time all right everybody so that is an introduction to in it allows a program
introduction to in it allows a program to run multiple tasks simultaneously it
to run multiple tasks simultaneously it helps to improve performance with
helps to improve performance with timeconsuming
timeconsuming operations it's useful with file input
operations it's useful with file input and output operations network
and output operations network communications or any other background
communications or any other background tasks and well everybody that is an
tasks and well everybody that is an introduction to threading in Java yo we
introduction to threading in Java yo we finally made it to multi-threading in
finally made it to multi-threading in Java multi-threading enables a program
Java multi-threading enables a program to run multiple threads concurrently at
to run multiple threads concurrently at the same time as we've talked about in
the same time as we've talked about in the previous lesson a thread is a set of
the previous lesson a thread is a set of instructions and they run independently
instructions and they run independently from other threads multi-threading is
from other threads multi-threading is useful for background tasks or other
useful for background tasks or other timeconsuming
timeconsuming operations in the prior lesson we've
operations in the prior lesson we've learned that there's two ways to create
learned that there's two ways to create threads we can either extend the thread
threads we can either extend the thread class or implement the runable interface
class or implement the runable interface the second option is better in most
the second option is better in most cases because we're not limited by
cases because we're not limited by single inheritance here's how we can get
single inheritance here's how we can get started multi-threading we're going to
started multi-threading we're going to create a new class file new Java class
create a new class file new Java class we'll call this class my
runnable my runnable will implements the runnable interface if
implements the runnable interface if we're implementing an interface it's
we're implementing an interface it's kind of like we're signing a contract we
kind of like we're signing a contract we have to override any required methods we
have to override any required methods we have to override the run
have to override the run method public void
method public void run whatever is within the run method
run whatever is within the run method this is the code that's going to perform
this is the code that's going to perform when this thread is up and running
when this thread is up and running so what would we like to do just for a
so what would we like to do just for a beginner's example let's count to five
beginner's example let's count to five using a four Loop we'll write a for
using a four Loop we'll write a for Loop we will create an index of I I'll
Loop we will create an index of I I'll set that equal to be one right away
set that equal to be one right away we'll continue as long as I is less than
we'll continue as long as I is less than or equal to 5 cuz we're counting to five
or equal to 5 cuz we're counting to five then increment I by 1 during each cycle
then increment I by 1 during each cycle this for loop I would like this thread
this for loop I would like this thread to wait for 1 second before printing
to wait for 1 second before printing whatever I is what whatever the current
whatever I is what whatever the current count is if we're counting we will
count is if we're counting we will access the thread class called The Sleep
access the thread class called The Sleep Method pass in 1,000 milliseconds to
Method pass in 1,000 milliseconds to sleep for a
sleep for a second we will need to surround this
second we will need to surround this method with try and catch
method with try and catch blocks we'll catch any interrupted
blocks we'll catch any interrupted exceptions but let's output the
exceptions but let's output the following we'll say thread was
following we'll say thread was interrupted after our thread sleeps for
interrupted after our thread sleeps for 1 second let's display the current count
1 second let's display the current count I'll just say I just to keep it
I'll just say I just to keep it simple let's go back to our main Java
simple let's go back to our main Java file we'll need to create a runable
file we'll need to create a runable object my
object my runable let's say my runable equals new
runable let's say my runable equals new my
runable we have to pass in this runable object to a thread object let's say
object to a thread object let's say thread thread equals new thread we will
thread thread equals new thread we will pass in our runable object
pass in our runable object to get this thread to start we have to
to get this thread to start we have to call the start method of our thread
call the start method of our thread thread. start
thread. start method and this should work we'll test
method and this should work we'll test it 1 2 3 4 5 and then we exit the
it 1 2 3 4 5 and then we exit the program another shortcut you can do too
program another shortcut you can do too instead of creating a named runable
instead of creating a named runable object we can pass in an anonymous
object we can pass in an anonymous renable object to the thread Constructor
renable object to the thread Constructor so let's copy this section delete this
so let's copy this section delete this line of code and then pass in a new
line of code and then pass in a new runable
runable object this will work too and it's a lot
object this will work too and it's a lot more
concise now we won't have just one thread we'll have two so let's rename
thread we'll have two so let's rename thread as thread one copy this line of
thread as thread one copy this line of code paste it rename the second thread
code paste it rename the second thread as thread two thread 1. start and thread
as thread two thread 1. start and thread 2. start
2. start so now we'll have two threads running at
so now we'll have two threads running at the same time they're running
concurrently so they both say 1 2 3 4 5 we have successfully
we have successfully multi-threaded you could differentiate
multi-threaded you could differentiate these by getting their name here's an
these by getting their name here's an example to get each thread's name we're
example to get each thread's name we're going to access the thread class called
going to access the thread class called the current thread method
the current thread method and then method chain the get name
and then method chain the get name method then I'll add a space plus our
method then I'll add a space plus our counter
counter RI just so we can see each thread by its
RI just so we can see each thread by its name and what it's counting exactly okay
name and what it's counting exactly okay let's try this
let's try this again we have thread one and thread zero
again we have thread one and thread zero now they won't always be in the same
now they won't always be in the same order they're running
order they're running independently thread zero that's our
independently thread zero that's our thread one Java's thread one is our
thread one Java's thread one is our thread
two okay here's an exercise we're going to have thread one say ping and thread 2
to have thread one say ping and thread 2 say pong like we're playing a game of
say pong like we're playing a game of pingpong we'll modify the my runnable
pingpong we'll modify the my runnable class we'll need some text a text
class we'll need some text a text variable we'll say private final we
variable we'll say private final we don't want it to
don't want it to change string text then we'll need a
change string text then we'll need a Constructor to assign it my
Constructor to assign it my runnable we have one parameter a string
runnable we have one parameter a string of text we will assign this. text equals
of text we will assign this. text equals the text we
the text we receive instead of printing our counter
receive instead of printing our counter we'll print our
we'll print our text all right and that's all we need
text all right and that's all we need going back to our main Java file we have
going back to our main Java file we have to pass in some text when we construct a
to pass in some text when we construct a runable
runable object for the first thread we'll we'll
object for the first thread we'll we'll say ping for the second thread we'll say
say ping for the second thread we'll say pong so here's what we have
program before we start the threads let's say game start there's one more
let's say game start there's one more thing I want to show you game
start after we start the threads let's try and say game
try and say game over game over here's what
over game over here's what happens game start game over and our two
happens game start game over and our two threads are still
threads are still running then we
running then we finish so the problem here is that in
finish so the problem here is that in our main thread it doesn't Wait For
our main thread it doesn't Wait For Thread one and thread two to
Thread one and thread two to finish our main thread ends
finish our main thread ends immediately we can have our main thread
immediately we can have our main thread wait for these threads to finish by
wait for these threads to finish by calling the join method of each thread
calling the join method of each thread our main thread we'll wait for these two
our main thread we'll wait for these two threads to
threads to finish after these two threads start
finish after these two threads start we'll use each join method thread 1.
we'll use each join method thread 1. join and thread 2
dojin and we do have to surround these with try and catch
blocks try thread 1. jooin and thread 2 do jooin if our main thread is
do jooin if our main thread is interrupted we'll output main thread was
interrupted we'll output main thread was interrupted okay this should work now
interrupted okay this should work now before we display game over we're going
before we display game over we're going to wait for our two threads to
to wait for our two threads to finish here's what we got game start and
finish here's what we got game start and we display
we display pingpong and we'll do that five times
pingpong and we'll do that five times and then display game
and then display game over all right everybody that is an
over all right everybody that is an introduction to multi-threading
introduction to multi-threading it enables a program to run multiple
it enables a program to run multiple threads concurrently a thread is a set
threads concurrently a thread is a set of instructions that run independently
of instructions that run independently multi-threading is useful for background
multi-threading is useful for background tasks or other timeconsuming
tasks or other timeconsuming operations and well everybody that is an
operations and well everybody that is an introduction to multi-threading in Java
introduction to multi-threading in Java hey everybody in this video we're going
hey everybody in this video we're going to create a working alarm clock that
to create a working alarm clock that plays music using
Java all right let's get started everybody this alarm clock is going to
everybody this alarm clock is going to to serve as a final project for us will
to serve as a final project for us will combine a lot of Concepts that we've
combine a lot of Concepts that we've learned throughout the series when
learned throughout the series when starting a new project a good first step
starting a new project a good first step is to declare all your variables or
is to declare all your variables or other objects that you'll need
other objects that you'll need throughout this program we'll begin with
throughout this program we'll begin with the scanner because we'll be accepting
the scanner because we'll be accepting user input a user is going to enter in a
user input a user is going to enter in a Time scanner scanner equals new scanner
Time scanner scanner equals new scanner pass in
pass in system.in and we'll be importing classes
system.in and we'll be importing classes as we go along at the end of this
as we go along at the end of this program we're going to close our scan
program we're going to close our scan but we'll actually move it later on
but we'll actually move it later on because our alarm clock class is
because our alarm clock class is actually going to be using it more on
actually going to be using it more on that later we have our scanner and
that later we have our scanner and currently we're closing it a user is
currently we're closing it a user is going to use the scanner and enter in
going to use the scanner and enter in hours minutes and seconds to set the
hours minutes and seconds to set the alarm when the user types in a string
alarm when the user types in a string representation of a time we need to
representation of a time we need to parse it into a local time object but
parse it into a local time object but we'll need a formatter object we will
we'll need a formatter object we will create a date time formatter object
create a date time formatter object you'll need to import this class too
you'll need to import this class too we'll name this object
we'll name this object formatter
formatter equals we will access the class of
equals we will access the class of datetime formatter called the of pattern
datetime formatter called the of pattern method within this method we have to
method within this method we have to pass in a pattern a pattern that
pass in a pattern a pattern that represents the time for hours minutes
represents the time for hours minutes and seconds within a string we will pass
and seconds within a string we will pass in two Capital H's for hours colon two
in two Capital H's for hours colon two lowercase M for minutes colon two
lowercase M for minutes colon two lowercase s's for
lowercase s's for seconds when a user types in a string
seconds when a user types in a string representation of a time using our
representation of a time using our scanner we'll use this formatter object
scanner we'll use this formatter object when we parse it into a Time
when we parse it into a Time object then we will create a local time
object then we will create a local time object which we will name alarm
object which we will name alarm time we'll instantiate that later import
time we'll instantiate that later import this
this class now we'll need a user to enter in
class now we'll need a user to enter in the time we'll create a
the time we'll create a prompt enter n alarm time we'll give
prompt enter n alarm time we'll give them a prompt for this format hours
them a prompt for this format hours minutes
minutes seconds let me switch this to print CU I
seconds let me switch this to print CU I like it on the same
line let's create a string variable of let's name this input time
variable of let's name this input time equals use our
equals use our scanner call the next next line method
scanner call the next next line method to get a line of text from the
to get a line of text from the user all right now here's where we're
user all right now here's where we're going to parse our string our input time
going to parse our string our input time and assign it to our alarm time object
and assign it to our alarm time object so we have to convert it we have to
so we have to convert it we have to parse it we will assign our alarm time
parse it we will assign our alarm time object set it equal to access the class
object set it equal to access the class of local time and there is a parse
of local time and there is a parse method we have to pass in two arguments
method we have to pass in two arguments the first is a string representation of
the first is a string representation of our
our time and our format object that we have
time and our format object that we have previously declared and
previously declared and instantiated then we'll output the
instantiated then we'll output the following
following message alarm set
message alarm set 4 plus our alarm time we can output it
4 plus our alarm time we can output it directly let's do a test
run let's say I set my alarm for 730 this is going to be in military time
730 this is going to be in military time alarm set for
7:30 what if we type in a time that doesn't make
doesn't make sense uh like the word
sense uh like the word Pizza well we encounter an exception a
Pizza well we encounter an exception a date time parse exception we can use
date time parse exception we can use exception handling to catch this
exception handling to catch this exception I'm just going to copy it and
exception I'm just going to copy it and then paste it
then paste it later this portion is considered
later this portion is considered dangerous code we can put that within a
dangerous code we can put that within a try block try this dangerous code catch
try block try this dangerous code catch and any of the following
and any of the following exceptions we will catch that date time
exceptions we will catch that date time parse exception which we will name
parse exception which we will name e import this
e import this class okay then take all of this
class okay then take all of this previous code stick it within our Tri
previous code stick it within our Tri block we will try this code and catch
block we will try this code and catch this exception if it pops up we'll
this exception if it pops up we'll output the following let's say invalid
hours minutes seconds let me change that to
use I've already used Pizza let's go with Taco for the alarm time invalid
with Taco for the alarm time invalid format please use hours minutes
format please use hours minutes seconds let's try
seconds let's try 8:00 alarm set for
8:00 alarm set for 8:00 all right good we know that that
8:00 all right good we know that that works why don't we prompt the user to
works why don't we prompt the user to enter in the time again if it is an
enter in the time again if it is an invalid format we can use a while
invalid format we can use a while loop while some condition is true
loop while some condition is true continue to do the following let's cut
continue to do the following let's cut our code our trying catch blocks stick
our code our trying catch blocks stick it within the while loop what's our
it within the while loop what's our condition while our alarm time is empty
condition while our alarm time is empty there's actually a value that you can
there's actually a value that you can assign an object and that is null null
assign an object and that is null null has no value
has no value within our while loop we'll continue
within our while loop we'll continue this while loop while our alarm time is
this while loop while our alarm time is equal to a value of
null so if I were to just hit enter we get an invalid format please use hours
get an invalid format please use hours minute seconds and it won't let me
minute seconds and it won't let me continue until I enter in a valid
continue until I enter in a valid time so I will set this to be
time so I will set this to be 9:00 and then our alarm is set for
9:00 and then our alarm is set for 9:00 the first section of this project
9:00 the first section of this project is complete we have successfully set an
is complete we have successfully set an alarm time our alarm time is a local
alarm time our alarm time is a local time object the next part is to create
time object the next part is to create an alarm clock class to create alarm
an alarm clock class to create alarm clock objects we're going to create an
clock objects we're going to create an alarm clock class file new Java class we
alarm clock class file new Java class we will name this class alarm
clock we're going to have our alarm clock run on a separate thread to do
clock run on a separate thread to do that we can implement
that we can implement the runnable
the runnable interface so we can do some threading
interface so we can do some threading but if we implement the runable
but if we implement the runable interface it's kind of like we're
interface it's kind of like we're signing a contract we have to override
signing a contract we have to override the run method public void
the run method public void run when this alarm clock is running on
run when this alarm clock is running on a separate thread it's going to execute
a separate thread it's going to execute any code within the run method but we're
any code within the run method but we're going to fill that in later currently
going to fill that in later currently our alarm clock needs one thing it needs
our alarm clock needs one thing it needs an alarm time
an alarm time which we will send it from the main Java
which we will send it from the main Java file let's set that up as a
file let's set that up as a field with our alarm time I'm going to
field with our alarm time I'm going to make it private I only want the alarm
make it private I only want the alarm clock class to be able to change it I
clock class to be able to change it I will also make it final it's
will also make it final it's unchangeable the data type it's an
unchangeable the data type it's an object it's a local time object which we
object it's a local time object which we will name alarm time and then we do need
will name alarm time and then we do need to import this class too
to import this class too all right then we need a
all right then we need a Constructor we will take our alarm
Constructor we will take our alarm clock we need one parameter
clock we need one parameter currently a local time of alarm time we
currently a local time of alarm time we will assign this do alarm time equals
will assign this do alarm time equals the alarm time that we
the alarm time that we receive all right that's
receive all right that's good okay let's go back to our main Java
good okay let's go back to our main Java file before we close our scanner we're
file before we close our scanner we're going to create an alarm clock
going to create an alarm clock object alarm clock is the class we will
object alarm clock is the class we will name this object alarm clock equals new
name this object alarm clock equals new alarm clock but the way that we set up
alarm clock but the way that we set up this class is that we have to pass in an
this class is that we have to pass in an alarm time a local time
alarm time a local time object we have our alarm time we've
object we have our alarm time we've already verified it using this while
already verified it using this while loop it should be a valid format we will
loop it should be a valid format we will pass in our local time of alarm time to
pass in our local time of alarm time to the alarm clock in order to construct it
the alarm clock in order to construct it since our alarm clock is going to be
since our alarm clock is going to be running on a separate thread we'll have
running on a separate thread we'll have to create a new
to create a new thread thread let's name this alarm
thread thread let's name this alarm thread equals a new thread and then
thread equals a new thread and then we'll pass in our alarm clock we can do
we'll pass in our alarm clock we can do this because our alarm clock it
this because our alarm clock it implements the runnable interface so our
implements the runnable interface so our alarm clock is going to run on a
alarm clock is going to run on a different thread than the main thread to
different thread than the main thread to start a thread you will take your thread
start a thread you will take your thread in this case alarm thread called the
in this case alarm thread called the start
start method so once we start our alarm thread
method so once we start our alarm thread it's going to execute the run method all
it's going to execute the run method all right so for testing purposes let's get
right so for testing purposes let's get the time right now to get the time right
the time right now to get the time right now we will create a local time object
now we will create a local time object let's just call it now what's the time
let's just call it now what's the time right now equals access the class of
right now equals access the class of local time called the now method I will
local time called the now method I will display the time right now just for
display the time right now just for testing purposes I want to be sure that
testing purposes I want to be sure that our alarm clock class is
working so we have to enter in a valid alarm time I'll just set it to be 8:00
alarm time I'll just set it to be 8:00 a.m. alarm is set and here's the current
a.m. alarm is set and here's the current time right now at least for me I'm
time right now at least for me I'm filming this video at 7:26 in the
filming this video at 7:26 in the morning it is going to be in military
morning it is going to be in military time and then we have a bunch of
time and then we have a bunch of milliseconds after we know that we're
milliseconds after we know that we're successfully calling the run method
so we have the time right now we're going to compare times is the time right
going to compare times is the time right now before our alarm time if it is we'll
now before our alarm time if it is we'll continue sleeping we'll have our thread
continue sleeping we'll have our thread sleep we can delete this print statement
sleep we can delete this print statement I was just testing
I was just testing it we need to check if the time right
it we need to check if the time right now is before the alarm time if it is
now is before the alarm time if it is we'll continue
we'll continue waiting we can do this with the while
waiting we can do this with the while loop take our time right
loop take our time right now call the is before method we can
now call the is before method we can compare local times is the time right
compare local times is the time right now before our alarm
now before our alarm time if it is we're going to sleep for 1
time if it is we're going to sleep for 1 second access the thread class sleep for
second access the thread class sleep for 1,000
milliseconds all right we do need to surround this with a TR and catch block
surround this with a TR and catch block let's do
let's do that try and sleep for 1,000
that try and sleep for 1,000 milliseconds
milliseconds if this thread is interrupted we'll
if this thread is interrupted we'll output the
output the following thread was
following thread was interrupted this is if we encounter an
interrupted this is if we encounter an interrupted
interrupted exception we're checking the time right
exception we're checking the time right now is it before our alarm time if it is
now is it before our alarm time if it is let's output the time currently I'm
let's output the time currently I'm going to condense some of this code
going to condense some of this code outside of our while loop we're already
outside of our while loop we're already creating an object of now so why don't
creating an object of now so why don't we do this let's cut this line
and do the following access the class of local time call the now method and then
local time call the now method and then method chain the is before
method chain the is before method basically every second we're
method basically every second we're going to get the time right now and
going to get the time right now and compare it to our alarm time is the time
compare it to our alarm time is the time right now before our alarm time if this
right now before our alarm time if this while loop is running we'll output the
while loop is running we'll output the time so we'll output
time so we'll output local time called the now
local time called the now method let's do a test
run ENT turn an alarm time I'll just say 8:00 a.m. to keep it
8:00 a.m. to keep it simple alarm set for 8 a.m. and here's
simple alarm set for 8 a.m. and here's the current time it updates every 1
the current time it updates every 1 second approximately every 1
second approximately every 1 second now let's do some formatting
second now let's do some formatting because I don't like all these
because I don't like all these milliseconds afterwards
here's what we could do we could create an integer variable of ours set it equal
an integer variable of ours set it equal to access the class of local
to access the class of local time called the now method then method
time called the now method then method chain the get hour method to return the
chain the get hour method to return the number of
number of hours then we're going to do this with
hours then we're going to do this with minutes int minutes get
minutes int minutes get minute int second
second okay I'm going to show you what happens if I print ours plus a
colon plus minutes plus a colon
again plus seconds here's what we have currently
I will set this to be 8 a.m. alarm set for 8 a.m. so this looks
a.m. alarm set for 8 a.m. so this looks pretty good but I would like some
pretty good but I would like some leading
zeros we could do that with print F so let's switch this
let's switch this around print
around print f for print F We'll add some
f for print F We'll add some placeholders which we can use with a
placeholders which we can use with a percent sign to display two leading
percent sign to display two leading zeros we can use
zeros we can use 02 if we're going to insert an integer
02 if we're going to insert an integer we have to use D for decimal so let's do
we have to use D for decimal so let's do this three times 02 D percent 02
this three times 02 D percent 02 D we are inserting hours minutes and
D we are inserting hours minutes and seconds let's try it
seconds let's try it again I will set the time to be 8:00
again I will set the time to be 8:00 a.m.
oh and then I'm forgetting the colons and a new line
character so let's insert some colons and then add a new line character
colons and then add a new line character to the end because I forgot to do
that that's much better and we have that leading zero if one of these values is
leading zero if one of these values is one digit that looks pretty good now
one digit that looks pretty good now what we'll do rather than updating the
what we'll do rather than updating the time and placing it on a new line every
time and placing it on a new line every 1,000 milliseconds we're going to edit
1,000 milliseconds we're going to edit it in
it in place here's how with our print F
place here's how with our print F statement we're going to insert back SLR
statement we're going to insert back SLR this is for carriage return it'll move
this is for carriage return it'll move the cursor back to the beginning and
the cursor back to the beginning and then we'll get rid of the new line
then we'll get rid of the new line character it should look something like
character it should look something like this now
our time is going to update in place rather than take up a new line for each
rather than take up a new line for each time it
time it updates I think this looks a lot
better all right so we're going to condense some of these steps instead of
condense some of these steps instead of accessing the local time class three
accessing the local time class three separate times let's just do it once
separate times let's just do it once we'll create a local time object named
we'll create a local time object named now
now equals access the class of local time
equals access the class of local time call the now
method when we assign ours we will access our object of now now is our
access our object of now now is our local time now. getet hour for minutes
local time now. getet hour for minutes now doget minute and seconds now. getet
now doget minute and seconds now. getet second and then we'll insert them using
second and then we'll insert them using our printf
our printf statement or even instead of assigning
statement or even instead of assigning variables we could just call now doget
variables we could just call now doget hour now. get
hour now. get minute and now. getet second and we can
minute and now. getet second and we can delete these variables cuz we don't need
delete these variables cuz we don't need them just for readability I'll place
them just for readability I'll place these on a new
up all right this should work too let's make
sure yes it does you can keep this code the way it was
you can keep this code the way it was before but I like it a little more
before but I like it a little more concise all right our while loop is
concise all right our while loop is done so once we escape the while loop
done so once we escape the while loop that means the local time is our alarm
that means the local time is our alarm time or past our alarm time so for
time or past our alarm time so for testing purposes let's output the
testing purposes let's output the following let's just say alarm
following let's just say alarm noises we haven't added any audio yet
for my alarm time I'm just going to set it to be 1 minute past what it is
it to be 1 minute past what it is currently in this case 7:44 but pick a
currently in this case 7:44 but pick a different time depending on what time it
different time depending on what time it is for you
is for you currently so I just need to wait for 20
seconds all right once we reach our alarm time or it's past our alarm time
alarm time or it's past our alarm time we display alarm noises and then exit
we display alarm noises and then exit the
the program I'm going to add a new line
program I'm going to add a new line character just before we display alarm
character just before we display alarm noises for our alarm we'll be playing
noises for our alarm we'll be playing some music later just for now we're
some music later just for now we're going to play a single beep just to be
going to play a single beep just to be sure that everything is working
sure that everything is working basically to have Java make a beep noise
basically to have Java make a beep noise you can do the following access the
you can do the following access the class of tool kit call the
class of tool kit call the get
get default toolkit
default toolkit method call the beep method and then we
method call the beep method and then we do need to import this
do need to import this class once we escape the wild Loop we
class once we escape the wild Loop we will display alarm noises and make a
will display alarm noises and make a beep sound a single
minute there we go we display our text of alarm noises
go we display our text of alarm noises and hopefully you heard that beep so we
and hopefully you heard that beep so we know that our alarm arm clock is working
know that our alarm arm clock is working to make a more sophisticated version
to make a more sophisticated version we're going to play an audio
we're going to play an audio file I have an audio file here it's a
file I have an audio file here it's a wave file the following code isn't going
wave file the following code isn't going to be compatible with MP3s if you do
to be compatible with MP3s if you do have an MP3 file you can always use an
have an MP3 file you can always use an online MP3 to wave converter that's what
online MP3 to wave converter that's what I did to make this convenient for me I'm
I did to make this convenient for me I'm going to place this wave file within my
going to place this wave file within my project
project folder here's my wave file going back to
folder here's my wave file going back to our main Java file I will create a
our main Java file I will create a string variable a file path string file
string variable a file path string file path
path equals here I can list a relative file
equals here I can list a relative file path or an absolute file path this wave
path or an absolute file path this wave file is within my project folder I just
file is within my project folder I just need to list the file name so I'm going
need to list the file name so I'm going to copy
to copy path file
path file name and paste it within that
name and paste it within that string with our alarm clock we're going
string with our alarm clock we're going to send it our file path we'll send it
to send it our file path we'll send it as the second argument along with the
as the second argument along with the alarm time but we have to set up the
alarm time but we have to set up the Constructor so that we can accept
it with our alarm clock class we will create a private final string of file
create a private final string of file path then we'll have to set up the
path then we'll have to set up the parameters we are also accepting a
parameters we are also accepting a string of file path the location to that
string of file path the location to that file to play the
file to play the audio this. file file
audio this. file file path equals the file path that we
path equals the file path that we receive with playing audio there's a lot
receive with playing audio there's a lot of code we have to write I'll dedicate
of code we have to write I'll dedicate an entire method just to playing
an entire method just to playing audio let's make this a private method
audio let's make this a private method so only our alarm clock can access it
so only our alarm clock can access it it's not going to return anything the
it's not going to return anything the return type is void let's name this
return type is void let's name this method play
sound once we reach the end we will call the play sound
the play sound method but we're going to pass in our
method but we're going to pass in our file
file path so we need a parameter setup of
path so we need a parameter setup of string file
string file path and now we are within the play
path and now we are within the play sound
sound method to play a w file we're going to
method to play a w file we're going to create a file object named audio file
create a file object named audio file equals a new file and then pass in our
equals a new file and then pass in our file path
import this class we'll be doing a lot of importing
class we'll be doing a lot of importing as we go
as we go along then we need to create an audio
along then we need to create an audio input
input stream audio input
stream audio input stream we'll name this audio
stream we'll name this audio stream
stream equals access the class of audio
equals access the class of audio system called the get audio input stream
system called the get audio input stream method
method yes that's a lot to
yes that's a lot to type then we will pass in our audio
type then we will pass in our audio file import this
class import the class for audio system to there's a lot of different exceptions
to there's a lot of different exceptions that we'll need to catch such as if our
that we'll need to catch such as if our audio file is unsupported like it's an
audio file is unsupported like it's an MP3 file we'll need some try and catch
MP3 file we'll need some try and catch blocks try this code catch any
blocks try this code catch any exceptions
exceptions here's one we'll start
with we will catch any un supported audio file
supported audio file exceptions which we will name e import
exceptions which we will name e import this
class if we encounter this exception we'll output the
we'll output the following audio file format is not
following audio file format is not supported
if the audio is unavailable for some reason let's say another resource is
reason let's say another resource is accessing it we can catch that
accessing it we can catch that too that exception is a
too that exception is a line unavailable exception line
line unavailable exception line unavailable exception of
unavailable exception of e let's say something like audio is
unavailable import the class then as a safety net
class then as a safety net we will catch any IO exceptions input
we will catch any IO exceptions input output
output exceptions IO exception e here we'll
exceptions IO exception e here we'll just
just say error
say error reading audio file it is good to catch
reading audio file it is good to catch specific kinds of exceptions first which
specific kinds of exceptions first which we are doing this just acts as a safety
we are doing this just acts as a safety net so with modern Java you can try with
net so with modern Java you can try with resources you'll automatically close
resources you'll automatically close those resources when you're done with
those resources when you're done with them when we create our audio input
them when we create our audio input stream let's cut all this
stream let's cut all this code and paste it within the triy with
code and paste it within the triy with resources block then delete that
resources block then delete that semicolon so we have our audio stream we
semicolon so we have our audio stream we need to create a clip object a clip acts
need to create a clip object a clip acts as a player that plays an audio stream
as a player that plays an audio stream within the tri block we will create a
within the tri block we will create a clip object clip
clip object clip clip equals access the class of audio
clip equals access the class of audio system system called the get clip method
system system called the get clip method to create a clip
to create a clip object import this
class then we will use our clip and open our audio stream
object to get the clip to play we will call the start method of our clip
call the start method of our clip clip.art
clip.art method one issue we're probably going to
method one issue we're probably going to run into is that once we we start
run into is that once we we start playing the clip the program is going to
playing the clip the program is going to end immediately so we might not even
end immediately so we might not even hear it so temporarily I'm just going to
hear it so temporarily I'm just going to sleep for a couple
sleep for a couple seconds let's just sleep for 5
seconds let's just sleep for 5 seconds and then I do need to add a
seconds and then I do need to add a catch clause for any interrupted
catch clause for any interrupted exceptions we'll be deleting this don't
exceptions we'll be deleting this don't worry I just want to be sure that it
[Music] we played our music for 5 seconds and
we played our music for 5 seconds and then we exit the program what I would
then we exit the program what I would like to do instead is that we stop the
like to do instead is that we stop the alarm if we hit enter here's how we can
alarm if we hit enter here's how we can set that up we can delete this method
set that up we can delete this method where we sleep for 5 seconds instead
where we sleep for 5 seconds instead we'll wait for a user to hit enter and
we'll wait for a user to hit enter and delete that catch statement too
delete that catch statement too we're going to be using a scanner within
we're going to be using a scanner within a big project different parts of your
a big project different parts of your project may require different scanners
project may require different scanners but I like to just reuse the same one
but I like to just reuse the same one the problem with having multiple
the problem with having multiple scanners is if they use system.in and
scanners is if they use system.in and one scanner closes
one scanner closes it it's going to close system.in for all
it it's going to close system.in for all of them so rather than close the scanner
of them so rather than close the scanner at the end of our main Java file we're
at the end of our main Java file we're going to do that within the alarm clock
going to do that within the alarm clock class when everything is all done so
class when everything is all done so we'll do that at the end of the tri
we'll do that at the end of the tri block however our alarm clock class has
block however our alarm clock class has no idea what the scanner is we're going
no idea what the scanner is we're going to send it as an argument to the alarm
to send it as an argument to the alarm clock class so we'll need to set that up
clock class so we'll need to set that up we will pass in our scanner and reuse it
we will pass in our scanner and reuse it within the alarm clock
class within the alarm clock class we will create a private final scanner
will create a private final scanner object which we will name
object which we will name scanner import this
scanner import this class set up the
class set up the parameters we will receive a scanner
parameters we will receive a scanner object that we can use throughout the
object that we can use throughout the alarm clock
alarm clock class this do scanner equals the scanner
class this do scanner equals the scanner that we receive all right and now we
that we receive all right and now we have access to that same scanner the
have access to that same scanner the same one that we have instantiated at
same one that we have instantiated at the beginning of our
the beginning of our program and remember we are not closing
program and remember we are not closing it at the end of the main Java file
it at the end of the main Java file anymore
anymore once our alarm is playing we will wait
once our alarm is playing we will wait for some user input let's create a
for some user input let's create a prompt we'll say
prompt we'll say press
press enter to stop the
enter to stop the alarm I'm going to use
print we will use our scanner called the next line
next line method our music is going to continue
method our music is going to continue playing until we hit
playing until we hit enter once the user hits enter we we are
enter once the user hits enter we we are going to take our clip and call the stop
going to take our clip and call the stop method then close the scanner when we're
method then close the scanner when we're done with
done with it and that should be everything let's
it and that should be everything let's run this one last
to get our alarm to stop we just have to press
press [Music]
[Music] enter and the alarm stops and we exit
enter and the alarm stops and we exit the
the program all right everybody that is a
program all right everybody that is a working alarm clock that you can write
working alarm clock that you can write using Java
Click on any text or timestamp to jump to that moment in the video
Share:
Most transcripts ready in under 5 seconds
One-Click Copy125+ LanguagesSearch ContentJump to Timestamps
Paste YouTube URL
Enter any YouTube video link to get the full transcript
Transcript Extraction Form
Most transcripts ready in under 5 seconds
Get Our Chrome Extension
Get transcripts instantly without leaving YouTube. Install our Chrome extension for one-click access to any video's transcript directly on the watch page.