Transcript for:
Comprehensive Java Coding Guide

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 relax and enjoy the 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 link then we just have to wait for it to download the download is complete we're going to open this executable select next 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 running Windows I will download the 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 think I will just for convenience 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 this but we'll just select next and 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 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 small here's how to change that go to the top toolbar go to settings go to 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 shift plus 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 favorite food is whatever you typed here let's add another line of code again type 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 this I like pizza it's really 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 pizza and I'll add a new line character I like pizza it's really good buy me pizza or again you could use print line so print Ln for print line and this will do the same 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 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 line let's print age and see what it 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 then we'll print our 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 one or 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 quotes So currently this says the year 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 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 dollars and cents $19.99 or perhaps a GPA a grade point average double GPA equal 3.5 or a temperature double temperature equals 12.5 all right let's output some of these let's do Price system.out.print Line let's output the price 19.99 let's add a unit of currency I'll pick American dollars 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 something or maybe a symbol 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 system.out.print line let's print our 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 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 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 name and then we will output our name system.out.print Line Print your 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 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 food your favorite food is pizza what about an email string email equals make up an email fake1 [email protected] 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 is plus email your email is fake1 [email protected] 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 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 double system.out.print line your GPA is then we will insert our GPA your GPA is 3.5 okay let's use our Char of 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 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 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 currency and a price system.out.print line the price is plus currency I picked American dollars plus 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 let's say $9,999 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 going to print there is a plus Car Plus the text of for sale else we will print something else I'll just copy this let's say the plus Car Plus is not for sale for sale currently that's set to false the Mustang is not for sale but if this were 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 to variables in 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 Line enter your 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 let's say hello plus 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 don't want any spaces you can use next 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 r plus our variable age plus years old 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 I think it'll look 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 instead of 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 not enrolled 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 false now if we put true 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 accepting a string let me 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 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 Age years old as well as you like the color plus our variable color here's what 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 zero and double area I will set that to be zero we're going to accept some user 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 these two lines then change width to height all right let's test it currently let's make up some numbers 3.1 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 our width times our 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 4.3 the area is 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 areas so let's say 5.3 and 6.4 the area is is 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 a scanner is going to help us accept user input we'll declare that and assign it scanner scanner equals new scanner parenthesis semicolon then within the parenthesis we will type 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 story we'll have four 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 zoo in an 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 period we'll say noun one was plus adjective two and our verb verb one then add some punctuation so we could say that harambe was big and sleeping so a verb is an 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 five print statements we will prompt the user to enter an adjective enter an adjective I'll give a hint that an adjective is a description we're describing something enter a noun enter a noun I'll give a hint that we are looking for a animal or 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 action and then another adjective all right now we just need to assign these variables we've already declared them adjective one equals take our scanner use the next line 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 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 description I'm going to say 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 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 can write using 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 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 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 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 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 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 X -- now X is -1 x -- X is -2 so those are the increment and decrement operators you'll see these again when we reach the topic on Loops the last thing I need to discuss today is the order of operations and there's an acronym PEMDAS it's parentheses exponents multiplication division addition then subtraction in that order you may hear the phrase to remember this please excuse my dear Aunt Sally but I like the phrase please excuse my dope ass swag that's my version that I like to use let's say we have the equation double result equals 3 + 4 time parentheses 7 - 5 divided by 2.0 I'm dividing by 2.0 because right now we're using integer division which we previously talked about so I'm going to use 2.0 so we retain that decimal portion again that's a topic for another day let's display the result so I don't know what the result is but it is 7 7.0 in what order do we solve this equation exactly well we can use that acronym of pendos from the left to the right we solve anything within parentheses first so going from the left to the right we skip over any addition multiplication we're looking for parentheses which we have right here if you enclose part of an equation within parentheses you would solve that first 7 - 5 is 2 there's no more parentheses then we check any exponents there are no exponents multiplication well we have multiplication right here we would solve that next 4 * 2 is 8 there's no more multiplication then we have division we have 8 / 2 which gives us 4 then any addition 3 + 4 is 7 and that was our original result and then you would do any subtraction last so that is the order of operations when it comes to arithmetic operators all right everybody so that is some basic arithmetic and different operators you can use in Java hey everybody so in this video we're going to create a shopping cart program a user is going to be able to type in an item set a price for each and then ask for a quantity the output is that it's going to give you a total based on the price and how much you're buying this would be a good exercise for us to get us more comfortable with accepting user input all right let's get started everybody we'll need the help of a scanner the scanner allows us to accept user input we'll need to import that at the at the top so be sure that you have this line of code import java.util.scanner we'll create a scanner object scanner scanner equals new scanner parentheses semicolon type system.in then if we open a scanner it's good practice to close it when we're done with it scanner. close if you leave resources open it can lead to unexpected behavior when creating a project I like to declare all of my variables at the top let's say we have an item name that data type is going to be a string string item what are we buying exactly we need a price that would be a double because there might be dollars and cents a quantity how many of something are we buying int quantity pick a unit of currency this could be a character char currency I'm going to initialize this right away American dollars and then a total we're going to multiply the price by the quantity to give a total double total now if you would like you can initialize some of these right away and assign them for example let's say we are at a pizza restaurant I could set the item to be pizza right away or within this program we could fill it in then let's create some prompts I'll use system.out.print what item would you like to buy then let's accept user input we're going to assign our string of item equal to use our scanner object and use the in next line 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 will output hamburger we know that we can get user input so let's delete this line I was just testing it let's ask for a price you could set an initial price if you would like or we could ask for one depending 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 double we'll use the next Double method we're going to assign our price equal to use our scanner. next 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 $4.99 and that outputs $4.99 so it is a good idea every once in a while to test your code just to be sure that it all works as you go along then we'll need a quantity let's ask how many would you like we will assign our quantity variable equals scanner. next int since we're working with whole numbers this time then let's test our quantity to see if it works I don't know maybe I'm buying a hot dog this time what is the price per each $4.99 how many would you like I would like 12 hot dogs 12 and I'm just going to make sure I'm 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 the variables that we've already had after assigning them total equals the price times the quantity and then I will just test the total maybe I'm buying a pizza or pizzas each is $4.99 and I buying three of them 44.97 instead let's output the following I'm going to use a new line character just to separate our output from the prompts you have bought plus our variable of quantity plus a space character plus our variable item but it might be more than one so let's say/ s it might be pizza or 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 character I picked American dollars but pick whatever you would like plus our total that we have calculated all right let's see the result what item would you like to buy I would like to buy a pizza what is the price for each $4.99 how many would you like I would like eight pizzas maybe it's for a party you have bought eight pizzas your total is $19.92 all right everybody so that is a 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 statement performs a block of code if its condition is true we've discussed how Boolean variables can be used within if statements we may be a little familiar with them already in this demonstration we will have a variable of age set it equal to be some age age will be an integer I would like to check if my variable of age is greater than or equal to 18 if so we can print a message that you are an adult to write an if statement will type if parentheses curly braces within the set of curly braces we can check a condition 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 adult now if this condition was false if it's not true let's say that my age is 12 well then we skip over the if statement we check if this condition is true if it is we perform this code if not we skip it alternatively we could add an else clause this would be another statement we would add else if this is false then do something else so let's output the following you are a 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 possibilities do this or do that now we could add something called else if Clause let's check else if age is less than zero if this statement is true then let's say you haven't been born yet now we're doing one of three things but it all depends on these conditions our else Clause is kind of like the default if none of the above conditions are true so let's test this my age variable is set to 19 this would display you are an adult if my age variable was -1 we would display you haven't been born yet this statement was false so we go down to the next one this is true NE 1 is less than zero so we do this or if I was 10 well then these top two conditions are both false so we do whatever is within the lse statement you can add as many else if Clauses as you would like so here's another one else if our variable age is equal to zero exactly double equals is the comparison operator we're checking if a variable or a value is equal to another value or variable you don't want to use single equals because that's the assignment operator Java thinks we're trying to assign a variable when making a comparison you use double equals is our variable age equal to zero then we'll print something else okay we're going to print you are a baby I will set variable H to be zero you are a baby because our variable age is equal to zero exactly let's add another L statement there's something I want to demonstrate let's check to see if age is greater than or equal to 65 then we will print you are a senior I'll set age to be 70 here's the result you are an adult so why did we print this statement rather than this one well with these if statements we check them from the top down this condition is technically true as well as this one 70 is greater than or equal to 18 so we execute this code and skip over the rest even though this one is also true you do have to pay attention to the positioning of your if and else if statements in this situation it would be better if we were to check to see if somebody's age was greater than or equal 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 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 slightly this time we will ask for user input we'll need the help of a scanner at the top of our Java file we're going to import java.util dothe class of scanner we'll need to create a scanner object scanner scanner equals new scanner within the set of parentheses type system.in then when we open a scanner it is a good idea to close it when we're done with it just so we don't leave any resources open with our variable of age we're going to create a prompt to have a user enter in their age I'm going to declare a variable of age but we'll assign it later let's create a prompt enter your age I'll use print instead of print line and then we will assign age equal to scanner. next int okay let's try this 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 haven't been born yet I am zero exactly you are a baby or maybe I'm 10 you are a child so with if statements we check a condition if it's true we do it we do this code if not we don't otherwise we can check another condition with else if and if none of these conditions are true we can perform whatever is within an else statement else acts like the default code if none of the above conditions are true now this time we're going to work with strings we're going to create a variable of name and it's going to be a string we'll declare it but not yet assign it we will prompt the user to enter in their name I will use print instead of print Line enter your name we will assign our variable of name 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 two we're going to create another set this will be group one for the name when somebody enters in their name they could skip the prompt like this enter your name I'm just going to hit enter to skip it we will check if our name variable is empty here's how if we'll check if our name is empty there's a string method for this we haven't discussed string Methods yet instead of saying name is equal to an empty space there is a built-in method of strings and that is to take our variable name dot is empty this is another way to check to see if a string is empty this will be our condition is empty will give you a Boolean of true or false so let's print the following if our name variable is empty let's say you didn't enter your name else if our name is not empty that means somebody typed in their name let's say hello plus name and I'll add an exclamation point okay let's try this again enter your name if I hit enter we'll perform then whatever is within the if statement then enter an age you didn't enter your name you are an adult this time let's type in our name our first name hello whatever your name is you are an adult this time we have two groups of if else statements group one is for the name group two is for the user's age this time let's create a Boolean Boolean is student then we'll create a prompt let's ask are you a student but we need a value of true or false cuz booleans can only be true or false 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 statements group three we need an if statement so with booleans we could say is student is equal to true but there is a way to simplify this a shortcut you can just say is student it holds a direct value of true or false we don't necessarily need to write like a whole condition so if we're a student we'll output you are a student else if a student is false then we'll output you are not a student we have three groups of if else statements group three is for is student group two is for the age group one is for the name just to make this more fun I'm going to add some emojis I think it would make it more interesting but you don't have to so if somebody doesn't enter their name I'm going to add a pouting face if somebody enters their name I will add a smiley face if somebody is a senior maybe we can find an emoji for a grandpa let's find one for an adult you haven't been born yet uh we could do like a spirit or something you are a baby you are a child you are a student we could do a school you are not a student we could do an office all right so this is our final program again we have three groups of if statements this time one for the name one for the age and one for is student and then for the prompt for are you a 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 let's try some of the other statements I'm not going to enter a name for the age let's say that I'm ne1 are you a student true you didn't enter your name you haven't been born yet you are a student so those are if statements everybody they perform a block of code if its condition is true check a condition if it's true do this if not you can do something else and well everybody that summar mizes if statements in Java hey everybody in this video I'm going to show you how we can work with the random class and generate some random numbers let's begin to work with random numbers we'll need to import the random class at the top of our Java file we will import java. u. random much like what we do with the scanner class we're going to follow a similar pattern for creating a random object much like a scanner object we will type the name of the class random the name of the random object random equals new random so random random equals new random let's say we have an integer an integer variable of number I'm going to assign our number variable equal to and here's where we'll generate a random number we will take our random object then we will use the next int method this will generate a random number however there's one issue with this I'm going to print our number the number is going to be very large so the random number that's generated it's going to be within a range between just about -2 billion and positive2 billion I'm guessing you don't want a number that big So within the next integer method we can set some bounds if I would like a random number between 1 and six like I'm rolling a dice or die I would say 1 comma 6 this 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 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 will give us 1 through six and there's six let's say this time you would like three random numbers you're rolling three dice let's say we have number one number two and number three all integers we'll assign number one with a random integer and we'll do this with numbers two and three as well number one number two number number three then we will print them number one number two number three 2 46 23 4 225 good enough for random numbers between 1 and 100 the second number is going to be 101 because it's exclusive so now we're generating three random numbers between 1 and 100 not only can you generate random numbers you can Generate random doubles so let's set this back to be 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 one just the decimal portion really you can also generate a Boolean this might be good in a situation where you need to flip a coin let's say we have a Boolean of is heads when we flip a coin is it heads random. nextext Boolean then we will display if the coin we flip is heads or not is it heads or it's Tails that's true it is heads now it's false it's Tails we could even use an if statement if is heads if our coin flip is on heads let's print heads else we will print Tails so this will simulate us flipping a coin we're getting a lot of Tails all right everybody that is how 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 constants and methods that you may be interested in as a beginner then at the end of this topic we'll cover a few exercises let's begin if at any time you need the value of pi there's a built-in constant of the math class so I'm going to print the following math with a capital M Pi all capital so that would give you the value 3.14 and some change so instead of creating a variable for pi it's always available to you within the math class you just have to access it there's also E math. capital E this is the exponential constant also known as ul's number you may never use this but it's available to you in case you do so again access the math class Dot to name the constant this time let's create a double variable named result here's a few methods I'm going to reassign result equal to access math dot to raise a base to a given power you can use the pal method let's raise 2 to the^ of 3 then print it let's print our variable result 2 ^ of 3 would be 8 and again I'm using a double that's why we have the decimal portion 2^ of 4 would be 16 2 the^ of 5 is 32 po meaning power you can raise a base to a given power these can be values or variables there's the 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 method gives you that number but positive if it's negative think of it as the distance away from zero if that helps for square root there's a square root method result equals math.sqrt what is the square root of 9 I did make a spelling mistake here if you're accessing the math class make sure it's 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 the round method let's round 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 method math. c l again I accidentally used lowercase M it's capital M let's round 3.14 up to the ceiling so 3.14 rounded up is four to always round down you can use the floor method math. floor so this time let's round 3.99 down normally it should round up right so 3.99 rounded down is three you can find the max between two values or variables math. Max method we'll have two numbers which are comma separated 10 and 20 what 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 replace Max with Min what is the minimum value between these two values that would be 10 so those are a few useful math methods and constants that you may be interested in we're going to cover some math related exercises if you would like additional practice in this first exercise we're going to find the hypotenuse of a right triangle you can follow this formula C the hypotenuse equals the square root of a^ 2 one of the sides plus b^2 the other side we're going to accept some user input we'll need a scanner we need to import the scanner class import java.util do scanner then we'll create a scanner object scan scanner scanner equals new scanner then place system.in within the set of parentheses then when we open a scanner it is a good idea to close it so we don't leave any resources open scanner. close we'll prompt the user to enter in the length of side A and B let's declare those as variables double a double b we'll also declare Double C that will store the hypotenuse Double C we'll need two prompts I will use print instead of print Line enter the length of side a with inside a within our variable of a we'll assign it to scanner. next Double let's do this with side B we can copy these two lines paste them replace a with B that is lowercase b let's do a test run just to be sure 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 that it is a good idea to test your code as you're writing it then we have to follow this equation C equals math. square root of a^2 + b^2 there is a square root method within the math class but we have to raise side a to the power of two plus b to the^ of two here's how we can do that so within the square root method we're going to raise a to the power of two first math po to raise a base to a given power raise a comma to the power of two plus again math.pow to raise a base to a given power B to the power of two and that's it so let's display whatever C is the hypotenuse the 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 would prefer we can add a unit of measurement such as centimet or inches so after side C add cm for centimet or I for inches whatever you prefer so let's try that again side a will be four side B will be five and side C is this really long number we haven't talked about the print F statement yet using print F you can display a given amount of digits but we do have centimeters at the end which is what we were looking for so let's try 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 the area then the volume that's if we're working with the sphere given the radius so be sure that we're importing our scanner at the top and we'll create a scanner object scanner scanner equals new scanner system.in then be sure to close your scanner scanner . close we'll prompt the user for a radius because we need a radius to work with we'll create a variable it will be a double named radius we'll declare it but not yet assign it we'll prompt the user using print instead of print Line enter the radius then we will assign our radius variable radius equals scanner. next Double once we have a radius we have to follow these formulas so we need a circumference area and volume let's declare those at the top of our program but assign them later double circumference I think I spelled that right double area double volume we will calculate the circumference here's the Formula 2 times we need pi to work with instead of typing 3.14159 so on and so forth we can access that from the math class math.pi Pi is always available to us then multiply this by the radius let's perform a test run I will display the circumference the circumference is plus our variable of circumference then I'll add a unit of 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 future using print F we can limit the amount of digits that are displayed I'll show you how to do that later on in this video then we need the area area equals here's the formula again we need Pi Pi is always available to us math. pi times our radius to the^ of two so we need the power method of math math.pow raise the radius to the power of two and I'll just copy this line because I'm lazy the area is our variable area now when working with an area the unit of measurement is going to be squared so we can raise it to the power of two or you can use superscript to if you're on Windows make sure numlock is on hold alt then on the numpad type 0178 for a superscript of two if you would like to use that instead so now what is the area enter the radius 5 the area is 78.53982 doubles times math. pi and again make sure the m is capital times our radius to the^ of 3 math. power method raise our radius to the power of three then display the volume the volume is our variable volume cm cubed for a superscript of three make sure numb lock is on hold alt then type 0179 that's if you're on Windows all right let's print the volume again my radius is five then we have the circumference the area and the volume and the unit of measurement is cenm cubed now we haven't talked about the print F statement we could display just a few digits here's 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 placeholder percent F to display a double but if you would like one digit between the percent and F type .1 so let's do this with area and volume replace the plus with a comma then instead of adding plus centim after our placeholder add CM then cm squar and cm 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 end of each of these that looks much better we're only displaying one digit after the decimal again don't worry about this this is a future topic the print F statement but if you would only like to display one digit that's how you can do that again we'll cover this later all right everybody so those are a few 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 statement in Java print f is a method used to format output we already do have a little bit of experience using print F in the last few topics involving math we'll get more in depth with the print F stat in this topic print f is an alternative to print and print line wherever we would like to insert a variable we can add a placeholder of a percent sign then add one of a few characters following it to format the output in this demonstration let's create a few variables let's create a string of name I'll assign some name I'll pick SpongeBob because many people know who SpongeBob is we'll need a character let's say character first letter equals s int age equals 30 and a double double height equals 60.5 and a Boolean Boolean is employed I will set that to be true SpongeBob is employed at the K crusty Krab so we have some variables they're all different data types we can insert 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 F we will display the following hello then I would like to insert this variable of name we're going to use a percent sign as a placeholder percent then we need a specifier our character what is the data type of the variable we're trying to insert if you're trying to insert a string you're going to use a lowercase s so after this word of hello we're adding a placeholder then inserting a string at this location so instead of adding plus the variable name we're going to comma separate any variables we're inserting so comma name here's the output hello our variable name which contains SpongeBob if we need to insert a character that would be lower case C so let's use system.out.print F I don't know let's say your name starts with a we're going to insert a variable we need a placeholder that perent sign lower case C for a Char 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 manually insert any new line characters we'll end each print F statement with a new line 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 line so that's how to insert a character percent C for chars then for an integer we use D so print f u r we're going to insert a variable we use D for integers you are our variable age years 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 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 double inches tall or you can pick centimeters up to you then we will insert our variable of height you are 60.5 then a bunch of zeros inches tall we can limit the amount of digits that are displayed after the decimal we'll have to set a Precision but I'll explain that later then a Boolean all we need is the letter b system.out.print f let's say employed add a placeholder B then a new line character we will display our variable of is employed employed then our variable of true now you can insert multiple variables within the same line here's how we'll use system.out.print f we're going to inst insert our variable of name SpongeBob for a string the specifier character is going to be lowercase s for a string so string SpongeBob is we're inserting an integer we need percent D years old we'll comma separate all variables we're inserting we have a string followed by an integer so that would be name comma age we're inserting two variables of this time SpongeBob is 30 years old so those are specifier characters add a percent sign a placeholder then follow this placeholder with a specifier character depending on what the data type is s for Strings C for chars D for integers f for doubles or other floating Point numbers and B for booleans it might take a little bit of time to remember these now we'll cover Precision with setting the Precision we can limit the amount of digits that display after a decimal let's create three different 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 $41 we're going to use print F to display these prices system.out.print F we're going to insert we'll use that percent placeholder then use f to display a double f for floating Point number comma our variable of price one then we'll do this with price two and price three price one price two price three and here are the prices oh and we have to add a new line character too because they're all in the same line I forgot to do that so back sln back sln back sln that's better naturally when we're using print F to display a floating Point number such as a double normally it displays six digits after the decimal point but we would like to limit that here's how we're going to set the Precision to display one digit after the decimal between the percent sign and the F Type .1 to display one digit so we have 10.0 this will automatically round the output so we have 10.0 100.2 and 54.0 for two digits that would be 02 999 10.15 and 54.1 or we could do three 3F then we have three digits after the decimal so that is precision it's useful 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 we can output a plus for any positive numbers positive 999 positive 10.15 54.1 is still negative to display a plus before any positive numbers just add a plus sign let's increase these 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 thousand's place after the percent sign add a comma at any thousand's place we have a comma grouping separator again this is useful for displaying prices by adding a single left parentheses any negative numbers are enclosed in a set of parentheses so let's revert these 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 space space if positive we have two positive numbers in one negative one so by using a space character any positive numbers are preceded with a space 54.1 is negative so we do not have that space it's good for aligning numbers the last specifier we have to talk about is width we're going to create some ID numbers these will be integers int id1 = 1 int id2 = 23 in ID3 equal 456 and int id4 equals 7890 these integers have a varying number of digits 1 2 3 4 by setting the width we can align them here's how again we're going to use print F we're displaying an integer so we need percent D we will Begin by displaying id1 then let's do this with 2 three and four as well 2 3 4 and again I am missing that new line character new line new line new line new line that's better so we have our four 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 these numbers with zero let's say four we have one variable 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 padded and they align vertically which is kind of nice so to add some zero padding follow our placeholder with zero then the amount of digits to Zer pad in this case four by setting a positive number we can WR justify these variables so let's replace zero with just four rather than having that zero padding we just have some spaces if you would prefer it that way or with a negative number we can left justify these values so let's set four to be instead -4 now these values are left Justified and we still have those spaces afterwards except for the last variable because it's already four digits all right everybody so that is the print F statement it's a method used to format output you add a placeholder then one of a few characters afterwards there is Flags width precision and specifier characters depending on the data type of what you want to display we'll have more 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 compound interest calculator using Java if you put money in a bank account or the stock market using the given formula we can determine what our final amount is going to be plus interest after a given amount of time this project serves as an exercise using Java let's begin all right let's get started everybody the first thing we'll need is a scanner we'll need to import it at the top of our Java file import input import java.util.scanner we need to create a scanner object again scanner scanner equals new scanner then within the set of parentheses type system.in when you open a scanner it is good practice to close the scanner when you're done with it so you don't leave any resources open after creating our scanner here the different variables we'll need double principal this will store the principal amount what's our original investment an interest rate double rate an integer for times compounded how often does our interest compound like yearly quarterly monthly then we need an amount of time such as years into years and the final amount double amount now we have to get some user 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 principal amount we are working with the double so we need the next Double method of our scanner principal equals our scanner do next Double then we need the interest rate this is going to be a double system.out.print enter the interest rate I'll add within our prompt that this is in a percentage form like 5% or so the number five instead of 05 so then we have our interest rate so we need our scanner do next double so let's say somebody types in five for 5% we would like the rate to be 05 rather than 5 after accepting the user input let's divide that number by 100 or let's say somebody types in seven we don't want the rate to be seven we want it to be 07 that's why we're dividing by 100 we'll fill in the times compounded variable we're going to use print enter the number of times compounded per year so this could be yearly that would be one quarterly four or monthly would be 12 in most cases it's probably going to be one for yearly times compounded equals use our scanner next int cuz we're accepting an 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 variable years years equals scanner. next int because we're working with an integer then we need to calculate the total amount here's the formula amount equals we need our principal amount times access the math class use the power method raay is 1 plus the interest rate divided by the variable times compounded so this is going to be the base we Comm separate the base and the power we are raising this part of our equation to the power of times compounded times the number of years and that's our formula it's a little confusing but it should work then we will display the amount system.out.print line the amount after plus years plus is pick a unit of currency I'll pick American dollars plus amount let's test this so let's say we have $10,000 or so and we're putting it in the bank what is the interest rate maybe 3% so I'm going to type three enter the amount of times compounded per year I'll go with one enter the number of years one so we should have 10,300 in our bank which we do 10,300 if you would like you can use a print F statement to format the output so if you're familiar with that let's replace print line with print F instead of concatenating these variables we'll add some placeholders instead so to display an integer we need percent D within print F years is then to display a double we need percent F then we'll list our arguments years comma amount so to display two decimals within a double between the percent and the F we're going to type 2 to display two digits after the decimal we'll proceed this placeholder with the unit of currency let's do American dollars okay let's see the total amount enter the principal amount $110,000 enter the interest rate 2% enter the number of times compounded per year this time let's do quarterly so four because there's four quarters in a year enter the number of years let's do two 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 write using Java what is going on everybody in this video I'm going to explain nested if statements in Java in Java it is possible to have if statements within other if statements kind of like this after checking some condition you could follow with another condition if the first condition is true you can add if statements L if statements and or else statements really depends on the program that you're trying to write so what we're going to do in this demonstration is have two Boolean variables a Boolean of is student let's say that we're selling movie tickets if somebody's a student they get a 10% discount on their movie ticket we also have a senior discount Boolean is senior if somebody is 65 or older they get a 20% senior discount or if they're a student and a senior they get a combined total of 30% off their ticket price let's say we have a double of price the price of a movie ticket will be $9.99 let's say that's actually kind of cheap nowadays we'll write an if statement to check to see if somebody is a student if is student is equal to true but since this is a Boolean variable we don't need the equals true portion we can just say if is student I will go ahead and set this to be true right away so if somebody is a student they get a student discount else they won't so if a student is true let's output the following you get a student discount of 10% then we will take our price price equals price time 0.9 that will give you a 10% discount account you could shorten this using the augmented assignment operator price times equals 0.9 that will set the price to be 90% or a 10% discount so to say if somebody's not a student they're going to pay full price price times equals 1 that really doesn't do anything but it might help with this visualization then we'll output the following the price of a ticket is pick unit of currency then I'll add our price let's perform a test 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 we'll use print F instead of print line after the dollar sign I will add a format specifier we're going to display a double we'll use f for a floating Point number comma price to display two digits after the decimal use 0 2 now we can display a price you get a student discount of 10% the price of a ticket is $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 originally now what if somebody is a senior and a student within our if statement we'll write a nested if statement as well as an else statement if is senior they get a student discount and a senior discount let's cut these two lines within the if statement and stick them within the nested else statement if somebody is a senior and a student you get a senior discount of 20% and a student discount of 10% so let's take our original price times equals 0.7 and an additional 10% off the orig so let's say is senior is true for 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 if is senior they get that senior discount but it's only 20% instead of 30 because they're not also as student price times equals 0.8 you could add else price times equals 1 that's if somebody is not a student and not a senior but you don't 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 a senior you get a student discount of 10% the price of a ticket is $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 $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 price of a ticket is $6.99 that's how nesa if statements can be useful you could check another condition after checking a condition already so that's just one example of 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 be interested in as a beginner using Java in this demonstration let's create a variable of name the data type is going to be a string type in your full name including a space I'll just use my YouTube channel name if at any time you need the length of a string you can use the length method I'll store that as an integer int length equals to access these string Methods you need a string or a variable that is a string dot then we have one of a few methods if you need the length you can use the length method and then let's print it print the length how many characters are in the string eight 1 2 3 4 5 6 7 8 this could be useful let's say somebody is setting a password and you have a maximum size of 12 characters well you can check the length to see if it's under 12 characters so that is the length method there's Char at that will give you the character at a specified index we'll be given a single character we'll store that as a variable Char letter equals take our string of name use the Char at method within the Char at method we'll list an index zero is the index of the first character because computers like to start at zero what what is the character at index zero well that letter is B at index one that would be R and two would be o that is the charat method it returns a character at a given index within a string we also have the capability of finding a letter at a given index let's say we have a variable of index take our name use the index of method find the first occurrence of an O so in my example that should be 2 0 1 2 that is the first index of this 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 of name then use the last index of method what is the last index of an O because index of gives you the first index last gives you well the last one what is the last index of O where is it exactly five 0 1 2 3 4 5 we can take a string and make all the characters uppercase all reassign that to our name variable so we're going to take our name use the two uppercase method then print our name after reassigning it now all the letters are uppercase there's also two lowercase we'll replace upper with lower and I should probably turn this into a comment now all the characters are lowercase we can trim any white space before and after a string let's add a few spaces before and after then print the name we can eliminate all this white space we'll use the trim method for that we'll reassign name equals name and use the trim method now while that white space is gone we can replace a character with another one name equals name we will replace one character with another let's replace any o's with A's for your own name feel free to change these so what is my name now broade there are methods that return Boolean values to check to see if a string is empty you can use the is empty method this would return a Boolean to 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 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 if statement if name do is empty method if our name is empty we will print your name is empty else we will print hello plus name currently my name is empty your name is empty this method returns true but if it wasn't 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 if that's true your name contains a space else will print your name doesn't contain any spaces so my name does contain a space that would return true your name contains a space if we're working with let's say a username usernames typically don't contain spaces your name doesn't contain any spaces there is a method to check to see if two strings are equal again I'm going to use a multi-line comment just to comment this out if our name equals using the equals method we can check to see if two strings are equal the given characters within them let's see if our name equals password this actually would be more appropriate if we were working with the string named password if our name if the string of name is equal to this string if they have the same characters exactly then we'll print your name can't be password else we will print 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 execute the L statement hello your name now the equals method doesn't account for case sensitivity so let's say our password has a capital P well then this method returns false hello password to ignore case sensitivity you can use equals ignore case then that would return true your name can't be password all right everybody those are a few useful string Methods you may be interested in as a beginner using Java all right everybody in this video I'm going to explain how the substring method Works in Java substring is a method that's used to extract a portion of a string strings have a built-in method of substring within the substring method you can list one of two indices this method will create a new string based on the positioning of the indices the start and the end I can best demonstrate this with us creating an email SCE ER program so what we'll do in this demonstration is create a string of email type in your own email I don't want to give you guys my actual email because some of you guys are weird no offense my email will be bro1 [email protected] our variable of email is a string strings have a built-in method of substring we can create a new string from portions of the original string here's how let's say I would like the first six letters but depending on your own email it may be different the substring method will return a new string so let's create a new variable the data type of string of usern name equals to create a substring we will take the original string use the substring method then list one of two possible indexes or indices the first index will be zero at what position would we like this substring to end I would like to end right before this at sign so that would be 0 1 2 3 4 5 6 the second index is exclusive so we're creating a new string of username by using the substring method of our original string of email then let's print it to test it we will display our username and now we have a new string mine is bro 1 123 but depending on what you wrote for your email it may be different now I would like a new substring of every character after the at sign this will be a variable named domain what is the domain of our email again we're taking our original string using the substring method then list one of two possible indices so again let's count this is index zero because in 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 if you have a starting index but you would like all the characters that come after all the way till the end you don't necessarily need an ending index X we could just say seven that would work too gmail.com there's one issue with how we wrote this program what if somebody has a different length of an email there's a 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 is [email protected] 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 code one to make this program more flexible instead of manually entering the indices we can determine this number should be with another string method we're going to use the index of method in place of a number we're going to find the at character let's replace our second index with email our string dot using the index of method then we will find the index of our at character we're going to replace this number with email. index of and find the at sign so now let's try printing our 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 which we're using as the index it's returning the index of this at sign I'm going to increase it by one so we get everything after the at sign so plus one and now the at sign is removed even better yet let's accept some user input we'll need a scanner import java.util do scanner we'll create a scanner object scanner scanner equals new scanner then we will need system.in then when we open a scanner it 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 email enter your email I'll use print instead of print line I'm going to declare my variables after our scanner that's just how I like to arrange things we'll declare our email but not yet assign it same thing applies with our username and our 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 user input scanner. nextt line let's display our username and our domain okay enter your email I'll make up something bro1 [email protected] here's my username and the domain we can take this a step further too we can check to see if our email is valid we'll use some of the string Methods we learned about in the last video so after accepting our email we're 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 then we'll perform all this code so let's cut it then stick it within the if statement else we will do something else let's print emails must contain 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 again fake guy one at maybe they're using Yahoo yahoo.com so my username would be fake guy one the domain is yahoo.com all right everybody so that is the substring method and how to create an email slicer program the substring method is used to extract a portion of a string you can list one of two possible indices within the substring method a starting index and an ending index we use the substring method on an email then created two new substrings one of username and the other of domain and well everybody that is the substring method in Java hey everybody in this video we're going to create a weight conversion program to convert a weight from pounds to kilogram or vice versa it will help us become more familiar with if statements so let's get started okay let's get started everybody what might be helpful to you as a beginner when creating a project is to use comments to describe what you want to do at each part of your program this is also known as pseudo code for example the first thing we'll do is declare our variables declare variables then we'll create a welcome 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 kilog option two convert kgs to LBS if somebody doesn't select option one or two we'll use an else statement else print not a valid choice so here's a rough outline of our program and what it's going to do we'll begin at the top we'll declare any variables that we'll need so we will need a scanner we'll create a scanner object scanner scanner equals new scanner then type system.in within set of parentheses if you hover over the word scanner you can import it automatically import java.util.scanner or otherwise you can type it in what are some other variables we'll need double weight for the original weight double new weight that's after we convert the weight we'll need to store it and int choice a user is going to type in one to convert pounds to kilograms or two to convert kilograms to pounds we have our variables now we need a welcome message I'll use a few print statements let's say weight conversion program one C and space this means opt one convert lbs meaning pounds to kgs kilog or Choice 2 to colon space convert kilogram to 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 to accept user input we're accepting an integer we'll use next int let's do a test run and I will print our choice temporarily weight conversion program one to convert pounds to kilograms or two to convert kilograms to pounds I'll type in one we get one or two then we output two we can delete this print line statement we were just checking to see if it works okay option one if somebody selects option one we have to convert pounds to kilograms well we'll need to check to see if choice is one we can use an if statement for that if choice is equal to one be sure you use double equals that is the comparison operator we're checking if these two values are equal if you use a single equals that is the assignment operator and Java thinks you're trying to assign one to choice so double equals for comparisons we're converting pounds to kilograms we'll ask a user to enter the weight in lbs I'll use print instead of print line we we will assign our weight equals use our scanner then use the next Double method then we will accept a double value so once we have our weight we have to convert it to kilograms because it's currently in pounds we will assign our new weight equal to the weight our current weight that is times 0.45 3592 then we'll output the new weight the new weight in kgs is then we'll add our new weight okay let's perform a test run we'll type in one to convert pounds to kilogram enter the weight in pounds what's 150 lb converted to kilog 68.0 388 if you would like to limit the amount of digits that display after the decimal you can use a print F statement instead of print line so to do that we'll convert this to print F where we would like to insert a value or variable we'll use percent since we're displaying a double we'll use f meaning floating Point number to display two digits after the decimal we'll use 0 2 or 0.1 to display one digit depending on your preference replace the plus with a comma we're inserting this variable at this location this placeholder let's perform that again choose an option convert pounds to kilograms enter the weight in pounds 150 is good the new weight in kilogram is 68.4 kilg now if Choice equals 2 we're going to convert kilog to pounds and really we can just copy the if statement paste it then convert it else if Choice equals 2 the user wants to convert kilogram to pounds enter the weight in kilog the new formula is going to be weight time 2.24 62 the new weight in pounds lbs is our new weight let's try it choose an option we will convert kilograms to pounds I'm going to press two enter the weight in kilogram let's say 68 kg the new weight in pounds is 14991 lb what if somebody types in a number that's not valid so we can get rid of this comment is use an else statement to print print that the user didn't select a valid choice we will follow this with an lse statement we will follow else if with an 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 that was not a valid choice and again like usual I'm forgetting to close my scanner because I sometimes forget to do that so at the end of your program close your scanner scanner. close because you don't want to leave resources open okay let's do one final test run let's convert pounds to kilograms what's 200 lb converted to kilograms 90.7 2 all right everybody so that is a weight conversion program you can write using [Music] Java hey everybody in this video I'm going to show you how we can use the tary operator in Java in Java the tary operator is a question mark followed by one of two possible values here's the formula we check a condition then use a question mark like we're asking a question is this condition true if it is we'll return a value if not we return something else a different value it's a simpler version to an if else statement here's a demonstration let's say we have an integer of a score score will equal 70 that's technically passing using an if statement I will 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 it were 55 well then I fail there's another way in which we can write this and that is by using the tary operator what we're going to do let's create a variable a string variable of pass or fail and we're basically just following this formula we have our condition is our score greater than or equal to 60 question mark we're asking a question is this condition true if it is let's return a string of pass colon think of it like otherwise will return fail and then I will print pass or fail to display it so 55 that means we fail but if it were 75 that means we pass by using the tary operator it's an alternative to writing an if else statement and it can be simpler in many cases here's a few other examples let's create a variable of number set it equal to some number using the Turner operator we will check if this number is even or odd I'll create a string of even or odd equals our condition we can check if a number is even or odd by using the modulus operator we will take our number modulus 2 the modulus operator gives you the remainder of any division 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 not equal zero is this number divisible by two we'll use the trary operator if it is we'll return a string of even otherwise we'll return a string of odd is my number even or odd so three is odd but if it were four well then it's even here's a more practical example let's say we're working with a time in hours this will be in military time hours equals 13 that would be the the same as 1 p.m. I will create a string of time of day equals we'll check if our hours is greater than or equal to 12 if it is we'll return PM if not will return am hours less than 12 tary operator is our hours less than 12 if it is we'll return a.m. otherwise will return p.m and then we will display the time of day 13 hours that's the same as 1: p.m. yep the time is 1: p.m. or if the hours were 9 that would be am all right last example let's say we have an income or salary income equals $60,000 let's pretend that you're a software engineer in the united states in the United States we have different tax brackets depending on your income this time we will assign a variable of tax rate equals we'll check if our income is greater than or equal to $40,000 for $40,000 question mark turnar operator if that's true then our tax rate is going to be 0.25 otherwise it will be 0.15 so with our income what is the tax rate 0.25 but if I changed it to 30,000 well then our tax rate would be 0.15 for 15% so that is the tary operator you follow this formula you check a condition within a set of parentheses then use the tary operator like you're asking a question if this condition is true return this otherwise if it's false return something else and then if you would like you can assign it to a variable and well everybody that is the tary operator in Java all right everybody in this video we're going to create a temperature conversion program to convert from Celsius to Fahrenheit or Fahrenheit to Celsius this is a practice project to get us more familiar using the tary operator so let's get started we will be accepting some user input so let's get the scanner out of the way first scanner scanner equals new scanner we need a scanner to accept user input within the set of parentheses type system.in and then I will just automatically import this class so at the top of your Java file you need this import import java.util.scanner then when you open a scanner it is a good idea to close it at the end of your file when you're done with it because you don't want to leave resources open we have our scanner to accept user input let's declare some variables what will we need we will need the original temperature this will be of the double data type double temp we'll need a new temperature let's say double new temp that's after we convert it and a unit we could use Char for the unit you know the letter F or c for Fahrenheit or Celsius but just to keep it simple I'm going to use a string because there's a built-in method of two uppercase we can take the input and make it uppercase automatically just to make it simple we'll use a string rather than a Char for the unit okay now we just need to get the temperature we'll need a prompt I'll use print instead of print line we will ask the user to enter the temperature we will assign the temperature temp equals scanner. next Double because we're accepting a value we're signing a variable of the double data type now we need the unit is it going to be Celsius or Fahrenheit we'll need another prompt I'll use print instead of print line we will ask the user convert to Celsius or Fahrenheit C or F let's ass our unit variable use our scanner then use the next method to get the next character we'll use the next method to get the next character we don't necessarily need next line we just want a single character so check this out I'm going to Output our temp and our unit what if somebody types in a lowercase C or F so let's say the temperature is 75 75° F and we would like to convert it to Celsius I'll type lowercase C rather than uppercase C our unit is currently a lowercase C we can convert it to be uppercase following the next method of our scanner where we assign our unit we're going to do something called method chaining we'll add another dot then use the two uppercase method of strings let's try that again and see if it works 75 I'll type in lower case C the two uppercase method will take that lowercase C and make it uppercase which is what we'll need in this next section we can delete these two statements now we're going to use the tary operator how the trary operator works is that we check a condition followed by a question mark like we're asking a question we will return some code if that condition is true colon meaning else if it's false we'll do some other code or return some other value we're going to follow this formula so what is our condition let's check to see if our unit is equal to a c take our variable of unit use the equals method because strings have a built-in method of equals does our unit equal in uppercase C question mark That's the tary operator we're asking a question if this is true that means we're trying to convert from Fahrenheit to Celsius the formula to do that would be the following we would be executing this code since it's true take our temp subtract 32 then multiply 5 / 9 now what if our unit does not equal C that means we're trying to convert to Fahrenheit we'll need that colon for the next part of the section now here's the formula to convert from Celsius to Fahrenheit this will be the false section of the trinary operator take our temp * 5 / 9 + 32 with the trinary operator how we've written this code is that we're going to be returning a double after converting it we need to do something with it so we're going to assign it to a variable our variable of new temp then we can do something with it once we have our new temperature let's display it I'll perform a test run let's print our new temp let's say it's 100° F and we're going to convert to Celsius I'll type in see well the temperature in Celsius is 37.7 repeating we're going to format this in a moment let's add a degree symbol plus a string on Windows to add a degree symbol make sure num lock is on hold alt then type 0176 plus our unit we're converting to let's try that again what is 100° fah converted to Celsius 37.7 repeating de C to limit the amount of digits that display after the decimal we we can use a print F statement let's convert our print line for the new temp to be 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 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 lock is on I'm typing 0176 then we will display the unit it's a string percent s for Strings we're inserting a new variable we're going to comma separate them then add our unit and let me just close this Gap let's see what the final product is let's convert 30.1 this will be in Celsius to Fahrenheit and the temperature in Fahrenheit is 48.7 De fahit okay everybody that is a temperature conversion program that you can write using the tary operator in Java why hello there today I got to explain something called enhanced switches in Java in Java there switches and then there's enhanced switches enhanced switches are a Java 14 feature I would recommend using using enhanced switches over standard switches so what is a switch exactly a switch is a replacement to using many l statements here's an example of us using a lot of lse if statements in this sample program we have a day of the week I set mine to be Friday with each of these if statements I am checking to see if the day equals Monday Tuesday so on and so forth currently my day is set to Friday this would give me it is a weekday if I set the day to be Saturday well then it is the weekend or Sunday let me show you the code it is the weekend then I have an else statement if none of the above conditions are true for example let's say day is pizza day which doesn't exist but it really should Pizza day is not a day this code does work but it could be more efficient we have a lot of redundancies we're 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 to make that so let's set our day to be Monday for example to create a switch we will type switch at a set of parentheses then a set of curly braces it's similar to an if statement already with within the set of parentheses for the switch we're going to examine a value or variable we're going to examine our string of day we will examine this value against any matching cases the first case will be a string of Monday if day is equal to this value a string of Monday we'll do something we'll use an arrow an arrow is the arrow operator in Java think of it as meaning do something do this if day equals Monday do this code so let's print something let's print it is a weekday and then for fun you don't have to but I'm going to add an emoji nobody likes Mondays let's be honest if day is Monday do this code let's add another case let me zoom in a little if Case is Tuesday Arrow op operator meaning do this code we will print we'll print the same thing it is a weekday we'll do this with the other days too I'll just copy this code then repurpose it to save some time case Wednesday it is a weekday case Thursday it is a weekday case Friday it is a weekday now if it's sat Saturday that means it's the weekend case Saturday it is the weekend let's change the Emoji case Sunday it is the weekend let's perform a test run if you're using intellig you may have These Warnings it's basically saying that these sections of code are unreachable we're manually setting a variable these sections of code are not going to execute so I would just ignore that for now so let's perform a test run my day is Monday day is equal to the 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 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 default Arrow meaning do this we'll print 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 statement if no above conditions are true then we will do this so what we'll do now is accept some user input using a scanner we'll need to create a scanner object scanner scanner equals new scanner within the set of parentheses type system.in and then I'm just going to automatically import this class at the top of my Java file import java.util.scanner we'll create a prompt for a user to type in the day enter the day of the week and I will use print instead of print line instead of manually assigning a variable we'll use our scanner scanner. nextt line to accept a string okay let's try this again enter the day of the week it is Tuesday it is a weekday let's try that again enter the day of the week it is Saturday it is the weekend and let's make up a day uh let's go with taco day taco day is not a day we could actually improve this widg even further intellig is saying we have a duplicate branch in our switch we have 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 Monday Tuesday Wednesday Thursday and Friday they all output the same thing so we're going to consolidate them I'll copy one of these print statements and delete all of them we can comma separate these cases so case Monday comma Tuesday comma Wednesday comma Thursday comma Friday then Arrow if our case is Monday Tuesday Wednesday Thursday or Friday then do the following we'll print it is a weekday now Saturday and Sunday do the same thing too let's cut one of these lines and delete them case Saturday comma Sunday Arrow meaning do this it is the weekend then we'll keep keep our default case in case there are no matches let's try this again enter the day of the week it is Wednesday it is a weekday it is Saturday it is the weekend it is Sunday it is the weekend uh then let's go with uh Hamburger Day hamburger day is not a day so those are enhanced switches they're a replacement to using many LF statements if you find yourself using a lot of lsif statements I would recommend using a switch instead but not just any switch an enhanced switch which is a Java 14 feature that you should know 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 calculator program using what we've learned with enhanced switches this is meant to be more of a practice project let's get started the first thing we'll need is a scanner we will create a scanner object scanner scanner equals new scanner within the set of parentheses type system.in and then when you open a scanner it is a good idea to close it when you're done with it scanner. close then be sure to import the class at the top of your Java file make sure you have this import import java.util.scanner what are the different variables we'll need a user is going to type in two numbers and an operator such as a plus for addition minus for subtraction so on and so forth the first variable will be up the double data type double num one double num two then an operator this 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 we'll stick with these four for now we'll prompt a user to type in the first number followed by an operator than the second number here's how we can write that let's ask the user to enter the first number and I will use print instead of print line we will assign num one equal to use our scanner to get user input next Double then we need the operator we will use a print statement enter n operator we'll have Plus for addition minus for subtraction an asterisk for multiplication a for slash for division let's add one more let's add a carrot this will raise a base to a given power feel free to add more if you would like but we'll just stick with these five a user is going to enter in a character one of these operators hopefully we will assign our variable of operator equal to scanner. next the next method will give you a string we can method chain the Char at method to return a single character when a user types in something just give me the first character this will also convert it to be a character rather than keep it a string so ideally our operator is going to be a plus a minus an asterisk a forward slash or a carrot then we need num two we can just copy these two lines paste them change first to be second and num one to be num two we have our two numbers and our operator we have to determine what the operator is we can use an enhanced switch for that we will create a switch within the set of parentheses we are examining our operator we're examining our operator against any matching cases the first case will be a plus sign and these cases are going to be within single quotes not double quotes because we're working with a character not a string with our switch if our operator is a plus character we're going to write an arrow meaning do this we will take our variable of result set it equal to be num one that's the first number plus num two that will be the case for addition then we have subtraction case minus Arrow do this assign our result equal to num one minus num 2 multiplication would be case a character vaster risk arrow take our result equals num one * num two now for division we have a forward slash arrow take our result equals num one divided by num two now with division if somebody divides by zero we'll return to this case later and make it a little more sophisticated where we check to see if num 2 is zero I would like for us to get a solid foundation first for this program so if somebody would like to 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 class the power method of the math class 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 works I'm going to display our result after the switch so Java is giving us a warning that variable result might not have been initialized that's because it's possible there's no matching cases and we would be keeping our result uninitialized so to clear that up when we declare our variable we can also 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 and the second number 1.1 the result is 4.24 let's do subtraction 3.14 minus 1.1 which gives us 2.04 multiplication 3.14 times let's do two 6.28 then division 3.14 divided by two that gives us 1.57 then we have power what is 3 to the power of three that is 27 3 * 3 is 9 * 3 is 27 3 ^ of 3 we have one potential issue though what if somebody divides by zero here's what happens what is 3.14 / 0 we get the output of infinity here's how we could prevent that underneath the case where we do division we'll write a few lines rather than just one but we're going to enclose them within a set of curly braces then I'm going to cut this line of code within this case we'll write an if statement we'll check if num 2 is equal to zero that's because we can't normally divide by zero if it is then let's print cannot divide by zero else we'll assign our result of num one / by num 2 we'll execute the L statement if num 2 doesn't equal zero because if it did this would be true and we execute this code instead let's try that again what is 3.14 / 0 cannot divide by zero however we still do display a result and that is by using this print statement what if somebody types in an operator that doesn't exist 3.14 I'm going to type in pizza for the operator type in I don't know one well we still display a result so let's modify this program let's display a result only if we have a valid operator because right now we don't Pizza is not a valid operator let's add a Boolean variable of valid 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 operation variable and set it to be 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 case let's output invalid operator then we will take our Boolean variable of valid operation and set it to be false so this is what our switch looks like feel free to pause the video if you would like a moment to look it over within our case of division we do have a few lines of code same thing applies with the default case we're only going to print the result if our Boolean of valid operation is true if valid operation is equal to true but really we can just shorten this to if valid operation then we'll print the result then we don't necessarily need an else statement because we're already printing either invalid operator or cannot divide by zero okay let's run this one final time 3.14 plus 2.1 is 5.24 3.14 minus 1.1 is 2.04 3.14 time 2.1 is 6594 4 3.14 okay 3.14 / 0 Let's see what happens cannot divide by zero and we do not display the result because our equation is invalid which is good we don't want to display the result we're displaying a type of error message instead let's raise 4 to the power of two which gives us 16 now let's type in an operator that doesn't exist 3.14 Pizza 69 invalid operator that's because Pizza is not a valid operator all right everybody that is a calculator program that you can write the purpose of this program is to more or less help us with enhanced switch statements depending on the operator we can perform one of a few operations we've also learned that your cases can take up more than one line if you would 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 logical operators they allow us to check or modify more than one condition there's and or not we'll discuss and first which is represented by two Amper Sands let's declare a variable of temperature temp meaning temperature I will set this to be 20 I would like to check to see if my temperature Falls within a certain range well to do that I could use the and logical operator we can check more than one condition so first I would like to see if my temp is less than or equal to 30 30° C and if the temp is greater than or equal to zero we have two conditions this time if this is true and this is true then do this code so let's output the following if our temperature Falls within this range we'll output the weather is good and for fun I'll let a smiley face cuz why not okay let's see how this works the temperature is currently 20 20° C the weather is good if the temperature were 40 40° C well we don't do anything this condition evaluated to be false but this one is true our temperature is greater than or equal to zero that is true but this one is false and using the and logical operator both conditions must be true in order for this entire statement to be true since only one of them was true where temp is greater than or equal to zero we don't execute this code the and logical operator is used to check more than one condition we can add as many as we would like to this time let's create a variable of is sunny this will be a Boolean Boolean is sunny is it sunny outside I will set that to be true not only are we going to check to see if our temperature is within a certain range we're also going to check and is sunny is this true so now we are linking three different conditions all three must be true so if all three are 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 temperature to not 240 20 these two conditions are true but this one is false so we don't do any of it we skip over it with the and logical operator all conditions must be true if is sunny we're true then well then we execute this code the temperature Falls within this range this is true and this this is true and this is true all three conditions are true so we execute this code the weather is good and it is sunny outside we check more than one condition and both must be true there's also the not logical operator it's a little different how it works is that it gives you the opposite you can check to see if something is not true let's add an elive statement we're going to copy these three conditions but make one change we're going to precede is Sunny with the not logical operator represented by an exclamation point it checks the opposite we are checking to see if something is not true is our temperature less than or equal to 30 and greater than or equal to zero and is it not Sunny so if something is normally false using the not logical operator it becomes true if it's normally true it becomes false it gives you the opposite for a Boolean value basically if the weather is good but it's not Sunny that must mean it's 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 outside the temperature Falls within this range and it is not Sunny the not logical operator checks to see if something is not true then we have the or logical operator represented by two vertical bars or is similar to the and logical operator however only one condition needs to be true that are linked by the or logical operator with and both must be true let's say our 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 and the else if statement let's add another LF statement we're going to check to see if our temperature is really hot or really cold we will check if our temp is greater than 30 or using two vertical bars temp is less than zero then we'll output the weather is bad if our temperature is -10 the weather is bad with the or logical operator at least one condition must be true this condition was false but this one was true so we execute this code because using the or logical operator at least one condition needs to be true or if the temperature was 35 35° C this time this condition was true but this one was false so we execute this code all right let's go over another example we're going to use these logical operators to validate a username when somebody tries to set a username so in this project we'll need a scanner scanner scanner equals new scanner we're going to type system.in then import this 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 username must be between 4 through 12 characters username must not contain spaces or underscores we'll create a string variable of 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 line we will assign our username using the scanner username equals scanner. next line we'll write a condition to check if our username is between 4 to 12 characters we're going to check if our username is under four characters or greater than 12 characters we'll check that within an if statement if our username use the length method to return the length of this string if the length of our username is less than four use the or logical operator or our username the length of it using the length method is greater than 12 that means our username is too short or too long we'll output the following username must be between 4 through 12 characters let's perform a test run enter your new username I'll type in something that's less than four characters username must be between 4 to 12 characters let's type in a really long username I'll just make up something username must be between 4 to 12 characters let's type in something actually within that range oh and then we need to add an lse state statement because I forgot else we will print welcome plus username enter your new username welcome whatever your username is the second part of this assignment is that we need to check to make sure that there are no spaces or underscores within our username after the if statement We'll add an L if statement to check that using the contains method of strings we can check if a string contains a certain character with our username we will use the contains method does our username contain any spaces or does our username contains any underscores if so we'll output the following user usame must not contain spaces or underscores let's perform another test run type in your first and last name including a space username must not contain spaces or underscores this time I will use an underscore to separate the first and last name username must not contain spaces or underscores let's type in a usern name that follows the rules that seems to work so that is the or logical operator if at least one condition is true then the entire statement is true and we execute it all right everybody so those are logical operators and checks more than one condition both must be true or checks more than one condition at least one needs to be true not not is a little different it checks if something is not 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 Java if I could summarize a while loop in one sentence a while loop will repeat some code Forever while some condition remains true first I'll give you a demonstration using an if statement then we'll convert it to be a while loop and we'll see how it's useful we'll need to accept user input in this demonstration I will create a scanner I'm pretty sure we know how to create one by now be assured to import the scanner class import java.util.scanner then be sure to close your scanner because I always forget to do that all right we are going to create a string of name I'll use an if statement to check to see if my name is empty if name use the is empty method now Java wants us to assign this name right away okay so I'm going to go ahead and initialize it we can initialize it with an empty space if our name is empty which it will be we will prompt the user to enter your name I'll use print instead of print line to keep it on the same line then we will assign our variable of name name equals scanner. next line after we escape the if statement we'll output our name let's say hello Plus name so this program will work but there's one issue what if I don't type in anything when I enter my name I'll just hit enter well we still continue with the rest of the program the output is hello we don't display a name because we didn't type in anything how can we prevent people from doing stuff like this skipping prompts well we could use a while loop rather than an if statement replace if with while what we're doing is while this condition remains true continue this code Forever Until this condition is no longer true let's try that again enter your name I'm just going to hit enter enter your name no enter your name no enter your name no okay I give up I'll type in my name then we escape the while loop hello your name so that's why a while loop Loop is useful we can repeat some code possibly Forever at times we may not want a user to continue without doing something a while loop would be really helpful for that they would be stuck until this condition is no longer true at the end of your while loop we go back to the beginning to check the condition if the condition is no longer true then we escape the while loop and move on with the rest of the program there's one thing you should be cautious of though and that is an infinite Loop let me give you a demonstration with our while loop if we have a condition that we can't change from within the loop that's called an infinite Loop so let's say while the number one is equal to 1 even my IDE intellig is giving me a warning that 1 is equal to 1 is not updated inside the loop I would not recommend following me along for this part your computer might freeze up but I'm going to print help I'm stuck in a loop within this while loop I have no way to change it from inside of it so we're going to be stuck in this while loop forever here's a demonstration we're just going to print this code forever let's check back later one eternity later it's still going we're stuck in a loop this may happen to you if you have some condition that you can't change within your while loop 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 they have to press the q key we will declare a string of response we'll use a while loop now for my condition for us to be able to escape the while loop our response I'm going to use the not logical operator equals a capital Q and this will be a string so while our response does not equal Q we continue the loop forever in order for somebody to escape this game they have to press Q to quit Java wants me to assign this variable right away and initialize it so I'll do so we don't want our variable to be empty when we use it to check a condition then intellig is giving us another warning that our response is not updated inside the loop if we don't update it we'll be stuck in an infinite Loop let's pretend that we're playing a game you are playing a game then we'll output press Q to quit then we will need to update our response response equals use our scanner for Single Character we can use next in case somebody types in a lowercase que we'll follow this method with the two uppercase method if a user was to type in a lowercase Q we'll convert it to be an uppercase q so that it matches once we escape the while loop we'll print you have have quit the game okay let's perform a test run you are playing a game press Q to quit no yes okay as long as our response does not 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 quit I will press q and we escape the loop you have quit the game while our response using the not logical operator while our response does not equal Q continue the loop forever let's go over another example we'll ask a user for their age int age I will set this to be zero right away we'll prompt a user to enter in their age enter your age we will assign our age variable AG equal scanner. next int then at the end of this program I will print you are our variable age plus years old let's say I would like to prevent somebody from typing in a negative number like -1 you are ne1 years old well we could use a while loop to reprompt the user before displaying the result so after we assign our age once let's use a while 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 can just copy these two lines and then paste them within the while loop we'll ask the user to enter in their age again and reassign it if we keep on typing negative numbers we can't escape the while loop we're stuck until we type in something that's valid you are 21 years old that's a valid number from the beginning if I type in something that's valid we don't enter the while loop at all it is possible to skip over it we check the condition of a while loop before entering it if we type in a number that's valid let's say ages 25 we check the condition it's false from the beginning so we don't enter the while loop at all we skip over it and go straight to the end in this program we only get caught in the while loop if we type in user input that's not valid there's a variation of the while loop known as a do while loop we do some code first and then check the condition if I was to convert this code to be a do while loop I would cut the while part do this code then check the condition at the 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 can't be negative enter your age you are whatever your age is years old so with the do while loop we do this code first and then check the condition at the end where it's different compared to a standard while loop is that with the standard while loop you may not enter the while loop at all if this condition is false but with the do while loop you always do this code at least once and then check the condition at the end let's go over one last example with the do while loop we'll prompt a user to type in a number that's between a certain range we will have int number and I will assign this to be zero right away let's use a basic while loop first while our number is less than one we'll use the or logical operator to check or 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 next int method and then at the end we will print our number you picked plus number so let's run this our number is set to zero enter a number between 1 and 10 let's do negative 1 11 -2 one kajillion I think I broke it okay I'll type in something that's valid like five you picked five rather than check the the condition from the beginning we could check it at the end so let's convert the while loop to a do while loop do this code once and then check the condition so this would work similarly so do this code once check the condition at the end all right everybody so those are while Loops they allow you to execute some code possibly forever while some condition remains true they're really useful when accepting user input because the user might not type in something that's valid and you have to keep on repr prompting them that's one good use there's two variations of while Loops a standard while loop and a do while loop it depends if you want to check the condition before entering the loop and well everybody those are while Loops in Java hello everybody in today's video we're going to create a number guessing game using Java let's get started in this program we'll be using random numbers we'll need to create a random object random random equals new random then import this class so at the top of our Java file import java.util random this random object can Generate random numbers for us we'll also accept user input we'll need a scanner scanner scanner equals new scanner then within the set of parentheses type system.in then import this class as well import java.util.scanner we have a random object to Generate random numbers and a scanner object to accept user input what are the different variables we'll need we'll need the following an integer to hold our guess so let's say we're going to guess a random number between 1 and 100 we'll use the scanner to accept an integer and place it within this variable of guess for example the guess might be 50 we need to keep track of the amount of attempts it took a user to get the correct number int attempts we'll assign these later and we'll need a random number int random number let's go ahead and assign this right away to generate a random number we're going to use our random object use the next int method of a random object within this method we can list two numbers a range if I would like a number between let's say 1 and 10 my two numbers would be 1 comma 11 the first number is inclusive the second number is exclusive let's perform a test run of a random number I just want to be sure that it's generating correctly when writing a program it is a good idea to test your code every once in a while just to be sure that everything is working so we should get random numbers between 1 and 10 1 10 5 8 good enough a random number stores a random number after generating it let's create a welcome message let's say number guessing game we will prompt the user guess a number 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 while loop so do this code once while this condition remains true and let me zoom in a little bit so what's our condition going to be we're going to continue playing this game while our guess does not equal our random number we'll keep on playing until we get the random number exclamation point equals means not equal so if our guess does not equal our random number this return turns true then we want to keep playing while our guess doesn't equal the random number within this do while loop will prompt the user to enter in their guess I'm going to use print line instead of print for guess a number between 1 and 10 now we'll prompt the user to enter a number enter a guess enter a guess for this I'll use print instead of print line we will assign Our Guest 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 get the correct 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 print you have one my random number right now is only 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 Loop so we know that this is working currently one thing this program is missing is that we'll want to give a user a clue if their guess is too low or too high because we have no way to tell I'm just typing in random numbers and I have no clue how close I am to the actual number that we need to guess let's get rid of this print statement we were using it for testing purposes within the do while loop we'll write an if statement we'll check if our guess is less than our random number that means we guess too low if that's the case we'll output the following two low try again else if our guess is greater than our random number that means we guess too high too high try again if our guess isn't lower than our random number and our guess isn't greater than our random number that means our guess must equal the random number so if that's the case we would be executing this lse statement because the preceding two conditions would be false that means we have the right answer the right guess so we'll output the following correct the let me zoom out the number was plus our random number and then we'll display the amount of attempts it took number of attempts plus our variable of attempts after each guess we increment it by one the last thing I'm forgetting is to close my scanner because I always forget to close it scanner. close okay let's perform a test run we're only guessing a number between 1 and 10 currently I'll guess something right in the middle five too low try again the random number we have to guess should be between 5 and 10 then I'll go with seven too low 8 too low nine too low okay it must be 10 then correct the number was 10 number of attempts it took five we're going to improve this code now what if we would like the numbers 1 through 100 this time well we could make this program a little more flexible instead of hardcoding these numbers within the next integer method we'll Place some variables here instead we will create int Min equals whatever you want the minimum to be let's say one int Max I will set the max to be 100 let's replace these two numbers the first one will be Min comma Max so these variables behave as if they were these numbers within this range the second number is exclusive so TW include 100 I'm going to add + one give me the numbers between 1 and 100 within this print statement let's use print F instead we'll replace these numbers with the format specifier a placeholder we 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 between one and 100 I'll guess something right in the middle too high try again our numberers going to be between 1 and 50 then 25 too high 12 too high 6 too high three too low between three and six four correct the number was four the number of attempts it took six attempts all right everybody so that is 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 a four Loop is similar to a while loop however a for Loop executes some code a certain amount of times a for Loop is different from a while loop a while loop could execute an infinite amount of times until its condition is no longer true so with for Loops we want to do something a certain amount of times to create a for Loop type four parentheses curly braces now within the condition of the for Loop there's three statements each is separated with a semicolon we have statement one statement two and statement three the first statement is used for ini ization we can create a counter to keep track of how many times we have iterated this Loop basically we're declaring a variable a counter this will be int now a common practice for a for Loop is to create a counter named I meaning index in I equal Z or some other number I is going to be used as a counter within this Loop also known as a loop control variable the second statement is a condition when do we want to stop maybe we would like to execute some code 10 times we'll continue this loop as long as I is less than 10 now the third statement the third statement is the step we can increment our counter of I by One or another number or even decrement after each iteration let's increase I by One 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 8 9 10 so a for Loop is good if you want to repeat some code a certain amount of times but there's a little bit of setup you have to do we'll need some sort of index or counter a condition in which you want to stop and you'll need to update the counter one way or another initialization condition update we can also print this index of I rather than printing the word Pizza let's print I to see what we're working with during the first iteration I is zero after our Loop is complete we increment I by One our counter so we have 0 1 2 3 4 5 6 7 8 9 We're looping 10 times but we set I to be zero to begin with if I were to set I to be 1 and I want to iterate 10 times I could say while I is less than or equal to 10 so now we're starting at 1 and counting up to 10 we can even decrement to let's set I to be 10 we'll continue the loop as long as I is greater than zero to decrement we'll set I to be 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 instead of incrementing by one let's increment by two and see what happens so this time we start at one and update our counter of I two each time or even three i+ equal 3 1 4 7 10 we can decrement by a given number let's set I to be 10 we'll continue this loop as long as I is greater than zero and we will decrement our step we will decrement by 2 i - = 2 now we're starting at 10 and 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 int method and now we're going to create a loop a for Loop again there's three statements each separated with a semicolon we'll need an index or counter to keep track of how many times we have looped let's say in I equals 0 for the next statement what's our condition we want to continue as long as I is less than the max I is less than our Max variable then increment I by one then we'll print I or something else let's try this how many times do you want to Loop let's Loop five times 1 2 3 4 5 again we set I to be zero so that's why we're beginning with zero if you would rather begin with one we can set I to be 1 then the condition would be I is less than or equal to Max let's try that again let's Loop six times 1 2 3 4 5 6 all right now we're going to create a mini project we'll create a program to simulate a countdown perhaps we have a variable of int start let's start at 10 we're counting down from 10 then we'll create a for Loop we will set our index of I equal to our start our start variable behaves as if it was the number 10 we'll continue as long as I is greater than zero then we will decrement by one with IUS minus during each iteration let's just print I then when we escape the the for Loop let's print happy New 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 would like we can use the thread class and have our program sleep for about 1 second between each Loop here's how you can do that after printing I this is a little Advan Java at this level you don't need to understand how this works but we're going to use the thread class called The Sleep Method then pass in an amount of milliseconds in which we would like to sleep 1,000 milliseconds now Java wants us to add the following Java wants this method of main to throw this exception if our thread is interrupted this is intermediate Java we will need the section of code in order for our program to sleep after you finish this lesson be sure to remove throws interrupted exception we'll no longer need it print I then our program is going to sleep for 1 second 1,000 milliseconds all right and here's our mini project 10 9 8 7 6 5 4 3 2 one Happy New Year let's modify this program a little bit now we'll use a scanner to accept user input scanner scanner equals new scanner we have already imported the class with start we're going to accept some user 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 all right let's try this 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 the end 3 2 1 happy New Year so those are four Loops we can execute some code a certain amount of times it's very similar to a while loop in fact there's a lot of overlap where you could use either a for Loop or a while loop use a for Loop if you want to do something a limited amount of times and well everybody those are four Loops in Java I have a pretty short video for you today we're going to discuss two important keywords when it comes to Loops break and continue break is used to break out of a loop continue skips the current iteration of a loop think of the break keyword as the stop button on a remote continue would be similar to skip with break we're stopping with continuing we're skipping let me give you a demonstration let's create a for Loop that will iterate 10 times let's say in I equals 0 will continue as long as I is less than 10 then increment I by 1 during each iteration I'll just print I then add a space here's what we got we have the numbers 0 through 9 so let's say when we reach five I would like to break out of the loop we're going to stop it well I could add an if statement let's say if I is equal to 5 then we will use the break keyword and break out of the loop entirely here's what happens once we hit five we break out of the loop previously we continued all the way until 9 now with the continue keyword we don't break out of the loop we just skip the current iteration like a skip button on a remote this time let's use continue rather than break and we'll see the differences between the two now since we're using continue the number five is missing we skipped that specific cycle of the loop and went back to the beginning that's why five is missing between four and six but we still continue to the end when working with loops if you ever need to break out you can use the break keyword to skip the occurrent iteration you can use continue and well everybody that is both the break and continue keywords in Java hello again friends today I'm going to explain nested Loops in Java a nested Loop is really just a loop inside of another loop you often see nested Loops within a matrix or matrices or when we reach the topic of data structures and algorithms they might not come up for a while yeah this can be any combination of for Loops or while Loops any kind of loop inside of another loop let me give you a demonstration let's say I would like to print the numbers 1 through N9 I can do that pretty easily with a for Loop so we will create a for loop I will set an index of I equal to 1 we'll continue this loop as long as I is less than or equal to 9 then I will increment I by One during each iteration I will display I so this will print the numbers 1- N9 or if you prefer you can have it all on the same l line by using print instead of print line then it would look something like this 1 2 3 4 5 6 7 8 9 you can even separate them with the space after printing our index of I let's print a space character and now the output looks something like this what if you would like to do this code three times let's say print the numbers 1 through 9 three times well you could copy and paste this for Loop then do that two additional times so we have the numbers 1 through 9 three times to put each row on a new line can use an empty print line statement then it would look something like this a matrix we seem to be repeating our code a lot in programming we like to follow the dry principle don't repeat yourself if you don't have to instead why don't we create a for Loop and stick this for Loop inside of that Loop let's create a for Loop to iterate three times I will create an index of I equal to 1 we'll continue as long as I is less than or equal to three then increment I by One all we're going to do is take our code including the for Loop and stick it within this other for Loop do pay attention to the indentation but we have we have one problem we're reusing this index of I you can see that Java is already giving us a warning here's what happens variable I is already defined in method main if we have a loop inside of another loop we can't use the same index a common naming convention for a nested Loop is to use an index of J rather than I because J comes next in the alphabet after I instead of printing I we're going to print J let's see how this works and here's 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 were to get rid of that we'll print the numbers 1 through 9 three times all on the same line let's put that back in nested Loops are really good when you're working with a matrix of data nested Loops come up pretty often in the topic of data structures and algorithms because we have to Loop over sets of data now we're going to cover a mini project we're going to create a matrix of a symbol that a user is going to type in a user will set the rows and columns for this Matrix we'll declare the following variables int rows int columns and and Char symbol we'll need a scanner so let's declare that we'll need a scanner scanner scanner equals new scanner within the set of parentheses type system.in let's be sure to import this class of scanner at the top of our Java 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 rows the columns and the symbol we're going to use let's create some prompts enter the number of rows I'll use print instead of print line we will assign our variable of rows equal to use our scanner use the next int 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 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 columns first let me zoom in we're going to set in I we can set it equal to zero we'll continue as long as I is less than our columns whatever the user types in then increment I by One during each iteration I'll use print instead of print line we will print our symbol let's perform a test run enter the rows it doesn't matter we didn't set up the rows yet uh for the columns let's do eight enter the symbol to use Let's do let's do a dollar sign that'd be cool we have the column set set up currently we should have eight dollar signs 1 2 3 4 5 6 7 8 we need to repeat this for Loop for as many rows as we 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 continue this as long as I is less than the rows the number of rows that a user types in then increment I by One let's perform another test run let's say I would like three rows of six and I will use an at sign so these are all on the same line we should have a total of 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 our inner loop ends after each group of six I'm going to print a new line we can use an empty print line statement our outer for Loop is in charge of the rows our inner for Loop is in charge of the columns let's see the final product I would like five rows of three three columns I'll use an Amper sand here we are we have three columns and five rows all right everybody those are nested Loops it's really just any kind of loop inside of another kind of loop it doesn't matter if it's a for Loop or a while loop we often use nested loops with matrices or when we reach the topic of data structures and algorithms they might not come up very often but you should at least be aware of their existence and well everybody those are nested Loops in Java what is going on everybody in this video I'm going to discuss methods in Java think of a method as a block of reusable code that is executed when you call it to call a method you use a set of parentheses kind of like it's a pair of telephones talking to each other why are methods is useful well with the method you can write some code once and reuse it whenever you want you just have to call it let me show you why a method is useful so let's say we have a task we have to sing a happy birthday song three times so without using a method we can do something like this we'll create one verse of a happy birthday song I'll just make something up let's say happy birthday to you happy birthday dear you you are we'll insert somebody's age here but let's say you are X years old then happy birthday to you again then I'll add a new line character to the end so when we run this code we sing Happy Birthday once if I need to sing Happy Birthday let's say three times well without using a method we could although it's inefficient copy this code and paste it to additional times then we're singing Happy Birthday a total of three times well you know this does work but we tend to be repeating ourselves a lot in programming we like to follow the dry principle don't repeat yourself how can we not repeat ourselves if we don't have to well let's create a method a method is just a block of reusable code so to create a method in Java outside of the main method do pay attention to these curly braces we'll create a new method a method can return something for now we'll type void much like our main method and we need a name for this method the method should be descriptive of what it does let's call it the happy birthday method all it does is sing happy birthday we need a return type a name for the method that's descriptive parentheses then curly braces let's cut our song of Happy Birthday birthday and paste it within the happy birthday method at any point to use this method I have to call it call it by its name happy birthday then add a set of parentheses so we have one issue in Java Java wants this method to be static much like the main method that we work within so in order for this program to work we need to add this keyword of static normally you don't need this keyword but since we're calling this method of happy birthday from another method that's static this method also needs to be static later on in the series we'll discuss what static does you'll likely have to include that for now all right let's do a test run so we are going to sing Happy Birthday once so again to call a method type the name of the method then a set of parentheses the pair of parentheses kind of represent a pair of telephones that's how I think of it at least so now we should sing Happy Birthday now this code is reusable we write it once and reuse it whenever we want we just have to call it again we will call the happy birthday method again now we are executing that block of code two times or even three happy birthday one thing you should be aware of is that methods are unfamiliar with any variables declared within other methods so let's say we have two variables a string of name type in your first name whatever it is and an integer of age set it to be some age if I was to use these variables within my happy birthday method well the happy birthday method actually doesn't know what these are so let's attempt to use them and see what happens within our happy birthday song Let's convert this print statement to be a print F statement and we will insert our name variable replace U with the format specifier and we are displaying a string see we already have a warning cannot resolve symbol name I'll attempt to run this code and we'll see what happens exactly Java cannot find variable name methods are not familiar with variables inside of other methods if we live in this method of main if it's our house so to say we can't see what's going on in our neighbor's house one way in which we can solve this is to pass arguments to this method from one method we can send information to another method these are known as arguments so when we sing Happy Birthday within the set of parentheses within the pair of telephones we can pass a value or a variable so let's send our variable of name to this method of happy birthday anything that you send a method is known as an argument but we have one issue though our method of happy birthday isn't set up to receive arguments if you send any values or variables to a method via arguments you need a matching set of what is called parameters our happy birthday method isn't set up to receive these arguments we need a matching set of parameters to set up some parameters we're going to list the data type of what we're receiving we're receiving a string Val value so the data type is going to be string and then we need a name for what we're receiving it doesn't have to be exactly the same but it might be helpful to keep these consistent so let's perform a test run after this print F statement I'm going to add a new line character happy birthday to you happy birthday dear your variable name so if I was to change my name to let's say sponge Bob we'll insert this value at this location within our method happy birthday dear SpongeBob let's also pass in our variable of age so any arguments you're sending to a method you're going to comma separate however we need a matching set of parameters our method isn't set up to receive this variable of age let's perform another test run so we have an error actual inform formal argument lists differ in length we need a matching set of parameters to the arguments we're receiving not only do we need a string variable we need an integer variable because we're receiving an integer so let's say int age we'll insert our age variable right here we're displaying an integer so we need percent D this will be a print F statement then I will include a new line character we are inserting our age variable let's say SpongeBob is 30 years old all right let's see how this works now happy birthday to you happy birthday dear SpongeBob you are 30 years old happy birthday to you so with these parameters you can rename them when you receive these arguments just be sure that the order and their data type is correct for example we could rename name as let's say birth day boy you know this would work too SpongeBob is the birthday boy the names of your parameters can be different from the arguments just be sure that you get the data type correct and the order in which you receive these arguments let's replace the name of SpongeBob with Patrick Patrick will be 38 so now now with the happy birthday method we're inserting new variables happy birthday dear Patrick you are 38 years old with methods they also have the capability to return a value so I'm going to collapse this happy birthday method we won't be working with it anymore let's create a method to square a number we'll create a method to square a number then return the result normally if we're not returning anything we would type this keyword avoid void but since we're returning a double we have to list the data type of what we're returning we're returning a double then we need a name for this method let's say double square all we're going to do is use the return keyword let me zoom in a little let's return a number times itself number we're going to receive one argument an argument of number we have to set up a matching parameter our number is going to be a double double number let's call the square method I will Square the number three and again since we're calling a method that's not static from another static method we need to add this keyword of static in order for it to run there'll be more on the static modifier in the future so if I was to run this we get no output we're returning a double back to the exact spot in which we call it we could assign it to a variable or print it directly let's say double result equals Square the number three then display the result so 3^ squar would give us nine so when returning something just imagine that after the method ends we're replacing that method call with whatever we're returning in this case nine picture it that way and then we're assigning nine to our double of result or we can just output it directly if you would prefer to do it that way let's print 3^ squar and that would also give us n now let's create a method to cube we're going to return a double double Cube we have one parameter a double of number we're going to return our number time number time number that would cube a number that we're given and again we need to add static because we're calling a method from another method that's static all right this time we will call the cube method and return the result so 3 cubed is 27 3 * 3 * 3 is 27 one last example we'll create a method to return full name after being given a first name and a last name we're going to return a string we'll call this method get full name we'll have two parameters a string of first for first name and a string of last for last name we're going to return our first name plus a space to separate them plus our last name of last and again we have to add static okay let's declare a string variable of full name equals call be get full name method then pass in some arguments let's pass in SpongeBob then for the next argument SquarePants and then we'll print the full name print full name our method returns one long string of SpongeBob SquarePants the return keyword will return a value after the method ends it will return that value back to the place in which you call that method after this method of get full name is complete just imagine that we're replacing it with one long string of SpongeBob SquarePants like this and then assigning it to this variable okay so I lied I have one last good example to give you will create a method to verify a user's age normally in the United States at least you have to be 18 or older to sign up for things like a credit card we'll create a method to check a user's age again we're going to use static because we're calling a method from another method that's static let me zoom in we're going to return a Boolean this time the name of the method let's name it age check and there's going to be one parameter and integer of age if we're going to do an age verification check we could use an if statement so within our method we'll write an if statement if our age parameter is greater than or equal to 18 then let's return true else we're going to return false this can be simplified to the following return AG is greater than or equal to 18 you could do it either way for a beginner it might be easier to read if we have separate IFL statements but both work the same all right so we now have a method to check a user's age so now we can use this method I will create an integer variable of age set it equal to some age I'll use an if statement we're returning a Boolean value I can use that within an if statement if H check then pass in an argument we will pass in our variable of age if this is true if age is greater than or equal to 18 you return true so let's print the following you may sign up maybe we're signing up for a credit card else let's print you must be 18 + 2 sign up our ages 21 you may sign up but if we were 12 that method returns false you must be 18 plus to sign up so that's a method everybody it's a block of reusable code that is executed when called again I like to think of the parentheses after a method as a pair of telones talking to each other to use a method you have to call it and well everybody those are methods in Java hello everybody in this video I'm going to explain overloaded methods in Java in Java overloaded methods are methods that share the same name but they have different parameters a method's name plus its parameters will give you a unique method signature each method signature needs to be unique no two methods can share the same signature but they can share the same name let me give you a demonstration let's say we have a method it's going to return a double the method name will be add we'll add two numbers together add is the method name and then we'll set up some parameters we'll have double A for the first number and Double B all we're going to do is return a plus b it's a simple method so I'm I'm going to print add the numbers 1 + 2 and then print it this will give us three what if I would like to add a third number you can see that Java is already giving us a warning expected two arguments but three found so if I were to run this program we get an error actual and formal argument lists differ in length once solution is that I could create another method also named ad but it has different parameters where we accept three numbers so let me just copy this method paste it then I'll add another parameter for Double C return a plus b plus C and that should work now the number is six these two methods share the same name but they have different parameters so that's actually legal in Java a method's name plus its parameters will give you a unique method signature no two methods can share the same signature with our second method let's delete the last parameter of Double C and attempt to run this and we'll see what happens exactly well we get an error message method add is already defined in class main Java is saying that we have two methods that share the same name and the same exact parameters methods can share the same name but they need different parameters if that's the case now if I would like to add another number like four I could create another overloaded method also named add but this one will have four parameters Double D return a plus B+ C+ D and this works too let's go over another example let's pretend that we're baking a pizza we'll have a string variable of pizza we'll create a method to bake a pizza but we have to pass an ingredients we'll declare a method with static we'll return a string that's the return type the method name will be Bake Pizza our parameters are going to be a set of ingredients for this method we'll just accept a string of bread we'll just return our bread variable plus the word pizza so this could be for example a thick crust pizza or a flatbread pizza so to say let's set our pizza variable equal to called the bake pizza method now this method only has a bread setup as a parameter an ingredient let's say flat bread for the bread and then we'll print our pizza system. out. print line our string variable of pizza here's what we have we have a string of flatbread pizza so when baking a pizza there's a lot of different ingredients let's create another method of baked pizza but we have a parameter of bread and a parameter of cheese let's copy this method paste it but we have to change the parameters we're already receiving a warning we'll have string bread and string cheese no pun intended let me zoom in now those warnings have went away we have two methods with the same name but they have different parameters which is fine we can do that so this time let's return a string of cheese plus a space character plus our bread plus the word Pizza let's pass in a type of cheese Mozzarella I probably misspelled that actually I spelled it correctly okay now we'll bake our pizza we have a mozzarella flatbread pizza if there's two or more methods with the same name we'll end up using the method where the parameters match we'll create one more overloaded method we'll create another baked pizza method but this one will have a custom topping string topping we'll return topping plus a space character plus everything we had previously then we can pass in A new ingredient how do you spell pepperoni I can never spell it pepperoni now this time we have a pepperoni mozzarella flatbread pizza all right everybody so those are overloaded methods methods can share the same name but they need to have a different list of parameters a method's name plus its parameters will give you a unique method signature and no two methods can share the same signature and well everybody those are overloaded methods in Java I got a relatively quick video for you today today we're going to discuss variable scope in Java variable scope is where a variable can be accessed there's two levels we'll discuss today local and class we'll cover local first inside of a method if you declare a variable it has what is considered a local scope in this demonstration let's create a variable of x x will equal some number such as one and then you know we can print whatever X is xal 1 a variable declared inside of a method has a local scope and I'll just add a comment that this is a local variable outside of the set of curly braces where this variable is declared X isn't going to be recognized that's why if we create another method we would have to pass it as an argument let's create another method this will be a static method that doesn't return anything I'm just going to say it's the do something method inside of other methods you can declare variables that have the same name within this other method we're going to create an integer variable of X but X is going to equal two so Java isn't giving us any warnings it is legal to have variables with the same name as long as they're within different methods the moment I place this variable within my main method Java is giving us a warning variable X is already defined in the scope this local scope variable X within main has a local scope variable X within the do something method also has a local scope and I'll just add a comment that this is a local variable if I was to print X within this method and if I was to call this method what do you think will output one or two take a guess two within the context of our do something method xal 2 this method isn't aware of the existence of this variable within this method of main they each have a local scope it's kind of like their neighbors they can't see inside of each other's house now a class variable is declared inside of a class but not within any methods you usually see them at the top let's create a static variable an integer of X where x equals 3 variable X within this class of main has a class scope in our analogy of houses you could say that this variable is out in the street these two methods can look out their window and see variable X and that it equals three if I was to delete these two local variables and print X here's the result xal 3 or within our main method if I was to print x x also equals 3 let's say that each method is a house they're neighbors you you could say that a class variable is outside they're walking down the street both of these methods can look outside their window and see this variable now if you had a mix of both local and class variables that share the same name let's say int xals 1 and this was a local variable and within our method of do something xal two let's call the do something method we'll print X within the main method and then within the do something method what do you think the output is going to be well we have one and two even though there's a third X variable within the class scope Java likes to use any local variables first if they share the same name as any class variables within our method of main this method thinks xal 1 it's going to use theal scope first you'll likely want to stick with local variables over class variables there are a few situations when a class variable would be better such as if you have constants where the value doesn't change or when working with object-oriented programming which is a whole another topic so that is variable scope in Java anything with the local scope is declared inside of a method or otherwise within a set of curly braces and is only recognized within this method other methods aren't aware of its existence that's sometimes why we pass them as arguments to other methods class variables are declared inside of a class they are recognized throughout the entire class and well everybody that is variable scope in Java hello everybody in this video we're going to create a very simple banking program using Java this video is meant to be a beginner's project to help us understand how methods work so if that sounds good to you let's get started as a beginner it might be helpful to you to break up your project into separate steps then tackle this project one step at a time I'll add a few comments of the different steps our program is going to take so first we're going to declare our variables I misspelled that then we will display a menu a user is going to pick a choice from this menu depending on what they want to do they can make a deposit show their balance make a withdrawal so on and so forth we will get and process users Choice we'll create a method of show balance in order to display the balance to the user let me zoom in another method to make a deposit then a method to withdraw withdraw funds we'll just say withdraw and then we will create an exit message at at the end once the user exits so again as a beginner it might be helpful to you to break up your program into different steps we'll start with our step of declare variables here's the different variables we'll need we have an account our account has a balance such as dollars and cents so a double would make sense for the balance because it includes a decimal portion sents so we have our balance we'll need a scanner because we're accepting us user input scanner scanner equals new scanner type system.in import this class import java.util.scanner and then we are going to close our scanner when we're done with it let's take care of that now because I'm probably going to forget we have our scanner our balance we're going to continue this program as long as a user doesn't exit we'll need a while loop we will declare and assign a Boolean variable of is running set that to be true continue this program while is running is true then we will accept a choice from the user this will be an integer a user is going to pick one to show balance two to deposit three to withdraw or four to exit the user is going to fill this in later using the scanner all right we have declared our variables now we'll a menu to the user I will print the following let's say banking program now you don't need to do this but I like to add some separators using a bunch of asterisks I just think it makes it look cool we will lay out the different options we will have option one option one will be to show balance option two will be to deposit option three will be to withdraw four will be to exit and then I'll add another separator again not necessary I think it would just look more organized now we need to get and process the user's choice we have a variable of choice we'll need to create a prompt we will say enter your choice then hint one through 4 I'll use print instead of print line because I like the user input on the same line as the prompt we will assign our variable of choice equal to use the scanner call the next int method ideally a user is going to type in a number 1 through 4 to do one of the following now we'll process the user's choice I think an enhanced switch would be great for this we will create a switch and examine our variable of choice we're examining our choice against matching cases if Choice equals a case of one we'll write an arrow to do something we'll do this we're going to call a method to show our B balance because one means the user wants to show their balance we'll fill that in later let's write a test message I'll use system.out.print LINE let's say show balance case two will be for deposit we'll just print a test message of deposit again we're going to fill this method in later and call it case three is for withdraw case three withdraw case four is to exit that we can actually fill in right away it's pretty simple we'll take our Boolean variable of is running and set it to be false then we'll add a default case in case somebody doesn't type in a number 1 through four we'll output invalid Choice Let's test numbers 1 through three first enter a choice I'll pick one that's for show balance again we'll be calling a method later to show our balance two is for deposit we're depositing three is for withdraw four is to exit but it doesn't do anything currently then any other choice such as five prints out invalid choice we want this program to continue running as long as is running remains true so let's enclose our code within a loop a while loop while is running you don't necessarily need to say equals true if it's a Boolean you can just say the Boolean variables name name while is running is true then do all this code so I'm going to cut our code currently and paste it within the wild Loop now we can test is running one is to show balance we show our balance two is to deposit we deposit three is to withdraw withdraw four is to exit and we should exit processed finished with exit Code Zero we know that that works now our next step is to show balance and this is going to be a method outside of our main method we're going to create a new method of show balance this has to be a static method because our main method is also static there will be no return type the return type is void the method name will be show balance there's going to be one parameter a double of balance when we call this method we have to pass in our balance variable within this method we're going to use a print F statement and I'll zoom in a little within this print F statement pick a unit of currency you would like to use for this banking program all use American dollars we need a placeholder we'll use a percent sign and then F to display a double f means floating Point number we will display our balance and from the beginning I'm actually going to set my balance equal to zero we're going to be testing it then let me zoom out for case one we're going to call the show balance method but we have to pass in our balance variable all right let's test it enter a choice I'll pick one to show our balance uh here's what we got currently 0 and a bunch of zeros after the decimal we are forgetting that new line character too so let's add a new line character to the end before I forget if you would like to display two digits after the decimal for example normally when you display a floating Point number using print F you display six digits after the decimal to limit it to two we can add the following after our placeholder our percent sign we're going to add 02 and to your choice I will type in one to show our balance our balance is $0 and0 we're displaying two digits after the decimal let's change our initial balance to be $10 and 99 ENT to your choice I will type in one our balance is $10 and 99 I think I'm also going to add a separator before displaying the balance too to help with readability although it's not necessary so I'm going to cut one of these lines where we display a bunch of asterisks and print it right before displaying the balance let's show our balance and here's our balance $10 and 99 and we have some of those separators before and after which I think looks nice our show balance method is complete I'm going to collapse this method we don't need to code within it anymore our next method is to make a deposit we'll create a method of deposit oh and then be sure to set your balance back to zero we will create a static method the return type is going to be double we will declare this method as the deposit method there will be no parameters but we will be returning something a double inside of this method I will create a local variable the data type is double the name will be amount a user is going to type in an amount the amount that they're depositing using this method this method isn't going to work properly until we return something add return statement just temporarily so everything runs fine I'm just going to return zero we'll take care of this later I just want everything to run a compile fine we will prompt a user to type in an amount I will use print instead of print line that's my own preference for prompts enter an amount to be deposited now here's one issue we're accepting user input from a user amount equals if I attempt to use our scanner scanner. next Double there's an issue our method isn't aware what the scanner is because we declared the scanner within a separate method our main method methods can't see inside of each other there's a few different options one we could create a local scanner within this method you know scanner scanner equals new scanner and all that I don't like the idea of creating creting several different scanners within this project because then we're leaving them all open to accept user input so why don't we do this let's take our scanner move it from this local scope and put it within a class scope so let's cut our scanner within the main method and stick it within the main class but it does need to be static because some static methods are using it this one scanner is accessible throughout the whole program now and that warning goes away so I think this would be better than creating several different scanners and leaving them all open throughout this program we're just going to reuse the same one at this point we're going to verify the amount that the user types in I'll use an if statement first if a user types in an amount that's negative well they can't make a deposit they can't deposit negative money that's stupid so we will check if our amount variable that the user types in is less than zero if that's the case we will print the following amount can't be negative and then we will return zero if the user does type in an amount that's valid we'll execute an lse statement where we're going to return let's cut our return statement at the end we'll return our amount now when we call our method we can delete this print line statement if a user selects two to make a deposit we're going to assign our balance variable balance equals our balance plus call the deposit method our deposit method is going to return a number an amount if it's valid we're going to return it back to the place in which we call it it we will add this to our current balance and reassign it to balance our balance will equal our current balance plus the deposit that we make we can shorten this too we could just say balance plus equals deposit okay let's do a test run banking program let's show our balance our balance is currently zero we'll select two to make a deposit two enter an amount to be deposited let's try and break it first let's say1 million amount can't be negative then we're brought back to the menu let's try and make a deposit again enter an amount to be deposited let's say $150 and a nickel 5 cents that seems to have worked let's show our balance again and here's our New Balance $150 and 5 cents all right the deposit method is done we can collapse it we no longer need to code within it and now we need a withdraw method we will declare a new method it's a static method we'll be returning a double the name of this method will be withdraw there will be one parameter we will pass in a balance double balance we do need to return something so temporarily just so our program runs correctly I'm just going to return zero we'll change that later within this method I'm going to create a local variable of amount double amount we will prompt a user enter amount to be withdrawn we will assign our amount equal to we're going to use our scanner and remember it's within the class scope so we have access to it within this method scanner. nextt double to accept a double if somebody tries to withdraw money that they don't have we can check that within an if statement if the amount is greater than our balance we're passing in our balance so we know what what it is if somebody tries to withdraw a million dollars but they have no money in their bank account well they can't do that we will print insufficient funds what if they try and withdraw negative money we can check that within an else if statement else if our amount that the user types in is less than zero will output amount can't be negative else if everything checks out we'll return the amount I will cut our current return statement we will return the amount that the user types in return amount So within our if statement return zero within our else if statement return zero when we reach the end we do need to return something even if it is zero and I'm going to use print instead of print line so let's go back to our switch right here we're going to be returning a double we will take our balance equals we're assigning it take our current balance minus call the withdraw method but we have to pass in our our balance our original balance from our current balance we're subtracting the amount that we're withdrawing we can simplify this expression too we could say balance minus equals then call the withdraw method all right let's do a test run first we'll make a deposit I will deposit $100 to keep the simple I will show our balance we have $100 I will try and withdraw like a kajillion dollars insufficient funds we don't have a kajillion dollar let's withdraw again I will try and withdraw negative money $ 42069 amount can't be negative we can't withdraw negative money okay let's try and withdraw something that's valid $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 you have a nice day just so the user knows that they have exited the program and for fun I'm going to add some text decoration some 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 will show our balance we have 0 I will make a deposit I will deposit $11,000 show our balance we have $1,000 I will withdraw let's withdraw a single penny 0.01 show our balance we now have $999.99 sense I will press for to exit and we exit thank you have a nice 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 rolling program a user is going to type in a number of dice they would like to roll based on the roll of each die we will displace masy art then at the end we will give the user a total the sum of all the dice that they have rolled so if that sounds good to you let's begin as a beginner it might be helpful to you to break down a large project into smaller steps let's list the order of steps we're going to take we will Begin by declaring our variables declare variables then we need to get the number of Dice from the user after we have the number of dice let's check to see if it's greater than zero we don't want somebody rolling negative dice check if number of dice is greater than zero we will roll all the dice get the total or the sum you could say the final part of this project we will display the asy art of dice all right here's a rough outline of our project the first step is to declare our variables we're accepting user input so we'll need a scanner scanner scanner equals new scanner type system.in import this class import java.util.scanner and then close our scanner when we're done with it scanner. close we'll be working with random numbers we'll need a random object to Generate random numbers random random equals new random import the class import java. u. random we'll need a number of dice the user is going to fill this in int num of dice how many dice are we rolling and a total int total we'll sum up all the dice for a total all right now we need to get the number of Dice from the user we'll need some input but we'll create a prompt first enter the number of dice to roll I'll use print rather than print line we will assign our variable of number of dice number of dice we will use our scanner to accept some user input we are looking for an integer we'll use the next int method of our scanner scanner. next in now we need to to check to see if the number of dice number of dice is greater than zero so let's take care of that we'll use an if statement to check that if num of dice is greater than zero then we'll roll some dice we'll get to that momentarily else we will print the following let's say number of dice must be greater than zero within our if statement let's say just temporarily you roll the dice okay we're doing a test run enter the number of dice to roll let's say I try and roll zero dice number of dice must be greater than zero let's try this again let's say I roll three Dice and then we're just printing a test message you rolled the dice okay we know that that works we can delete this print statement we no longer need it we were just testing it now we actually need to roll all the dice we'll take care of that within our if statement if the number of dice is greater than zero then we will roll the dice we're going to create a for Loop that will iterate once based on the number of dice we have so let's create a for Loop for in I will be our index in I equals z we will continue as long as I is less than our number of dice then increment our index of I by One during each cycle within this for loop we're going to generate a random number I will create a local variable of r r will equal now we'll use a random object to generate a random number a random number between 1 and six we will use the next int method of our random object we will specify our range 1 through 7 the first number is inclusive the second number is exclusive this will give us a random number between 1 and six then once we have our roll let's print it 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 rolled one you rolled two then we'll add these numbers together for a sum or total let's take our total total equals our total plus our roll and this is within the for Loop so Java does want us to initialize this variable so set total equal to zero when you declare it so total equals total whatever it currently is in this case zero plus roll we can shorten this too we could just say total plus equals roll we'll use the augmented assignment operator for addition then when we escape the for Loop we will print the total let's say total colon space plus our variable of total let's do a test run I Will Roll three dice we have 3 2 2 for a total of seven 3 5 7 okay we know that that works we have rolled all the dice and get the total now here comes the hard part we're going to display some ASI art based on the result of each die that is rolled so we're going to declare a method to take care of that for us let's do so outside of the main method we will create a static method that's not going to return anything the return type is void let's name this method print D D is the singular version of the word dice we're going to set up one parameter int roll what did we roll we're going to call this method before we display the output of you rolled whatever the RO is we will call the method of printing die and pass in our roll it's going to be a number between 1 and six let's head back to our print die method within the print die method we're going to create some asky art the asky art is going to be made of strings let's create a string of dice one equals now instead of a standard string that takes up one line we're going to create a 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 we're going to create some dice some asy art of dice so this will be an art lesson today let's start with seven dashes on the next line we'll create a vertical bar and on the other side we need a vertical bar too I'm going to shift these dashes over by one same thing with the vertical bar we need a another set of vertical bars another set and then we can copy our dashes again so we should have a shape like this right in the middle we're going to add a bullet point the easiest way to do this is to pull up the charm map application so if you hold windows and type R you can look up charm map hit 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 character map and paste that bullet point or otherwise you can find it from someplace else online let's print it just once I'm just going to print dice one let's do a test run I'm just going to roll one dice and this isn't going to be accurate right away 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 change dice one to dice two and move this bullet point around so this is Dice two then we need dice three dice three there will be a bullet right in the middle dice four we need the bullets in each corner and none in the center that's dice four dice five we'll have a bullet point right in the middle along with the corners and dice six we have two rows of bullet points and those are the dice that we need now we'll create an enhanced switch what are we examining so going back to our parameters right here we're examining the role that we pass in it's going to be a number 1 through six we'll examine our role against matching cases if roll matches a case of one we'll do this we will print rather than print line dice one dice one is this image the string if roll matches a case of two we will print dice two if Case is three we will print dice three four if Case is four print dice four five print dice five and six print dice six and a default case we might as well add one if there are no matches we'll print the following we'll say invalid roll all right and that's it let's run this enter the number of dice to roll I'll roll three Dice and here's what we got I rolled a six a two and a six all right everybody so that is a dice rolling program that you can make using Java what is going on everybody in this video I'm going to discuss arrays in Java an array is a collection of values of the same data type as a beginner it might be helpful to think of an array as a variable that can store more than one value it's a little more complicated than that but that might be a good way to think of it let me give you a demonstration suppose we have a string variable a fruit pick a fruit I will pick an apple and then you know we can print our variable of fruit which would give me an Apple well what if I told you that this variable can store more than one value if we were to turn it into an array here's how after the data type of our variable add a set of straight brackets enclose any values within a set of curly braces and there we go we now have an array we have an array of strings this array can store more than one value but they all have to be the same data type in this case strings let's add some more fruit let's add an orange a banana and a coconut the name of your array should be descriptive of what it contains let's say fruits instead of fruit technically in the English language fruit would still be plural but by adding an S it's more descriptive that it contains more than one value I know English is a weird language at times if I was to print my array of fruits here's the result while we get a memory address arrays fall under the category of a reference data type if we access the name of our array we're given a memory address each value within an array is known as an element to access an element we have to indicate an index number after our array name let's add a set of straight brackets and then an index number as is the case with many things in programming toxis the first of something it usually has an index of zero that applies to arrays as well print our array of fruits at index of zero that's going to give you the first element of Apple for the next element that would be an index of one which is orange two would be banana three coconut if we attempt to access an element that doesn't exist here's what happens we get an exception an exception is similar to an error we have an array in index out of bounds exception this error message appears when you try and access an element that doesn't exist within an array there is no index of four there's only 0 1 2 3 in this case now you do have the capability to change the value at a given index to do so we will take the name of our array in this case fruits specify an index using the set of straight brackets at index of zero let's set that equal to a string of pineapple rather than Apple and then we'll print it print our array of fruits at index of zero that would give us a pineapple rather than an apple by specifying the 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 property for that let's say say we have an integer variable of num of fruits meaning number of fruits to access the length of an array take our array in this case fruits use dot which is the axis modifier then type length give me the length of my array of fruits how many elements are within this array take a guess four there's four elements within this array 1 2 3 4 if you ever need the length of an array use the length property of your array this will return an integer which you can assign to a variable if you would like if you need to print all of 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 zero how many times do we want to iterate this Loop let's continue as long as I is less than we need to determine the length of this array well we can use that length property that we discussed take our array of fruits access the length property this should return the number four continue as long as I is less than four then we will increment our index of I so our for Loop in this case is going to iterate four times let's perform a test run if I was to print my array of fruits at index of zero this is what happens exactly it's going to print fruits at index zero four times apple apple apple apple what I need is to print each element of this array we could use our index V for that so replace zero with i i is going to change during each iteration of this loop we're increasing it by one after we complete each cycle of the loop so here's what happens now we get all the elements of our array Apple orange banana coconut this index of I is going to increase after each cycle of this Loop each iteration alternatively rather than printing each fruit on a new line we could use print then after printing each element we could add a space character that would print each element and separate each with a space if you so choose there's something called an enhanced for Loop an enhanced for Loop will cycle once for each element within an array we'll start with a normal for Loop to create an enhanced for Loop within the set of parentheses we will list the data type of each element of the array in this case strings now we need a unique identifier for each element within the Sur array since we're working with an array of fruits let's say fruit singular then we need a colon then our array that we're iterating through in this case fruits basically we're saying for every fruit in my array of fruits do this let's print each fruit fruit will be the current element we're cycling through here's what happens we print each fruit we have all the elements of our array of fruits Apple orange banana coconut this is an enhanced for Loop also known as a 4 each Loop it simplifies iterating through a collection such as an array if you need to sort your array there's a built-in sort method we're going to access the class of arrays you may need to import it import class arrays so make sure you have this import import java.util.arrays this class provides a lot of functionality when working with arrays there's a built-in sort method we're going to pass in our array 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 coconut but after sorting there they're now apple banana coconut orange they're all arranged alphabetically or if these were numbers they would be arranged in ascending order there's also a fill method with arrays we can fill all the elements of an array with a given value again we're going to access the arrays class called The Fill method pass in our array comma the value 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 element and here's our new array we have filled our array of fruits with the value of pineapple all right everybody that's an introduction to arrays think of an array as a variable but it can store more than 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 enter in user input into an array so let's get started before assigning values into an array our compiler needs to know the size of the array beforehand we have to first allocate space for the array let's begin by creating an array of strings we'll create an array of strings we'll enter in some food I will name this array Foods equals add a set of krly braces and then within this array you can enter in some values pick some food that you like I'll enter in a pizza taco and and hamburger the size of this array is three elements once you set a size for an array normally you can't change it this array will have three elements however all the elements are already filled with values to create an empty array you don't want a set of empty curly braces then we're creating an array of no elements just to demonstrate that I'm going to print the length of our array Foods foods. length this is going to give us zero and we can't assign any values even if I attempt to let's say Foods at index zero equals a string of pizza here's what happens well we have an exception and array index out of bounds exception before assigning values we'll want to be sure that we're setting a size of the array even if it is empty instead of assigning a set of values we'll create an empty array we'll set our array equal to use the new keyword type the data type of our array straight brackets and within the straight brackets we'll set a size a number so let's say three we're creating an empty array that has space for three elements three values let's try this again the length of our array is three and we can assign the values so let's say Foods at index 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 Loop list the data type we're working with an array of strings for every food in our array of foods we will print each food that would give us pizza Taco hamburger we have declared and instantiated an empty array and filled in the values later let's modify this program so a user can type in some values let's delete these lines if we're accepting user input we will need a scanner we'll declare that and instantiate it scanner scanner equals new scanner within the set of parentheses typ system.in import the class for scanner import java.util.scanner and close the scanner when you're done because I sometimes forget to do that still scanner. close so we have an empty array of three elements we'll create a for Loop to iterate over the length of our array of foods so four we'll create a counter of in I equals z will continue as long as I is less than our array of foods length property which returns three because there's three elements then increment I by One during each iteration of this Loop let's do the following we'll output the following prompt enter a food I'll use print instead of print line because I prefer that we'll assign our array of foods at index of I I changes during each cycle at first it's zero then 1 then two then three we'll set that equal to use our scanner to accept some user input call the next line method okay let's perform a test run currently we have an array with three empty elements we'll cycle this loop three times because the length property of the array is three then print all the elements when we're done here's what happens exactly enter a food pizza Taco hamburger here are the elements within our array of food pizza Taco hamburger let's say that we change the size of the array let's say for this time Pizza Taco hamburger hot dog Pizza Taco hamburger hot dog we're going to make a few changes instead of setting a static size for the array we'll have a user enter in the number of food they would like to enter we'll replace this number with a variable to determine the size what we'll do now is we will declare our string array of foods but instantiate it later once we know the 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 variable of size I'll declare it but not yet fill it in until after our prompt let's set the size the size of the array that is equal to use our scanner and call the next int method we are accepting an integer once we know the size of the array we can finish instantiating it let's take our array of foods that we've declared but have not yet assigned and we'll assign it our array is made up of strings we'll use the new keyword new list the data type string it's an array so we need a set of straight brackets and instead of a number we're going to use our variable the user is going to determine what this number is going to be there's one final step this is specific for scanners since we're accepting an integer and then we're accepting a string for our user input we have to clear the input buffer next integer isn't going to pick up the new line character at the end so just to demonstrate that let's say we want one food item there's still that new line character within the input buffer we didn't get the opportunity to enter in a food we are just going to clear our scanner by using scanner. next line and 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 pizza Taco hamburger hot dog and Sushi and here's our food pizza Taco hamburger hot dog sushi in summary to enter values into an array you'll likely want to create an empty array but you need to know the size of the array first if the size of the array is predetermined you can always set that to be a number otherwise if one way or another if a user is going to determine the size of the array you'll have to get that from the user and you can set the size of the array to whatever the user types in just be sure to do that before filling in the values if you would like a copy of this code you can look in the comment section down below be sure that you're looking in the playlist and well 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 can search through the elements of an array let's begin we'll need an array to work with to keep the simple let's create an array of integers we'll create an array of integers named numbers equals make up some numbers to put 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 let's say I'm searching for the number number two I will create an integer variable of Target set it equal to two in data structures and algorithms we'll be performing what is known as a linear search we're going to use a for Loop to iterate through these elements and then see if there's a match we'll create a for Loop create an index of I I will equal zero we'll continue as long as I is less than R array of numbers access the length property that will return the length as a number then increment I by One I will check using an if statement if our Target is equal to our array at the current index of I at first I will be zero and then we increment it during each cycle of this 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 in case we find the target for example two we don't need to search through the rest of the array we could add what is known as a break statement to break out of the loop if we find the target break out of the loop let's perform a test run we're searching for the number two and we'll be given the index element found at index 2 let's look for one one is found at index zero four which is near the end is found at index 6 0 1 2 3 4 5 6 what if we 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 once we reach the end of the array we don't do anything so let's add a Boolean variable of is found and set it to be false we'll check if is found is false if that is the case we'll output a message that element wasn't found in the array so if we do find our Target we'll take our Boolean variable of is found 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 that we'll say is found but we'll use the not logical operator the not logical operator gives you the inverse of a Boolean value or variable if is found is false if something isn't true if we don't find the target then we execute this if statement where we will print the following let's say something such as element not found in the array all right we are looking for the number seven which does not exist within this array that would give us this message element not found in the array because is found was false we could never find it within this for Loop so we're checking if is found is not true what if we have an array of strings and we're searching for an element well instead of using the comparison operator we have to use the equals method of strings because strings are a reference data type so this time let's say we have an array of strings named fruits think of some fruit I will pick an apple an orange and a banana the target this time will be a string let's say I'm searching for an orange will iterate through our array of fruits the condition for the for Loop will be I is less than the length of our array of fruits now we can't necessarily say is our Target equal to fruits at index of I we're comparing two strings and since strings are reference data types we would end up comparing the memory addresses of two different strings we would be saying are these two memory addresses the same are they at the same location which isn't the case if we're comparing the value of strings we'll use the equals method let's take fruits at index of I call the built-in equals method of strings and pass in our Target as an 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 program slightly we'll accept some user input but we'll need a scanner import the class java.util.scanner and close your scanner when you're done with it scanner. close instead of assigning our Target we'll accept user input we'll use our scanner use the next line method and we will also need a 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 is found to the top here I'll declare our string of Target but not assign it and then after the prompt I'll assign our name of Target this is just how I like to arrange things but it all works the same now we can search for an element after acting user input and I will convert this to be a print statement instead of print line 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 that's how to search through an array using Java hello everybody in this video I'm going to explain variable arguments also known as VAR args in Java variable arguments allow a method to accept a varying number of arguments they make methods more flexible and there's no need for overloaded methods overloaded methods are methods that share the same name but have different parameters in this example I have several add methods they each have different amounts of parameters if I was to add a few numbers together for example I'll add 1 + 2 + 3 well then I would use this method what if I told you instead of creating several different methods that basically do the same thing we could instead create one method that accepts any number of arguments we'll only need to declare one method we will create one add method that accepts a varying amount of arguments so let's create a method the return type let's say is an integer we'll create a method of add our method will have one parameter what is the data type of the values we're sending this method in this case integers we're going to follow the data type with three dots and ellipses how this works is that the Java compiler is going to pack the arguments we send it into an array we'll need a name for this array let's say numbers just to demonstrate this temporarily I'm going to print my array of numbers when we call the add method we can send any number of arguments for example 1 2 3 4 and they're going to be packed into an array within this method we're now working with an array let's perform a test run let's return void actually so we're given a memory address of this array now let's actually add these numbers together we need to cycle through the elements of this array we can use a for Loop or an enhanced for Loop for that so let's return an integer in this 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 number in my array of numbers let's take our sum and add the current number sum plus equals number then at the end we will return our sum and there we go and then we need to print the output I'm going to cut this and paste it within a print statement let's perform a test run the sum when we add these four numbers together the sum is 10 and we can pass in any number of arguments the result is now 21 basically the Java compiler is packing all of these arguments into an array when we send them to a method then within the context of this method we would just need to work with this array one way or another but it's a lot easier than having several different overloaded methods okay this time let's create a new method we'll create a method of average average will find the average value of whatever we send it so we will create a static method that's going to return a double this time the method name will be average what is the data type of what we're sending let's say double then we need the ellipses the three dots then a unique name for this array let's say numbers so to find the average we can perform the following code let's say we have double sum I will set that equal to zero we will create an enhanced for Loop the data type is double for every number in my array of numbers do the following we will take our sum and add the current number sum plus equals number then at the end we will return sum divided by now since we're working with an array there is a built-in length property numbers. length to find the average you take all the numbers add them together then divide it by the amount of numbers that you have let's perform a test run I'm going to print call the average method let's find the average of a few numbers I don't know what that's going to be so the average of these four numbers is 2.5 I can pass in any number of arguments so the average of these numbers is four 4.0 you can even pass in no arguments if you so choose but with this method that we have created here's what happens we're actually dividing by zero because the length of our array is zero there's no elements that we're passing in in this specific example let's create an if statement if our array of numbers if the length of it we can access the length property is equal to zero let's return zero instead of receiving noted number we're calling the average method but passing in no arguments this time that would give us zero because the length of our array is zero because we're passing in no arguments I already everybody so those are variable arguments they allow a method to accept a varying number of arguments it makes methods more flexible and there's no need for overloaded methods the Java compiler will pack the arguments into an array when setting up the parameters of a method declare the data type and add a suffix of an ellipsis Three Dots and well everybody those are variable arguments in Java hey there everybody so today I'm going to explain 2D arrays in Java also known as multi-dimensional arrays a two-dimensional array is an array where each element is an array it's useful for storing a matrix of data let me give you an example let's say we have some basic one-dimensional arrays I will create a string array of fruits think of some fruit I'll add an apple an orange and a banana then I'll create another separate array let's create a string array of vegetables think of some vegetables I will add a potato an onion and a carrot let's create one more I will create a string array of meats I will add chicken pork beef let's add one more and fish these three arrays are all separate one-dimensional arrays well what if I told you we can make an array made of arrays where each element is an array here's how we're going to combine all these arrays together into a grid or Matrix I will create a two-dimensional array of strings we will need two sets of straight brackets I will name this two-dimensional array groceries and then we need our curly braces this two-dimensional array each element within this two-dimensional array is going to be an array we have fruits vegetables and meats let's attempt to display these elements you can use a for Loop or an enhanced for Loop within this for Loop what is the data type of each element well each element is a string array so we need to list the data type as a string array let's give a nickname of each element as Foods in our two-dimensional array of groceries let me show you what happens if I print each element within our two-dimensional array of groceries I will print each array of foods here's what we got well we get a bunch of memory addresses because arrays are a reference data type 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 is the data type of each element within each well we're working with strings so the data type is going to be string let's give a nickname of each element as food in our array of foods during each cycle of this Loop let's print not print line each food and then I'll add a space here's what we got currently we have our first array and our second then third after finishing each array I'm going to add a new 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 there's columns and rows each row is a separate array now when initializing an array you don't necessarily needed names let's remove fruits copy the elements of this array including the curly braces and paste them within this two-dimensional array just for readability I'm going to place each row on a new line let's replace vegetables with the elements including the curly braces same thing applies with meats and we can delete all this this would work the same groceries is a matrix of data a gri let's print this and that works the same if you ever need to access or change an element you'll need to use two indices for example let's replace apple with the pineapple we will take our two-dimensional array of groceries and list two indices the first index applies to the row the second index applies to the column so we're saying at row 0 column 0 we can change it or access it let's say that row 0 column 0 is now a pineapple rather than an apple then we have pineapple orange banana let's replace our potato with something else that would be Row one column 0 Row one column 0 is now celery celery onion carrot let's replace the carrot with celery then that would be Row one column 2 0 1 2 Row one column 2 potato onion celery let's replace pork with eggs that 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 within a 2d array you need to list two indices the first for the row the second for the column okay now we're going to create a mini project we'll create a two-dimensional array that resembles a telephone number pad this two-dimensional array will be made up of characters the data type is Char and then we have two sets of straight brackets let's name this two-dimensional array telephone 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 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 double quotes for the second row we'll have four 5 6 the third row will be 7 8 9 now for the last row we'll have an asterisk character Zero and pound or hashtag as I like to call it so here's our Matrix our grid of 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 type of each element within this two-dimensional array well each row is an array of characters that's going to be the data type of the outer for Loop we have an array of characters let's give a nickname of each inner array as a row in our two-dimensional array of telephone for every Row in our telephone do this then we'll need a nested Loop what is the data type of each element within each array their characters the data type will be Char let's say for every number in each array of row we'll print the following we'll use print rather than print line we'll print each number and I'll add a space character let's do a test run after each row I'm going to print a new line character so when we escape the inner four Loop I'll add an empty print line statement and here's our telephone we have rows and columns it's a two-dimensional array of characters so those are two-dimensional arrays they're an array where each element is an array it's useful for storing a matrix of data we probably won't be using 2D arrays too often but you should still be familiar with them and well everybody those are two dimensional arrays in Java hello everybody in this video we're going to create an interactive quiz game using Java for this project you'll create an array of your own custom questions and a two-dimensional array of all the different options for answers that we have you'll type in a number 1 through four depending on your guess after all of the questions are answered we will display a final score depending on the amount of correct guesses that you have so let's begin as a beginner it might be helpful to you to break down your project into different steps as comments we'll list all of the different steps we need to take to get this program up and running the first thing that we need is an array of questions questions will be an array we will also need options options will be a two-dimensional 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 we will use a loop now within this loop we're going to do a few things we will list our options then get guess from user then check our guess to see if it's 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 step at a time let's begin with creating an array of questions we'll ask the 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 project we'll have five 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 feel free to come up with your own here's a few that I've looked up online my first question will be what is the main function of a router that'll be the first question I'll put each of these questions on a new line just for readability the second question will be which part of the computer is considered the brain then I'll go to a new line what year was Facebook launched who is known as the father of computers then for my last question what was the first programming language all right here are the questions questions is an array of strings a one-dimensional array now we'll create a two-dimensional array of 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 options for our first question each value within this first array is going to be strings and I'm going to zoom in a little so we can both read it what is the main function of a router here's where you're going to list all of the different possible answers but only one of them is going to be correct I'll say one. space storing files for option two that will be encrypting data option three will be for directing internet traffic this will be the correct answer number three number four will be managing passwords this will be my first array all the options for question one now for question two for question two we'll have four options honestly I'm just going to copy these and then paste them within each array just to speed things up what part of the computer is considered the brain here's the different options option one will be CPU that's going to be the correct answer the central processing unit two hard drive three Ram four GPU question three what year was Facebook launched option one will be 2000 option two 2004 and that's the correct answer 2006 or 2008 who is known as the father of computers let's say Steve Jobs Bill Gates Allan Turing or Charles Babbage and that's the correct answer what was the first programming language either cobal C for Tran or assembly the correct answer is actually Fortran it's the first commercially available programming language one more thing we're going to create a one-dimensional array what are the correct answers we'll need some sort of key we could include this with our declare variable step we will create an integer array of answers we will list the correct answers as integers the correct answer to question one is directing internet traffic so we will list three for the next question what part of the computer is considered the brain that is the CPU option one Facebook was launched in the year 2004 that's two who is the father of computers that is Charles Babbage that's four and the first commercially available program ining language is for Tran that is three here are the correct answers are key there's a few more variables we'll need we will create an integer variable of score we can set that to be zero if we would like and an integer of guess guess is going to store whatever the user types in 1 through four so it's going to be an integer we will also need a scanner to accept user input scanner scanner equals new scanner it doesn't really matter where we declare it just as long as we declare it before we use it system.in and then we will import this class import java.util.scanner and then 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 questions our next step is to create a welcome message let's output the following let's say welcome to the Java quiz game and then I'll add some 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 idea to test your code as you're coding it just sure that everything is working fine and that is our welcome 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 equals z we'll continue this loop as long as I is less than the length of our array of questions questions access the length property which will return a number in this case five because there's five questions we will increment I by one as a test let's print our questions at index of I I will start at zero so we're returning the first question at index zero then during each iteration of this Loop we will display each question let's do a test run so here are the five questions we're displaying each element of our array of questions after each question we have to list all of the different options that's the next step we'll display a question then create a nested Loop to display all of the options I'm going to use an enhanced for Loop for this what is the data type of each value within each array within options well we're working with strings the inner for Loop is going to be an enhanced for Loop the data type of each value is a string string option colon meaning in rray of options at index of i options is a two-dimensional array if we retrieve a value at a given index will be given an array display every 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 through and print all of the options now before moving on to the next question we have to get some user input we don't want to display all the questions right away just one at a time so we will do this within the outer for loop after printing all of the options 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 of print line because I like the user input on the same line we will assign our variable of guess guess equal scanner. next int the user going to type in a number 1 through 4 then we have to check our guess is it correct or not we can do the following we'll use an if statement if our guess is equal to our array of answers it's a one-dimensional array at index of I we're using the index of I because we're still within our for Loop during the first iteration of this Loop I will be zero so is our guess equal to answers at index zero if that is correct let's print the following let's say correct and for fun 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 lse statement if we don't have the correct answer that means we have the wrong answer and I will output wrong and I will just space this out a little bit all right let's do a test run for the first question the correct answer is three I'll type in three then we print correct which part of the computer is considered the brain I will intentionally get this wrong let's say the GPU wrong and I'll guess the others wrong wrong wrong then we have to calculate a final score okay then we have to display the final score so after we get the correct answer we will increment our score by one score Plus+ then we will display the final score your final score is I'll use string catnation to keep this simple we'll add our score variable plus the words out of plus we're going to get the length of our questions questions is an array questions. length property I'm just going to add a space right before out because I'm forgetting that let's run this one last time what is the main function of a router that that is three directing internet traffic which part of the computer is considered the brain that is the CPU what year was Facebook launched I'm going to get this one wrong intentionally I'm going to say 2000 and that is wrong who is known as the father of computers that is Charles babage 4 what was the first programming language well the first commercially available programming language that would be three for Tran correct your final score is four out of five all right everybody so that is an 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 rock paper scissors for beginners so let's get started as a beginner when creating a project it could be helpful to you to break down a project into smaller steps just as comments I'm going to list the different steps that we'll need to take so let's say first we will declare our variables then then get a choice from 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 goodbye message it may be helpful to you as a beginner to list the different steps that your program is going to take just for more organization all right let's work on step one we will declare our variables we'll need a scanner because we're accepting user input scanner scanner equals new scanner within the set of parentheses we will type system. in import the class for scanners import java.util.scanner and then we will close our scanner when we're done with it scanner. close because we don't want to leave any resources open we will be generating random numbers we will need to create a random object random random equals new random and then import this class as well import java.util random we're going to create an array of choices they will be strings rock paper or scissors we will create a string array named choices equals an array this will be an array of strings at the first index we'll have Rock then paper then scissors we'll store our choice within a variable this will be a string we'll name this variable player choice I will declare this variable but not yet assign it and the computer's Choice string computer choice we're going to create a while loop that will ask the user to play again when they reach the end we'll create a string variable of play again and I will set this to be yes basically while play again is yes continue the game let's work on our next step get the choice from the user we need to prompt the user we'll use a print line statement and say enter your move I'll add a set of parentheses that says rock paper scissors just so the user knows what to type in I'll use print instead of print line because I prefer user input on the same line once we have our prompt we're going to assign our player choice variable player choice equals we will use our scanner to get some user input we need to accept a string so we can use the next line method to accept a line of text in case a user types in any uppercase characters for example Rock we could follow this with the two lowercase method just to make it all lowercase whatever the user types in accept the next line of user input then make it lowercase just for consistency now we should have our player choice we need a way to determine to see if this user input is valid did the user pick rock paper or scissors or something 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 and doesn't equal paper and doesn't equal scissors so we can write the following statement we're going to use the not logical operator first not will give you the opposite the inverse if player choice use the equals method pass in a string of rock if the Player's Choice doesn't equal Rock then we'll use the and logical operator and the Player's Choice doesn't again I'm using the not logical operator equals paper again we're going to use the and logical operator and just to help with readability cuz we're going to have one really long line I'm going to place 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 together if our player choice doesn't equal Rock and our player choice doesn't equal paper and our player choice doesn't equal scissors if all of these conditions are true that means a user didn't type in something that's valid so let's do the following again I'm within my set of curly braces we'll output the following we'll say something like invalid choice all right let's perform a test run enter your move rock paper scissors let's choose Rock nothing happens that's good paper nothing happens scissors nothing happens all right I'm going to type in something that's not rock paper or scissors uh I choose the gun invalid Choice that's good that's what we want we're picking something that's not rock and is not paper and is not scissors so we execute this if statement if that's the case now for the next step we have to get a random choice for the computer we don't need user input this time we will assign our variable of computer Choice equals access our array of choices at a given index zero would be Rock because it's the first value in our array one would be paper two would be scissors well why don't we use our random object random and call the next int method then pass in three this method of a random object would return a random number between 0 and two zero for rock one for p paper two for scissors then we'll output it using a print line statement let's say computer Choice col in space then add our variable of computer Choice let's do a test run I'll type in rock the computer picks paper I will pick paper the computer picks scissors I will will pick scissors the computer picks scissors as well all right we know that that works using this method of a random object we're generating a random number as the index now here's the tricky part we have to check all the win conditions I feel like the best way to handle this would be to create an if statement followed by an else if statement followed by an else statement within our if statement this will be for a tie let's output the following it's a tie our Eli statement will be used if you win we'll output you win else will be used for you lose you lose if we have a tie that means the Player's Choice is equal to the computer's Choice that's how you get a tie within the of statement we can check the following condition if our player choice variable use the equals method of strings then pass in the variable of computer choice we're comparing two strings the're reference data types so we're going to use the equals method you can't use double equals because then you're comparing memory addresses of two different strings we're going to be using equals the equals method if these two strings are equal will print it's a tie now for the wi conditions within this LF statement this is where things are going to get kind of tricky we're going to list all of the different win conditions within our LF statement first we'll check if the player picks Rock and the computer picks scissors if our player choice use the equals method if the player picks Rock a string of rock and the the computer's Choice equals let me zoom out a little bit scissors that means we win within our condition of our LF statement we'll be adding the different win conditions but temporarily I'm going to add a few else if statements just to help me explain this so if we pick Rock and the computer pick scissors that means we win but we will also win if the player pick paper and the computer let's add that right here picks rock that means we also win and then temporarily I'll add another LF statement else if the player picks scissors and the computer picks paper that also means we win we could condense all of these LF statements into one but we'll do that in a moment I just want to be sure that it all works first let's do a test run I will pick Rock the computer picks scissors that means we win I will pick paper the computer picks paper it's a tie I'll keep playing until I lose I will pick scissors the computer picks paper we win let's try scissors again the computer picks Rock we lose we know that these different wi conditions are working this is fairly readable but if you prefer we can condense all of these steps down together into one else if statement optionally what you could do 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 can see it I'm adding or to the end or let's take the entire condition within our LS if statement then paste it after the or logical 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 operator to the end cut this condition for the next LF statement and delete this LF statement and paste it so here's our LF statement there is a lot going on here this should work too but if you prefer to keep it the other way just for readability feel free to do so if you like to condense some of the code here's how you could do that so let me just be sure that everything's working fine I will pick Rock computer picks Rock it's a tie I will pick paper computer picks scissors you lose I will pick scissors computer picks paper you win all right this LF statement does work again if you would prefer to add more LF statements feel free to keep it the other way now we need to ask the user if they want to play again after displaying either it's a tie you win or you lose We'll add a prompt I will use print instead of print line I'll ask play again yes slash no we have one variable we haven't used yet our play again variable and currently it's yes play again equals use our scanner use the next line method and I will take the user's input and make it lowercase right away to lowercase method we're going to enclose all of our code right before the variables within a loop a do while loop so we'll say do all 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 and then check the condition at the end what's our condition going to be we'll continue playing while our play again variable equals a string of yes play again equals yes one more change we're going to make if the user picks something that isn't valid we're going to skip the current iteration of this Loop we can use continue for that we want to go back to the beginning if a user types in something that is invalid then the last step is to create a goodbye message we're doing this outside of the while loop cuz when we're outside of the while loop that means we're no longer playing let's print the following thanks for playing all right let's run this one last time I will pick Rock computer pick scissors you win play again again I'm going to type yes enter your move I will pick paper computer picks rock you win I will play again I will pick scissors the computer picks Rock You Lose I'm going to type no to play again and we escape that Doh Loop thanks for playing all right everybody so that is a game of rock paper scissors you can make using Java hello everybody in this video we're going to create a slot machine program using Java a user is going to bet an amount for the symbols of our slot machine we'll be using emojis if a user gets any matching symbols they'll receive a payout then at the end we'll give a final balance if that sounds good to you let's get started all right everybody when working on a project it might be helpful to you to tackle your project one step at a time as comments we'll list the different steps that our program is going to take this will give us a rough outline of our project the first thing we'll do is declare our variables then display a welcome message display welcome message we will play if our balance meaning the money that we have is greater than zero if we don't have any money we can't play it is a slot machine after all a user is going to enter bet amount then I'll write a few Subs steps underneath here we need to verify if the bet is greater than the balance you can't bet money that you don't have then verify if bet is greater than zero you can't bet negative money so we'll need to check that then subtract bet from our balance once we subtract the BET from the balance then we will spin our row our row is going to contain emojis but we'll need to display it we'll create a method to print our row of emojis once we display our row we need to get a payout if we win something if we have any matches then ask to play again if the user doesn't want to play we will display an exit message display exit message so here's a rough outline of our project we will Begin by declaring our variables we will be accepting user input we'll need a scanner for that scanner scanner equals new scanner type system.in within the set of parentheses import this class import java.util.scanner then when we're done 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 100 100 as in $100 this could also be done with other units of currency we'll need an amount for our bet int bet how much are we betting how much are we risking int payout how much money do we win we'll be adding our pay pay out to our balance if we win and a string array named row our row is going to contain our symbols our emojis that will display to the output window that's why we're creating a string array to store all of them here are the variables we'll need we'll move on to the next step our next step is to display a welcome message let's say something like this I'll use a print line statement we'll say welcome to Java slots underneath this line we'll add another print line statement I will print the word symbols and here we'll list all the different symbols we would like to use within our program I'll be using emojis to pull up the Emoji menu if you're on Windows hold on the window key then hit the semicolon button so pick some emojis that you like here's a few that I typically see cherries watermelon lemons bells and stars if you would like to stick to a certain theme feel free to change these but these are a few symbols you may see on a slot machine and I'm just going to work on the spacing a little bit that looks pretty good just to make this a little more fancy I'm going to add a bunch of asterisks as separators before and after not necessary I just think it looks cool and that's a good enough reason let's perform a test run just to be sure that this looks fine I think that looks pretty good all right we have our welcome message our next step is to play our game if our balance is greater than zero this can be done with the while loop while our balance is greater than zero we will continue playing then we have to enter the BET amount that's the next step first we'll display our current balance current balance colon space pick unit of currency I'll pick American dollars plus we will display our balance variable we will ask a user for some input place your bet amount I'll use print rather than print line because I like the user input on the same line we will assign our bet variable use our scanner to accept some input let's say next int we won't deal with cents we'll just bet whole dollars then we have a couple substeps we have to verify if our bet is greater than our balance we'll write an if statement if bet is greater than our balance we'll output the following let's say insufficient funds we'll want to skip the current cycle of this Loop we'll use continue to go back to the beginning then we'll verify if the bet is greater than zero we don't want a user to bet negative money else if our bet let's say less than or equal 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 from the balance we could say balance equals balance minus bet but we can shorten this using the augmented assignment operator we can say balance minus equals bet Within our LF statement we're going to use the continue keyword to skip the current iteration of this Loop so 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 run okay welcome to Java slots current balance $100 place your bet amount I will bet money that I don't have one1 kajillion dollars insufficient funds current balance $100 place your bet amount we can't bet negative money I'll bet1 bet must be greater than zero then we're brought back to the beginning I will bet $10 and our new balance is $90 all right we know that that works we can delete this print line statement we no longer need it we were just testing something our next step is 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 Row first I'll print the following message let's say the word spinning then we will call a method to spin our row but we will need to declare this method we will do that outside of the main method this will be a static method the return type is going to be an array of strings 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 we do need to return something because we promised that we're going to return a string array in order for this program to run a compile fine I will add The Following return statement return a new empty array of strings we'll be replacing this later but we do have to return something in order for this method to at least work we'll be creating a few local variables the first is a string array named symbols equals then within a set of cly braces we need our emojis let's go back to the beginning copy our emojis then place them within this array they do need to be surrounded with a set of double quotes because this is an 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 is going to be empty it's going to be a new string array that can hold three elements row is an empty array that can hold three strings which will be picked at random we will be generating random numbers we need a random object random random equals new 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 aray of symbols at index of zero that should output this first Emoji a cherry I'll just bet a dollar doesn't matter and we have our Cherry one should be our watermelon watermelon then four should be our star star we need to choose a random number between zero and four when we select our array of symbols within the straight brackets where we list an index we will take our random object call the next int method we will generate a random number between zero and five the first number is inclusive the second number is exclusive if your range starts with zero you don't technically need this first number you could just say five let's run this a few times just to see what happens so that time I got a bell a cherry and a watermelon if we have more or less emojis we would need to change this number why don't we use the length of our symbols instead symbols then give me the length property of this array if we were to add more or less symbols our length is going to change automatically when we run and compile this 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 statement portion of this we need to generate three random symbols we can use a for Loop for that for in I equals 0 we will continue as long as I is less than three then increment I by One we will take our row at index of I in the beginning I is going to equal zero then one then two then the four Loop ends we will assign row at index of I equal to cut this line of code we're picking a random symbol from our array of strings our array of emojis at the end we will return our row we're returning our array of strings just to test it I'm going to Output using print row at index zero plus 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 don't wor we can delete this statement we were just testing something now this method is complete we can close it we're returning a string array back to the place in which we called this method we can assign this 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 array which we're assigning to row once we have our row we're going to print our row we'll need to create another method for that we will create a static method it's not going to return anything the return type is void the name will be print row there will be one parameter we accept a string array which we will name row after assigning our row we will call call the print row method but we have to pass in our row because we have one parameter we have to pass in a string array which we are so here's where we'll print and display our row of emojis let's output the following I will display a space character plus now the string class has a few useful methods type string with a capital s dot call the join method for each character within a string we can join them together with another character I will join them by a space a vertical bar then a space comma Row for every string in my string array of row we're going to join them with the vertical bar along with a space before and after here's the output currently I'll just bet a dollar here's what we have we have three emojis each separated with the IAL bar I'll add some of those separators too those asterisks 14 Aster risks should be enough all right let's take another look I'll bet $10 that looks pretty good I'm happy with that our next step is to get a payout if there's any matches we can collapse this method we no longer need it now we need to get our payout after printing our row we will call a method of get payout which we still need to declare we'll pass in two things our string array of row and our bet how much money did we bet we need to declare this method after the print row method we will declare a static method this method is going to return an integer our payout the method name will be get payout we have to set up the parameters we're accepting a string array we will name the string array row and a bet our bet is an integer int bet we do need to return something just temporarily at the end I'm going to return zero we need to check to see if we have any matches what we could do first is check to see if all three elements match are all these strings the same symbol here's how we can do that let's write an if statement if our row at index of zero that's the first symbol now you can't use the comparison operator for Strings cuz they're reference data types you would think you could say if row at index 0 is equal to row at index one but you actually need to use 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 the first two symbols match but not only that we have to compare row at index one and row at index 2 do those match as well we're checking to see if all three symbols match we will use the and logical operator and we can copy this check paste it and if row at index one equals row at index 2 if all three symbols match then we execute this if statement why don't we use an enhanced switch a switch can return something we'll use the return keyword create a switch within the switch where are we examining let's examine one of these symbols we can just pick any I'll just pick the first one we are examining our row at index zero all three symbols are going to be the same so it doesn't matter which one you pick we'll examine this value this Emoji against any matching cases the first case will be our first symbol of a cherry if these two values match we'll do the following we'll write an arrow and we're going to be returning something let's return our bet times three let's say we get a payout of three times what we bet for our next case that was a watermelon the payout will be four for a 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 there's no matches default Arrow return zero looks like I'm missing a semicolon at the end if all three symbols match return our bet times a certain amount depending on which symbols match the get payout method is going to return an 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 we won something if that's the case let's let's output U1 pick a unit of currency plus our payout whatever we win then we will add that to our balance balance equals balance plus our payout but we can shorten this using the 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 win anything we'll output sorry you lost this round okay let's do a few test runs I'm going to keep on running this until we get three matching symbols just to be sure that it all works I will bet a dollar our message is sorry you lost this round and the current balance is $99 I'll bet another dollar you lost you lost you lost it's hard to get three matching symbols here we go I have three matching cherries you won $3 and my current balance is $86 now if you would like to check to see if the first two symbols match or the second two you can add the following code let's copy our if statement paste it change if to be else if we'll only be checking the first two symbols we can delete the second condition if the first two symbols match we'll give a reduced payout let's say for two matching cherries that will be two for watermelon that will be three 4 5 and then 10 if the second symbol matches the third one we'll write another L statement index one and index two will give the same payout hello this is from the future there's just one bug that I need to fix the else if statement where we check if our second symbol matches the third within our switch we have to examine one of these two symbols I forgot to change that originally both these symbols should be the same so it doesn't matter which one we pick I'll just pick the index at one back to the previous LF statement index zero is fine because the first two symbols should match I just needed to fix that that is all let's check to be sure that works I'll bet a dollar so my first two symbols match we 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 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 use print rather than print line there's one more variable we'll need that I'm forgetting let's create a string variable of play again we will assign play again equal to use our scanner call the next line method we'll want a user to type in either capital y or capital N after accepting 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 capital Y then we will break to break out of the loop that we're in then go to the exit the exit message one more thing we need to add though I'm going to play a bet we get that prompt to play again but the program exits after typing in a number there's still a new line character within the input buffer because we're using next int next integer we need to clear that input buffer after this line of codee where we call the next int method we can take our scanner called the next line method to get rid of that new line character and that should work I'll bet a dollar then we can play again if we type in y we display our current balance we can place another bet hey $50 that time I'll type n to not play again then we exit the last thing we're going to do is display an exit message we'll take care of that right here once we're out of the loop let's output the following game over your final balance is pick unit of currency then I will add our variable of balance okay let's run this one last time welcome to Java slots I'll bet a dollar sorry you lost would you like to play again I will type y for yes current balance $99 I will bet a dollar again I lost I'll just keep playing till I win hey I won $10 we have two matching Stars I'll play one more time I will bet $10 and I won 20 we have two matching symbols I will type in no to not play again and we get our game over message your final balance is $117 so we came out ahead all right 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 what is an object exactly look around wherever you're sitting right now you are surrounded by different objects for example next to me I have my phone a cup of coffee and a microphone in programming an object can represent a real world entity they can do one of a few things objects can hold data and they can perform actions the data they hold are known as attributes the actions that they can perform are known as methods objects can have things and they can do things some attributes that a person may have would be a name their age their height and their weight a few methods meaning actions that a human could do a person well they could eat and they could sleep objects are reference data types we store the data for an object in a location known as the Heap in this demonstration we're going to be creating some car objects but we'll need a Class A Class can serve as a blueprint to create objects so what we're going to do is create a new Java class we will create a class of car we have two classes our main class and our car Class A Class can behave as a blueprint for creating objects we'll start by listing the different attributes that a car may have so what does a car have exactly well a car could have a make that would be a string we can assign it if we would like think of a car you'd like or a car you drive I'll pick my favorite car the make will be Ford another attribute could be a model and I will pick a Mustang cars could have a year that would be an integer into Year I'll pick the year 2025 a price that could be a double double price equals let's say $58,000 99 a car's engine could be running that could be a Boolean Boolean is running I will set that to be true or false if the car is turned off things that an object has in this case car these are known as attributes they are things that an object has now heading back to our main class we will create a car object we're already a little familiar with working with objects for example a 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 would type random random equals new random Now to create a car object we're going to be utilizing this class we'll type car then think of a name for this car we'll just say car all lowercase equals new car we're following a similar pattern car car equals new car we don't need the scanner or the random object I was just demonstrating something we now have a car object that we can use our car object has these attributes these things if I was to print my car object here's what we can see well since objects are a reference data type if you were to print your car directly you get a memory address if you need to access one of these attributes you have to follow the object name with a DOT a DOT is known as the dot operator it allows you to access things within an object if I need the model of my car I would take my object name use the dot operator followed by the attribute name if I was to print the model of my car that would output Mustang let's print some of the other attributes car. make who manufactures the car Ford what is the year of my car car. year 2025 what's the price car. price $58,000 and 99 is my car running or not car do is running false the car is not currently running you can modify and change these attributes too with our car object let's access the is running attribute I will set that to be true like we're turning the car on is running is now true because we changed the attribute of is running not only do objects have the capability to hold data meaning attributes they can perform actions they can have their own methods going back to our car class we'll Define a few methods what sorts of actions can a car take well we could start a car within this class we will Define a method we don't need that static keyword this time we need a return type we'll say void we're not returning anything we will Define a method of start let's do the following let's output you start the engine we'll create another method void stop let's say you stop the engine so now with our car we can delete these print line statements we'll take our car object use the dot operator call the start method 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 methods let's change one of these variables one of these attributes within our start method let's take is running set that to be 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 output car do is running after starting the car let's output car dot is running and then stopping the car will output car dot is running the car is currently not running that's false you start the engine the car is now running that's set to true you stop the engine the car is no longer running that is false let's add two more methods we can 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 concatenate the model of the car so my car is a Mustang we will create a method to break you break the plus our model variable our model attribute we can delete these lines of code let's drive the car car. drive you drive the Mustang and here's 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 though with our class of car every car 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 equals new car we'll rename the first car as car 1 and I'll output some of their attributes Car 1make Plus a space plus car 1 model we'll do this with our second car object too Car 2 car 2. make car 2. model these cars have the same attributes it would be nice if we had a way to customize them so that each car is unique because currently they're all the same they're different cars but they have the same attributes and methods which is kind of lame that's why in the next video we're going to discuss Constructors by passing in arguments we can create unique objects in summary an object is an entity that holds data it has attributes and they can perform actions they can perform methods they have things and they can do things and and well everybody those are objects in Java hey yeah today we're talking about Constructors in Java a Constructor is just a special method within a class it's used to initialize objects by using a Constructor we can create objects with unique values when you create an object you can pass arguments to a Constructor to set up the initial values here's a demonstration what we're going to do is create a new class let's go to file new Java class let's create a class of students this will be the student class what are some attributes that a student should have they should have a name let me zoom in a little so you can read it NH AG int ag ag GPA meaning grade point average let's create a Boolean of is enrolled that is good enough for now there's one issue with this let's say that all students that I create using this class they're all going to be named SpongeBob going back to my Java file I'll create a few students we type the name of the class and name for this object let's say student one equals new student the name of the class again then we'll create a second student student two 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 objects they're all named SpongeBob what if we would like to give each object a unique name well we can do that with the help of a Constructor a Constructor is just a special method within a class to set up a Constructor we type the name of the class in this case student you need a set of parentheses then a set of curly braces we automatically call this Constructor when we instantiate an object of that class when we say new then the name of the class parenthesis behind the scenes we're calling this Constructor and we can pass in arguments within the set of parentheses we can pass in arguments so let's pass in what are we missing a name age GPA is enrolled as well but we'll take care of that momentarily let's pass in a name age and GPA student one's name will be SpongeBob SpongeBob's age will be let's say 30 he seems about 30 SpongeBob's GPA can be 3.2 that's pretty good we have a warning our Constructor isn't set up to take these arguments going back to our Constructor since we're receiving arguments we need a matching set of parameters just like any other method we have a string for name integer of age double GPA we'll take care of these three first we have string name int age double GPA to assign some of these attributes we're going to use the this keyword this dot the name of the attribute this do name equals our parameter of name this. AG equals the age that we receive this. GPA equals the GPA that we receive going back to our Java file we can now construct an object if I attempt to run this currently we are receiving a warning our Constructor expects three arguments but we don't pass in any zero are found if I were to run this we get this error message actual and formal argument lists differ in length in order for us to create a scent object we have to pass in these three things a string for the name an integer for the age and a double for the GPA if we are missing these three we can't construct an object but previously we could with without the Constructor for our second student let's pass in a 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 2's name we get SpongeBob and Patrick let's display some of the other attributes we have name age 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 3.2 these are all the unique attributes of our student object student 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 otherwise working with imagine that when we construct student one imagine we replace the this keyword with the name of the object we're assigning student one's name equal to the name that we receive same thing applies with our age and our GPA the same thing would apply with student 2 when we construct student 2 imagine during the process we replace this with student 2 this refers to the object we're currently working with or constructing with these parameter names they don't necessarily need to be the same as your attribute names just to demonstrate let's rename name as a age as B GPA as C this.name equals a this. age equals B this. GPA equals c this should work too each object still has their unique attributes but I like to keep the parameter names the same as the attributes it makes the code easier to read and understand we haven't assigned to this attribute of is enrolled each object that we create using this Constructor let's assign this objects is enrolled attribute equal to you don't always necessarily need to assign arguments to these attributes for example let's just say that when you become a student you are enrolled that is true we don't necessarily need to pass in an argument for that going back to our main class let's print take student ones is enrolled attribute and 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 enrolled to be true they are enrolled in classes and that applies to Patrick as well student to Let's create another student object just so that we get the hang of this repetition is going to help you remember let's create student 3 student 3 is an object new student to create a student we have to pass in three things a string for the name an integer for the age and a double for the GPA student 3 will be be Sandy Sandy is 27 let's say Sandy is smart she'll have a 4.0 GPA and then we'll print student 3's attributes student 3. name student 3's age student 3's GPA student 3 is enrolled our object of student 3 has these attributes Sandy 27 4.0 and true if if your class has any methods for example all students have the method to study void study I'll just output the following let's take our name attribute but I'm going to use this.name plus the text of is studying let's delete these print line statements we'll take student one call the study method 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 use them within methods too or change them this refers to the object we're currently working with if student 3 meaning Sandy was to call her study method imagine we're replacing this with student 3 student 3's name attribute all right everybody those are Constructors they're a special method found within a class to initialize objects you can pass arguments to a Constructor when you initialize them they're used to set up the initial values when you construct an object a Constructor is automatically called when you create a new object but you need a matching set of arguments if there's any parameter setup just like any other method by using a Constructor we can 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 overloaded Constructors allow a class to have multiple Constructors with different parameter lists much like overloaded methods they enable an object to be initialized in various ways here's a demonstration we are going to create a new class let's go to file new Java class we will create a class for users we will create a user class let's say that users have three things they will have a string of username a string of email and an integer in age let's say that when we create a user object these three fields are optional if these three attributes are optional we may or may not receive them when we construct a user object so let's do this let's create a Constructor if somebody were to create a user object with just a username to create a Constructor we type the name of the class in this case user we need to set up a parameter for our username we will receive a string of username we will assign this St user usern name equal to the username that we receive as an argument let's go back to our main Java file we will create a new user let's say user user one equals new user we're receiving a warning though in order to create a user object we have to pass in a string of username let's say that our user is going to be SpongeBob because that's the first thing that came to mind for me we'll use this Constructor where we have a username we can also set up the default values for our attributes too let's say this. email equals a string of not provided this. AG equals 0 going back to user one I will output the following user one dot username user one's email user 1's age here's what we got currently username is SpongeBob email is not provided age is zero these attributes were optional when we construct this object we're just assigning them to some default values what if we create a user that has an email well we could create another Constructor with the same name but we need a different set of parameters this is very similar to Method overloading you can have methods with the same name but they need different parameters not only do we have a string of username we'll have a string of email our email attribute equals the email that we receive we can use either of these Constructors depending on the arguments that are passed in let's create a second user user user 2 equals new user the username will be Patrick Patrick's email is let's say p Patrick is probably still using AOL for some reason let's say aol.com then we'll print user 2's attributes user 2. username user two. email user 2.age here's what we got we have all the attributes for user one and user two Patrick P star aol.com our age is still zero we can create different objects with a varying number of arguments let's create a third user this time we'll have a parameter for our age attribute I'm just going to copy this cuz I'm lazy we'll have an INT age we will assign our age variable with the age argument we receive we'll create user 3 user user 3 equals new user username will be Sandy email will be S cheeks gmail.com then an age let's say 27 then I'll print user 3's attributes user 3. username email then 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 profile this. username will equal guest or a guest profile this . email equals not provided this. AG equals z now we could create a user object then pass in no arguments user user 4 equals new user this time we don't have any arguments then I'll display user Force attributes username email age here's what we got username guessed email not provided age is zero in a way by creating an object and passing in no arguments you can set up some default values all right everybody those are overloaded Constructors they allow a class to have multiple Constructors they just need different parameter lists they enable objects to be initialized in various Ways by passing in a varying amount of arguments this would be great in a situation where some fields are optional when creating an object and well everybody those are overloaded Constructors in Java hey everybody in this video I'm going to show you how we can create an array of objects using Java it's pretty useful at times and you should probably know how to do it we'll Begin by creating a new class let's go to file new class we will create a car class let's say that cars have the following attributes we'll just pick two to keep it simple a string of model and a string of color we'll need a car Constructor we will pass in a string of model and a string of color we will assign this. model equals the model we receive this. color equals the color that we receive we'll add one method void drive all cars can drive well I'll put the following using a print line statement you drive the plus this. color plus a space plus this. model okay we are done with the car class we'll construct a few car objects let's start with car one car car 1 equals a new car we have to pass in a model and a color think of some cars that you like I will pick a red Mustang for one car let's create Car 2 Car 2 equals a new car I will pick a Corvette that is blue one more car car 3 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 an array you have to list the data type of what you're storing we're going to be storing car objects the data type of the array is going to be car objects car then for an array we need a set of straight brackets what is the name of this array going to be well I think cars would be appropriate cars equals if you're creating an empty array you're going to use the new keyword list the data type of car within the straight brackets specify the size of this array let's say three elements Max or we could go ahead and just assign these right away too using a set of cly braces let's Place car 1 Car 2 and car 3 within this array we'll place these three car objects within this array of cars now you could use a for Loop to iterate through this array here's how we'll start with the standard for Loop we'll need an index in I equals z we'll continue as long as I is less than our cars length property then increment I by one we'll access our array of cars at index of I which is going to increase each time but it 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 yellow 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 braces what is the data type of each element within this array car objects we'll need a nickname for each element within this array let's say car colon think of colon as in then our array of cars for every car object in our array of cars do the following we'll take each car object call the drive method and that's going to do the same thing you drive the red Mustang you drive the blue Corvette you drive the yellow charger another thing you can do to when creating an array of objects you can pass in Anonymous objects rather than first instantiating the objects then assigning them to the array here's how you can do that for each element we're going to call the car Constructor with the new keyword call the car Constructor then pass in the details for each car the necessary arguments we'll pass in our Mustang that's red that's the first element I'll just copy it to save some time then we're creating a new car but this will be a Corvette that's 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 cars constructing a new object without giving the object a unique identifier like car 1 Car 2 or car 3 these are known as Anonymous objects So within an array you can create Anonymous objects if you would rather not give each of the car is a unique identifier another thing you can do too with an array of objects is let's change the color of each car using our enhanced for Loop car do color let's change the color to be black for each 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 black charger all all right everybody those 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 static is a keyword it modifies a variable or method so that it belongs to the class rather than any specific object we see the static keyword within the main method when you modify a variable or method with the static keyword static is used to create utility methods or other shared resources let me give you a demonstration we're going to create a new class let's go to file new class we'll create a front class we will create some friend objects because you're lonely let's say that all friends will have a name attribute string name we need a Constructor it's the same as the class name parenthesis curly braces when we construct a friend object we have to pass in a string of name we will assign this object's name attribute equal to the name parameter that we receive let's construct two friends we'll say friend friend one equals new friend but we have to pass in a name pick a name my default is SpongeBob because most people know who SpongeBob is if I was to Output friend one's name then it should be SpongeBob we just want to be sure that it works yes it does SpongeBob now going back to our friend class let's say we would like to keep track of how many friend objects we create well that could be an attribute let's say we have an integer of num of friends meaning number of friends whenever we create a friend object we will increment number of friends by one num of friends Plus+ so going back let's output friend On's number of friends attribute num of friends so this should be one yep num friends is one we have one friend but what if we create a second friend object I'll just copy this line of code paste it change friend one to friend two we'll pass in a new name let's say Patrick we'll print friend One's number of friends and friend two's number of friends how many friend objects have we created we have created two but what's the out put well it's one for both here's why each friend object has their own copy of the number of friends variable we're incrementing each copy of number of friends by one when we create the object of friend one we're incrementing its attribute of number of friends by one same thing applies with friend two when we create friend two friend 2's number of friends is zero and we're incrementing it by one what if we would like to keep track of the total amount of friends that we created and store it within one variable well there is a way we can do that and that is with the static modifier so going back to our friend class we're going to precede the data type of this attribute with the static modifier static int number of friends rather than all objects all friend objects having their own copy of number of friends they're all going to share one so going back let's print a number of friends now it's two we have two total friends if I was to create a third friend friend three friend three will be Squidward and then I'll output friend 3's number of friends we have three total friends we are receiving a suggestion when accessing a static variable or calling a static method it's actually best to do so through the class itself rather than any object created from that class instead of saying you know friend one then accessing the static member we will instead use the name of the class in this case friend it's better for clarity to access a static member by the name of the class itself rather than any object because you and other developers will know that this is a static attribute or method to display the static variable we would want to access it by the class name then access that static attribute how many friends do we have now three let's create a fourth friend friend four will be Sandy then display the number of friends we have now we have four friends going back to the friend class it's as if all these objects are sharing the same variable but rather than any one object having ownership of this variable rather the friend class owns it and all objects have access to it methods can also be modified by the static keyword we will create a static method that doesn't return anything the return type is void this method will be the show Friends method we'll just output the following we'll output you have plus normally when you access an attribute you type this dot the name of the attribute such as you know name if you're working with the static attribute you don't need this for example this. number of friends you don't need this we even have a warning here that friends. this cannot be referenced from a static context if you're working with a static attribute you don't need this this refers to the object you're currently working with but since this attribute belongs to the class we don't need this you have your 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 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 total friends another place in which you see static members is through the math class for example let's say you would like to round a number you would type the name of the math class math. round and you can round a number round is a utility method we access it through the class name of math you don't need to go ahead and create a math object such as math math 1 equals new math and then access it through this object that would be silly round is a static method it behaves as a utility method we can access it through the class name and we don't need to create any math objects because that's stupid and to prove this 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 search for it here's the round method so round is a method and we have that static keyword round is a utility method for the math class we can access it through the name of the class all right everybody so that is the static keyword it modifies a variable or method so that it belongs to the class rather than any specific object it's commonly used for utility methods or shared resources among objects created from that class such as the number of friends all those friend objects share the same attribute rather than each of them having their own copy and and well everybody that is the static keyword in Java what is going on people today we got a very important topic to discuss today and that is inheritance inheritance is where one class inherits the attributes and methods from another class much like how a child can inherit traits from A parent well in programming we could do something similar one class a child's class can inherit traits from A parent here's an example we're going to create a few classes but we'll start with a new class of animal let's go to new class I will create an animal class what do animals have let's say that all animals are alive they will start by being alive is alive let's create a Constructor of animal I will set is alive to be true when we construct a new animal object but not only are all animals alive all animals can eat they will have an eat method void eat we'll print something like the following the animal is eating easting eating that is good enough for this class so what we're going to do is create two more classes file new class 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 dog and cat class will be its children in order for a class to inherit all the attributes and methods from another class after the class name you will use the extend keyword then specify the parent class dog extends animal our dog class will inherit all these traits these attributes and methods from the animal class the cat and dog class don't have any anything within them let's see if they actually do have these attributes and methods even though there's nothing within them let's create a dog object 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 so cat do is alive look at that they're both true they should also be able to eat dog. eat method cat. eat method the animal is eating the animal is eating even though these classes of dog and cat don't have anything within them since they extend to the animal class we're specifying that the animal class is the parent the cat and dog classes are the children of the animal class they inherit all these attributes and methods from its parent of animal even though they don't have anything within them this isn't as useful if you only have a few classes such as two because you know you could just copy and paste all this code within each and then just change the Constructor but imagine if you had hundreds of classes hundreds of children you'd have to do that for hundreds of classes but not only that if you have to make any changes to say you know this animal is eating you'd have to make that change for hundreds of classes and we are repeating ourselves a lot it'd be a lot easier if we can just make that change in one place if we have to change the to this all of the children classes will inherit this updated method we're following the dry principle don't repeat yourself we're writing the code once and just reusing it all the children classes will inherit this updated method but not only that each child class can have their own unique attributes and methods too let's say that all dogs will have one life int lives equals 1 they will also have their own unique speak method void speak when our dog uses the speak method let's output the following let's say the dog goes woof then within the cat class cats will have have nine lives and they can speak but they will say something different when they speak let's output the cat goes meow going back let's output our dog objects lives how many lives does our dog have same thing applies with our cat cat. lives our dog has one life our cat has nine lives they also have their own unique speak methods dog dope cat dope the dog goes woof the cat goes meow there's also the concept of multi-level inheritance we'll create a new class to serve as a sort of grandparent a child class will inherit from a parent a parent will inherit from a grandparent so let's change this program around a little bit we're going to create a new class file new Java class we will create a class of organism animals will extend the organism class let's cut our is aive variable and the Constructor if you inherit from the animal class you will get an eat method if you inherit from the organism class you are alive and that's it but we need to change the Constructor animal inherits from organism dog and cat inherit from the animal class so from the perspective of our dog and cat class the organism class is you could say a grandparent going back to our main Java file let's take a look at our is alive variables dog. is 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 further let's create a class of plant plant is going to inherit from the organism class because plants are a type 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 eat but they can photosynthesize photosynthesize I think I spelled that right probably not but who cares if you're a plant and you photosynthesize then the plant absorbs sunlight hey this is bro from the future I forgot to extend the organism class so let's take care of that heading back to 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 inherits from the organism class that's true and plants can photosynthesize plant do photosynthesize the plant absorbs sunlight it's kind of like we have a whole family tree dog and cat inherit from animal animal inherits from organism and plant inherits from organism but animals and plants aren't related they're siblings but they're not the same going back to our main Java file let's see if our dog has a photosynthesize method dog. photosynthesize looks like they can't we do not have a photosynthesize method for dogs they do not inherit this method because they're not related to plants all right everybody so that's inheritance it's where one class inherits the attributes and methods from another class A Child class will inherit all the attributes and methods from a parent class parents can also be considered children too and inherit it from a let's say grandparent class you just have to use the extends keyword and well everybody that's inheritance in Java yo so let's get started today I got to discuss the super keyword super just refers to the parent class when using inheritance a child class is also known as the sub class the parent class is also known as the super class super just means parent for all intents and purposes the super keyword is used within Constructors and Method overwriting method overwriting is a whole another topic that we'll discuss we're more focused on Constructors in this topic we use the super keyword to call the parent Constructor to initialize attributes let me give you an example we'll be creating a few different classes let's go to file new class we will Begin by creating a class of person person will be the parent the super class let's say that any person object has the following attributes they will have a string of first meaning first name then string last meaning last name we'll need a Constructor it's going to be the same as the class name Person parentheses curly braces when we construct a person object we will need to pass in the following arguments a string for first name first and a string for last name last this objects first name attribute this. first equals the argument that we receive for first same thing applies with last this. last equals the argument we receive for last and then we'll create one method in this demonstration this method won't return anything we will name the method show name all we'll do is output the following this do first plus a space plus this. last okay let's test this class out person person equals new person but we do have to pass in a first and last name I've already used SpongeBob for too many examples so let's mix it up this time I'll pick Harry Potter or feel free to pick a different franchise that you like so one person from Harry Potter is Tom Riddle we have a person object with this first name and this last name first last our person is going to have a show name method show name then call it there we go there's our person objects first and last name Tom Riddle our person class will be the parent class we'll create a few other classes to inherit from this person class we're going to create a class of student that's going to inherit from the person class the student class will inherit these attributes and methods let's create a new class of student student will extends the parent or super class of person since student is inheriting from person student is going to have a first and last name already and a show name method what other attributes does a student have that a person might not well students have a GPA a grade point average we'll declare that as an attribute double GPA we're going to create a student Constructor let's say that when we create a student we need to pass in a string for first name String first string last and double GPA what's their grade point average now rather than assigning our first and last name within this Constructor such as this. first equals first this. last equals last and this. GPA equals GPA we are receiving a warning there is no parameterless Constructor available in person we're not able to assign these attributes of first and last within the Constructor for student this is because student inherits from the person class since the Constructor of our parent requires a first and last name we have to pass these arguments to its parent of person how we can do that going back to the child class we're going to be using the super keyword any arguments that the parent requires we have to send the parent these arguments from the child Constructor and how we can do that is use the super keyword and then pass in those arguments of first and last and now Java is Happy super just refers to the parent imagine that we replace the super keyword with person think of it like that and now this should work going back to our main file we should be able to create a student object student student equals new student we have to pass in a first name first name will be Harry last name will be Potter then we have to pass in a GPA because our student Constructor requires it Harry Potter has a 3.25 GPA let's say our student object should have these attributes this method and this attribute from the student class of GPA Let's test it student. show name this student's name is Harry Potter and they should have a GPA let's print students GPA attribute 3.25 but not only that let's create a method to display their GPA within the student class we will create a method that doesn't return anything it will be show GPA we will output the following let's say this. first plus a string apostrophe s so Harry's GPA is plus this. GPA let's take our student object call the show GPA method that we have declared Harry's GPA is 3.25 let's create one more class we will create an employee class class employee employee will inherit from the person class employee extends person since employees aren't studying they're not students they instead get a salary we will create an integer attribute of salary and then we need that Constructor for our employee object all employees will require the following arguments a string for first name String first a string for last name String last and an integer for our employee salary I will attempt to assign these attributes for our employee again it's not going to work but let's try it this. first equals first this. last equals last this do salary equals salary again we're receiving that warning there is no parameter list Constructor available in person since employee extends person and our person Constructor requires a first name and a last name we have to send our person Constructor these arguments first and last so again going back to our employee class we will call the Constructor of our parent using the super keyword and then passing in those arguments first and 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 name apostrophe yes we'll create the employee of Hagrid their salary is pick unit of currency I'll pick American dollars plus this do salary now we'll need to construct an employee object employee employee equals new employee we have to pass in a first name a last name and a salary in order to construct an employee object we're going to pick Hagrid Hagrid's first name is actually rubius last name Hagrid Hagrid's salary will be $50,000 let's 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 $50,000 in conclusion super refers to the parent class student and employee inherit from person since the Constructor of the parent of person requires a first name and a last name any children objects that we create we have to call the Constructor of the parent and pass in those arguments to satisfy Java if the parent didn't require these arguments then you wouldn't need to and well everybody that is the super keyword in Java what's going on people today I'm going to discuss method overwriting using Java method overwriting is when a subass provides its own implementation of a method rather than use one that's inherited from a parent it allows for code reusability and you can give specific implementations of a method let me give you a demonstration we'll be creating a few classes file new class we will Begin by creating a class of animal then a new class of dog a class of cat then finally a class of fish dog cat and fish are going to extend the animal class after the class name type extends animal so let's do the this with cat and fish the dog cat and fish classes are all children of the animal class animal class is the parent class there's not a lot we have to write with this example if a child class inherits from the animal parent class they will inherit a method to move let's define a method of move all we'll say is this animal is running we can keep the dog cat and fish class is empty for now so going back to our main Java file let's construct a dog object dog dog equals new dog a cat object cat cat equals new cat and a fish fish fish equals new fish all three of these animal objects dog cat and fish should have a move method let's take our dog call its move method say same thing with the cat and the fish cat. move method fish. move method currently when we run this program we get the following output our dog is running our cat is running and our fish is running but fish don't have legs though they can only swim the move method that the fish class inherits isn't appropriate for that class this animal is swimming would be more appropriate so why don't we do this within the fish class why don't we do some method overwriting specifically for the fish class we will create a unique move method only for this class we will Define a new move method where we will say this animal is swimming however it is good practice to add this annotation of at override so that you and other Developers know that this method is being overridden our fish class does inherit a move method from its parent of animal if you have the same named method defined in a child class you'll use that one first it has precedence going back to our main Java file let's call the move method for our fish our dog is running our cat is running but our fish is swimming within the fish class we have overridden the move method we have given a specific implementation for this method just for this one class the cat and dog classes will use what's inherited from their parent not only is a good practice to add this annotation of at override but let's say that you misspell this overwritten method rather than move let's say moves even though it should be move we're receiving a warning that this method does not override the method from its super class it's parent if you didn't have this annotation you may not notice that you misspelled this method and you're not actually overwriting it adding the at override annotation provides a system of checks and balances when overwriting method this error will go away once we actually are overwriting a method all right everybody so that is Method overwriting it's when a subass provides its own implementation of a method rather than use one that's already defined it allows for code reusability and you can give specific implementations of a method we'll be seeing method overwriting again with the two string method coming up in a future topic and well everybody that is method overwriting in Java hello everybody today I got to explain the two- string method using Java the two- string method is inherited from the object class whenever you create an object behind the scenes the object class is a super class the two-ring method is used to return a string representation of an object if you were to Output it directly using system.out print line the default behavior of the two- string method is that it returns a hash code as a unique identifier for that object but it can be overridden to provide meaningful details which is why we've learned about method overriding in the last video in this demonstration let's create a new class file new class we will create a car class let's say that all cars should have the following attributes a string of make who manufactures the car a string of model what's the model of the car int year for the year and string color for the color we'll need a Constructor and then we'll assign these attributes we have a string of make a string of model an INT of year and a string of color then we'll assign these attributes this St make equals make this St model equals model this.e equals year this. color equals color that looks good enough for now going back to our main Java file we'll construct a car object car car equals new car but we have to pass in the details for our car Constructor our car Constructor requires a make a model a year and a color so pick a car that you like I like Ford Mustang I'll pick a Ford Mustang the make will be Ford Model will be Mustang I need a year 2025 and a color I'll pick the color red car is an object if I were to Output my car object directly using system.out.print line here's what you'll see if you output your card directly technically you'll be given a hash code a unique identifier for that car object hashing is kind of an advanced topic that I don't want to introduce right now but typically with hashing it's a unique identifier that uses the object's memory address to calculate a hash you don't need to know any more than that right now but wouldn't it be useful if we were to print our car object directly we were given the details of the car normally what we would have to do is output something like this this is if we wanted to Output the details of the car we could say something such as car. color that would would be first plus a space character plus car do which should be next let's say the year color year then make and model car. make plus a space plus car. model this print line statement is giving us meaningful details of this car object this is the output red 2025 Ford Mustang it would be nice if we were to print our car object directly using print or print line we could be given these details instead well we can do that with method overwriting going to our car class we will be overriding a method we need the at override annotation we do need this keyword of public this is a publicly accessible 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 this print line statement going to our car class within the two string method we have to return a string because we set the return type to be a string we promised that we would return a string let's paste all the details of that car we'll need to replace car with this this refers to the object we're currently working with that and add a semicolon to the end if we were to print our car object directly using this print line statement or a print statement or even printf instead of that hash code we're instead given meaningful details of that car that we've customized the cars color year make and model we have overridden the two- string method that's normally available to all objects let's construct another car object let's rename car is car one we'll have car car 2 equals new car pick some different details for a car I will pick a Chevrolet Corvette the year will be 2026 and the color will be blue I'll print car one then print Car 2 here's car one and car two Car 2 is a blue 2026 Chevrolet Corvette all right everybody so that is the two-ring method objects inherit from the object class the object class does have a two string method but it can be overridden so that when you print an object directly you can display meaningful details such as the details of that object instead of displaying a hash code if you were to print the object it's pretty useful at times and well everybody that is the two string method in Java all right everybody it's about time we get into abstraction overall abstraction is the process of hiding implementation details and showing only the essential features think of it like this if I'm teaching somebody how to drive I'm not going to open up the hood of the car and explain how the engine works I'm instead going to tell the user that the gas pedal is to drive and the brake is to stop the car abstraction is the process of hiding implementation details a user just needs to know what the gas pedal is and what the brake is we can make classes and methods abstract by using this abstract keyword this provides a few benefits abstract classes can't be instantiated directly abstract classes can also contain abstract methods which must be implemented they can also contain concrete methods which are the opposite these are real and physical methods you could say concrete methods are inherited so I know that's a lot let me give you an example we're going to be creating an abstract class that can't be instantiated directly meaning we can't create any objects from this class in this demonstration we're going to create some shape objects shape is going to be the parent then we'll have circle triangle and rectangle classes as its children so we're going to go to new Java class we will create a shape class then a class for Circle a class for triangle then a class for rectangle our shape class is going to be abstract we can't create any shape objects before the word of class we will add this keyword of abstract we can't create any shape objects it's an abstract class now circle triangle and rectangle are going to extend the shape class Circle extends shape circles are type of shape same thing applies with triangle and rectangle let's attempt to create a shape object shape shape equals new shape and we get an error message shape is abstract it cannot be instantiated since shape is an abstract class we can't create any objects from this class it adds a little bit of security to our program we don't want anybody creating any generic shape objects we want them to create a certain kind of shape a circle a triangle or a rectangle but we can create some circles triangles and rectangles so let's do so circle circle equals new circle triangle triangle equals new triangle rectangle rectangle equals new rectangle we can create circle triangle and rectangle objects just not shape because it's an abstract class that's good though because we don't want people creating any shape objects it's too generic we want a user to pick a certain kind of shape abstract classes can contain abstract methods and concrete methods an abstract method is a method which must be implemented by its children within our shape class we will define an abstract method use the abstract keyword let's list a return type of double every child class of the shape class needs an area method I'll add a comment that this is an abstract method abstract So within our Circle class we get an error message Circle must either be declared abstract or implement the abstract method of area circle is going to inherit this abstract method of area from its parent of shape we need to implement this method so let's do so this is going to be an overridden method we need The annotation of override we need to define a method of area but we'll fill it in momentarily just for now I'm going to return zero and now that error message goes away since we inherit from the shape class and there's an abstract method of area we need to implement this method this helps to ensure consistency among the children classes you can see that we're missing that same method with triangle and rectangle so why don't we copy this code where we override the area method and paste it we'll be filling these in later going back to our shape class abstract classes can contain abstract methods and concrete methods which are kind of the opposite concrete methods are defined and inherited within an abstract class let's define a method of display this method doesn't return anything the return type is void we'll just output the following this is a shape I'll add a comment that this is a concrete method in an abstract class a concrete method is inherited within our circle triangle and rectangle classes we don't need to implement it we don't need to override this method it's inherited going back to our main Java file if I was to take my circle object call the display method we get the following output this is a shape and that applies with triangle and rectangle to triangle. display rectangle. display this is a shape this is a shape this is a a shape this concrete method of display was inherited from the shape class their parent now we'll Define the area methods area is an abstract method that means that the children classes have to Define it to calculate the area of a circle we'll need a radius we'll Define that as an attribute all circles will have a radius attribute Double Radius and we'll need a Constructor a circle Constructor when we construct a circle object we have to pass in a double for the radius this. rius equals the radius we receive now the formula to calculate the area of a circle will be we're going to return access the math class access the constant of Pi from the math class times radius time radius that's how to calculate the area of a circle now for our triangle we need the following a double for base a double for height we need a Constructor parameter 1 will be double base parameter 2 will be double height this. base equals base this do height equals height for the area we will return 0.5 time base time height then we have a rectangle double length double width we need our Constructor of rectangle parameter 1 will be double length parameter 2 will be double width this do length equals length this. width equals width return length time width within the area method and we're good let's go back to our main class we're missing those arguments we have to pass them in for our Circle object let's say the radius is three for the triangle the base and height will be 4 and 5 the rectangle the length and width will be 6 and 7 we are going to Output using system.out.print line take our circle 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 rectangle so that's the abstract keyword abstraction is the process of hiding implementation details from a user and showing only the essential features that's why we've created a shape class that's abstract we can't directly create any shape objects we want a user to create a certain kind of shape whether it's a circle a triangle or a rectangle a shape is too generic an abstract class can contain abstract methods which need to be implemented by the children classes or concrete methods which are inherited and the children classes will have access to it all right everybody so that is abstraction and the of the abstract keyword in Java all right what's going on everybody in this video I got to explain interfaces using Java an interface is very similar to an abstract class in fact there's a lot of overlap where you could use either one but there's a few key differences an interface is a blueprint for a class it specifies a set of abstract methods that any implementing classes must Define one key difference is that by using interfaces we can achieve multiple inheritance like Behavior normally with inheritance a class can only have a single parent but by using interfaces a class can have multiple parents like two three or more so in this demonstration we're going to create two interfaces let's go to file new Java class rather than creating a class we're going to create an interface we will create an interface of prey and the other for predator file new Java class interface Predator we're going to be declaring some methods but not defining them if a class inherits from the prey interface they will have to finish defining a method of flea the return type will be void if you're considered prey you need a flea method to run away if you're a predator you need to define a method to hunt cuz you're a predator now we'll be 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 Predators unless you count that one rabbit from Monty Python and the Holy Grail that's the exception our rabbit class is going to implements the prey interface we get a warning message class rabbit must either declare abstract or Implement abstract method flee since the rabbit class is implementing the prey interface we have to finish defining this method that's declared within the prey interface it's kind of like a contract the prey interface is telling the rabbit class hey if you're going to implement me you need to Define this method a flea we'll need to do that in order to create rabid objects we're going to be overwriting this method using the override annotation this method will be flee void flee and we'll want to add this axis modifier of public it's a publicly accessible method in this method we're going to Output the following let's say the rabbit is running away and that error should go away let's go back to our main class we'll create a rabbit object and test it rabbit rabbit equals new rabbit let's take our rabbit object have it call the flea method and this should work yes the rabbit is running away now let's go to our Hawk class Hawk will implement the Predator interface but we have to override this method of hunt because with The Predator interface it's kind of like we're signing a contract if Hawk is going to implement the Predator interface then we have to finish defining this method we will add the at override annotation and Define this method and then again we do need an axis modifier we'll pick public let's output the following the hawk is hunting let's create a hawk object Hawk Hawk equals New 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 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 is that you can Implement more than one interface so fish they eat smaller fish and they flee larger fish they could be considered both prey and predators we will implement two interfaces Implement prey comma Predator then we need both of these methods we have to finish defining both again we're going to use the at override annotation we will create a publicly accessible method a flea where we will 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 print the fish is hunting let's say all right let's test it we will create a fish object fish fish equals new fish our fish can flee and our fish can hunt the fish is swimming away the fish is hunting our fish object implements both the prey and Predator interfaces it has to Define these two methods so that's one key difference with interfaces compared to abstract classes a class can inherit more than one interface normally with inheritance you can only have one parent but this is a way around that using interfaces fish are considered both prey and predators all right everybody so that is a quick introduction to interfaces an interface is a blueprint for a class that's specifies a set of abstract methods that implementing classes must Define and it supports multiple inheritance like Behavior there's a lot of overlap where you can use abstract classes or interfaces you should be familiar with both and well everybody that's a quick introduction to interfaces using Java so yeah it's about time I explain polymorphism using Java polymorphism is a Greek word poly means many morph means shape together you get the concept of many shapes or forms it's a general programming concept objects can identify as other objects objects of different types objects can be treated as objects of a common super Class A dog identifies as a dog but it can also identify as an animal it can also identify as an organism it can also identify as an object it can identify as more than one thing in this topic we're going to create a few vehicle objects let's create a few classes file new Java class we will create a super class of vehicle iicle this class doesn't have to be abstract but let's make it abstract we can't create any vehicle objects we will declare an abstract method that doesn't return anything the return type is void if you're a vehicle you need a go method so what we're going to be doing is creating a few different types of vehicles a car bike and boat class which will inherit from the class of vehicle so let's create these classes file new Java class we will create a car class that extends the vehicle class but there is an abstract method of go that we need to Define we will use the at override annotation the method will be return type of void go all we'll do is output you drive the car all right let's do this with a few other classes I'll just copy this method because we'll reuse it we'll create a bike class bike bike extends vehicle and we need that method of go you ride the bike and a boat class file new Java class Boat Boat extends vehicle you sail the boat that is good enough for now going back to our main Java file let's create these objects starting with our car car car 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 object use its go method followed by bike bike Dogo method and Boat Boat Dogo method you drive the car you ride the bike you sail the boat so let's say we would like to have a race we're going to place all of these objects within an array our car bike and boat objects so what should the data type of the array be let's attempt to create an array of car objects and place our bike and boat objects within that array and we'll just see what happens exactly for learning purposes I will create an array of cars the data type is car it's an array named cars equals curly braces let's stick our car bike and boat objects within here we're already getting a few error messages incompatible types bike cannot be converted to car bikes and boats don't identify as cars cars identify as cars s that's one of the shapes that bikes and boats don't have they don't identify as cars if this were an array of bikes bike bikes equals R array of objects well then we have another a message car cannot be converted to a bike and you can assume the same thing applies with boats cars and bikes don't identify as boats what we could do is declare our array of what they have in common well our car bike and boat they all extend the vehicle class you could say they also identify as Vehicles we're going to change the data type of our array to hold Vehicles we have an array of vehicle objects and then let's change our array name to be Vehicles cars identifies cars but also Vehicles bikes identifies bikes but also Vehicles boats identify as boats but also Vehicles that's the one thing they have in common they're all extending the vehicle super class they're also considered Vehicles that's another one of their forms they shapes for every object within this array I would like to have each object use its go method like we're 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 vehicles we will give a nickname of each vehicle as vehicle in my array of vehicles for every vehicle in this array of vehicles let's take each vehicle call the go method take every vehicle object call its go method here's the result you drive the car you ride the bike you sail the boat oh and another thing I'm forgetting polymorphism can also be achieved 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 interface we will declare a method of go that doesn't return 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 you prefer interfaces in summary polymorphism means many shapes it's where objects can identify as themselves but also other objects objects can be treated as objects of a common super class and well everybody that is an introduction to polymorphism using jav Ava what's going on people today I got to explain a runtime polymorphism also known as Dynamic polymorphism how I would explain it in a single sentence is when the method that gets executed is decided at runtime based on the actual type of the object in this demonstration a user is going to pick a type of animal they want as a pet a dog or a cat but that's going to be determined at runtime after the program is already running we'll create a total of three classes first we'll create an animal class which will be a parent class we will create a class of animal we might as well make this an abstract class for good practice we don't want anybody creating any animal objects we will have an abstract method the return type is void this method will be speak when an animal speaks they'll say something unique we'll create a dog class file new Java class we will create a class of dog that extends the animal class but we do need a speak method we will use method overwriting the return type is void with our speak method we will output the following the dog goes woof all right then we need a cat class file new Java class we will create a class of cat cat extends animal and we'll just copy the speak method just to save a little bit of time when the cat speaks we'll output the cat goes meow that's good enough for this example since animal is an abstract class we can't create any animal objects I'll attempt to do so animal animal equals new animal and we get an error message animal is abstract can be instantiated that's good though animals are too generic we would rather have a user create a certain kind of animal either a dog or a cat in this demonstration we're going to have a user pick if they want a dog or a cat but we don't know which one they're going to pick so why don't we do this let's declare an animal object but not instantiate it we will assign our animal equal to a new dog or a new cat based on the user input so animal animal this will either be animal equals a new dog or animal equals a new cat based on the user input we will declare an object that's at least an animal we'll accept some user input we'll need a scanner scanner scanner equals new scanner we will pass in system.in and import this class 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 I'll use print rather than print line because I like the input on the same line let's declare a variable of choice this will be an integer we'll use our scanner called the next int method and then we'll do the following we'll examine if our choice variable is equal to one if it is we'll finish instantiating our animal object but we'll assign it to be a new dog object then we will have our animal use its speak method so if it's a dog it should go woof else if choice is equal to two then we will 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 necessary this is good enough for now before running the program we don't know what kind of animal we're going to create it's either going to be a dog or a cat if I select one we get a dog the dog goes woof if I select two we get a cat the cat goes meow the actual method that we call is determined at runtime after the program is already running before we run the program we know that we're going to use a speak method we're just not sure which one so that's runtime polymorphism it's when the method that gets executed is decided at runtime based on the actual type of object that we create and well everybody that is an introduction to runtime polymorphism using Java all right everybody today I'm going to be explaining getter and Setter methods using Java getter and Setter methods help protect object data and they add rules for accessing or modifying that data here's a demonstration we're going to create a class of car file new class we will create a car Class A few attributes that cars could have include a string of model A String of color and an INT let's say price then we'll need a Constructor we'll have three parameters a string of model A String of color and an inch of price we will assign this do model equals model this do color equals color 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 already used red Mustangs for too many examples I'll pick something else let's say a charger that is yellow and the price will be $10,000 but I don't know if that's good or not we don't even know the year of the car anyways so we have our car object and then let's output these attributes just to test them car. color I'll add a space character to plus car. model plus a space character plus car. price I'm intentionally not adding a unit of currency so here's our car I have a yellow charger and the price is 10,000 10,000 of a unit of currency that you choose but that's not important with our car object its attributes are publicly accessible meaning we can view and change them easily to demonstrate let's say that the model of our car is now a Corvette we have a yellow Corvette that is $10,000 we don't want the model of our car to magically become a Corvette once we assign its model to be charger we don't want it to change what we could do when to declaring these attributes is add this access modifier of private preceding the data type private string model private string color private and price we can't access them and let's test that you can see that the font color already changed to 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 price has private access in car since these attributes are private we can't normally access them outside of the car class but there is a way around that and that is by using getter and Setter methods getter methods make a field readable Setter methods make a field writable use get to read set to write we'll set up some getter methods first I would like the car's color model and price here's how we can do that within the car class we will create a method we'll start with the model the return type will be string because our model is a string data type we'll create a getter method following this naming convention get then the name of the attribute model all we're going to do is return this. model and then we'll do this with the color and the price and I'll just copy this method because I'm I'm feeling a little lazy we have get model get color return this. color and get price return this. price oh and this returns an integer not a string because our price is an integer let's go back to our main Java file rather than accessing these attributes directly because we can't we're going to call these getter methods get model if you need the model get color if you need the color get price if you need the price replace car. color with car do get color and this is a method car. getet model and car. getet price and that should work yep we can now read those attributes we have a yellow charger and the price is 10,000 another thing you can do too with getter methods you can add additional logic so with our get price method let's instead return a string we will return a unit of currency I'll pick American dollars plus the price let's see how that changes again we are calling the get price method there we go yellow charger $110,000 getter methods make a field readable and you can add additional logic when retrieving one of these attributes and in this demonstration I just added a dollar sign just to keep it simple then we have Setter methods Setter methods make a field writable going to our car class we have model color and price I don't want the model attribute to be writable once we've declared the model of our car we don't want to change it our charger can't magically become a Corvette even though that'd be pretty cool but the color you could change you can paint your car and the price you can sell your car for a different price we'll declare Setter methods for our color and price but not the model because we don't want this attribute to be writable so let's scroll down to the bottom following a similar pattern we're going to create a method the return type is void this will be set color we have one parameter a string of color we will assign this do color equal to the new color that we receive we'll do this with our price too void set price we'll have one parameter and int of price this. price equals price the new 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 blue that's the first thing that came to mind and car. price equals you know what the car's on sale it's $5,000 well I can't change these we still have that red text for color and price because the color and price attributes are still private instead we're going to call these Setter methods we will set the color and then pass in the new color rather than assign it directly set color pass in a new color set price passing a new price 5,000 then using our Getters we should be able to print these attributes yes we now have a blue charger and the price is $5,000 we don't have a Setter method set up for the model that's good though we don't want the model to change we only have set and set price if I attempt to access a 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 want to change the model if you want this attribute to be writable well then you could add a Setter method void set model we'll pass in a string for the new model this model equals model and then you could change it we have a blue corvet for $5,000 which is really cheap but you know what I don't want the model to be writable just readable if you don't want an attribute to be writable when you declare it you 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 logic so with our price let's do the following let's add a check if our price is less than zero then let's output the following price can't be less than zero else if everything checks out if our price is zero or above then we'll assign this do price equals the price that we receive as an argument Let's test it 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 the price it stayed the same at $10,000 so those are getter and Setter methods they help protect object data and add rules for accessing or modifying that data getter methods make a field readable Setter methods make a a field writable depending on your object's attributes you may want some to be readable or writable or both it's up to you and well everybody those are getter and Setter methods using Java all right let's do this today I got to talk about aggregation in programming aggregation represents a has a relationship between objects one object contains another object as part of its structure but the contained object or objects can exist independently B basically speaking an object can contain another object but those objects can exist independently what we'll do for this demonstration is create some book objects then we'll create a library object to contain the book objects the books and the library can exist independently that's aggregation the library object will have book objects we'll create a new class of book file new class book and a class for Library file new class Library let's design our book objects let's say that books have a string of title and an integer for Pages you could include an author too if you would like but I don't want this example to be too big we'll need a Constructor for our book objects we'll set up the parameters we need a string of title and an integer for Pages this. tile equals title this. Pages equals Pages if you would like you can set these attributes to be private but that might be overkill for this lesson why don't we create a method to display the book's info this method will return a string we'll Define a method to display info we will display the info of this book Let's return the following let's return this. tile plus a space character 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 parenthesis you can also use a print F statement if that's easier for you but I want to try and keep this beginner friendly okay that's good enough for the book class let's create a few book objects we'll start with book one book book one equals a new book but to construct a book we have to pass in at least the following a title and a number of pages so I've picked out a few books already feel free to choose your own if you would rather choose different books for the first book that I'll pick I will pick the Fellowship of the Ring this will be all one string and the number of pages at least according to wekipedia is 423 then we'll create another book another book object this will be book two book two will be the two towers the number of pages will be 352 and then book three book three will be the Return of the King the number of pages will be 416 all right we have our independent book objects then what we'll do is stick them all within an array we'll create an array of book objects named books equals then within a set of curly braces we can place our book objects within here book one book two book three we have an array of book objects before moving on let's test the display info method of each of these books so we'll need a print statement book one. display info so we should get book one The Fellowship of the Ring 423 Pages I'm just going to make one change I'll put the right parentheses at the end that's better let's display book two the two towers 352 Pages book three the Return of the King 46 Pages you could also Loop through this array using an enhanced for for Loop the data type of each element in my array is book for every book in my array of 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 Ring The Two Towers The Return of the King and we can delete this for Loop we no longer need it now we're going to create a library object our library object will contain our array of book objects because libraries contain books going to our library class what should libraries have let's say that our library should have a name what's the name of the library maybe a year in which the library was established in year and libraries should contain book objects we will create an array of book objects named books we'll need to instructor for the library class we'll need the following a string for the name of the library an integer for the year of the library when was the library built and an array of book objects this St name equals name this doe equals year this. books equals the books that we receive this array all right going back to our main Java file this is where aggregation is going to come in we will create a library object library library equals new library but we have to pass in the following as arguments to the Constructor a name for the library a year for the library and an array of book objects so for the library I'm going to say the NYC the New York City public library after a quick Google search this library was built in the year 1897 then we also need an array of book objects I will pass in my array of book objects named books this is aggregation our library object has book objects within the library class let's also create a display info method for the library we'll make it a little bit different this method won't return anything let's say the return type is void we'll name this method display info we'll display the following information about this Library let's output the following the this.e of the library plus a space character plus this.name you can also also use a printf statement if you would prefer to use that I'm trying to keep this as beginner friendly as possible so let's test this we will take our library object call it display info method the 1897 New York City public library then within this method of display info for the library let's also list all the books that it has this Library has aggregated a whole bunch of book objects so then we can display them or use them for something let's output the following let's output books available then we'll use an enhanced for Loop the data type of what we're iterating through is book objects for 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 this method returns a string there we go let's test it so after calling the display info method of the library we should display the information of the library including its books the 1897 New York City public library and we display the books available which are the array of books that we have created so that's aggregation it represents a has a relationship between objects our library object has book objects within it there's another similar concept called composition with aggregation if you were to delete this Library class for example I'll delete it well these book objects can exist independently outside of the library the books aren't built into the library so they can exist independently which is a key compared to composition which is the next topic we'll cover and well everybody that is aggregation using Java hey everybody in this video I'm going to explain composition to you in programming composition represents a part of relationship between objects for example an engine is part of a car an object can be part of another object this allows for complex objects to be constructed from smaller objects in this demonstration we're going to create a car object the car object is composed of an engine 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 have let's say a string of model an INT of year and an engine object engine engine we'll need a Constructor we'll pass in a string for the model an INT for the year now for the engine we're not going to be passing in an engine object let's say that when we construct a car object we have to pass in a string for the engine type is it an inline engine is it a V6 that sort of thing we will assign this St model equals the model that we receive this. year equals the year that we receive now with our engine this. engine we're going to call the Constructor for a new engine object and then we can pass in our engine type but we still however have to set up the Constructor for our engine class when constructing a car object we will also be constructing a new engine object so let's go to our engine class let's say that engine have a string of type you could say engine type but that would be redundant I would say let's just say type then we need a Constructor for our engine class we will need a string of type to pass in this.type equals type so going back to our car class when we pass in a string for the engine type you could say that this is type this term is kind of ambiguous though because a user is going to think that the type is for the car type rather than the engine type so when you pass arguments your parameter names can be different from the argument names that you pass in we simply rename them when this Constructor receives that argument but type refers to the engine type all right so this is a basic demonstration of composition now we'll construct a car object car car equals new car and then we have to pass in the following a string for the model an inch for the year and a string for the engine type pick a card that you like this time I will pick a Corvette the year will be 20125 and for the engine I will pick a V8 engine then let's see if we have these details I'm going to Output my car objects model and these attributes I did not set to private but you can set them to private and use Getters and Setters if you would like so we have model year and we have an engine object here's what we have we have our model Corvette year 2025 now for the engine our engine is an object it's a reference data type so if you you output it directly you're given a hash ID to represent that engine object so if we need the type of engine we're going to access our engine object then get the type so following our engine object we will use that access modifier that dot then access the type the attribute so the engine type is a V8 so it's like we have an object that's composed with another object our n is part of our car you know what let's create a method for the engine we'll create a start method void start we'll output the following let's say using a print line statement you start the plus this. type meaning type of the engine plus the word engine then going to our car class let's create a start method for the car class void start when we start the car we also start the engine let's take this. engine call it start method and then we can output something else too if we would like let's output the plus this do model plus the words is running now if we start the car let's take our car call it start method and we should get the following you start the V8 engine the Corvette is running now a key difference with composition is that if we delete our car object that should also delete our engine cuz our engine is part of our car so to demonstrate that I'm going to delete our car object and we no longer have access to the engine all right everybody that is composition it represents a part of relationship between objects for example an engine is part of a car this allows for complex objects to be constructed from smaller objects and well everybody that is composition using Java well look who showed up today I got to talk about rapper classes rapper classes allow primitive values you know such as as integers characters doubles booleans those sorts of things rapper classes allow these primitive values to be treated as objects or basically wrapping primitive values within an object kind of like a Christmas present generally you don't need to wrap Primitives unless you need an object for some reason like if you're using a collections framework in Java and rapper classes also give you access to a lot of useful static utility methods so let me give you a demonstration of rapper classes the method of creating rapper classes I'm about about to show you is actually depreciated but it's going to help you visualize how this works wrapping A Primitive within an object the modern approach is using a technique called autoboxing but the method I'm about to show you is a good way to visualize this whole thing so let's say we have an INT of a variable a a equal 123 we can treat this primitive as an object by using a wrapper class here's how rather than declaring this variable as an INT we will use the rapper class of integer integer variable a equals a new integer and then we're going to pass in that number that integer as an argument a is an object we're passing in that primitive data type that int as an argument to the integer class so a is an object but it does contain A Primitive value again this is depreciated as a version 9 so you shouldn't do it this way but this is a good way to visualize it then if you need a double we'll use the wrapper class of double let's say variable b equals a new double then we'll pass in a double 3.14 is good then we have char which is character that's the rapper class character C equals a new character then pass in a character I'll pass in a dollar sign We'll add one more let's say a Boolean we will use the wrapper class of Boolean Boolean D equals a new boan then pass in a Boolean value here's just a few examples these are all objects a b c and d by wrapping these Primitives within an object that allows us to use these primitive values within collections Frameworks such as array lists which we'll talk about in the next topic the modern way to use rapper classes is actually just to assign them directly to their primitive values the class of integer a equals 123 doubleb equal 3.14 character C equals a dollar sign character and then D equals true this technique is called autoboxing We're directly assigning these Primitives into an object using a rapper class now this is very similar to how we declare and assign strings to create a string you would say string let's say E equals a string of characters such as the word Pizza you can see that there's a similar pattern we have always created strings this way but with autoboxing it's a similar process these are all reference data types they're a type of object there's also a technique called unboxing to convert a rapper class back to its primitive this is unboxing so let's say we would like to convert our object of a it's an integer object back to its primitive let's say int x equals all you got to do is set it equal to your object in this case our integer object of a this is unboxing we're taking a primitive that's wrapped in an object and unboxing it we unwrapping it and setting it back to its primitive if we were unboxing a double we would say double some variable equals b or chars Char x equals our character object of c and then Boolean Boolean x equals D again this is autoboxing we're wrapping up a Christmas present we're wrapping up a primitive within an object and then unboxing is removing it we're opening the Christmas present now these rapper classes themselves do have some pretty useful utility methods that are static let me demonstrate a few you might be interested in but there would be too many to cover in just this one video if you ever need to convert a primitive data type into a string there's a two- string method of these utility classes so let's say we have string a string B string C and string D I can convert an integer into a string using the integer wrapper class it's ACC statically so we type the name of the class integer called the two string method which is static and then pass it an integer like 123 so let's do this with the double we will access the double wrapper class called the two string method and then pass in a double 3.14 then to convert a character to a string we would use the character wrapper class character to string and then pass in a character and then Boolean we will access the Boolean wrapper class called the two string method and then pass in a Boolean so strings can be concatenated together we should be able to do the following let's say string X = A + B + C + 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 rapper classes to convert these primitive data types into Strings if you ever need to convert a primitive to a string then use that primitive data types rapper class and call the two string method then you just need to pass that value in as an argument then it's going to spit out a string for you now on the other hand to convert a string to a primitive data type there's another useful utility method of wrapper classes so what we'll do is parsing we will have an INT of a a double 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 method of parse int we can convert a string to an integer I will convert a string of 123 to an integer now with doubles you will call the double wrapper class and we will parse a double we'll pass in a string of 3.14 now characters don't have a parse method what you could do instead is with any string let's say we have a string of pizza strings do have built-in methods one of which is the Char at method return the character the first position where index is zero again character doesn't have a parse character method so you would have to use charart at which is unrelated to wrapper classes so then with the Boolean we would access the Boolean wrapper class called the parse Boolean method and we can convert a string representation of a Boolean such as true into an actual Boolean and then let's output them now we shouldn't be able to add these together much like what we did when we used the two string method for example string X = A + B + C + D this isn't going to work because we're mixing 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 data type there is various parse methods to handle that within our rapper classes it depends on the data type you're working with there's a couple other miscellaneous utility methods within rapper classes I'll just cover two more so let's say we have a Char of letter pick a letter I will pick the letter lowercase B I'm going to use a print line statement we can check to see if our letter actually is a letter we can access the character wrapper class call the is letter method and then pass in our letter this returns a Boolean true or false is this character a letter that is true this would be useful for verifying user input what if this was a dollar sign is this a letter well this returns false that is not a letter I'll switch this back to lowercase b there's also a built-in method to check to see if this letter is uppercase or not there's a built-in utility method of the character rapper class class to check to see if this is uppercase or not character is uppercase and then pass in our letter is it uppercase currently it isn't that is false but if it were uppercase that returns true some of these utility methods of the character rapper class would be great for verifying user input like a username or a password all right everybody so those are wrapper classes we're basically taking a primitive and wrapping it in an object kind of like a Christmas present in the next topic we're going to be working with array lists and array lists only work with objects so we need to utilize these rapper classes in order to work with array lists and wrapper classes do provide some useful static utility methods that you can always access all right everybody and those are wrapper classes and in the next video we're going to cover array lists all right people it's about time we get to array lists and Java an array list is a resizable array that stores objects you can store Primitives if so you'll be using autoboxing which we learned about in the last topic on rapper classes arrays are fixed in size but array lists can change they're Dynamic here's how to create an array list first we'll follow our similar pattern with creating many objects in Java array list let's say list equals new array list we will need to make One Import import java. u. arraylist following the type of array list we're going to use the diamond operator this has to deal with generics which is a future topic but for now we're going to specify what type of object we're going to be storing within our array list and you can always use the appropriate wrapper class to store Primitives for example if you need to store integers you can say integer and then we do need that diamond operator after the second array list you don't also need to specify the data type within the second Diamond operator Java can infer that you're going to follow this pattern to create an array list this array list can store integers you just have to specify that type so for example let's take our list and add a few numbers three 1 and two and then we can print our list our list I will print our list and we have three numbers 312 now if you were storing doubles you would set the type to be double and use the double wrapper class 3.14 1.99 2.01 I'm just making up numbers here there we go so let's store strings let's create an array list named fruits we will store the names of some fruit so the array name is going to be fruits and then we will print our array list of fruits think of some fruit I will add an apple an orange a 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 coconut to add an element to an array list you can use the add method add is a built-in method of array lists to remove an element you can use the remove method then specify an index so let's take 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 at index one that should get rid of our orange apple banana Coco nut there's also the set method take our Ray list of fruits called the set method add a certain index let's say zero we can set that element to be something else let's replace apple with pineapple replace the element at index zero with pineapple then we have pineapple orange banana coconut or index one would be apple pineapple banana coconut that's the set method with an array list to get an element at a certain index you can use the get method then specify the element number get the element at index zero that's going to return Apple get the element at index one would be orange two banana 3 coconut you can also get the size of an array list take your array list call the size method that will return the total amount of elements within your array list so my array list has four elements to sort your array list you will use the collections framework call the sort method and then pass in your array list our array list is named fruits and then you do need to import this class java.util doc collections after sorting our array list let's print it print my array list of fruits so these all should be in alphabetical order starting with a for apple b for banana C for coconut o for orange so that's how to sort an array list you can use the collections framework you could use an enhanced for Loop to iterate through all the elements of an array list so the data type of my aray list is strings we specified that type for every fruit in my array list of fruits let's print each fruit and here they are apple banana coconut 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 all the food that they want within this array list so to help us with this exercise we will need a scanner scanner scanner equals new scanner pass in system.in import this class and then be sure to close your scanner at the end because I tend to forget scanner. close we'll need an array list again we'll follow a similar pattern with creating objects array list let's say list equals new array list using the diamond operator we're going to specify the type of what we're 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 the name of food we'll create a prompt we'll ask a user enter the number of food they would like to store enter the number of food you would like and I'll use print rather than print line for the user input we'll create a variable of num of food to store the number of food that we're going to store equals take our scanner call the next int method to get the next integer from the user once we accept an integer we should clear the input buffer because there's going to be a new line character within there take our scanner call the next line method to clear it let's do a test run and enter the number of food you would like I'll just say three and that seems to work for now we have the number of food we're going to store within this array list in my example let's say I would like to enter three food items well we could use a for Loop to iterate three times we will ask your user to enter in a food three times then so we can use a for Loop for that within our for loop we're going to create a counter of I meaning index we can set that to be zero or one let's stick with one we'll continue this for loop as long as I is less than or equal to our number of food variable if I would like to enter in four food items this would be four so we should iterate this Loop four times we will increment I by One during each cycle of this Loop during each iteration of this Loop we will ask for a food item I'll use print rather than print line we will ask a user to enter food number then I'll add plus our index of I so during the first cycle I is going to be one then 2 3 four so on and so forth then I'll add a colon then a space we'll create a local variable of food this will be of the string data type we will set this equal to use our scanner called the next line method to get a line of text from the user once we have our string of food we're going to add it to our array list of Foods so take your array list of foods call the ad method to add an element we will add our string of food to our array list of foods and then once we're done let's print our array list using a print line statement we will print our Ray list of foods all right let's test it enter the number of food you would like I'll say four so we should ask for four food items enter food number one I'll say pizza hot dog hamburger and then Taco and here's my array list of food pizza hot dog hamburger taco all right everybody those are array lists an array list is a resizable array that stores objects you can store Primitives you're just going to use Java's autoboxing feature if that's the case once you have your array list there's various methods to add remove move or set elements and well everybody those are array lists in Java today I'm going to talk about exceptions using Java an exception is an event that interrupts the normal flow of a program these exceptions pop up if you do things like divide by zero you can't find a resource for some reason or if there's a mismatch with the input type let's say the program asks for a number and you type in a string of characters these sorts of events interrupt your program they're called exceptions there's a way that we can handle them and that is by using a few blocks of code try catch and optionally finally so any code that's considered dangerous where it might interrupt your program you can surround with a tri block here's an example so let's say I'm going to take the number one and divide it by zero mathematically speaking you can't divide by zero that causes an exception more specifically and arithmetic exception I'm actually just going to copy this and save it this code is dangerous it's interrupting our program by causing an exception we can gracefully handle this exception so that it doesn't interrupt the normal flow of our program any 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 block we will catch any exceptions but we're going to list the specific kind of exception we're going to catch well let's catch that one exception that arithmetic exception this is the type we're setting up a parameter here arithmetic exception is the type we will give this exception a name of e for a nickname if we encounter this exception we can take a different course of action instead of interrup the program so let's do the following let's output you can't divide by zero idiot so if we run this again it shouldn't interrupt our program we catch this exception and output this text instead so any code that's dangerous where it might cause an exception you can surround with the tri block you can add more than one catch block to catch and handle spefic specific exceptions so this time we're going to accept some user input we'll need a scanner for now I'm going to write the scanner outside of the tri Block near the end of this video there's a feature called used with resources I'll show you how to do that later scanner scanner equals new scanner type system.in and then import this class import java.util.scanner anytime you accept user input it's almost always d dangerous code because a user can type in anything this time let's prompt a user to enter a number and I will use print let's create a local variable of int number equals use our scanner called 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 instead well we get an exception an input mismatch exception Java was expecting an integer but we typed in a string instead we can handle these exceptions too and I'm just going to copy the name of this exception because we'll reuse it let's catch the following let's catch any input mismatch exceptions this is the type we will give this exception a nickname of e so this exception we actually do have to import import java.util do input mismatch exception in case there's a mismatch with the data type we're asking the user for a number but they type in a string Let's help with the following let's say that wasn't a number let's try it again enter a number uh I'll type in the word I already did pizza let's do Taco that wasn't a number and our program finished with no problems you can catch and handle more 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 good practice you want to let a user know exactly what went wrong if all else fails and there's an exception that you don't anticipate you could just say okay something went wrong you could technically use this by itself enter a number for example I'll type in hot dog something went wrong this does prevent our program from being interrupted it is good practice to let the user know what went wrong exactly I'm looking at you Microsoft catching all exceptions acts as some sort of safety net you should only do it at the end in case there's something you don't anticipate it is better to catch and handle specific types of exceptions because you can let the user know what went wrong exactly now there's also the finally block this is optional finally will always execute whether there's an exception or not this is where you might clean up any resources for example with my scanner I forgot to close it we can actually close it within the final block when we're done with our scanner let's close it because if we encounter an exception we might not close the scanner other times finally might be useful is if you open a file within a tri block then you'll want to close the file when you're done with it you can do that within the finally block for testing purposes I'm just going to add this always executes all right let's do a test run enter a number I'll type in 12 three and then we output 123 see that finally block does execute this always executes if we encounter an exception enter a number I will type in Taco we get our exception message for input mismatch and then that finally block does execute finally is quite often used for cleanup cleaning up your program when you're done with it when you open a file or resource you want to close it we'll have more practice with this on the next topic of file handling now there's also try with resources and actually Java is recommending this rather than declaring our scanner outside of the tri block we can place within a set of parentheses and then Java is automatically going to close those resources when it's done opening them so this works too so enter a number 123 enter a number Pizza that wasn't a number all right everybody so those are exceptions they're events that interrupt the normal flow of a program exceptions occur when you divide by zero you can't locate a resource or there's a mismatch of the input type that a user types in you'll want to surround any dangerous code with a tri block anytime you accept user input or try and locate an external resource that's almost always dangerous code try any dangerous code catch any exceptions and optionally you can add finally to do any resource cleanup and well everybody those are exceptions in Java all right everybody in this video I'm going to show you how you can write a file using Java after doing some research I've encountered four popular options the first way I'm about to show you is the most simple and is what I'll be demonstrating in this topic we'll be using a file writer object it's good for writing small or medium-sized text files there's also buffered writer this has better performance for large amounts of text print writer is best for structure data like reports or logs then there's file output stream which is best for binary files such as images or audio files files of that nature in this topic I'm going to cover file writer just so we get the hang of the basics I might make videos on the other writers but I haven't decided yet here's how we can write a basic file using Java we'll need a file writer object file writer I'll name this file writer just writer for short equals new file writer then we need to pass in a file path or a file name let's create a file named test and include a file extension let's say it's a txt file a plain text file now you could include an absolute file path I'll show you how to do that later our plain text file a test is going to appear in our source folder reading or writing files is kind of unpredictable you could consider that dangerous code any dangerous code we want to enclose within a tri block try this dangerous code catch any exceptions that might interrupt our program with modern Java you can try and open up some resource add a set of 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 including the extension now we do have to import this class import java. file writer if for some reason we can't write this file we might encounter an exception we will catch any IO exceptions IO meaning input output catch any input output exceptions that's the type we will give this exception a nickname of e then we do have to import this class too in order to work with IO exceptions java.io doio exception in case there's a problem writing this file we'll catch this exception if it comes up this acts as more of a safety net if we encounter this exception we can say something generic such as could not write file but it is best practice to handle specific kind of exceptions first momentarily we're going to add a catch clause for a file not found exception in case we can't locate a file path but we'll take care of that in a moment within the tri Block in order to write a file using Java using file writer we will take our file writer which we named writer called the write method and then pass in a string let's say I like then pick your favorite food as you know my favorite food is pizza then after writing this file if we don't encounter any exceptions we'll print a confirmation message let's say the following file has been written all right let's test this file has been written since we didn't specify a file path your file is likely going to be within your Source folder and here's mine test.txt and it says the following I like pizza now you could pick a different location for example you could use an absolute file path so let's say I would like to write this file to my desktop so what I could do I'm going to go to my desktop I'm going to get the file location my desktop I'll just right click on one of these folders go to properties copy this location then I'm going to paste that file path you'll likely need to use double forward slashes Java interprets a single forward slash as an escape sequence so you may need to use double slashes when I write this file it should be at this location this absolute file path Let's test it file has been written let's go to my desktop and here's that file test it says I like pizza let's say that we get the file path wrong instead of desktop I'll misspell this as deskto run this again we counter that exception could not write file that's because Java couldn't locate this file path I misspelled it now when handling exceptions it is best practice to catch specific types of exceptions first here we're relying solely on our safety net that catches all input output exceptions another kind of exception that we can catch is the following file not found exception we will give this a nickname of e then we do need to import this class java.io file not found exception this this is if we can't locate a file or a file path is invalid so let's output the following could not locate file location let's try that again remember that my file path is misspelled could not locate file location let's spell this correctly this time I'm going to delete this file maybe I'll add another line of text I like pizza it's really good okay let's try that again file has been written going to my desktop here's that file and it says I like pizza it's really good for better organization what you could do is create a string a file path and set that equal to a string we're going to cut everything within our file writer and paste it within the string we're going to assign the string of text equal to a string variable a file path then we'll pass in the string variable to the file writer and instead of passing in a string literal to the right method of a file writer for better organization 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 I like pizza it's really good buy me pizza okay let's run this again file has been written go to our test file and here's our test file I like pizza it's really good buy me pizza if you have a string that takes up multiple lines another option is to write a multi-line string by using a triple set of double quotes So This is if you have a lot of text this time I'm going to write a poem roses are red violets are blue booty booty booty rocking everywhere all right so this is a multi-line string you use a triple set of double quotes that's if you have a lot of text to write okay let's test it again file has been written let's go to our desktop open this file and here's our poem roses are red violets are blue booty booty booty rocking everywhere all right everybody so that is how to write a file using Java to write small or mediumsized textt files you can use a file right writer but you will need a try and catch block and well everybody that's how to write a file using Java hey everybody in this video I'm going to show you how we can read a file using Java after doing some research there's three popular options the first and which I'll demonstrate in this video is to combine a buffered reader and a file reader both together this technique is best for reading text files line by line buffered reader can't read a file by itself you can say that it acts as a middleman between the program and the file system it helps us read files more efficiently and a file reader is what actually reads the file so we'll be using these two together which I will demonstrate momentarily another technique is to use a file input stream which is best for binary files such as images and audio files then there's also Random Access file that's best for reading or writing specific portions of a large file so use this if you need to read something specific from a big file in today's video we're going to combine a buffered reader and a file reader together but first we need a file to work with pick a location where you would like to read this file from for me I'm going to create a file on my desktop I will create a new text document I'll name this test and what should our file say think of something to write so there's a poem that I like to use roses are red violets are blue booty booty booty rocking everywhere we will need the name of this file including the file extension I'm going to right click go to 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 of quotes cuz we're working with strings I will paste that file path and include the file name including the extension test.txt now we're going to be combining a buffered reader and a file reader together first we will create a buffered reader object buffered reader we'll name this reader equals new buffer reader we will need to import this class import java.io buffered reader we can't create a buffered reader object without first passing in a reader object which is why we'll be combining this with a file reader object within the Constructor we'll be passing in an object a new file reader object and then we do need to import this class too import java.io file reader within the Constructor of our file reader we're going to pass in that file path that string when reading and writing files you'll need try and catch blocks you can see that Java is already giving us a warning when working with files it's considered dangerous code because you don't know if you'll actually locate that file or not or reading or writing that file might be unsuccessful for some reason we will use a try and catch block try this dangerous code catch any exceptions with modern Java you can use with resources we will add a set of parentheses after try copy the snippet of code where we create a buffered reader object and then paste it within that set of parentheses remove the semicolon when using try with resources you'll automatically close this reader when you're done with it we're going to catch any file not found exceptions within the catch block so catch file not found exception that's the type we will give this exception a nickname of e within the parameter and we do need to import this class as well import java.io file not found exception if for some reason we can't locate this file at this file location let's output the following could not locate file to catch all other input output exceptions We'll add another catch block this will act as a safety net we will catch any IO exceptions IO exception we will give it a nickname name of e this is where we'll say something went wrong and import this class as well just temporarily within our Tri block I'm going to Output that file exists so let's test it that file exists so that file is at this file location on my desktop for some reason if we can't locate that file let's say that I misspell desktop as deskto run this again well we get that exception that file not found exception could not locate file let's make sure the file path is correct now here's how to actually read the file within our Tri block let's 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 loop during each cycle of the while loop we're going to write the following within a set of parentheses we're going to set our string of line equal to use our buffered reader object call the read line method we're taking our reader reading the current line this will return a string which we're assigning to the string variable of line after reading one line our reader is going to point to the next line however if we run out of lines the readline method is going to return null so we're going to continue reading lines while line does not equal a value of null use the reader read each line assign it to this variable of line if we run out of lines if this is null we'll escape the while loop during each cycle of the while loop we'll output each line it's going to be 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 rocking everywhere so that's one way in which you can read a file using Java you can combine a buffered reader and a file reader it's best for reading text files line by line but there's other methods you should be aware of too such as file input stream and random access file I'm not sure if I'll make videos on these yet and well everybody that's how to read a file using Java hey everybody in this video we're going to create an audio player using [Music] Java let's get started all right let's get started everybody now in this following project what I'm about to show you isn't compatible with MP3 files but you could easily convert an MP3 file to a wave file you can do that online otherwise to play an MP3 file you'll need an external library or framework such as Java FX and I do have another video on that if you need some sample of music you can always use YouTube's audio library these songs are free to use as long as they're within the context of YouTube you could search for songs find one that you like and download it this is the song I picked it's currently an MP3 file I'll need to convert it to a wave file you can easily 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 desktop I'll delete the MP3 file and we now have a wave file to make 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 begin once we have a wave file we're going to create a string for our file path you can use an absolute file path or relative file path since this wave file is right next to my main Java file I can use a relative file path easily we're going to copy the name of this file we're going to copy path file name and then paste it within the string the song that I picked is a caring friend and this is a wave file be sure to include the extension too once we have our file path we'll create a file object but we have to pass in our file file path as an argument to create a file object file file equals new file then within the Constructor we will pass in our file path to the file Constructor then be sure to import this class for file when handling files it's considered dangerous code because accessing files can be unpredictable we'll use a try and catch block try this dangerous code catch any exceptions one exception that we may run into is an IO exception we'll give it a nickname of e then be sure to import this class this catch statement will act as a safety net to catch any unexpected IO exceptions here we'll output something went wrong it is better to handle specific kinds of exceptions first we will do that momentarily within the tri block we will create an audio input stream object that's the first step to playing audio the type of object is audio input stream let's name this object just audio stream equals we will access the audio system class we're accessing it statically so we type the name of the class call the get audio let me zoom out a little get audio input stream method and then we will we'll pass in our file object be sure to import this class too we'll be doing a lot of importing so get used to it now with the get audio input stream method we have to add a catch clause for any unsupported audio file exceptions well we can write a catch block for that catch the following exception type where the type is unsupported audio file exception this is if somebody tries to use an audio file that's not imported not one of the following we will give this a nickname of e import this class 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 Java you can use try with resources add a of parentheses after try we will cut the snippet of code and paste it within the set of parentheses delete the semicolon if you use triy with resources you'll automatically close this object when you're done with it you don't need that finally Clause so now we're going to create a clip object clip clip equals access the audio system class we're doing it statically call the get clip method import this class for clip in simple terms a clip is like a music or Sound Player it allows you to load an audio file and then play pause stop or reset the audio so it gives you some controls and we do need a catch clause for this too for any line unavailable exceptions so let's add that catch clause in case we encounter a line unavailable exception which we will nickname e you might encounter this exception if another resource is trying to access that audio file or if it's unplayable for some reason it's unavailable we could output something such as unable to access audio resource then import this class as well there we go once we have our clip it gives us some controls but we do have to use it to open the audio stream object we will take our clip object call the open method and then pass in our audio stream object the clip object which is our player is going to open our audio stream now we're not going to play it quite yet before we actually do play it I'm going to add another catch Clause we're going to catch any file not found exceptions if we can't locate our audio file file not found exception of e will output could not locate file import this class two so we have four catch blocks the last one acts as a safety net now let's be sure that we can locate this file first so temporarily let's output no problems detected I'm going to run this program could not locate file if that's the case with our relative file path we're going to access the source folder then access that audio file there it is no problems detected if this file is unsupported 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 audio file exception if that's the case yes audio file is not supported because we're trying to use an MP3 file so let's switch that back to wave or whatever yours was originally and delete our MP3 file we were just testing it all right now we're actually going to play the clip now one last thing that I'm going to add it's optional I'm going to add a finally block once we're done with this program we can output the following let's just say by this will make sense in just a moment why I'm doing this there's one problem we're going to encounter when we play our audio now to actually play the audio we're going to take our clip object call the start method to start the 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 right away the issue that we're running into is that our program doesn't wait for the audio to finish once we start the clip we immediately end the program so we need some way to keep the clip open and there's a bunch of different options you could use threading within a while loop to check to see if the clip is still running but I haven't taught that yet so here's another option we create a prompt for the user to play stop reset or quit the audio program the audio will continue playing unless the user decides to stop or quit the program so we'll need a scanner to work with to accept user input scanner scanner equals new scanner pass in system.in import this class now if you open a scanner you do want to close it when you're done with it you can do that within the final finally block like this scanner. close with modern Java you can use try with resources which will automatically close any resources and we can do that with our scanner too let's cut our scanner paste it within the tri block now be sure to include the semicolon our scanner is going to automatically close when we're done with this program because we're using try with resources you can use try with resources if an object implements the autoc closable interface scanner and audio stream both do clip doesn't so we'll keep that within the tri block rather than start our clip let's create a string variable of response we'll create a while loop while our response equals let's say capital Q now we want to say while our response doesn't equal capital Q we'll use the Notch logical operator and to make our while loop happy we do have to initialize our response we'll set that to be an empty string so a user is going to type in a response as long as it's not Q meaning quit we'll continue the program within the while loop we'll give a user a few options let's output the following let's say p equals play Let's copy this print line statement s equals stop R is to reset and Q is to quit then we will ask a user to enter your choice I'll use print rather than print line to keep the user input on the same line we'll take our response which is a string set it equal to use our scanner get the next character by calling the next method in case a user types in a lowercase character we can make it uppercase by Method chaining the two uppercase method all right we'll do a test run and let's be sure that we start the clip just temporarily clip.art method what's likely going to happen is that we'll 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 going to stop it's because the program closes down and exits now we want to give the user a few options after they type in their response we can use an enhanced switch 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 we will create a switch we will examine our response does our response match any cases if our response matches a case of P we'll write an arrow to do the following take our clip then call the start method if our response matches a case of s that means stop take our clip object called the stop method if our response matches a case of R do the following take our clip to reset you're going to call the set micro second position then pass in zero do pay attention to the capitalization s is a lowercase if our response matches a case of Q take our clip call the close method to close the clip then if there's no matching cases let's output the following system.out.print line invalid Choice all right and that should be everything enter your choice just to be sure that the default case is working I'm going to type Taco invalid Choice we'll press P to play s to stop P to play again R to reset and Q to [Music] quit all right everybody that is an audio player that you can write using Java what's up everybody in this video we're going to create a working game of hangman using Java a user is going to guess certain characters and we'll see if there's a match within a secret word near the end of this video topic will be importing a file of words and one of those words will be secretly selected so let's get started all right let's get started everybody near the end of this video we'll have our program choose a random word from a list of words but to keep this program simple in the beginning for a testing purposes let's create a string variable of word here we'll select a word that we're going to use throughout the program just for testing pick a word for me I'll say you know what let's go with pizza so this will be my word so we have our word we'll be accepting user input so we need a scanner scanner scanner equals new scanner pass in system.in import the scanner class and close your scanner at the end of the program scanner. close here's where we'll be working with array lists we will create an array list of characters to do that we type array list then specify the type within a set of angle brackets we can't use Primitives such as Char we'll have to use the rapper class of character to store characters I will name this array list word State equals a new array list use the diamond operator set of parenthesis semicolon we'll need to import this class now within the diamond operator you don't need to list character again even though that does work Java can infer what the type is in the beginning our word state is going to contain a bunch of underscores and we're going to fill them in one letter at a time by guessing we'll also need a variable to keep track of our wrong guesses int wrong guesses this will initially be zero we'll set that equal to be zero within our array of word State we're going to add an underscore for every letter within our word we'll create a for Loop that will cycle once for every letter in our word here's how we can do that so we'll start with a basic for Loop create an INT of I for index equals 0 we'll continue as long as I is less than take our word and strings have a built-in length method return the length of this word so in this case it's going to be five because there's five letters in this word then increment I by One during each cycle of this for loop we're going to take our array of word State and and add a character by using the add method we will pass in an underscore an underscore character be sure you're using single quotes not double quotes because these are chars technically not strings all right let's do a test run I'm going to Output our word state to see what we have so we should get 5core characters and we do one 2 3 four five p i z z a throughout this game by guessing letters we'll be filling in this word state by replacing the underscores if there's a match let's change this word just so we know that everything's working I will pick watermelon because that's the first thing that came to mind so watermelon has 10 characters 1 2 3 4 5 6 7 8 9 10 all right we know that that works I will switch it back to Pizza delete this print statement and we can move on word state is an array list made up of characters currently they're all underscores but we'll be replacing each with the character if we get the correct guess after the for Loop why don't we create a welcome message let's say welcome to Java hangman now you don't need to do this but I'm going to add some decorators just a bunch of asterisks before and 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 main method we're going to declare another method that's in charge of returning asky art based on the number of wrong guesses that we have this will be a static method it's going to return a string we'll name this method get hangman art we will have one parameter we have to pass in how many wrong guesses we have then depending on the number of wrong guesses we'll return a certain image represented as a string within our get hangman art method we'll be returning a string a string representation of our asky art we can best do this with the switch now a switch can return something we'll use the return keyword create a switch end it with a semicolon within our switch what are we examining we're examining the number of wrong guesses this will be a number 0 through 6 we'll need a case for each of those numbers for each of those guesses depending on how many wrong guesses the user has we'll display one of a few images so here we'll be working on our art skills today too if we have a matching case where wrong guesses matches a case of zero that means they have no wrong guesses case0 Arrow meaning do this will return the following in Java you can write a multi-line string but you have to use a triple set of double quotes and I'm just going to line these up within this triple set of double quotes I'll have three empty lines between them we won't display anything if the number of wrong guesses is zero then for case one if a user has one wrong guess we'll display our man's head represented by an O if wrong guesses is two we can represent that with case two we will draw the man's 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 actually an escape sequence to display a 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 reference and then k6 is for the right leg we'll need two backs slashes we'll want to a default case if there's no matching cases we'll just return an empty string just to make Java happy all right and this method is done based on the number of wrong guesses we'll return one of a few strings Let's test it I'm going to use a print line statement call our get hangman art method we'll start with zero zero wrong guesses we should end up displaying three empty lines if wrong guesses is one we should display The Hangman's head two two is for the body three is for the left arm four is for the right arm five is for the left leg and six is the full body that's when we lose when wrong guesses is six all right we know that the get hangman art method works I will collapse it because we're done with it to get the art for our hangman we just have to call this method then pass in the current number of wrong guesses let's delete this print line statement we no longer need it now when we print our word State let me show you we get this ugly formatting where we have a set of straight brackets then all the underscores are comma separated we can customize that so here's what 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 stay on the same line we'll create a for Loop an enhanced for Loop for every character in our array list of word State we're going to display an underscore with no formatting using an enhanced for Loop we have to list the data type of what we're cycling through we're cycling through an array of characters Char a common convention with enhanced for Loops is to name each letter C because we can't use Char because that's a data type and character is kind of long so C is short for character for every character of C in our array list our array list is named word State we'll do the following we will output our character of C plus a space so then when we output this oh let's use print rather than 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 an underscore they're all separated with a space when we guess each letter we'll be flipping these underscores to its matching character if they do match I'll add an empty print line just so we go down to the next line okay for the next part we'll have a user guess a letter we'll need some user input we'll need a prompt guess a letter colon space I'll use print not print line we'll create a variable of guess guess will be a letter we'll need to accept user input we'll need to accept user input using our scanner scanner. next next will get the next character now since we're working with lowercase characters we can method chain the two lowercase method just to make it 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 character we can easily convert that to a character by using the Char at method but we have to pass it an index we're only accepting a single character so we'll use Char at zero we're telling Java with the string that the user types in give me just the first character and convert it to be a Char so guess is going to be a single letter it'll be of the Char data type 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 which is good how about a z yep our guess is z if I were to type in a full word like pineapple we still end up with just the first character the first character in our string which is good though let's delete this print line statement we no longer need it for this next part we're going to check to see if our guess matches any letters within our word we'll use an if statement for that if take our word it's a string in this case Pizza we'll use the built-in index of method and then pass in our guess so basically with the index of method it's going to return the index within the string of the first occurrence of the specified character for example let's say I guess the letter Z well Z is in the word Pizza it's at index 2 that's the first occurrence if my guess was Z index of is going to return the number two because that's the first occurrence of Z we will check if the first occurrence is greater than or equal to zero that means there's a matching letter if that's the case if there's a matching letter well will output correct guess and then I'm just going to add a new line character to the end all right let's do a test run I will guess the letter Z that's a correct guess but are there any X's there is not so we don't output correct guess if it's the wrong guess we can output using an lse statement wrong guess then I'll add a new line character to the end let's try that again I will guess an X wrong guess there are no x's in the word Pizza okay so within our if statement if we get the correct guess we're going to change our word state to reflect it that's one less letter that the user has to guess we're going to cycle through the length of our word using a for Loop for in I equals 0 we'll continue as long as I is less than our words length by calling the length method then increment I by one we have to see where there's a match exactly which index within our word we'll use an if statement we will take our word in this case Pizza called the Char at method then pass in our index of I during each cycle I is going to increment but during the first cycle it's going to be zero so we're saying take our word in this example Pizza give me the first character so for pizza that would be the letter P is that equal to using the comparison operator are guess so let's say I do guess P the first character of my word is P that means that they match we're going to take our array list of word State and we're going to update it by using the set method we have to pass in an index and a new value our guess let's test it so with the word Pizza are there any z's correct guess oh then we have to Output it too we're going to continue playing as long as wrong guesses is less than six once wrong guesses is six or greater then the game ends so so let's cut this portion of code cut it don't delete it we'll write a while loop while our wrong guesses variable wrong guesses is less than six we'll continue playing this game within the while loop 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 reflect two Z's because my word is pizza but if there's no matching letters it doesn't get updated because there's no matches let me fill this in p i ZZ a and we get the full word all right that's good so far so good so we'll need to keep track of wrong guesses within our else statement we're going to take our variable of wrong guesses incremented by one using the increment operator then back to the beginning of the loop we're going to display our hangman art by calling the get hangman art method this method will return a string so we can put that within a print statement let's use print call the get hangman art method then pass in the number of wrong guesses let's do another test run we have three empty spaces because we haven't displayed any parts of the hangman yet I will guess the wrong letter X we get the head of the hangman I'll guess some more wrong letters CV b n m at the end we'll have to display the full hangman when we lose let's display the right letters p i z a okay good what happens when we lose if wrong guesses is six or greater so outside of the while loop our while loop ends right here we'll write an if statement if our variable of wrong guesses is greater than or equal to six okay we will again use a print statement called the get hangman art method and then pass in the number of wrong guesses we'll also display a game over message game over then display the word the word was colon space plus our original word of 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 was pizza I think I'm going to make a few changes I'm going to remove these new line characters it's a little too much space I think all right we're good so how do we win let's add that after the for Loop if we get a correct guess we'll check to see if our word State doesn't contain any lowercase characters so take our array list of word State call the contains method and then pass in an underscore character but we want to check to see if our word State doesn't contain any lowercase characters we can prefix this with the not logical operator an exclamation point if our word our word State doesn't contain any lowercase characters that means that we guessed all the letters and we win if that's true let's display our hangman One Last Time system.out.print get hangman art pass in the number of wrong guesses and we'll display you win and display the word again the word was colon space plus our word then we'll want to break out of this Loop cuz we're stuck in a while 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 I lose game over the word was pizza all right I'll actually win this time but I'll guess a few wrong characters q w t I'll guess some correct characters a z i p you win and we display our current score the current state of our hangman we display you win the word was pizza in this next part of this video we're going to create a more advanced version of this program by importing a file of words a word is going to be randomly chosen from a file instead of just setting one in the beginning okay everybody in this next section we're going to create a file that contains all the words that we can possibly use for this Hangman game within our project folder why don't we create a new file file new file I'm going to name this file words and this will be a txt file for all the different possible words in this game place within this file you can copy and paste them from somewhere online if you would like just to make reading this file a simple as possible I'm going to list all the words on a separate line so think of some words or like I said copying paste them from somewhere I'll just add several Apple orange banana coconut pineapple grape lime lemon that's good enough in my project folder I have this file words.txt temporarily with my game I'm going to write a multiline comment and just 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 path this will contain either a relative file path or an absolute file path since 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 list we'll create a new array list AR array list the data type is Going to Be Strings so string I will name this array list words equals new array list Diamond operator parenthesis semicolon now we'll actually need to read this file reading files is considered dangerous code because it's highly likely that something can go wrong we will write a try with resources block we need that set of parentheses after try we will catch any except options when you try with resources you'll automatically close any resources listed within the set of parentheses within the set of parentheses we will create a buffered reader object buffered reader which we will 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 file reader to the Constructor new file reader then within our file reader Constructor we will pass in our file path the location to that file now our file reader object wants us to catch any file not found exceptions we'll place that within our catch block file not found exception of e then we'll output if we can't find this file could not find file We'll add another catch block just as a safety net we'll catch any IO exception e exceptions this is where we'll say something went wrong this just acts as a safety net if there's something we don't anticipate so we have our reader object within the tri block we will create a local variable it's a string of line we will read this file line by line using a while loop while within a set of parentheses assign our line equal to use our reader called the read line method if we run out of lines this is going to return null while the value that's returned does not equal null we'll continue reading this file reader is going to give us each of these words line by line we're going to assign them to our array list of words take our array list of words call the add method we will add the current line if there's any white space after these words this will pick that up and our program will consider them to be 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 yep and here's our words all within an array list let's delete that line we're going to choose one of these words at random we'll need a random object random random equals new random import the class here's where we're going to choose our word I'm going to copy this from the previous code and paste it rather than setting our word to be hard-coded string we're going to take our array list of words call the get method but we have to specify an index with our array list return a string at a given index that index is going to be randomly generated by using this random object we will pass in a random object call the next int method to generate a random integer the range of random numbers is going to be dependent on the size of our array list of words take our words call the size method so with our file I have let's see how many words how many strings 1 2 3 4 5 6 7 8 the size method of words is going to return the number eight just imagine that I'm replacing this with the number eight return a random index between 0 and 8 that's kind of how that works and then let's output our word for testing purposes what is my word this time my word was pineapple but it's likely going to change every time you run it Apple lime Apple again pineapple grape it really likes pineapple for some reason let's delete this print line statement we'll integrate our code back 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 chosen word I don't know what it's going to be for me it's six letters I'll guess some of the vowels a there's one a e i o u it's probably orange but I'm going to guess some more wrong letters for testing purposes okay game over the word was Orange let's run it again this one is seven letters a e i o u it's coconut Co n u t you win the word was coconut all right everybody that is a game of hangman that you can code using Java hello there everybody in this video I'm going to show you how we can work with dates and times using Java this serves as more of an introduction we can work with local dates times date times and UTC timestamps let's get the date right now using local date we will create an object of local date let's name this date for short equals access the class of local date called the now method if I was to Output our date object we'll print our date that's going to give you the current date whatever it is right now I'm filling this video December 17th 2024 post the date that you're watching this in the comment section down below that is local date there's local time to get the time let's replace date with time local time. now and rename this as time cuz that's more appropriate print the time currently the time for me is a little after 9:00 a.m. 9 hours 29 minutes 52 seconds and a bunch of milliseconds to retrieve both the date and the time you can use date time local date time local dat time.now method print the current date time and currently for me it is December 17th 2024 at about 9:30 in the morning you can also use UTC time that's a little different we will create a instant object instant instant equals access the class of instant called the now method and print our instant object which will give us the current date and time in UTC December 17th 2024 in UTC time I think that's 300 p.m. it's in military time that's how to get either the current date time date time or UTC timestamp when you output the current date and/ or time it's kind of ugly and 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 current date time local date time we will name this date time equals access the class of local date time called the now method then we'll need to create a formatter object date time formatter we'll name this formatter equals date time formatter I'm just going to copy it call the of pattern method and then we're going to pass on a string let me move the cursor so you can see this within the string we will write pattern letters what is the pattern in which we would like to display our date and our time if you go to the official Java documentation there's an extensive list here's a few beginner friendly ones for the day type 2DS dash for the month two Capital M's for the year Das y y y y four y's this will display the day the month and the year I'm an American so we display the month first followed by the day so I'm going to switch this around but you can keep it as it originally was if you prefer so that's how to display the date in that format month day year now for the time you can do the following for hours do two Capital H's colon minutes is two lowercase M's colon then for seconds it's two lowercase s's that is a good pattern we will create a new string named new date time equals take our current date time it's an object call the format method we are going to pass in our formatter to format our date time to this pattern once we have our new date time we're going to print it let's output our new date time and it should be in that format yeah that looks pretty good December 17th 2024 about 9:00 in the morning 9:30 at least for me instead of getting the time and date right now we can create a custom date time object here's how so we'll start with a local date local date I'll name this object date equals local date we're accessing the class statically we'll call the of method depending on the date you would like to create we'll pass them in as arguments let's say I would like to pick Christmas of 2024 the first argument corresponds to the year I will pick 2024 the next is for the month 12 meaning December then the 25th 25th of December I'll type in 25 all right just to test it I'm going to Output it let's print our date the year is 2024 December 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 would be 12 for the minutes 0o for the seconds zero then let's print this again let's output our date well technically it should be date time but that still makes sense here's our date time December 25th 2024 at noon 12:00 p.m. you can also compare dates too let's copy the snippet of code paste it rename the first date as date one the second date as date two for the second date let's set that to New Year's Day 2025 the month will be January the 1st of 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 Year's Day January 1st 2025 all right now to compare dates we can use the following we'll use an if statement let's check if date one called the is before method dates have a built-in is before method pass in date two is date one before date two and that is true let's output date one plus a string of is earlier than plus date 2 let's check that our first date Christmas is earlier than New Year's our second date else if date one let's just copy this date one is after date two then we'll output something different date one is later than date 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 date you can also check if they're equal let's add else if let me scroll down date 1 is equal to date 2 and then we'll say that they're equal date 1 is equal to date 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 could be good for some sort of alarm clock checking to see if two date times are equal all right everybody so that is an introduction to working with dates and times using Java well hello again friends today I got to explain Anonymous classes in Java so what is an anonymous class it's a class that doesn't have a name meaning it cannot be reused it's when you want to add custom Behavior without having to create a new class because it can be really inconvenient to create a new class just for one object if that one object is different from the rest in one way or another they're often used for onetime uses when utilizing features such as timer task the runnable interface or callbacks these are more advanced Java topics so let me demonstrate why an anonymous class would be useful let's begin with this example where we create a dog class file new Java class we will create a class of dog let's say that in this dog class there's a single method a speak method void speak all we'll do is I'll put the following the dog goes woof and then let's create a dog object dog dog equals new dog we'll take our dog object have it use its speak method which will output the dog goes wo so what if there's a unique kind of dog it's different from the rest let's say it's scoobydoo now Scooby-Doo he doesn't speak dog he speaks English if I want Scooby be do to say something else I'd have to override this method so one option would be to create a new class again this is me not using Anonymous classes you'll see their usefulness in just a moment let's create a new Java class let's create a talking dog class I know it's kind of a weird example so our talking dog class will extend the dog class and then we'll override the speak method override void speak then we'll I'll put the following Scooby Do says what's he usually say rut row or something rut row I think that's how you spell it but you get the idea going back to our main Java file I can create a talking dog object talking dog talking dog equals new talking dog that's a lot to 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 it is a lot of work to create a whole new class just for one unique object our talking dog of Scooby-Doo is the exception so rather than creating an entirely new class just for this one object just for Scooby-Doo our talking dog let's instead create an anonymous 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 but it's going to have some unique features that set it apart from other dogs such as the ability to speak English let's rename dog is Dog one we'll create another dog named dog 2 equals new dog add aside a parenthesis now to create an anonymous class you're going to add a set of curly braces then make sure there's that semicolon at the end within the set of curly braces you can Define any unique features or override any methods dog 2 is going to be different from all other dogs with it speak method so let's override that method at override void speak and then we'll say Scooby Do says rut row dog one is going to speak and dog two the dog goes woof Scooby-Doo says rut R so instead of creating an entirely new class just for one dog Scooby-Doo we can create a normal dog and just override one of the methods using an anonymous class so those are Anonymous classes it's a class that doesn't have a name and it cannot be reused if you need to reuse a class you're better off just creating a new class it allows you to add custom Behavior without having to create a new class which is what we did with the speak method Anonymous classes are often used with timer task which we'll talk about in the next video the runnable interface and callbacks so it is an important topic that you need to know going forward at least to create an anonymous class after you construct an object add a set of curly braces within that set of curly braces you can Define new behavior and well everybody those are Anonymous classes in Java so uh yeah I got to talk about timers and timer tasks in Java timer is a class that schedules tasks at specific times or periodically timer is useful for sending notifications scheduled updates or repetitive actions when you need to schedule a task at a specific time you can use the timer class now timer task is the task that's going to execute cute when our timer says so in order to use timer task you're going to extend the timer task class and then Define your task and we're going to be doing this by using Anonymous classes which we learned about in the last video we'll Begin by creating a timer we need a timer to well keep track of the time let's say timer timer equals new timer and then import these classes I'm pretty sure you're used to importing these by now we're going to select the timer from the utility package all right we have our timer then 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 class all right so here's the situation with our timer class we have to implement the run method to override the run method we could create a child class from the timer task class but here's a better option we're going to create an anonymous class after the set of parentheses we will add a set of curly braces then add that semicolon to the end within this Anonymous class we can update or change the behavior of our timer task object what we'll do is override the run method override to overrun this method this will be public void run it's the run method when we execute our task what would we like to do let's output the following let's just say hello so our task is to print hello but we have to do it when our timer says so so they work together let's say I would like to say hello after 3 seconds to do that we're going to take our timer call the schedule method and then there's two arguments we're going to pass in our task what are we going to do that's the first argument the next argument is the delay after how many milliseconds will we execute this task I said 3 seconds let's say 3,000 milliseconds then after a delay of 3 seconds 3,000 milliseconds do your task that we're passing in so after 3 seconds will output hello or if this were 1,000 millisecs it would only take a second hello you can also schedule at a fixed rate our timer can do things periodically so let's repeat our task of saying hello more than just once so we have our delay you know what I'll set that to be zero the next argument is for the period what is the delay in milliseconds between repetitions let's say 1,000 milliseconds so 1 second starting immediately 0 milliseconds print hello every 1,000 milliseconds every second let's try it hello hello hello hello I think you get the idea or you could add a delay that's the second argument let's say after a delay delay of 3,000 milliseconds 3 seconds repeat this line of code every 1,000 milliseconds 1 second so now there's going to be a delay of 3 seconds then we output hello every 1 second now how do you cancel this timer once it's started well you can use the cancel method where should we add that exactly well we can add that within our task we'll need some sort of stopping condition kind of like a wild Loop so let's say this I would like to say hello three times I'll create a local variable of count I'll set that to be three intellig wants me to make this final you don't have to I'll keep it as is so again we are within our Anonymous class we're declaring a variable to use within the context of our task within the run method we'll output hello decrement our count by one count minus minus then using an if statement this is how we're going to escape if our count is less than zero then let's say task complete and then to cancel the timer we 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 immediately every 1,000 milliseconds print hello whoops it looks like that's less than or equal to zero I fixed it all right so starting immediately the delay is zero every 1,000 milliseconds print hello but only do it three times and then we cancel the timer to stop because we don't want to say hello forever and here it is 1 2 3 task complete all right everybody so that is timer and timer task timer is a class that schedules tasks at specific times or periodically it's useful for sending notifications scheduled updates or other repetitive actions timer task is the task you're going to perform when the timer says so in the next video we're going to use timer and timer task to create a countdown timer all right everybody so that is both timer and timer task in Java why hello there everybody in this video we're going to create a countdown timer program using Java this is meant to serve as more of a mini project to get us used to working with timer tasks let's begin we'll accept user input but we're going to set that up near the end it's going to be easier for us to understand this program at first if we set the countdown timer to be a raw number like 10 to work with timer tasks we'll need a timer to keep track of the time timer timer equals new timer we'll be importing our classes as we go along long be sure to do that import them from the Java utility package then we'll need a timer task timer task I'll name this task for short equals new timer task be sure to import this class now there's one issue though with our timer task object we have to override the run method one option although it's not the best is to create a new class and then inherit from the timer task class so this would be the parent class and then we can override the run method but since we don't plan on reusing that class what we could do instead is use an anonymous class after the set of parentheses add a set of curly braces then add that semicolon to the end for a onetime use we can override the run method of our timer task object because we only plan on using it once so we can write an anonymous class rather than create a whole new class that we're only going to use once so we will override the run method public void run when our timer executes our task what would we like to do well we're going to Output a number the number for our countdown timer so within our Anonymous class let's create an integer variable of count for the time being let's set this to a low number like five intelligent wants us to make this variable final but we'll be accepting user input momentarily so you don't need to do that my IDE of intelligent is recommending that you can just ignore that so let's say that our count is going to start at five and we'll decrement by one then display happy New Year when count to zero so why don't we do the following within our run method we'll output our count variable at first it's going to be five then we'll decrement count by one count minus minus we'll need to escape the run method well we can do that with an if statement 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 method now we have to set up our timer we will do that outside the timer task Anonymous class so right here is good we will take our timer called the schedule method schedule will take a task our timer task and execute it after a delay let's set the delay to be zero now this is only going to run once there's a better method for this let me just demonstrate so we get the number five and our program stops so what we're going to use instead is schedule at fixed rate the schedule at fixed rate method but there's three arguments we have to pass in first is the task the delay and then the period we have our task the delay is zero what is the period in between executions let's set that to be 1,000 milliseconds every 1 second 1,000 milliseconds perform your task and our task is to display our countdown whatever the count currently is all right let's test this again we're setting our count to be five initially but we'll be accepting user input momentarily we start at 5 and we're going to count down to zero then display happy New Year all right after zero we display happy New Year and our program exits because we canceled the timer now if we don't cancel the timer 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 seconds so that's why we need to cancel the timer so that it stops all right now we'll accept user input because we want a user to type in the number to countdown from rather than us programmers just typing in a random number so we will need a scanner scanner scanner equals new scanner then pass in system.in import this class and then we'll need a prompt let's output the following enter number of seconds to countdown from I'll use print rather than print line let's create an integer variable of response set that equal to use our scanner call the next int method to get the next integer from the user then we will set our count variable equal to the response whatever the user types in so now the user can type in a number and we can count down from that number rather than just placing a random number here all right let's test this enter number of seconds to count down from let's say 10 we're going to 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 number you could even set this to a higher number like 60 but I'm not going to make you wait that long all right everybody that is a countdown timer program that you can write as a mini project using Java hello there every everybody in this video I got to cover generics in Java generics it's a concept it's where you can write a class interface or method and it's compatible with different data types there's two things we need a type parameter and a type argument so with type parameters it's a set of angle brackets with a letter inside for example T basically this acts as a placeholder and it gets replaced with the real type now on the other hand type arguments with various objects and data structures you'll see a pair of angle brackets with a type inside such as a string but it really can be anything it can be an integer or a Boolean really anything type arguments specify the type we send arguments to parameters really our type parameter is just acting as a placeholder anything that uses this type parameter it doesn't know the data type that it's going to receive it's set up to receive really anything or a primitive using a rapper class let me give you an example of where you already see a gener being used for example array lists to create an array list we add a set of angle brackets after array list and we have to specify the type what is this array list going to store for example strings we would write the data type of string let's say that this array list is named fruits fruits equals new array list and then we need a set of angle brackets again parenthesis semicolon in modern Java within the second set of angle brackets you don't necessarily need to type the data type again Java can infer that so you can leave it empty this is the diamond operator we have an array list that can store strings we have specified the type argument and now we can store some strings within our array list so let's take our array list of fruits call the ad method and add a few names of fruits such as an apple let's do two more Apple orange banana currently the way that we set up this array list it's compatible with strings because that's what we set the type argument to be now if I set this to be integers well we can't store strings anymore but we could store numbers 1 2 3 that's fine let me change that back generally speaking an array data structure can store all sorts of different data types but when we create one we have to specify what we're storing that's the type argument it's because within the array list class we have a type parameter set up a set of angle brackets with a letter inside in many cases you'll see t meaning type for type parameter so let's actually take a look at our array list I am going to locate array list jump to Source here's the class for our array list there's a lot of advanced Java in here don't worry about that but what I want you to pay attention to is the type parameter that comes after after the array list class name we have angle brackets and a letter inside in this case e meaning element because an array list has elements of data by using this type parameter our array list is set up to store elements of various types we just have to specify what the type is going to be when we actually do store data and in my example we're using strings but like I said before we can change the data type of what we're storing we just have to change the type argument I'll store booleans true false true I don't know what that has to do with fruits but I'm just trying to prove a point here so now what we're going to do is actually use type parameters so let's delete our array list using generics you can write some logic within a class interface or method and it's compatible with many different data types so what we're going to do in this example is create a class of box class box we'll be using a type parameter to store all sorts of different things within our box we can store a string within our box an integer a double A Boolean even more complex objects so we will set up a type parameter with a set of angle brackets then type t t is a common convention meaning type let's say that when we create a box object our box is going to act as a container we'll store a value inside our box is going to be a reusable class we won't always know what the data type of what we're storing is going to be so what we could do is set the data type to be T let's say that this variable is an item we're storing an item within a box with t it does mean type but I like to think of it as thing we're storing a thing an item within our box we don't know what this thing is going to be but really it means type and that's not as fun T item we don't know what the data type is if it's always going to be a string we could just set this to be a string but what if somebody is storing an integer an INT or we can use the rapper class of integer we don't know what the type is going to be let's create a method where we will set our item let's say that this is public void it's not going to return anything set item we'll have one parameter what's the data type of what we're receiving well we don't know so we're going to use our type parameter of t t is the data type it's generic we will receive an item let's take this. item and set it to be the item that we receive we'll create a method to get our item public now we're going to be returning an item the data type is T so the return type is also going to be T 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 things from our box all right this class is done our box class is set up to be reusable we can store all sorts of different things so to say within our box we will attempt to create a box object for now let's say box box equals new box but there's one step that we're missing we have a warning here raw use of parameterized class box we need to set up a type argument what are we going to be putting in our box what's its data type our box class wants to know so we will use a type argument after the class of box add a set of angle brackets then type what we're going to store so let's say we're going to store strings within our box values of the string data type and then we do need the diamond operator after the second box and we're good we now have a box object but it's set up to store strings let's add some items to our box we've even created a few methods for this set item let's take our box call set item but we have to pass in a string let's add a banana to our box and then we will get the banana from 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 from the box our box class is compatible with all sorts of different data types this time let's store an integer we will use the wrapper class of integer but we can no longer add a banana to the Box because it's a string I'll attempt to do so string cannot be converted to integer unfortunately bananas are not numbers but I can add the number three to our box we have the number three within our box if I attempt to add a double like 3.14 we get a warning incompatible types double cannot be converted to integer so I would have to set the type argument to be double to add doubles to our box 3.14 basically with our box class we're writing the logic of how a box works you put something in and you can take something out and it's compatible with different data types we just have to use a type argument when creating a box object we have to let Java know what we're storing within it exactly all right let me give you another example now with type parameters you can have more than one type we can have two or more different types usually the common convention is to use U after T so we're going to create a new class file new Java class we will create a class of product here we're going to write the logic of how a product works with a product you have an item and you have a price we will set up a type parameter let me zoom in we'll have one type of t and a common convention for the second type is U because in the English alphabet the letter U comes after T if you had a third argument that would be V by Common convention so we'll just stick with t and u we will have a generic type of item and another generic type of price we don't know if our item is going to be a string or a more complex object our price could be an integer a floating Point number a double we don't know but that's why we're setting it up this way now we'll need a Constructor we will take our product then set up some parameters the data type of our item is t t item but if we're creating a product we also need a price the data type of our price is u U price this. item equals the item that we receive this. price equals the price that we receive okay let's do a test run let's go to our main Java file product product equals new product and again we need those type arguments so this time we actually need two because our class is set up to receive two type arguments T and U for our product let's say that the first type is going to be a string followed by a double and then we need the diamond operator after the second product all right now we have to pass in arguments to the class because we have a Constructor we have to pass in an item and its price and with our type arguments we set that up to be a string and a double we have to pass in those types for our product let's say that it's an apple and an apple is 50 Cents that's a double let's create two methods within our product class we will create a method to get our item let's say public we're returning an item the data type is T so we're going to return T get item we will return this do item then to return the price let's say public U cuz we're returning the price it has a type of U Get price return this do price we have our product object I'm going to Output take our product object called the get item method and this is going to return are apple or I could get the price get price and that is 0.5 you can use string format but that might be overkill for this lesson all right let's create a second product so we'll have product one and product two Now product two will use an integer instead of a double and let's say that these are tickets like movie tickets ticket and the price will be $15 for $15 let's take product two call the get item method so we have our ticket and we should have a price get price the price of a movie ticket is$ 15 $15 all right everybody so that is an introduction to two generics it's a concept where you can write a class interface or method that is compatible with different data types basically we're writing the logic of how this class works and it's compatible with all different types you just have to set up a type parameter and then pass in type arguments and well everybody that is an introduction to generics in Java well it's up everybody so today I got to explain hashmaps in Java hashmaps are a popular data structure they store a pair of values a key value pair you have a key and a value associated with that key the keys have to be unique but the values can be duplicated hashmaps do not maintain any order but they are very memory efficient when creating a hashmap we have to set up type parameters we have to specify what the data type of the key is and its value here's how to create a hashmap we will type hashmap let's say map for short hashmap map equals new hash map we'll need to import this class it looks like we're missing something let's take a look raw use of parameterized class hashmap if we take a look at the hashmap class we have type parameter set up there's two values we learned about type parameters in the last video on generics we can store any two types of values within a hashmap we have a key and a value represented by K and V we have to send type arguments to the type parameters when creating a hashmap we'll have to set up some type arguments so after our hashmap we have to list the data type of what we're storing these have to be reference data types so let's say with our map we're going to have products an item and a price so for the item that could be a string a string representation of our item so for the price we could do an integer but I think a double would be better because you can have dollars and cents then we also need to use the diamond operator after the second hashmap you don't need to State the data types again even though you technically could Java can actually infer what the data type is so after the second hashmap add the diamond operator and there we go we have our hashmap that we have named map the way that we've set this up is that we've told the hashmap class we're going to store a string as the key and a double as the value so to put things in a hash map we're going to take our map called the put method we're going to put something in the hashmap we've specified that we're storing a string then a double a string for the key and a double for the value so let's say we have a store and in our store we sell produce we will have an apple and its price will be 50 CS 0.50 to put some something in a hashmap you use the put method we have to pass in two values as arguments all right let's add a few more things we'll have an orange an orange will be 75 cents let's say then a banana bananas are pretty cheap they will be 25 cents all right let's take a look at our hash map I'm going to show you what happens if we output our map directly system.out.print line our map our hash map and here's what we have we have all the key value pairs printed within our hash map we have a string and a double string double string double now with hash Maps the keys have to be unique for example let's say I try and put another orange within here we'll attempt to add another orange and we'll see what happens exactly put another Orange within our map and let's say that the price is 1 million Venezuelan dollars yes oranges are very expensive in Venezuela because of inflation so here's what happens if we have duplicate Keys you actually overwrite the previous key value pair our orange is now worth 1 million Venezuelan dollars so do keep that in mind hashmaps cannot have duplicate keys if you put another key value pair with than a hashmap and it already exists you'll overwrite it but that's also good if you want to change one of the key value pairs let's add one more key value pair let's say a coconut map. put we will put a coconut within our hash map coconuts are a little more expensive they'll be $1 let's print our map to test it there's our coconut then we can remove an element to remove an element take your map call the remove method here you're going to pass in a key let's remove our Apple then print our map there the apple is gone we have orange banana coconut but no apple so I'm going to keep that in but turn it into a comment to get the value associated with the key you can use the get method so let me delete this print line statement we will take our map called the get method let's get the value with this key give me the value where the key is Apple is what we're saying that would be 0.5 meaning 50 or we can get our coconut the value associated with this key is one meaning $1 all right you can also check to see if a key or a value exists here's how we'll use the contains key method take our map call the contains key method and then pass in a key is there a key of banana that returns a Boolean in this case true is there a pineapple there is not so that returns false you could use this with than an if statement here's how we will check if let me zoom in if our map call the contains key method and then pass in a key does our map contain any apples contains key Apple if that returns true we'll output map. getet then we'll get our Apple this will give us the price else if 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 have an apple we've set this up to return the price but let's say we are looking for a pineapple contains key pineapple if we do find a pineapple we will get the price price currently there's no pineapples within our map key not found so that's how the contains key method would be useful we also have the capability to check to see if a map contains a value so we will take our map within a print line statement called the contains Value method and then pass in a value is there anything that's $1 1.0 this returns a Boolean and that's true our key of coconut has a value of 1.0 $1 and you do have to pay attention to the data type too if I were to pass in an integer this does return false you do have to keep that in mind too that's how 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 method currently there's four key value pairs within our map this will return the number four to get the size of a map call the size method all right now the last thing that we're going to do if we were to print our map we're given this ugly formatting where we have a set of curly braces then all the key value pairs comma separated this time using a for loop we're going to cycle through all the key value pairs we will create an enhanced for Loop what we're going to iterate through is every key and these have a string data type because that's the way that we set them up the data type of each element is going to be a string which we will name key colon think of it as in for every key in now what we have to do is get all the keys from our map and there's actually a method for that a beginners friendly way to get all the keys from our map what we can do is take our map call the key set method this will return all the keys within our map and they're iterable so we can use them within a for Loop for every key in our set of keys what do we want to do let's do the following within a print line statement let's print our key plus we'll list each product and its price key plus maybe I'll add a colon space then pick a unit of currency I'll pick American dollars for every key we need to get its value so we can use the get method plus map. getet pass in our key by using an enhanced for Loop we can customize the output of the key value Pairs and I think this looks a lot better we have each product each piece of fruit and its price laid out in this format you could technically use print F if you want to display two digits after the decimal but that might be a little too much for this lesson I want to keep it as simple as possible all right everybody so those are hashmaps it's a data structure that stores key value pairs the keys have to be unique but the values can be duplicated we have to specify the type for the key and its value and well everybody those are hashmaps in Java all right let's do this thing everybody today we're talking about enums en nums is short for enumerations they're a special kind of class they represent a fixed set of constants by using enums they improve code readability and are easy to maintain one of the major benefits of enums is that they're more efficient with switches when comparing strings so basically an enum is a special kind of class where we declare constants here's a demonstration we're going to create a new class file new Java class we're going to select enum enum is a special kind of class sort of like like how an interface is a special kind of class we will create an enum of day public enum Day within this Java class we can declare some constants what we're going to write is enum constants a common convention for these constants is that all the letters are uppercase so after the enum constant We'll add a set of parentheses then associate this constant with the value so let's say that we're working with days of the week Sunday will be the the first day of the week Sunday we'll have a value of one let's do this with the other days of the week Monday parentheses then a value 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 constants they have values 1 through 7 we're receiving some warnings here expected zero arguments but one found what we need to do is create a Constructor a Constructor for our day class when we Define these enum constants we're automatically going to call the Constructor for this enum class and then pass in this value let's create a field of day number for days of the week we'll make these values private we'll use the private access modifier we don't want the ability to change them we'll make them final these are integers that's the data type we'll name these values day number when we Define these enum constants we're automatically going to call the Constructor and then pass in this value to the Constructor for the parameters we'll have int then our field of day number this day number equals the day day number that we receive if you would like you can add a getter method to actually get the day number we'll use the public access modifier we're returning an integer we'll Define a method of get day number and we will return our field of this. day number all right and we have set up our enum class reading and understanding these enum constants is a lot easier than these numbers if I was looking at the number five I would have trouble understanding that that means Thursday now how do we work with these enum constants exactly here's how within our main Java file we will create a day object by using this enum class let me delete this day day rather than saying new day and then passing in a number like one there's a different approach we will access the day class Dot and then specify a constant a day of the week let's say Sunday remember that this is all caps our day is an object let's output our day and see what it outputs this will output Sunday all caps if you would rather get the day number the value that's associated with this enum constant then we can use that getter method day. get day number so we have Sunday and one where this is really going to be helpful is when working with switches here's a demonstration we will actually use an enhanced switch what are we examining we're examining our day object if our day matches a case of Monday now this isn't a string If This Were A String we would enclose this within a set of quotes but using enums within a switch is actually faster than using strings if it's Monday then we'll output the following we'll use an arrow because this is an enhanced switch then we'll output it is a weekday then if we have a case of Tuesday let me just copy this Tuesday we'll also output it is a weekday you can actually combine these cases together too you just have to comma separate them so case Monday comma Tuesday do this then let's do this with the other days of the week just for readability I'll put these on new lines each of these cases so we have Wednesday Thursday Friday these are all the weekdays Monday through Friday then if we have case Saturday then it's the weekend case Saturday today we'll do the following output it is the weekend and we will also add a case for Sunday so currently our day is 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 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 we'll need a scanner scanner scanner equals new scanner pass it system.in import this class be sure to close your scanner because I tend to forget scanner. close then we'll need a prompt we will output the following we'll use print rather than print Line enter a day of the week we will create a string variable let's say response equals use our scanner call the next line method all these constants are uppercase we'll method chain the two uppercase method to make our user input uppercase when creating a day object by using the enum class we will use our response we will use the value of method and then pass in our response now we should be able to type in a day enter a day of the week I will type Monday it is a weekday let's run this again I will type Sunday it is the weekend what if we type in a day that doesn't exist like pizza day well we get an exception an illegal argument exception we can catch that exception using a try and catch block any dangerous code we're going to enclose 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 these e nums then we'll output the following please enter a valid day let's try it again enter day of the week let's try Tuesday it is a weekday Saturday it is the weekend Pizza day please enter a valid day Pizza 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 week at least it should be we'll need a case for pizza day Pizza day will also be part of the weekend that just makes sense to me all right let's try that again enter day of the week Pizza day it is the weekend all right all right everybody so those are enums meaning enumerations they're a special kind of class kind of like how interfaces are a special kind of class they represent a fixed set of constants they improve code readability and reliability and where they're really useful is when working with switches because when working with switches using enums is faster than strings if I wasn't 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 I would have no idea what these numbers are but if they're enum constants this is perfectly readable to me these are days of the week that makes sense and well everybody those are enums in Java what's going on people in this video I'm going to teach you all about threading in Java threading allows a program to run multiple tasks simultaneously it helps to improve performance with timeconsuming operations such as file input output network communications or any other background tasks any code that is considered timec consuming we can have it run on a different thread so that it doesn't inconvenience our main program there's two options to creating a thread option one is to extend the thread class this is the simpler option but it's limited option two is to implement the runnable interface this option tends to be better because by extending the thread class we're limited to single inheritance but by implementing the redible interface that's one way around that in this demonstration I'm going to show you option two it's actually not that more difficult than option one and it gives you more possibilities I'll give you a demonstration of why threading is useful in this program where about to write let's say it's a game or a quiz or something a user has 10 seconds to respond and if they don't times up currently we have one thread we're running our program on what is known as the main thread without using any other threads besides the main thread I might write my program something like this we'll start with the scanner because we'll be accepting user input scanner scanner equals new scanner pass in system.in import this class 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 enter their name you have 5 Seconds to enter your name we will create a prompt enter your name I'll use print rather than and print line we will assign a string variable of name use our scanner called the next line method and then once we have the name we'll output hello plus the user's name hello plus name so let's do a test run currently we don't have a timer setup you have 5 Seconds down to your name I can type in a name hit enter we display hello the name and then the program exits processed finished with exit Code Zero if we were creating some sort of timer we could do the following to make this simple we could use a for Loop the for Loop is going to cycle five times we will have an index of I in I equals 1 that's where we'll start we'll continue as long as I is less than or equal to 5 and then increment I by One during each cycle of the for Loop to mimic waiting for one second you can access the thread class call the Sleep Method pass in 1,000 milliseconds when you use thread that refers to the current thread that we're working with in this case the main thread which is what our main program runs on but since our thread might be interrupted we do need a try and catch block because this is considered dangerous code we will try this code where we will have our main Java thread sleep for 1,000 milliseconds and we will catch the following exception an interrupted exception So within our catch block we will catch any interrupted exceptions which we will name e if our thread is interrupted we will say thread was interrupted in our imaginary timer we'll need an exit condition let's say if our index of I is equal to 5 that means times up so we'll output times up I'm going to show you why this won't work the way that we think we have 5 Seconds to enter our name but there's no prompt or anything then we get the message times up and only after that Loop is complete are we allowed to enter our name and then we can type in our name we get the output of hello our name and then the program exits so the problem that we're running into is that all of this code is running on our main thread we have 5 Seconds to enter our name but we can't reach that code until the 5 seconds are up because our main thread is waiting for this Loop to finish so what we could do is create a separate thread where we're counting to five and our main thread is going to be in charge of accepting our user input so here's how to create another thread we're going to extend the runable interface to create a runnable object let's go to file new Java class this will be a class we'll name this class my runnable or something unique that's relevant to what you're creating my runnable is going to implements because we're working with interfaces the runnable interface if you implement an interface it's kind of like you're signing a contract we have to override any required method me we need to override the run method we need the at override annotation then we will override the run method public void run within this run method we're going to add any code we want to run in the background on a separate thread going back to our main Java file we're going to cut this Loop and then paste it within the run method when we call this run method we'll have this countdown timer run running in the background on a separate thread any code you want to run on a separate thread place within the run method all right going back to our main Java file we'll tell the user they have 5 Seconds to enter their name we have our class of my runnable we will create a my runnable object or whatever it is that you named to this class let's say my runnable will be the name of the object equals new my runable we will take this runnable object pass it into the Constructor of the thread class here's where we're going to create a new thread thread thread equals new thread pass in your runnable object as an argument to the thread Constructor now we just need our thread to start you'll take your thread call the start method and this should work let's try it you have 5 Seconds to enter your name and we get that prompt of enter your name but I'm not going to type in anything we get the message times up because we ran out of time let's try it again I'll type in my name this time there we go we get our output hello bro then we get the message time is up both these threads are running at the same time the code within our run method is running on a separate thread it's running in the background while our main program is running running so that's why threads are useful so let me extend this time let's say 10 seconds if I is equal to 10 just to give us some more time you have 10 seconds to enter your name now check this out you have 10 seconds to to your name I'll type in my name immediately we get the output hello whatever your name is but the program is still running because that second thread is still running in the background our program doesn't exit until all threads are done if your main thread is done you can end all other threads but you'll want to set those threads to be what is known as Damon threads a Damon thread will end when the main thread is over we will take our thread call the set Damon method pass and true this thread is going to end as soon as our main thread is finished let's try it again you have 10 seconds then to your name I'll type in my name we get our output and then our program exits without saying time is up processed finished with exit code zero that's because we set our second thread to be a Damon thread it ends when the main thread is over now on the other 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 and I can still type it in hello bro process finished with exit Code Zero optionally what you could do to get your program to exit go to your runnable class wherever you would like your program to exit when seconds equals 10 that's where I would like to exit to exit the program prematurely I can access system called the exit method pass in an exit code of zero that will ENT the program all right let's try this again you have 10 seconds to end to your 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 way that we've set up this program is that we want this program to exit either when we finish typing in our name or we run out of time all right everybody so that is an introduction to in it allows a program to run multiple tasks simultaneously it helps to improve performance with timeconsuming operations it's useful with file input and output operations network communications or any other background tasks and well everybody that is an introduction to threading in Java yo we finally made it to multi-threading in Java multi-threading enables a program to run multiple threads concurrently at the same time as we've talked about in the previous lesson a thread is a set of instructions and they run independently from other threads multi-threading is useful for background tasks or other timeconsuming operations in the prior lesson we've learned that there's two ways to create threads we can either extend the thread class or implement the runable interface the second option is better in most cases because we're not limited by single inheritance here's how we can get started multi-threading we're going to create a new class file new Java class we'll call this class my runnable my runnable will implements the runnable interface if we're implementing an interface it's kind of like we're signing a contract we have to override any required methods we have to override the run method public void run whatever is within the run method this is the code that's going to perform when this thread is up and running so what would we like to do just for a beginner's example let's count to five using a four Loop we'll write a for Loop we will create an index of I I'll set that equal to be one right away we'll continue as long as I is less than or equal to 5 cuz we're counting to five then increment I by 1 during each cycle this for loop I would like this thread to wait for 1 second before printing whatever I is what whatever the current count is if we're counting we will access the thread class called The Sleep Method pass in 1,000 milliseconds to sleep for a second we will need to surround this method with try and catch blocks we'll catch any interrupted exceptions but let's output the following we'll say thread was interrupted after our thread sleeps for 1 second let's display the current count I'll just say I just to keep it simple let's go back to our main Java file we'll need to create a runable object my 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 thread thread equals new thread we will pass in our runable object to get this thread to start we have to call the start method of our thread thread. start method and this should work we'll test it 1 2 3 4 5 and then we exit the program another shortcut you can do too instead of creating a named runable object we can pass in an anonymous renable object to the thread Constructor so let's copy this section delete this line of code and then pass in a new runable 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 as thread one copy this line of code paste it rename the second thread as thread two thread 1. start and thread 2. start 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 multi-threaded you could differentiate these by getting their name here's an example to get each thread's name we're going to access the thread class called the current thread method and then method chain the get name method then I'll add a space plus our counter RI just so we can see each thread by its name and what it's counting exactly okay let's try this again we have thread one and thread zero now they won't always be in the same order they're running independently thread zero that's 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 say pong like we're playing a game of pingpong we'll modify the my runnable class we'll need some text a text variable we'll say private final we don't want it to change string text then we'll need a Constructor to assign it my runnable we have one parameter a string of text we will assign this. text equals the text we receive instead of printing our counter we'll print our text all right and that's all we need going back to our main Java file we have to pass in some text when we construct a runable object for the first thread we'll we'll say ping for the second thread we'll say pong so here's what we have currently pong ping and then we exit the program before we start the threads 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 over game over here's what happens game start game over and our two threads are still running then we finish so the problem here is that in our main thread it doesn't Wait For Thread one and thread two to finish our main thread ends immediately we can have our main thread wait for these threads to finish by calling the join method of each thread our main thread we'll wait for these two threads to finish after these two threads start 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 interrupted we'll output main thread was interrupted okay this should work now before we display game over we're going to wait for our two threads to finish here's what we got game start and we display pingpong and we'll do that five times and then display game over all right everybody that is an introduction to multi-threading it enables a program to run multiple threads concurrently a thread is a set of instructions that run independently multi-threading is useful for background tasks or other timeconsuming operations and well everybody that is an introduction to multi-threading in Java hey everybody in this video we're going to create a working alarm clock that plays music using Java all right let's get started everybody this alarm clock is going to to serve as a final project for us will combine a lot of Concepts that we've learned throughout the series when starting a new project a good first step is to declare all your variables or other objects that you'll need throughout this program we'll begin with the scanner because we'll be accepting user input a user is going to enter in a Time scanner scanner equals new scanner pass in system.in and we'll be importing classes as we go along at the end of this program we're going to close our scan but we'll actually move it later on because our alarm clock class is actually going to be using it more on that later we have our scanner and currently we're closing it a user is going to use the scanner and enter in hours minutes and seconds to set the alarm when the user types in a string representation of a time we need to parse it into a local time object but we'll need a formatter object we will create a date time formatter object you'll need to import this class too we'll name this object formatter equals we will access the class of datetime formatter called the of pattern method within this method we have to pass in a pattern a pattern that represents the time for hours minutes and seconds within a string we will pass in two Capital H's for hours colon two lowercase M for minutes colon two lowercase s's for seconds when a user types in a string representation of a time using our scanner we'll use this formatter object when we parse it into a Time object then we will create a local time object which we will name alarm time we'll instantiate that later import this class now we'll need a user to enter in the time we'll create a prompt enter n alarm time we'll give them a prompt for this format hours minutes 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 equals use our scanner call the next next line method to get a line of text from the user all right now here's where we're going to parse our string our input time and assign it to our alarm time object so we have to convert it we have to parse it we will assign our alarm time object set it equal to access the class of local time and there is a parse method we have to pass in two arguments the first is a string representation of our time and our format object that we have previously declared and instantiated then we'll output the following message alarm set 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 alarm set for 7:30 what if we type in a time that doesn't make sense uh like the word Pizza well we encounter an exception a date time parse exception we can use exception handling to catch this exception I'm just going to copy it and then paste it later this portion is considered dangerous code we can put that within a try block try this dangerous code catch and any of the following exceptions we will catch that date time parse exception which we will name e import this class okay then take all of this previous code stick it within our Tri block we will try this code and catch this exception if it pops up we'll output the following let's say invalid format please use hours minutes seconds let me change that to use I've already used Pizza let's go with Taco for the alarm time invalid format please use hours minutes seconds let's try 8:00 alarm set for 8:00 all right good we know that that works why don't we prompt the user to enter in the time again if it is an invalid format we can use a while loop while some condition is true continue to do the following let's cut our code our trying catch blocks stick it within the while loop what's our condition while our alarm time is empty there's actually a value that you can assign an object and that is null null has no value within our while loop we'll continue 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 minute seconds and it won't let me continue until I enter in a valid time so I will set this to be 9:00 and then our alarm is set for 9:00 the first section of this project is complete we have successfully set an alarm time our alarm time is a local time object the next part is to create an alarm clock class to create alarm clock objects we're going to create an 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 that we can implement the runnable interface so we can do some threading but if we implement the runable interface it's kind of like we're signing a contract we have to override the run method public void run when this alarm clock is running on a separate thread it's going to execute any code within the run method but we're going to fill that in later currently our alarm clock needs one thing it needs an alarm time which we will send it from the main Java file let's set that up as a field with our alarm time I'm going to make it private I only want the alarm clock class to be able to change it I will also make it final it's unchangeable the data type it's an object it's a local time object which we will name alarm time and then we do need to import this class too all right then we need a Constructor we will take our alarm clock we need one parameter currently a local time of alarm time we will assign this do alarm time equals the alarm time that we receive all right that's good okay let's go back to our main Java file before we close our scanner we're going to create an alarm clock object alarm clock is the class we will name this object alarm clock equals new alarm clock but the way that we set up this class is that we have to pass in an alarm time a local time object we have our alarm time we've already verified it using this while loop it should be a valid format we will pass in our local time of alarm time to the alarm clock in order to construct it since our alarm clock is going to be running on a separate thread we'll have to create a new thread thread let's name this alarm thread equals a new thread and then we'll pass in our alarm clock we can do this because our alarm clock it implements the runnable interface so our alarm clock is going to run on a different thread than the main thread to start a thread you will take your thread in this case alarm thread called the start method so once we start our alarm thread it's going to execute the run method all right so for testing purposes let's get the time right now to get the time right now we will create a local time object let's just call it now what's the time right now equals access the class of local time called the now method I will display the time right now just for 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 a.m. alarm is set and here's the current time right now at least for me I'm filming this video at 7:26 in the morning it is going to be in military time and then we have a bunch of 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 now before our alarm time if it is we'll continue sleeping we'll have our thread sleep we can delete this print statement I was just testing it we need to check if the time right now is before the alarm time if it is we'll continue waiting we can do this with the while loop take our time right now call the is before method we can compare local times is the time right now before our alarm time if it is we're going to sleep for 1 second access the thread class sleep for 1,000 milliseconds all right we do need to surround this with a TR and catch block let's do that try and sleep for 1,000 milliseconds if this thread is interrupted we'll output the following thread was interrupted this is if we encounter an interrupted exception we're checking the time right now is it before our alarm time if it is let's output the time currently I'm going to condense some of this code outside of our while loop we're already 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 method chain the is before method basically every second we're going to get the time right now and compare it to our alarm time is the time right now before our alarm time if this while loop is running we'll output the time so we'll output 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 simple alarm set for 8 a.m. and here's the current time it updates every 1 second approximately every 1 second now let's do some formatting 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 to access the class of local time called the now method then method chain the get hour method to return the number of hours then we're going to do this with minutes int minutes get minute int second seconds get 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 pretty good but I would like some leading zeros we could do that with print F so let's switch this around print f for print F We'll add some placeholders which we can use with a percent sign to display two leading zeros we can use 02 if we're going to insert an integer we have to use D for decimal so let's do this three times 02 D percent 02 D we are inserting hours minutes and seconds let's try it 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 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 one digit that looks pretty good now what we'll do rather than updating the time and placing it on a new line every 1,000 milliseconds we're going to edit it in place here's how with our print F statement we're going to insert back SLR this is for carriage return it'll move the cursor back to the beginning and then we'll get rid of the new line 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 time it updates I think this looks a lot better all right so we're going to condense some of these steps instead of accessing the local time class three separate times let's just do it once we'll create a local time object named now 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 local time now. getet hour for minutes now doget minute and seconds now. getet second and then we'll insert them using our printf statement or even instead of assigning variables we could just call now doget hour now. get minute and now. getet second and we can delete these variables cuz we don't need them just for readability I'll place these on a new line and I'm just going to line them up all right this should work too let's make sure yes it does you can keep this code the way it was before but I like it a little more concise all right our while loop is done so once we escape the while loop that means the local time is our alarm time or past our alarm time so for testing purposes let's output the 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 currently in this case 7:44 but pick a different time depending on what time it 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 we display alarm noises and then exit the program I'm going to add a new line character just before we display alarm noises for our alarm we'll be playing some music later just for now we're going to play a single beep just to be sure that everything is working basically to have Java make a beep noise you can do the following access the class of tool kit call the get default toolkit method call the beep method and then we do need to import this class once we escape the wild Loop we will display alarm noises and make a beep sound a single beep I will set my alarm to be 747 I'll have to come back in one minute there we go we display our text of alarm noises and hopefully you heard that beep so we know that our alarm arm clock is working to make a more sophisticated version we're going to play an audio file I have an audio file here it's a wave file the following code isn't going to be compatible with MP3s if you do have an MP3 file you can always use an online MP3 to wave converter that's what I did to make this convenient for me I'm going to place this wave file within my project folder here's my wave file going back to our main Java file I will create a string variable a file path string file path equals here I can list a relative file path or an absolute file path this wave file is within my project folder I just need to list the file name so I'm going to copy path file name and paste it within that string with our alarm clock we're going to send it our file path we'll send it as the second argument along with 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 path then we'll have to set up the parameters we are also accepting a string of file path the location to that file to play the audio this. file file path equals the file path that we receive with playing audio there's a lot of code we have to write I'll dedicate an entire method just to playing audio let's make this a private method so only our alarm clock can access it it's not going to return anything the return type is void let's name this method play sound once we reach the end we will call the play sound method but we're going to pass in our file path so we need a parameter setup of string file path and now we are within the play sound method to play a w file we're going to create a file object named audio file equals a new file and then pass in our file path import this class we'll be doing a lot of importing as we go along then we need to create an audio input stream audio input stream we'll name this audio stream equals access the class of audio system called the get audio input stream method yes that's a lot to 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 that we'll need to catch such as if our audio file is unsupported like it's an MP3 file we'll need some try and catch blocks try this code catch any exceptions here's one we'll start with we will catch any un supported audio file exceptions which we will name e import this class if we encounter this exception we'll output the following audio file format is not supported if the audio is unavailable for some reason let's say another resource is accessing it we can catch that too that exception is a line unavailable exception line unavailable exception of e let's say something like audio is unavailable import the class then as a safety net we will catch any IO exceptions input output exceptions IO exception e here we'll just say error reading audio file it is good to catch specific kinds of exceptions first which we are doing this just acts as a safety net so with modern Java you can try with resources you'll automatically close those resources when you're done with them when we create our audio input stream let's cut all this code and paste it within the triy with resources block then delete that semicolon so we have our audio stream we need to create a clip object a clip acts as a player that plays an audio stream within the tri block we will create a clip object clip clip equals access the class of audio system system called the get clip method 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 clip.art method one issue we're probably going to run into is that once we we start playing the clip the program is going to end immediately so we might not even hear it so temporarily I'm just going to sleep for a couple seconds let's just sleep for 5 seconds and then I do need to add a catch clause for any interrupted exceptions we'll be deleting this don't worry I just want to be sure that it works I'm going to set it for 802 I got about 40 seconds [Music] we played our music for 5 seconds and then we exit the program what I would like to do instead is that we stop the alarm if we hit enter here's how we can set that up we can delete this method where we sleep for 5 seconds instead we'll wait for a user to hit enter and delete that catch statement too we're going to be using a scanner within a big project different parts of your project may require different scanners but I like to just reuse the same one the problem with having multiple scanners is if they use system.in and one scanner closes it it's going to close system.in for all of them so rather than close the scanner at the end of our main Java file we're going to do that within the alarm clock class when everything is all done so we'll do that at the end of the tri block however our alarm clock class has no idea what the scanner is we're going to send it as an argument to the alarm clock class so we'll need to set that up 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 object which we will name scanner import this class set up the parameters we will receive a scanner object that we can use throughout the alarm clock class this do scanner equals the scanner that we receive all right and now we have access to that same scanner the same one that we have instantiated at the beginning of our program and remember we are not closing it at the end of the main Java file anymore once our alarm is playing we will wait for some user input let's create a prompt we'll say press enter to stop the alarm I'm going to use print we will use our scanner called the next line method our music is going to continue playing until we hit enter once the user hits enter we we are going to take our clip and call the stop method then close the scanner when we're done with it and that should be everything let's run this one last time I will set my alarm to be 807 [Music] to get our alarm to stop we just have to press [Music] enter and the alarm stops and we exit the program all right everybody that is a working alarm clock that you can write using Java