you're about to learn how to program in Java from Farhan hassin children Farhan is an experienced software developer here at free code camp and he is great at breaking down concepts for beginners this is a great course if you want to learn Java and you can follow along with the whole course from within your web browser Farhan will teach you the basics of java using replit replit is an online IDE that allows people to write all sorts of programming languages right within their web browser and repl provided a grant that made this course possible so it's time to learn Java hello everyone welcome to the Java for beginners course I am Farhan Hassan chodri and in this course I will teach you all the fundamental concepts around Java now ideally a programming course usually starts by downloading and installing a lot of sdks or Ides or whatnot but since we will be using rapidly throughout the entire course we don't need to do any of those replete is an online collaborative IDE that you can use right from your browser to start go to www.reply.com and you should land on the page you can create an account on replete or if you already have an account just go ahead and log into that I will just use my Google account to log in once you have logged in you will land on your home page from here you can create a new Ripple by using this create button now from the list of language we will pick Java but just so that you know refleet supports a long list of languages make sure you are giving your new Rebels some descriptive names such as hello world finally hit the create triple button and wait until the process finishes now if you have worked with some other code editors such as Visual Studio code the look of replete should not be very different to you you can change its default layout by going to settings and default layout by default it should be side by side but you can also pick stacked if you like that layout Now the default Java Ripple usually comes with a bunch of code and you may have already guessed that this is the famous hello world program written in Jaffa to run this code click on this run button here and you will see the code's output on the console there you go congratulations on creating and running your first Rebel on the next lesson I will explain what's going on just before we leave remember you can always run replay dark by clicking on this Moon icon and if you prefer dark themes over the lighter ones please go ahead the hello world program is probably the simplest executable Java program that you can write yet it's very important that you understand each part of this program as you may have already guessed source files in Java end with the dot Java extension and compiled byte codes usually end with the dot class extension to see the compiled byte codes on replay click on these three dots on the files menu and click on show hidden files the program starts with a class declaration a class is a collection of related code in Java in every Java source file that is the file with the dot Java extension you can have one top level public class and that class has to match the name of the source file this is because if you have multiple classes in your program like this you will see that the Java compiler produces individual byte cores for each class to avoid any confusion about which of these classes is the entry point to the program the jvm is designed to treat the bytecode that matches the name of the source file as the entry point inside the class there is a main method those of you familiar with C C plus plus or go may already know that the main method or function serves as the NG point to your program the jvm is programmed in a way that it will specifically look for a static method that is named main has Public Access takes an array of string as a parameter and doesn't return any value so you will have to write your main method as public static void main string arcs and nothing else one thing that you can change however is the name of the args array to something like arguments the array holds the command line arguments passed to the program upon execution the system.out.print element method prints out whatever string you pass to it as an argument unlike python or JavaScript semicolons are mandatory in Java so if you leave it out the program will fail to compile that's pretty much it about the hello world program don't worry if you didn't understand all the terms used in this lesson you will have a much better idea about topics like public and private access modifiers Statics classes methods in later lessons now if you try to run the program using the Run button everything works out just as expected another thing that you can change is the entry point this will make sure that replit opens the correct Java source file whenever you decide to return to this project now there are a lot of other options in this dot replete file but those are not important right now the hello world program you have been seeing so far is pretty simple if you want to write more complex programs you will at least need some understanding of the different types of data and variables variable is any entity that can take on different values for example if you want to store your age inside a variable you can do so like this first you will have to write the type of the variable age is an integer or int then you will have to write the name of the variable which is age in this case then you can finish off by putting a semicolon you just declared a variable declaring means the compiler will know that this variable exists however you will also need to Define it you can do so by assigning a value to this variable like this write the name of the variable then an equal sign followed by your desired value in this case the equal sign is known as an assignment operator we'll learn about operator in lot more detail in lateral lessons now you can print out the variable to the console like this and just in case you are wondering using a plus sign is one of the many ways to print out a dynamic value in between sentences keep in mind you cannot use an uninitialized variable in Java so if you remove this line and try to run the code the code will fail with the error message variable age might not have been initialized instead of declaring and initializing the variable in different lines you can do it in one go like this on the line of Declaration after the name of the variable put an assignment operator followed by your desired value now if you try to run the code again see everything's back to normal you can change the value of a variable as many times as you want so if you set the value of the age variable to 28 instead of 27 just before printing it out you will see that the value has changed in the output although you can assign new values to the variable multiple times you cannot declare the same variable twice so if you do something like this and try to run the code the code will fail with the error message variable age is already defined in method Main if you look closely you will see two different sets of curly braces in this code the first set marks the start and end of the hello world class the second set is inside the class and marks the start and end of the main method code inside a set of curly braces is known as a code block since the main method is inside the hello world class any variable you declare inside the method will be only available inside the method these are local variables however you can also declare variables outside the method like here in the hello world class code block if you do that the variable will be available within the entire class to use this variable inside the main method you will have to declare it as a static we will discuss the reason behind this in a later lesson for now just remember that is static method can only work with static variables moving out the Declaration of the age variable and marking it as a static has not made any difference whatsoever but if you remove the value of the variable and attempt to rerun the program you will see the program runs without any issues this time and prints out 0 as the value of age this is because whenever you declare a variable in the class level the Java compiler will assign a default value to it for numbers it's always zero now another thing that I'd like to show you is if you redeclare the age variable inside the main method now there will be no problem whatsoever because the initial Declaration of the age variable is not local to the main method so as long as you do not re-declare a variable within the same code block you will be good to go when it comes to naming your variables you can name them anything as long as the names don't start with a number and don't have any spaces in them there are also around 50 words reserved by Java itself as keywords and you cannot use any of them either you can start a variable name with a dollar sign or an underscore but excessive usage of these signs can make your code unreadable in case of multi-word names always follow camel casing when naming your variables if you want to learn about different programming naming conventions I leave the link to this article in the description finally avoid naming your variables using single letters now that you know about variables we will discuss the different types of data keep in mind I have reorganized the source file to better reflect what I will be talking about at a high level there are two types of data in Java there are the Primitive types and the non-primitive or reference types primitive types store values for example int is a primitive type and it stores an integer value a reference type on the other hand stores the reference to a memory location where a dynamic object is being stored we will discuss reference types later there are eight primitive data types in Java six out of those eight types deals with different types of numbers first there are the bytes these are small numbers within the range of -128 to 127. then there are the shorts with a much larger range than bytes and the integers with an even larger range if you ever need to store a value so large that it doesn't fit in an INT you can use the long type by default any number with no decimal point is treated as an integer by the compiler to let the compiler know that a number is actually a long you have to append the letter L at the end of the number you can also use a small l in instead of the capital L if you want for numbers with decimal points in them there are double and Float types doubles are double Precision 64-bit floating Point numbers with a very long range floats on the other hand are single position 32-bit floating Point numbers with a smaller range by default any number with a decimal point is treated as a double by the compiler to let the compiler know that a number is actually a float you have to append the letter if at the end of the number like the lungs you can use a small If instead of the Capital One here Boolean data type can have only two values true or false at the moment usage of a data type that can only hold true or false as values may not seem that useful to you but once you learn about conditional statements you will see their usefulness finally the character type can hold any valid Unicode character the Unicode is kept sequence for the copyright symbol is backslash u00 A9 so if you store this value in a car variable and print it out on the console like this we have you will see that the copyright symbol has been printed on the console instead of the value we have saved of course you can also save any standard character from your keyboard instead of this kind of Unicode subsequences for example if we remove the name Copyright symbol and change it to something like percent symbol and replace these Unicode Escape character with the percent sign and update our code accordingly you will see the percentage symbol printed out on Console instead of the copyright symbol there you go now for the most part when working with integers the in-type should suffice and for numbers with decimal points the double type should suffice but you should also know about the other types although you cannot store one type of data inside another type of variable conversion between the different types is absolutely possible type conversion in Java can be either implicit or explicit when the compiler converts a smaller type of data for example an integer to a larger one like a double automatically it's known as an implicit or narrowing type conversion let's see an example first get rid of all the old code in our project then Begin by declaring a new integer you can call call it anything then declare a double and for the value of the double type assign number one like this is essentially doing is first taking an integer with a value of Phi and then taking a double and assigning number one as its value let's try to print it out using the standard system.out.print Ln function number two and run so as you can see the compiler has successfully converted the integer to a double this is because a w is larger than an integer but what will happen if you try to do the reverse let's try out this time start with a double 5.8 Maybe then an INT okay I missed the two here now system.out.print Ln number two and drop so as you can see the program immediately fails saying incompatible types possible lossy conversion from double to in what the compiler is saying that an integer to double con conversion is not possible automatically although conversion from an in to a double is not possible automatically you can still do it explicitly by letting the compiler know that you want this to happen the cast operator can be of help here first inside a set of parentheses right end this will tell the compiler that you want to convert this double to an it let's try to run the program once again and this time the program works without any issues but you have lost the point eight part after 5. if you are doing explicit type conversion in Java be extremely careful whether the type you are converting to will be able to hold the entire value or not in this case I knew that an integer will never be able to hold the entire 5.8 value and I will lose the second part but I went with it anyway so as long as you know what you are doing you should be all right but at any given moment if you perform an explicit conversion and lose a bit of data accidentally the results can be catastrophic now that you know about variables and the different types of data you can work with in Java you will have to learn about operators keep in mind I have made some changes to our code to better explain our topic in hand and since our code has become much longer than before I suggest that you go to settings and change the default layout from stacked to side by side and then hit the reset layout button to apply the new layout this will give you a lot of vertical space and make the code easier to read operators in Java or programming in general are certain symbols that tell the compiler to perform certain operations such as arithmetic relational or logical operations although there are six types of operators in Java I will only discuss four bitwise operator are a little bit more complex than the other ones and I don't think they fit well in a beginner's course like this we will begin our discussion with arithmetic operators arithmetic operators are the ones that you can use to perform arithmetic operations such as addition subtraction multiplication or division or so on there are five arithmetic operators in Java and these are the addition operator the subtraction operator the multiplication operator the division operator and the remainder operator the remainder operator is also known as modulo or modulus operator addition subtraction multiplication and division these four are pretty self-explanatory you can have a look at our code example here and you should be able to understand what they do and how they do it if you have used a calculator in real life the arithmetic operators in programming work similarly in our code we have two integer numbers number one and number two with the values 12 and 6 respectively so if you add number one and number two together the result will be 18. if you subtract number two from number one the result will be six if you multiply number one with number two the result will be 72 and finally if you divide number one by number two the result will be two we will talk about the remainder or modulo operator later the addition and multiplication operations in this code are pretty simple but the subtraction and division operation needs some more discussion so we'll get rid of our addition and multiplication code here we'll comment out the division code and the remainder code and focus solely on the subtraction part as you can see the value of number one is 12 and number two is six which means the number one is greater than number two as a result the result of the subtraction operator comes out as positive but if we change the order of the operation here so if we make number two the first operand and number one the second operand you will see that the result of the operation changes from 6 to -6 again if you have used calculator cngl live before you should already be aware of this situation now the division operation since dividing 12 by 6 yields the result 2 this operation is perfectly fine but if we change 6 with something like maybe five then the result will not be a whole number as you can see according to this program the result will be 2 but if we perform the same operation in a calculator or by hand we will know that the result of this operation should have been 2.4 now this happens because if you divide an integer with another integer the result will always be an integer so let's try by changing this integer type to a double for both operands and run the program once again as you can see this time the result is 2.4 but what happens if we divide a double by an integer again the result is 2.4 and if we change the first operand to an end and the second to a double the result will still be 2.4 which means if you divide an integer by another integer the result will always be an integer but if you divide a double or float by an integer or divide an integer by a double or float the result will always be another double now let's get rid of our division code as well and focus solely on the remainder or the modulus operation now for this example I would like to go back to our original verus which are 12 and 6 in the beginning and I'd like to go back to integer let's run the program and see what is the output compiling a program may take some time but we just need to be patient here so as you can see the result of this operation is zero first we need to understand what is a remainder now you may or may not already know that a reminder is the value that remains after you have divided a number with another one so if you divide 12 by 6 the result will be 2 and there will be nothing left you can always divide a 12 into two sixes but if I change 6 to something like maybe um eight and run the program once again as you can see the value has changed from 0 to 4 this is because if you try to divide 12 by 8 there will always be 4 left I hope you got the idea you have already seen examples of the assignment operators in previous lessons it's pretty simple you can use the equal sign to assign a value to any variable in your code but you can also combine the assignment operator with the five arithmetic operators you just learned about for example here we have a integer with a value of 12. now if I tell you that you will have to add 5 with this value and Save in the same variable you can do that like this [Music] now the output of number should be 17 instead of 12. very simple but instead of doing this in such a verbose manner you can do it far more easily let's just remove the second part here and instead of using the assignment operator use a plus sign then the assignment operator and then five this small line of code is actually equivalent to number equals number plus pi let's comment this out and see if this gives the same result as before or not okay yeah 70. so you can use all the five arithmetic operators similarly say for example if you want to take out 6 from 12 you can do so by saying number minus equals 6. and this will turn the value of number from 12 to 6. there you can also do modulus operation like this like if you say modulus equals and then 2 the result of this operation is 0 because when you divide 12 by 2 there will be 2 6s as a result and nothing left I hope you got the idea of using assignment operator with all the five arithmetic operators and I would suggest that you try out usage of the other ones like the multiplication sign and the division sign with the assignment Operator by yourself and see how the result varies from time to time so far in this course you have learned about the arithmetic operators and the assignment operators the arithmetic operators usually lets you perform different types of arithmetic operations on your numbers and the assignment operator usually lets you assign different kinds of value to variables relational operators on the other hand usually check the relation among multiple operands by relation what I mean is for example in this code we have two integer numbers number one and number two with the values 12 and 15 respectively now you may want to know whether number one or number two is equal to each other or maybe number one is greater than number two or maybe number one is less than number two or not these are the relation between these two numbers so in Java there are six types of relational operators the first one is the equality operator now keep in mind each relational operator in Java or in other programming languages as well usually returns true or false as a result of an operation for example on line 7 I have written system.out.printellent number one equals equals number two the usage of this double equal sign here is the equality operator now if I run the code since the value of number 1 and number 2 is not equal the output will be false which is correct in this case now you may also want to check whether number one is different from number two or not for that you can use the not equal to operator instead of putting two equal signs side by side you will have to put an exclamation sign followed by an equal sign now if I run the code again you will see that the second operation gives us a true because indeed number one is not equal to number two then you can also use the greater than operator to check whether number one is greater than number two or not since 12 is smaller than 15 the output of this line will be false there you go there is also the opposite of the greater than operator which is the less than operator and this operation in this case will give us true because number one is actually smaller than number two finally there are the greater than or equal operators and the less than or equal operator now the greater than or equal operator will give us true only if number one is greater than number 2 or equal to number two the less than or equal to operator on the other hand will give us true only and only if number one is less than number two or equals to number two since number one is actually less than number two the greater than or equal operation will give us false and the less than or equal operation will give us the result true now the usage of these relational operators may not seem uh that much fun to you at the moment but once you start working with things like relational statements you will start to understand how important these operators are The Logical operators in Java or in programming in general lets you make logical decision based on multiple conditions for example imagine you are writing a program that can only be used by people within the age limit of 18 years old to 40 years old here we have an integer number with a value of 25. now we will have to make two checks first we will have to check whether age is greater than or equal to 18 or not and then we will have to check whether age is less than or equal to 40 or not so you have already learned about the greater than or equal and less than or equal operators in the previous lesson here I will teach you how you can combine these two operators using a logical and operator to make a connected decision okay so let's write system dot out dot print Ln because we want to print out the result of our operation here and start with the graded then or equal operation age is greater than or equal 18 then you will have to put double M person sign and this is the logical and operator in Java and then age is less than or equal to 40. let's run the code and see what the output is as you can see the output is true here let me explain the logical and operator in Java or in other programming languages as well works in this way if the left side of the logical and operator and the right side of the logical and operator yields true as a result then the whole operation will give the result true here the value of age is 25 which is larger than 18 which means the left side is true and it's also less than 40 which means the right side is also true that's why the result of this end operation will be true but if you change this value to maybe something like 45 which is clearly over 40 years old and run the program once again you will see that the output becomes false because although the left side is true the right side is not so in case of a logical and operator both side of the operator has to be true I apart from The Logical and operator there is also a logical or operator okay let's imagine another scenario maybe you are writing a program for your school's library and to be able to borrow books from the library a person either has to be a student of your school or a member of the library so we can have two booleans here is a student which is false maybe this person is not a student of your school and is the library member is equals true maybe he is a member of your library [Music] now to check whether this person is a student or is a library member you can use the logical or operator like this system dot out Dot println and first we will check if this is a student or not student or unlike the logical and operator you have to use two pipe characters to express the logical or operator and then we will check is Library member I hope you remember that in order for the operation to be true in case of a logical and operation both sides of the operator had to be true but in case of the or operation if either side of the operator is true the entire operation will be true so as you can see although easy student is false given is Library member is true the operation gives us the result true so if if you turn both of these booleans to true the result will still be true and the only case when you will get a false result is if both of these booleans are false yes false and finally there is another type of logical operator in Java which is the not operator the not operator in programming usually reverses a Boolean value for example here the value of the easy student Boolean is clearly false right if if you run the program it will surely print out false but if we put a not operator in front of this this this exclamation sign is actually the not operator and run the program you will see that it it turns out as true so instead of using the not operator over a single Boolean value you can actually reverse the value of an entire and or or a person in Java like this let's go back a few steps and I I hope you remember that in this case we got the result false because both of these booleans are false now if you put a not operator in front of the Esky student Boolean this will be turned to true so now if I run the program the result of the entire operation will be true yes there you go the different types of operators that you have learned about so far easily work with multiple operands at a time except the not operator it usually works on a single value or variable at a time now these kind of operators that usually work with a single operand is usually called unary operators apart from the not operator there are also two more operators that are unary in nature and very commonly used in programming these are the increment operator and decrement operators assume that you are trying to make a game where you have to store the score of the player and the number of turns left now you can store these values in two different integer numbers maybe named score and turns now whenever you have to increase the value of score by 1 you can do so by saying score plus equals one you have already learned about the usage of the arithmetic operators along with the assignment operator in previous lessons well this is one way to do this using this method you can actually add any number pre-score but since here in this code you will only increase the score by one well you may think that what kind of gain that is that gives you one in every term well that's just for the example okay just very good you can do it like plus plus so putting two double plus signs after an integer or maybe float or double or any number kind out there will increase its value by one similarly you can put 2 minus signs to decrease or decrement the value of a number time now if we print out the values of these two variable with system dot out Dot println score and we will just make a copy of this line and change it to terms you will see that the value of score is now 1 and the value of turns is now 9. so this is pretty simple incrementing and decrementing values there is nothing fancy until I I make it a bit complex let me show you something let's get rid of all this code and declare a new integer it's called number and maybe its value is 55. now if I say system dot out dot print Ln a number plus plus you may think that this will print out 56 because you know the EU increment 55 by 1 and it becomes 56 well let's see if if that's true or not hmm seems like that the value has not incremented at all okay let's make a copy of this line foreign and run the program again this time the value has changed but at line 5 where you have used the plus plus or the increment operator the value remained unchanged but on line 6 while you have haven't used any uh operator at all the value seems to be incremented or you see when the compiler reads your code it usually goes from left to right so when it comes to system.out.println and sees the number variable here it immediately prints out its value so at that point the value of number will be 55. then it sees that there is an increment operator here and it goes like Oh that means I have to increase the value by 1 as well then the compiler increases the value of number 256 and keeps that in memory so if you ever print out the value of number later on it will actually print out 56. now this is same for the minus minus sign or the decrement operator initially the value will be 55 even though the value has changed in the memory and on the second pretty statement it prints out 54. so far I have showed you only one way of writing the increment or decrement operator instead of writing it at the end you can also put it in front like this and let's see what output we get in this case as you can see this time we are getting 56 because when the compiler reads your code from left to right it goes like system.out.printellin and it immediately encounters the increment operator and then it sees the number and goes like okay so I have to increase the value of number and then print it out so it prints out 56 on line 5 and on line 6 as well same goes for the decrement operator 54 and 54. so this is something that you should be aware of when using the increment or decrement operator inside other statements like in this case the println method call if you are just incrementing or decrementing the number outside of anything like this method called like this number plus plus then you shouldn't have any problem at all see so if you ever get like unexpected values after using the incremental decrement operator in your program just make sure that you are using it correctly or you are using it in the right place I hope that you remember in a previous lesson I have taught you about the character type it is one of the Primitive types in Java and you can store any Unicode character in it like in this example I have stored the percentage sign in a character variable called the percent sign and I have printed out the character on my console using the standard system.out.printlend method now the character type is good and everything but if you want to store multiple characters together for example your name or a sentence you cannot use a character for that for this type of scenarios we have string in Java there are multiple ways of declaring a new string let's see the literal way first so instead of car you will need to type a string with a capital s and then name of the string in this case name and then the value so this is my name you can put any string right here and then you can print it out like any other variable in Java let's run the code foreign to declare a string in Java is by using the new keywords the new keyword in Java can be used to create new objects from classes now we have not discussed classes at all in this course yet but we will get into classes and objects and object rendered programming later on for now just remember that the new keyword can be used to create a new object from a class Now to create a string using the new keyword you will have to write string then the name of the string equals new string and the value like if you run the program there should be no change whatsoever because essentially declaring the string this way or that way it doesn't make any uh visible changes to the program but there is a slight difference in in these two techniques now the jvm or the Java virtual machine usually uses a portion of your computer's memory to store strings now this little portion of memory is usually called the string pull now whenever you create a new string in the literal way Java will first check whether this string Farhan has injury already exists in the string pull or not if it does then the jvm will simply reuse that previously string with a new name but in case of the new keyword the gvm will create a new object regardless of whether this value already exists in the pool or not I think this can be demonstrated with an example very well for this I will create four strings first one string literal E string 1 equals to A B C and I'll create another literally string with the same value but different name there you go now I will create two object string I mean don't get me wrong these strings are actually same but I am just naming them as literally string and object D string to make clear that which is what now object string equals to new string maybe e f g or XYZ [Music] so I'll make a copy of this string change its name to object string 2 with the same value now if I compare these four strings with each other like this print Ln literal string one equals equals literal string two and I'll make a copy of this line and use object string instead of literal ones sorry let's make this wider so that the code becomes easier to read and now if you if we run the code as you can see when declaring a new string using the literal format since the value ABC was already present in the string pool that jvm actually reused the older value with literally shrink to but when using the new keyword even though the same value has been assigned to the two string variables they are not same you have already learned that the W equals sign checks for the two objects are same or not and in this case the literally strings are actually same since they are using the same value from the pool and the objective strings are different entities because they are not reusing the same values from the pool now depending on your Necessities you may go with either of these techniques but I'd suggest that you go with the literally string technique if there is no problem with that because this will not only make your code easier to read there is no new or there is no duplicate is string written in the code but also it will let the compiler optimize your code a little bit but the strings in Java are not primitive types these are object types and the strings are literally one of the most powerful types in Java you will use strings a lot throughout your entire programming carrier and there are a lot of methods that we can use with this Stream So now I will demonstrate a few of those essential method that you can use on strings and do fancy things with this depending on the type of software you are working on you may or may not have to work a lot with string formatting now let me explain this topic with an example first I would suggest that you go back to the Stacked layout from side by side because now our code will get a lot longer sideways and not vertically okay let's begin by removing everything and writing a single system Dot out dot print as an statement and in here we will write a pretty long sentence this time Chase hello world I am sorry I am from Bangladesh and I am 26 years old very simple program if we run it here so you're getting the entire line without any changes now we can take out a bunch of stuff from this line such as my name then uh my country name [Music] finally my age now to use these variables inside this string you can use the plus sign you you may have already seen example of using the plus sign to like slotting Dynamic variables inside the strings you can do the same here so I'll get rid of farhanasan Chaudhary and in the string here [Music] so now the first string starts here and ends here the second one is starts here and ends right here and in between the two strings I put my name next I can take out the country name as well so I will separate the strings put two plus signs and put country in here nice finally the AIDS same drill separate the string to plus signs and the variable name okay let's save the code cross our fingers and run it yeah as you can see the output is fine but I hope you are getting a sense of how complicated this string can get once you start adding more variable sites such as if I add my company name the company word for uh company girls let's say free code camp a really nice place to work at so I can change it to I work or and then plus plus company now you can put plus and a DOT yeah works just fine so the point I'm trying to get through is the fact that Azure string grows and you start to use more and more variables in it using the plus sign to concatenate strings or add them together becomes really clumsy there is a better way to do this and that's formatting your restraints so let's declare another string called formatted string equals then we will write is string Dot format so my name is modulus s I am from modulus is [Music] I am modulus T years old [Music] and I work or modulus s so once we have written this line we will say comma so my name is modulus s so this modulus is or modulus D these characters are called format specifier so when the Java compiler comes and reads your line like this my name is modulus is the compiler knows that there will be a certain string here and when it reads I am modulus D years old the compiler will know that there will be an integer number here but the compiler doesn't know yet what is string or what integer value will replace this format specifiers so once you have finished writing your string along with the format is specifiers you will have to put a comma and then put in the variables in the same order of the formatting specifiers for example we have my name is modulus s and we want to replace this part with a name variable so we will put name then we will put a comma and then I am from modulus s and we want to replace this format specifier with the country name so country comma then we have modulus D which we want to replace with the h finally we have one more modulus s that we want to replace with the company name that's full stop here there you go now we have a formatted string so instead of writing this a long string with plus signs and variable names and what not in it we can just write for method string let's run the code and as you can see it works out just fine so far you have seen the format specifiers or strings and integers there are also certain formative specifiers for floating Point numbers and booleans so the format is specifier for a floating Point number B it a float or a double in Java is modulus f so if I put in a double here like Maybe by GPA equals uh three point eight and this is not real and I can write my GPA is modulus F and we can replace this modulus if with the value of GPA foreign excellent finally the format is specifier for a character is modulus C and A Boolean is modulus B now I can't think of any fun example to demonstrate modulus B and modulus C but I'll just go with it okay maybe character percent sign equals to put the percent sign here and I can say I have attended 100 percent of my University classes excellent and after the GPA I can just use a comma and put percent sign here cool then let's put a Boolean as well Boolean m i telling the truth equals false now I'm not reading the truth I I haven't added 100 of my classes and my GPA is also not 3.8 so [Music] um am I telling the truth yeah right these are all modulus B planes and I can put a comma here and then am I telling the truths yeah that's a really horrible name to be honest let's run the program again excellent my name is Farhan Hassan Chaudhary I'm from Bangladesh I am 26 years old I work for free code Camp my GPS 3.8 I have attended 100 of my University classes these are all false claims so as you can see the string dot format method returns a formatted string by replacing all the specified format specifiers with your given values now instead of saving this formatted string in a separate variable like I have done here you can actually just copy the entire thing and paste it inside the println call although it works and you can do this if you want but I would not suggest doing this because there is something called the printf function that you will learn later on in this course that actually lets you uh use the formative specifiers right in the print function so for now I would suggest that you save your formatted string in a different variable and then print that out using println or use that however you see fit so remember the format is specifier for a string is modulus s for an integer number also for shorts and Longs is for modulus d for floating Point numbers both floats and doubles modulus f or characters modulus C and finally for booleans modulus B while working with strings in Java it's really common to check the length of a string or you may want to check whether a string is empty or not like a lot of things in Java doing these two tasks is really easy let's start with a single string okay so extreme name Farhan has seen I have to check the length of this string you can write first the name of the string which is name then Dot length the length is a method that remains inside every string that you create in Java now if you run the code as you can see the length of the string is 22 which means there are 22 characters in the entire name including the spaces in between okay now you can also check whether a string is empty or not to do so you can just write the name of the string which is name in this case and then Dot and is empty this is another method that returns either true or false if the string is not empty then it will return false and if it's empty then it will return true let's run the code and the output in this case should be false since the string actually contains some characters in it now if I get rid of the name inside the string and just put two quotation marks with nothing in between them and run the code again this time the string will be treated as an empty string and the output will be true now the length and is empty methods can be pretty useful in certain scenarios so I would suggest that you remember them and practice their usage as you go along you can also convert strings from lowercase to uppercase or uppercase to lowercase in Java to do so first you will need a string then to convert this string to uppercase you just need to write the name of this string which in this case is same then a DOT and two upper case this is a method and if you run this program you will see that the name has become uppercase however you may think that these two uppercase method has actually changed the original string which is not true so if we add another println here printing out the original name you will see foreign variable is actually unchanged you can also convert the name to lower guess by using the two lowercase method and this will convert the entire string to lowercase there you go in a previous lesson I have taught you two ways to declare new strings in Java there was the literal way that usually reuses the string value if it's found in the string pool and then there was the usage of the new keyword and I hope that you also remember that when you created a string using the new keyword like this difficult to new string and the value can be something like a b c then make a copy of it and put a string two with the same value and try to compare them using the equals equals operator or the equality operator like this stem dot out dot print Ln is string 1 is equals equals string you will see that the output of this operation comes out as false this is because even though the value of the two string is same these are not the same object and the equality operator usually checks whether the object on the left side is same as the object on the right side or the object on the right side is same as the object on the left side now to compare strings you will have to instead use the equals method so we'll first write the name of one of the strings then equals and string two let's run the program once again and this time the output is true however if you change the second value of ABC to Capital ABC sure the output will be false this time since the values are not same but there can be cases where you want to check whether a string is equal to another string or not ignoring their cases so for those scenarios you can use the equals ignore case method instead of the regular equals method so as you can see even though the two strings have different casing the output is still true you can also replace a part of a string in Java to do so first you will need a string such as the sky is blue [Music] and then say for example we would like to replace the word blue with the red hair system dot out Dot println uh string which is the name of our string right now and then replace you'd like to replace the word blue three great then run the program and see what the output is as you can see the word blue has indeed been replaced with red now you may think that the replace method changes the original string but it doesn't there you go what it actually does is it replaces the white blue with red in the string and Returns the updated string as a new one so instead of putting it directly into the println method you can also do something like a string updated string equals to this and then put updated string inside the println method so this will give us the same result as before foreign you may not always want to replace a substring within a string but you may want to check whether a string contains a certain word or substring or not you can do so in Java as follows so we will use our previous string which says the sky is blue and we'll check whether this string contains the word sky or not to do so you will say string which is the name of our string here then a DOT and then contains and you will need to pass the string that you want to check for to the contains method in this case it's sky save the code and run it since the string contains the word Sky the output is true but if you put something that is not present within the string such as free quote cam and run the code the output is false back when I was learning to code for the first time one of the things that I learned and it gave me a sense of achievement was being able to take input from the user so far in this course you have learned about different types of data operators and outputting text on the console in this lesson I will show you how you can take different types of inputs from the user as well as print out text on the console in some other formats if you are familiar with programming languages like python where taking input is a matter of a single line you may be disappointed to learn that in Java you have to write quite a bit of code to take an input from the user now the first thing that you need to take input from the user is something called an scanner object now scanner is one of the classes in Java and you can use the new keyword to create a new scanner object from the class so you begin by writing scanner since the type of the object will be scanner and you can name it anything but I prefer naming it something simple like scanner then equals new scanner and you will have to let it know from where you are getting the input so since you will get the input from the console or The Terminal you will have to write system dot in now this scanner class that you are seeing here it doesn't exist in your program yet you will have to import it first so before the first line where you declare the class you will have to write import Java dot util dot scanner now you may be seeing this import statement for the first time here but it's nothing complicated there will be scenarios where a certain class will not be a part of your current program or your current class and you will have to import it from somewhere else so the Java language comes with a lot of such classes that can be really useful in different scenarios this scanner class is one of them so once you have defined the new scanner object you can take input from the user so first I would like to speed out something informative on the screen like system dot out Dot print Ln what is your name and then I'll in the line here and I will say scanner Dot next line that's it now the scanner dot next line method can be used to take strings as input from the user you will have to save this input somewhere though so you can say a string name equals scanner dot next line then you can print it out just let's print out the name for now okay let's run the program and and see if it works or not okay as you can see there is this quickly line under scanner and if you hover over it it says resource link scanner is never closed well what it essentially says is once you are done with the scanner you will have to close it it's like an Open Door so if you if you do not close it it will be active on the memory so you will have to go like scanner Dot close and this quickly line should go away yes it did yeah now the programming's fine let's run it yeah what is your name okay enter and yeah it prints out my name pretty nicely now you may notice that inputting my name after the prompt like what is your name then inputting my name in the next line may look a bit little bit weird so instead of using the println method what we can use here is the print method so the print method is actually similar to the println method but the main difference is that it doesn't have a new line character at the end of the line let me show you so as you can see now the text prompt is right after the question marks so I can say for huh yeah enter and yeah that's nice now in case of a println method there is usually a new line character at the end so this causes the text cursor to go to the next line let's run the code to see how it changes our output yeah as you can see now it mimics the behavior of the print element okay now apart from the print method there is another useful cousin of this print alone method called the printf in a previous lesson I have showed you how you can create formatted strings using different types of format specifiers and I also told you that there is a variation of the print Ln method that lets you use this format specifiers right within the print method okay that's that's the printf method or print formatted now instead of just printing out the name like this we can say hello modulus s [Music] how are you and then we will put a comma and we would like to replace the modulus with the name so we put name I hope you remember all the different affirmative specifiers that you have already learned about if not you can just go back and re-watch that lesson let's run the program again foreign treats me and also asks how am I okay let's do something more so you have learned that the next line method usually gives back a string from the user but you can also ask for specific data types such as maybe an integer so to do so let's modify the next print Affair so hello Farhan how old are you okay and then we would say int age equals to scanner Dot next Clint okay yeah nice and we would like to print out yeah and sorry not printed on print f modulus D is an excellent age to start programming okay like any age is like accidental learn programming so you know and we will put age here so this modulus D part will eventually be replaced by the age variables okay let's run it what is your name okay my name is Farhan how old are you 26 maybe yeah 26 is an excellent age to start programming nice I like it okay now so far so good like the next line method and next int method there are also methods for double like scanner dot next Double and next float and all those different types that you can think of but one thing that I would like to draw your attention to and something that catches a lot of uh Java beginners or card is a little quirk so as you can see I am asking for the name using the next line method then I'm asking for the age using the next int method and it works out just fine but let me show you what happens if I try to use another next line method after this next int method okay so if I say system dot out dot print Ln or PDF okay let's just reuse this line okay some excellent cage just start programming what language do we pray for yeah and after that we'll say string language equals to scanner dot next line okay Extreme Dot out Dot printf modulus is is a very popular programming language will stop close here now sorry I I missed the language here yeah now look carefully what happens when I run the program okay so I run the program so first it asks for my name Chase Farhan sure ask how old am I so 26 and then it skips the last prompt where I'm asking about the programming language preference and just insta program abruptly and the worst part is there is no error or no failure at all which can help you to debug this problem well this is something uh this has to do with the way the next end and the next line method works so let me explain so when you are saying a string name equals to scanner dot next line and I'm inputting my name then I'm pressing enter the next line method is actually taking the entire name along with my enter or my new line character at the end or the character when I press enter that goes as an input but when it comes to the next int method it only takes the number or 26 as an input and leaves the new line character or carriage return in the buffer in the input buffer so what happens is when I say at 26 and then I press enter this part will be consumed by this method next end but the enter will be left in the input buffer so so when the second next line call comes it sees that there is already an enter in the input buffer and mistakes it as a Enter key press from me so it assumes that the user has already inputted the text they wanted to input and insta call right there okay I hope it makes sense now there are multiple ways to like deal with this problem and one of the ways is whenever you put a next in call or next Double call or next float call whatever it is except next line then you will have to put okay an extra scanner dot next line here so this just like cleans up the input buffer so this next line method eats up the enter that was left by the next int and cleans the input buffer so if we run the program now okay let's say forehan and how about am i 26 what language do you prefer well Java yeah so this is something that you should keep in mind that whenever you are using a next ink call anything but a next line call and you want to put another next line call after that like we have here an extent and the next line you will have to put an extra scanner dot next line call just to clean up the input buffer just to get get rid of that uh leftover Enterprise okay otherwise your program May skip the next call okay another way to deal with this situation is instead of using methods like next end or next float you can just use next line for taking all the inputs and then once you have taken an input you can just like convert it to something else okay for example uh instead of using the next ink if we use the next line method here and this will give us a string so what we can do is we can say integer dot parse int and then put the scanner dot next line in there okay and let's run the program and see what happens on 86 um Java yeah it works out just fine and we do not have to use any extra scanner objects as well now if you had like instead of int you may have like uh double here you can do so a double say for example if we uh want to take the GPA of the user equals to to be the double Dot first double and then scanner Dot next one and this will work out too okay so uh all of the first method that we have in these classes like integer.parsing double dot purse double we can use all of this now you may think that how would I know uh which method to use when you are trying to purse a number from a string well uh one way that I suggest everyone is you can just Google it uh saying how to purse integer from a string in Java or maybe how to purse a double from a string in Java and so on or this is something that I would leave up to you to figure out because this is something that you do not learn in courses okay so I hope you have learned about taking inputs from the user the main thing you need is a scanner object and you will have to let it know from where you are getting your input uh you can also take input from a file and some other places but those are a bit of advanced for what you know at the moment and you will also have to remember to import the scanner class first otherwise the code will just fail okay if I comment this out and run the code you will see the program simply fails to find the scanner class it says cannot find symbol so make sure that you have imported the class at the top here and the rest is pretty simple I guess so now that you have learned about taking input from the user and outputting text on Console using printf print and println uh in the next lessons we will learn about something called the conditional statements and we'll make a very simple calculator project that will just show you how much you can do with what you have already learned now you have already learned about The Logical operators and taking input from user to all the most important things in programming in this lesson I will teach you something called conditionally statements that lets you make logical decision based on some conditions and Branch out your code in different ways for example we will make a calculator in this lesson and we will let the user perform addition subtraction multiplication and division operations uh based on their inputs so first we will need a scanner of course and let's get rid of all this code okay yeah so you need to close the scanner as well okay let's begin with a double double number one equals to scanner dot next Double and then we will also do number two scanner dot next w we need to output something on this screen as well print is on sorry let's use print here enter the first number and then we'll put enter the second number it's and let's just output the numbers to make sure that the input is working fine number one and then let's make a copy of this line number two yes let's run the code five and ten yeah looks like the input is working fine now we'll need to ask the user what operations they want to perform for that let's speed out what operation do you want to perform and okay we will use print instead of print alone and then we will have to take a string input it's a string operation equals to scanner dot next line so as I have already told you that this next Double calls will leave two next line characters in the input buffer so we will need to clear them out first so let's just put this extra calls here and once we have taken the string operation then we can check what it is okay so the if statements in Java or in programming in general lets you check uh whether a certain value meets a certain condition or not for our case we can say if then a set of parentheses operation Dot equals sum so if the user has written some as the name of the operation then what you want to do is system dot out Dot println and we will say not println printf modulus D plus modulus T equals to modulus D comma so we want to replace the first modulus D with number one this should have been F actually since you're working with double sir and not integers then number two finally number one plus number two space them out in the line with the semicolon excellent now let's check out our simple calculator and see if we can do the summation correctly or not so the first input will be five you can put anything you want the second number will be 10. what operation do you want to perform okay sum yeah 5 plus 10 equals 15. now what happens if I put anything but sum okay for now we are checking if the operation is equals to sum or not and this will return true if it returns true then the line inside the if statement will be executed but what happens if we input something else let's check it out ten two maybe subtraction or sub you see nothing happens so for situations where an if statement fails to fulfill the condition we can put an else statement and we can print out system dot out Dot println print F modulus s is not a supported operation and you can put a semicolon here and we can say comma operation let's see how it turns out okay five ten what's up sub is not a supported operation excellent now I have already said that we will Implement a summation subtraction multiplication and division for that what we can do is we can put lcv statement here so if this condition fails we can say else if and we can put another condition here so operation dot equals sub then what do you want copy this line put it here change the plus sign with minus and also change the operation here minus then we'd want to close this Gap make it look good so now what will happen the program will ask for the first number then the second number then ask for what kind of operation the user wants to perform and then first it will check if the operation is equal to sum or not if it's equal to sum then it will print out the sum of the two numbers if it's not the sum then the ladder will check whether the operation is equals to sub or not if it's sub then it will perform the subtraction operation and give out the value and if the operation is not sun and also not sub then it will go into the else block and print out that this is not a supported operation let's check it out foreign Ty is larger than the first one the value is negative similarly we can just implement the multiplication and division operations so let's just do them else if operation Dot equals multiplication then and just copy this entire line and yep [Music] yeah that's it finally the division operation is a little different operation equals to div then first we will have to check we put another if inside this lcf and this is called a nested if block so we will check if number two is equals equals zero then we want to print out system dot out dot print Ln okay cannot divide by zero because you just cannot divide a number by zero and then you will put else and we'll perform the division inside and we'll bring up the else block here and now let's let's check out the Division and multiplication operations as well let's put 10 0 and div cannot divide by 0 excellent let's rerun the program enter the first number then do gives five excellent finally the multiplication operations then a mul a multiplication via 80. excellent so we have already managed to create a very simple calculator here capable of Performing the basic arithmetic operations using IF else now I'm not saying that this is the only way to implement a calculator you can actually uh find even much better ways of making calculators but so far what you have learned this is a pretty good implementation of all your knowledge now when it comes to branching out your code based on one or more conditions if else's statements are pretty common but this is not the only way of doing things there is another statement called switch case statement that can do the same thing as a complicated if else ladder in this lesson we will convert our calculator application to use a switch case statement instead of ifills statements now before we dive into our code I would like to go to settings and change our layout from stack to side by side because as I'm seeing our code is becoming much longer vertically and it's becoming harder to read we can also make the console smaller for now because we need to focus on our code now we can retain most of our code from our previous example we can keep the scanner the inputs for number one and number two the input for the operation and the only thing that we need to get rid of is the Ifill statements now instead of removing the code entirely what I would do is I will just comment it out now to write switch case statement in Java you will have to begin by writing switch and then within a set of parentheses you will have to put the variable that you are trying to test so if you remember from our efels statement we are testing out the value of the operation variable and see whether it matches one of the four operations or not so inside the switch put operation then we will put a set of curly braces now you may have already guessed from the name of switch case statements that there will be multiple cases inside a switch now these cases are like this individual if statements where you are checking the value of the operation variable against something so in the first case of this statement we will check whether the value of the operation is some or not to do so you will have to write case and then the value you want to check against which is sum in this case then you will put a colon here and on the next line you can put the logic for the summation so I will just copy the code from our previous evil slider and put it here okay let's run the code and see what happens okay Enter the first number I and put five into the second number 10 and stop okay it says 15 which means it works now try to put a value that is not defined within the switches statement like sub let's rerun the program 5 10 sub and as you can see just like the if statement when you didn't have an ill server it doesn't print out anything at all now in case of switch cases statements you do not have else but you will have a default guess which you can write as default [Music] and then you can just print out that this is not a supportive operation let's run the program and see what happens first number five then and okay savvy's not a supported operation fine now so far this looks okay but let me show you a problem here if I run the program if I put the numbers and then say sum you will see the program not only prints out the summation of the two numbers but it also prints out is not a supported operation well the way switch cases are designed that if one of the cases match then the program will not only execute that case but also the cases that comes after that to stop the program from going through all the cases here what you'll need to do is you will need to use the break step so when the program comes and it sees that the sum case has been matched it will execute the logic here and then it will encounter the break statement and breakout of this entire switch case statement okay and it will go directly to scanner.close Let's test it out once again sorry let's put five then and some so as you can see it prints out the sum and breaks the program right there okay that that's cool now you can actually Define the other cases such as case sub and we will of course take the subtraction logic from our previous efl slider put it here put the break statement in let's just copy this best okay so the third case would be the multiplication case and we'll change the minus sign so if the multiplication sign and finally the division case [Music] now I hope that you remembered that we also had a check to make sure that the user is not trying to divide by zero we will have to do that as well and for that we do not have anything fancy we will just need to rely on plain old if else step map so we will write if number two is equals equals zero then we would like to print out cannot divide by zero else we would like to perform the division operations keep in mind that you should write the break statement outside of both the if and else block otherwise if you put the break inside the if or the else then it will only work if one of them are active but if you put it out here no matter what happens in DC fills block the break will always work let's try it out and see if it works or not save the code and run it again okay then zero and div cannot divide by zero okay let's rerun the program and check if the normal division function works or not then two give yeah it works finally let's check the multiplication [Music] 10 5 multiplication 50 yeah it works just fine now you can get rid of the commented out if it's a statements now although e-fills statements and switch cases statements are more or less do the same thing in the context of Java or in the context of other programming languages as well a switch case statement is actually faster than an if else letter in Java so if you can put your logic within a switch case statement instead of a really elaborate if else statement try to do that so far in this course you have only stored single values in single variables but there is a way to put multiple values within a single variable these are called arrays now before I start working on arrays let's do some cleanup you can get rid of more or less everything in our code you can also get rid of the Java util.scanner now to declare a new array for example if I want to declare an array of characters and I want to store all the vowels in English alphabets you can do so like this first you will have to type out the type of the array which in this case is car or character space then the name of the array which will be files and two square braces then you will put an equal sign and new car then you will put another set of square braces and inside of these Square braces you will have to put the length of the array now we know that there are five vowels in the English alphabet so you will put five now we have an array of characters but it's completely empty to insert a new value to this array you will have to write files and then an index of the array which in this case 0 then equals then the value you want to save in the array a now I have already told you that this array is of 5 length which means it can store five characters in it now these characters here can be stored like a e i o u and each of this character will have a number associated with them this number is called the index now the first index of an array in Java is always zero so by putting vowels and 0 inside a set of square braces you are essentially addressing the first place in this array then you put equals a and you fill it up now the other spaces are still blank now you can copy this line and paste it to insert the other values as well so 0 then 1 . then index 2 will be I index 3 will be o and finally index 4 will be you you now you have completely filled this array with the five vowels of English alphabet you can also print out these individual files using the same square brace syntax so if I copy files to from here and write system dot out Dot println and put files and two inside Square braces and print it out you will see I printed out on the console yeah as you can see there is I you can also print out an entire array but that's not as simple as printing out a single character or number or a string as you may have already guessed the print printf or println function prints out stuff on the console as strings so before you can print out the array you will have to convert it is string to do so import the arrays class like this import java.util Dot erase and then inside the println method call you will write arrays Dot to string and in the name of the array which in this case is vowels see we have printed out the entire array now you can also print out an array using Loops which you will learn in later lessons for now just be informed that there is also other ways of printing out an entire array to the console so I have already mentioned that this array has a length of 5. and since its index count starts from 0 it will obviously end at 4. now if you try to put something in an index that doesn't exist like five and maybe put X here run the program you will see that it fails with an exception saying index 5 out of bounds for length 5 which means for an array of length 5 you cannot have an index 5. let's get rid of that line and our code should be back to normal now instead of declaring and defining your arrays separately you can actually declare and Define your array in one line to do so after you have written car files the pair of square braces and equal get rid of the new keyword and put a set of curly braces here then you can actually put the values [Music] and in the line with the same colon get rid of these lines here and run the code there you go now you can also replace any of these values from the array at any moment for example if you want to replace the I with any other character out there you can do so in this way vowels curly braces and the index of I is 0 1 2. so put 2 here equals and put X put a semicolon at the end run the program and as you can see the eye has indeed been replaced with x another thing that I forgot to mention is the fact that when you are declaring and defining your array in a single line the array will actually infer its length from the number of values you are defining it with so since there are five values in the definition the areas length will always be 5. the light strings arrays in Java are reference types and like strings arrays also have a bunch of useful methods in them for example if you ever want to know about the length of an array you can do so by saying that let's get rid of this line first and you can write the name of the array files and Dot left I hope you remember that in case of a string the length was actually a method but in case of an array it's a property so if we run the program and you can see the length of the array a one of the most common tasks regarding arrays that you may have to do again and again within your programs is sorting an unsorted array right now we have ordered our files array according to the order of the letter as they come in the English alphabet so a e i o u but if we change the order and kind of randomize it so I will put e first then u a and I so a e i o u then it's totally out of order now there is a method called sort within the arrays class that you can use to sort your arrays in order to do so you will have to write arrays Dot sort and then put the name of the array balance then let's bring back our arrays.goo string method and we'll save outs let's run the program and see if it works or not so turns out that the arrays.sort method takes an array as its parameter and it sorts the array in place so it actually changes the original Source array by default the arrays.sort method performs the Sorting on the entire array so it will begin from the first letter and go through the entire array until it reaches the last letter and sort them in order but if you want to perform the Sorting within a certain range of the array let's say for example if I want to keep the e and i as they are right now and I just want to sort the u a and o I can do so so after I have put the array name now to define the starting and ending index of the sort method you can let's just Define to integer cells so int starting index equals I'd like to start the Sorting from U so 0 1 [Music] than in ending index I want to perform the Sorting until all but here is the thing if I put 0 1 0 1 2 3 3 as the ending index the O will be left out from the Sorting because the ending index is usually not inclusive in this case so I will have to write 4. which means the Sorting will take place from U to o n it will actually not affect I Let's test it out after I have written the name of the array I will put a comma here and I'll put the starting index then the ending index save my code and run it so as you can see the sort method has actually sorted aou in order and did not touch e and I at all so this is one of the useful things that you should know about sorting arrays in Java apart from sorting an array you may also want to search for a certain value within an array okay so for example we have e u a o i here and if you want to look for o in the entire array you can do so by using the arrays.binary search method now one thing that you will have to remember is that these areas.binary search method only works on sorted arrays so if you have an array that is not in order make sure you have sorted it before performing the search now to search for maybe o within this array I will say arrays Dot binary search and then I'll put the name of the array that I want to perform the search on so files and then the key or the item I am looking for so I'll write key and I create a new character here uh key equals to and I'm looking for what I'm looking for oh okay now this binary search method right here returns an integer which is the index of this key is found so I will write int found item index equals to errors dot binary search files excellent now first I would like to print out the entire array and then I would like to print out the found item index so found item index e let's save the code and test it out sorry I mistyped the name of the variable here you know mistakes like this can happen yeah so in the array a e i o u o is at index number three so we can verify that 0 1 2 and 3 o is at index number three like the sort method that you learned about just a few moments ago the arrays dot binary search method can also take an starting and an ending index to use them first we will need to define the index integers like int starting index I think I should have just kept them and I will start the search from one so I put one then I will also create an ending index equals to 4 because I want to perform the search within the middle three values and like the sort method the ending index is not inclusive in this case as well so once I have defined the two integer numbers I will say binary search vowels and then the starting index comma the ending index and finally the key I am looking for now let's see if it works or not run okay so it says 3 which is correct in this case as well I have found o at 0 1 2 3. now so far in this lesson I have shown you a bunch of searches and all of them has worked out fine but what will happen if one of your searches failed to find the value you're looking for for example we do not have an X in the entire array so if I get rid of the starting and ending index and look for an X within our array you will see that the output is -6 now instead of looking for an X if I look for a b within our array you will see that the output changes from -6 to -2 so you may have already guessed that depending on the item you are looking for and if it doesn't exist within your array then the output can differ but one thing that's constant is if the search fails you will always get a negative output and if the search succeeds you will get a positive output and that positive number will be one of the indexes from your array where the item you are looking for exists now there is a way to actually calculate this value there is logic behind why the output is sometimes 2 and sometimes six but I will not get into that much details in this course if you are interested about learning this I will leave the link to this article on free code Camp under this video's description so you can follow that link and read more about it now being able to sort an unsorted array and look for any certain item within an array is useful now another small but useful thing that you can do with arrays is that you can fill them with a certain value for example we have five vowels listed out of order within our vowels array but maybe for some reason you want to fill the entire array with x or maybe empty characters now you can do that by using the arrays.fill method before that let's get rid of some of these codes and write arrays Dot feel then put the name of the array that you want to fill which is files and the character or the value that you want to fill the entire array with [Music] let's run the code and see if it works or not yeah as you can see the entire area has been filled with excess now you can also have starting and ending indices with this fill method starting index equals let's start from one and in end ending index equals to 4 this is the same drill with the other methods as well the ending index is never inclusive so if you want to perform the field from 1 2 3 upon these three values make sure to include the last one as well or the item that's just after the one you want to end the field action act okay now arrays.fill comma vowels then we will put the starting index the ending index finally the value that you want to fill the array with okay so rs.2 string valves let's see if it works or not yeah it does uh the E and I is untouched and the U and O and A has been replaced with x's I have already said that arrays in Java are reference types and one of the complexities that we get with any reference types out there is making copies of them for example if we have an array of integers this time just for changing our test a bit I will write int numbers same thing equals then inside of a pair of curly braces I will put one two three four and five then I will create another array saying int copy of numbers which is an array equals to the number sorry okay so ideally the copy of numbers array should be a copy of the original numbers right let's see if that's true or not print Ln arrays dot two string numbers let's make a copy of this line and put copy of numbers sorry let's run the code and see what happens turns out I have made another typo here I have Mr T let's put it back and run the program so it seems like that the copy of numbers array is indeed a copy of the original number setting but I'm not convinced let's do another thing okay let's make some changes to the original area so we can say arrays Dot fill numbers and I'll fill the original array with zeros and then run the code let's see what happens but this is unexpected isn't it I have actually made some changes to the source arrays and the changes have somehow applied to the copy as well but the reason for this is the fact that arrays in Java are reference types and when you use an assignment operator to make a copy of an array or any other reference type for that matter it doesn't actually makes an entirely new copy of the source material what it does is it creates a new variable and points that variable to the original Source array so although the second array has a different name it's still pointing to the same values so you can treat this copy of numbers array as kind of an alias for the original numbers area so how do you make a copy of an array correctly then now to copy an array properly you will have to use the arrays dot copy of method the method takes the name of the original array as its first argument and at the second argument it asks for the length of the new array so the length of the original array as we can see is one two three four five so you can count that by hand or you can be a little bit clever and put numbers dot length as the length for the new array let's run the code and see whether the copy gets affected by the field call or not this time so as you can see that the original Source material and the copy of it are now two separate entities which we want now instead of putting the same length as the original array you can also make the array larger or smaller let's say if you make it larger with 10 indexes you can do so so as you can see the first five elements of the copied array are from the original array and the rest of the indexes has been filled with 0 which is the default value for integers you can also make it smaller so 2 . and the copy array can hold only two values while the original array could hold five now like the sword and the search method you can also Define the starting and ending indexes for the areas.copy of method but for that instead of using the copy off method you will have to use copy of range now inside this method you will have to first give it the name of the source array then and starting index and and ending index and just like before we will have to Define this integers here and the starting index equals to Let's uh 0 1 let's start the copy from one and in ending index equals to r 4. let's run the code and see what happens so as you can see the method has successfully copied 2 3 and 4 from The Source area now one thing that you may have already noticed that in case of the copy of range method you do not need to use a link for the newly copied array so how can you increase the length of the new array if you want to well right now we are performing the copy from index number one to index number four right so if we put a larger value than the original length of the array like then let's see what happens so as you can see the copy works out fine the method copies 2 3 and 4 from the original array also 5 and 10 fills up the rest of the space with zeros so although you cannot explicitly Define a new length for your copied array you can change the length of the new array by changing the ending index of the copy of range method just like copying a reference type is more complex than copying A Primitive type comparing preference style is also a bit complicated I hope you remember from our lessons on string we couldn't compare two strings simply using the equal SQL signs we had to actually use the equals method so it's kind of similar in case of arrays say for example we have the original numbers array then we have a copy of the numbers array let's just use copy off instead numbers dot length x length and get rid of the field method and try to compare our arrays using the equality operator so we'll send numbers equal equals copy of numbers let's run the code and see what happens as you can see it says false but we know for sure that the copy of numbers array is an identical copy of the original Source material now to compare to identical arrays like this or maybe two different arrays what you'll have to do is you will have to write arrays dot equals then inside this method you'll have to pass the two arrays copy of numbers let's run the code and see what happens yeah this time it comes out as true since there is no such thing as casing in case of an array there is no equals ignore case method for arrays like we had for strings in programming you may want to repeat a certain set of instructions again and again for your projects you can do that by using loops now there are four kinds of Loops in Java and we will start our discussion with a for Loop first I will write out the code for a very simple for Loop in Java that can print out the number from 1 to 10. for that I will write for this is the starting of our for Loop then inside I will take an integer int number equals to 1. now after the semicolon I will write number is less than or equals 10. and then number plus plus then I will put a set of curly braces here and inside this block of code I will write system dot out Dot println number we do not need the arrays class import right now so we will get rid of that and let's run the code and see what happens then I will explain each line of this for Loop to you as you can see the program successfully prints out all the numbers from 1 to 10. so what's going on here well every single for Loop usually has four parts the first part is the initialization where we are initializing a certain variable in this case an integer with the initial value of 1. then there is a condition that we are checking against so we are checking whether the number is less than or equal to 10 or not and if the number is less than or equal to 10 we will print out the number so this is the loop body system.out dot println anything that you write inside this set of curly braces will be the loop body then once we are done with the loop body we will go to the third part here inside the set of parentheses and this is called the update and we will update the value of the number variable so I will repeat every single for Loop will have four parts there is the initialization where we initialize a variable with a value then there is a condition that we will check in every iteration there is the loop body and then there is the object so when this Loop runs for the first time the value of number will be 1. and this condition will be true since 1 is indeed less than 10. so the loop will print out the value of number which in this case is 1. then the loop will increase the value of number by 1 and go back to the condition part and check whether the updated value is less than or equal to 10 or not well 2 is less than 10 so it will again go inside the loop body and print out 2 on the console so like this the loop will keep printing out all this number until it reaches 10. when the loop has printed out 10 on the screen it will go back to the update part and increase the value of number from 10 to 11. and it will go back to the condition once again and check whether 11 is less than or equal to 10 or not in this case the condition will come out as false and the loop will stop iterating the program ends here and we get all the numbers between 1 to 10 printed out on our console I hope that makes sense you can also use a for Loop to Loop over an array for example if we create an array here int numbers equals to 1 2 3 4 5 6 7 8 9 and 10. then we can use this for Loop to Loop over this array and print out each of this number to do so we will need an integer and we can call that the index so we want to run this loop as long as the index is less than the length of this array so numbers dot length numbers dot length finally we will increase the value of index by 1 on every iteration finally inside the println call we will send numbers and then we will put the index here let's see if it works or not so as you can see the program actually brings out all the numbers from 2 to 10 and doesn't print out to 1 because since the index count starts from 1 which is its initial value it starts accessing the array elements from index one so if you change the value of index from 1 to 0 then you should get all the numbers from 1 to 10. so what's happening here is you are initializing an integer with a value of 0 and then inside the condition part you are checking whether the value of the index is less than the length of the numbers array or not if it's less than the length of the numbers array then you go inside the loop body and print out whatever number is in the current index so it starts from index 0 which means one then index 1 which is 2 then 3 4 5 6 and so on you can also do some interesting things within this Loop instead of printing out all the values you can add them all together and print out the sum to the screen to do that what you will need is you will need another integer here goes to zero initially the sum will be zero and then inside the loop what we are going to do is we will say sum plus equals numbers and then the index okay finally we'll move out this system dot out Dot println outside of this Loop and print the sum on the screen let's see what happens when you run the code I forgot the semicolon here yeah so the sum of all the numbers from 1 to 10 is 55. now let me show you two more interesting programs that you can write using a for Loop the first one is that you can print out multiplication tables of any number using nested for loops for that what we need is a number so we will Begin by taking a new integer in number pi then inside the for Loop let's get rid of all this code and rewrite the for loop from scratch so we will say for then another integer the multiplier we will begin from one then if the multiplier is less than 10 we will keep going and we'll also increase the value of multiplier by 1. then inside the loop body we can say system dot out Dot print F in this case modulus D into modulus D is equals modulus t now we will say number then the second part would be the multiplier and finally number into multiplier now I hope you remember that the printf method doesn't have any new line character at the end so if you run the program at its current state let's see what happens as you can see it prints out the entire multiplication table in a single line which we do not want so what we can do is we can put a backslash n at the end of the line which will print out each row in a new line run the program excellent now we can take it a bit further to the audience let's get rid of the current code and let's begin with the new for Loop okay for inch number equals one number is less than 10. and number plus plus then inside the for Loop we will have a nested for loop I hope you remember that we have worked with nested if statements in the past we can also nest for Loops within each other so we can do 4 into multiplier equals one multiplier is less than 10 and multiplier plus plus now inside the loop body we will say system dot out Dot printf modulus T into modulus T equals to modular state so the first thing would be the number so since the nested for Loop is inside the outer for Loop any variable declared within the outer for Loop will be accessible inside the nested folder but any variable that you declare inside the nested Loop such as this multiplier here will not be visible to the Outer Loop so we can send number so we will replace the first modulus D with a number then we will say multiplier and finally number into multiplier in the line save our code and let's run it okay just like before we have to add a new line character at the end to make it look a bit nicer so as you can see now we have successfully printed out the multiplication table for all the numbers from one to nine but if you would like to include 10 here you can say less than or equal and then run the code yeah it works fine and I also just noticed that we are missing again here and you can fix that by saying multiplier is less than or equal to 10. right so let me explain what happens here first inside the outer for Loop you are initializing a number with one and you are continuing to Loop until the value of number exceeds 10 so less than or equal 10 and then inside the loop body you have another loop so first it comes and says okay number is equals one it's less than 10 then it goes inside the inner for Loop and it sees that there is a multiplier with the value of one multipliers value is less than 10 then it goes inside the body once a body has been executed it prints out one into one equals one and then it goes back to the update part of the inner loop and it checks again then it keeps looping within the inner loop once the value of multiplier has exceeded 10 the inner loop breaks and the program goes back to the outer loop it increases the value of number by 1 which becomes 2 now and it goes inside the inner loop again and prints out the multiplication table for two then it goes on to print out three four five six seven eight nine and ten so if you're having difficulty deciphering this complicated code here I would suggest that you write this code yourself and use a notebook to understand how these values changes in each iteration okay so finally I would like to show you an example of using an if else statement within afford for example if I tell you to print out all the odd numbers from 1 to 50 you can do that by using a for Loop and a single if else statement let's begin for int number equals one number is less than or equals to 50. number plus plus so this Loop will begin at one and end at 50. then inside the loop body what we want to do is we want to check if number modulus 2 is equals equals one then system dot r dot println number [Music] so if you divide a number by 2 and the remainder is 1 it's pretty sure that the number is an odd number we all know that so what we are doing is inside the for Loop we are taking whatever the value of number is we are dividing that by 2 and checking if the remainder is one or not that's what the modular operator is for I hope you remember and if the number is an odd number we will print it out and if it is an even number we will skip that let's run the code and see what happens so as you can see we have successfully printed out all the on odd numbers from 1 to 50 so 1 3 5 7 9 11 13 15 and it goes on to 45 47 and 49. there is another variant of the for Loop that makes looping over collections such as array is much easier now for that first we'll need an array numbers equals uh I'll just put the regular numbers here there you go now to use this special type of for Loop you will have to write for then inside you will say int number this type has to match with the type of the array and then you will put a colon here and then you will put the name of the array then inside the area body you can say system dot out dot print Ln number let's see what happens so as you can see the loop successfully goes through the entire array and prints out each element to the console now What's Happening Here is uh you are saying for every single integer number in the numbers array you want to print them out so instead of using an integer as an index and accessing the elements individually you are kind of taking a shortcut and extracting each value from the numbers array and putting them in the number variable on each iteration now you can do anything that you could have done in a regular for Loop such as if you want the sum of all these numbers you can do so like this some classicals number [Music] and then system dot out Dot println it's so make sure you are putting the printerland call outside of the loop otherwise this will be printed every single time the loop iterates let's run the code and see what happens there you go other than the for Loop there is also the while loop and do while loop in Java these are two different kinds of Loops that can more or less do the same thing as a for Loop but the for Loops are a lot more common in the wild than the while Loops now I will show you two examples of using a while and two while loop first let's begin with the while loop we will simply print out the multiplication table like we did in the case of the for Loop but this time we will use a while now first you will need a number just like before then you will need the multiplier now to write a while loop you will have to say while multiplier is less than or equals 10 then inside the loop body you will say system dot out Dot printf modulus T into modulus T equals modulus T since all of the variables are integers in this case then you will put number then the multiplier finally the number into multiplier excellent then once you have printed out the row in the multiplication table you will have to increase the multiplier by 1. multiplier plus plus let's run the code and see what happens so here looks like the program works just fine we have to just put a new line character to make the output a bit more readable foreign there you go now the main difference between a while loop and a for Loop is the fact that the while loop only has one component which is the condition in case of a for Loop we had the initialization we had the condition we had the loop body and we also had the update part but in this case there is just the condition and of course we have the loop body so you will have to do the initializations outside of the loop and you will have to perform the update or the incrementation of the multiplier or maybe counter or whatever you are working with inside the loops body so this is how a while loop looks like now a do while loop Works similarly but in a different order and also looks a bit different so in case of a do while loop you will have to write do then you will have the loop body which in our case is these two lines we want to print out the multiplication table once again and also increase the multiplier and after the loop body you will say while multiplier is less than or equals 10. let's comment out our old while loop make our console bigger and run the code foreign output now the main difference between a regular while loop and a two white Loop is the fact that in this case first the loop body will be executed and then the condition will be checked whereas in case of a while loop the condition gets evaluated and then the loop body gets executed so you will surely find usage of both kind of Loops if you worked long enough but I can say from experience that for Loops are a lot more common than whites or do vials let's just clean up our code before we leave from this lesson yeah so far in this course you have learned about only one way of putting a bunch of values together and that is the arrays but arrays have some limitation and the biggest one of them is the fact that you cannot resize an array the only way to make an area larger or smaller than it already is to copy it and change its length during the copy but there is another type and error list which is like a dynamic array you can create an arraylist you can put item in it or you can take away items from it and it will also adjust its length depending on how many elements it's holding now to use an error list in your code you will have to first import the error list class to do so you will have to write import java.util Dot errorist then to create an array list you will have to write array list then you will have to put a less than sign and inside you will have to write the type of the data you want to store in this array list now I know so far you have been only seeing int and this is the first time you are seeing something called an integer used as a type I will explain what this is but let's just keep on typing and finish creating our new error list okay so error list integer then name of the error list which in this case will be number equals new error list integer that's it we now have an empty error list of integers I forgot the is there now what's this integer class here I have taught you that data types such as int or double or float Boolean these are all primitive types but in Java you can also make them as reference types using the wrapper classes so this integer class share integer is actually a wrapper class for the Primitive type INT in other words integer is the reference type form of the regular inch type so just like integer you also have double float Boolean and so on and when you are creating an array list you cannot use the Primitive in type you have to use the integer wrapper class I hope that makes sense since we have an in the error list in our hand let's put some item in it now to insert a new item in an error list you cannot just use the old Curly braces syntax rather you will have to use the add method in this way you will have to write numbers then dot add then the value that you are trying to add which in this case will be one and a semicolon you can make a bunch of copies of this line and just add other numbers as well there you go now to print out an error list to the console you will have to write system dot out Dot println numbers which is the name of our error list in this case then Dot to a string now the two string is a method that is present in every single reference type in Java and later on when you will learn about object oriented programming you will also learn about creating your own twisting methods within your custom classes for now just remember that to print out an error list you will have to write out the name of the error list first and then the method to history let's run the code and see if it runs fine or not so as you can see the error list looks like an array in the console now you can also print out a single value from the arraylist if you want to but for that you will have to use the get method so you'll subdoc then get then the git method actually takes an integer which will be the index of the value you are trying to print like arrays error listers are also zero based so the first index of an error list will always be zero so the index of one in this case is 0 to 1. 2 three and four so if you want to print out three on the console you will have to send numbers dot get and then two here let's run the code beautiful we have three printed out on the console I have already said that analysts are Dynamic so you can add as many elements as you want using the add method and you can also remove elements from an error list so if you say numbers dot remove and it will take a number which will be the index of the element you are trying to delete so if you want to remove 3 from our error list we will say numbers dot remove and pass2 then let's print out the entire error list and see if she exists or not question okay let's run the code yeah three has been successfully removed but you can also remove items by value so for example if I want to get rid of 4 I can do so but instead of passing and primitive 4 if you write 4 here this will be a primitive integer Type 4 it will work as an index but if you pass a reference Type 4 like this integer dot value of and then pass the Primitive type which in this case is 4 and if we run the code you will see that we have successfully removed four from our error list now an error list can store anything starting from integers booleans characters strings and your custom class objects anything that you can think of we will work with much more complex at least in later lessons for now just let's get hang of the basics okay now you can also remove all the items from an error list by saying the name of the earliest Dot clear this will clear out the entire error list and make it empty there you go so I have already showed you how you can add new items to an error list how you can get them remove them clear an entire analyst now let me show you how you can update an element inside an error list for that there is the set method so you will type out the name of the error list then Dot and is a set and you will have to put an index here so again let's update the 3 here and its index is 2 we'll put 2 here comma then you will have to put the value that you want to replace three with and since the the error list is of reference types you will have to use the integer Dot value of method once again and we will say 30 so we will replace 3 with 30. let's run the code and see what happens excellent it it works out just fine so like an array you can also sort your array list right now we have added the numbers in a sequential order here but if we randomize them like for example if we put five at the top then one after three then two at the end okay let's get rid of this indices because now these are getting misleading okay let's run the code and see what happens so as you can see the numbers are all jumbled around now to sort this error list you will have to write the name of the arraylist the DOT and then sort in the method now you can see that there is a small squiggly line under the sort method name and this is because the sort method will actually take a parameter which is known as a comparator okay so as you can see it says comparator in the parameter list let me explain what this is first let's import the comparator class so it's a import Java dot util Dot comparator and then inside the sort method we will say comparator dot natural order which which is a method inside the comparator class and what we are saying is that sort this error list in its natural order okay let's run the code and see if it works or not yeah it works just fine we have successfully sorted our error list now you can also reverse the order of this error list by saying compared to Dot reverse order which is similar to Natural order but this time all the values will be sorted in a reverse manner there you go we have five four three two one liftoff now three very small but useful methods that the allergies have is the size method the contains method and the intimator first let's see what the size method does so if you ever want to know how many elements are there inside an error list you can just say the name of the error list and then size now this size method will return an integer after counting all the elements in the error list you can also check whether an error list contains a certain value or not and to do that you will have to write contains and since these are all reference type numbers we'll have to use the integer Dot value of method and we will have to put for example one let's check if the error list contains one or not see it says true which means it contains one and if we put 10 here the output should be false and yes it does now there is another method that checks whether an error list contains anything at all or not and it's the is empty method and since our analyst here actually contains some elements the output should be false and yes it is but if we clear our list just be before checking for emptiness we will see yeah it says true now the final thing that I would like to show you is the for each Loop now you have learned about the for Loop already in a previous lesson and you know that you can use it to Loop over regular arrays but when it comes to an arraylist there is another kind of loop let me show you how it works now keep in mind the forage Loop looks and works a lot differently than the for Loops but I'll try my best to explain them as lucidly as I can foreign list that you want to Loop over such as numbers and then for each then here it says action what you will say is number then you will make an arrow like this and then a set of curly braces now inside the set of curly braces you will say something like system Dot out dot print Ln and let's multiply each number with two just as an example so you'll send number into two and in our line now let's also print out the entire arraylist at the end so numbers dot to string yeah let's run the code for now and then I will explain what's happening inside the for each Loop run so as you can see we have successfully multiplied each value in this error list and we have also printed out the original arraylist here now let me explain the forage Loop for you so when you are saying numbers dot for each number you are saying that for each number in the numbers arraylist you want to perform the actions within this set of curly braces or within this block of code so imagine this Arrow like we are ordering the compiler like for each number perform this action that I am pointing towards now technically it's called a Lambda expression it's it's like a method that doesn't have any name now of course I'm over simplifying stuff here but for now this is enough to understand now as you can see that although you are multiplying each value of the numbers I released we do inside the forage Loop body the original error list remains unchanged now let's just for practice uh update the original error list and replace each value with their multiplied counterparts okay now to do that what we can do is let's first print out the original error list we will say uh B4 and plus yeah we are going to use the plus sign once again in this case because it's a simple program and then we will take this out and we will say after plus and then number start doing string okay now inside the for each Loop what we want to do is we want to say numbers dot set and inside the set of parentheses we will say numbers Dot index of which is another method that can return the index of a given value so will bus number here comma number into two so you are essentially using the index of method to get the index of the current value of the number variable and then we are updating its element with the multiplied value okay let's get rid of the println call here and let's keep our fingers crossed and try to run the program yeah seems like it has worked out we have successfully overwritten all the values of the error list with their multiplied counterparts now this is one of the many fun programs that you can write to practice your skills I would suggest that you go around the internet find interesting problems that feels challenging to you and solve them to flex those Java muscles okay now that you have learned about air release let me show you another kind of collection that's pretty common and pretty useful in some scenarios these are called hash Maps now hash maps are actually key value Pairs and if you want to compare it python then python dictionaries are kind of similar to Hash Maps now to work with hash Maps first you will have to import the hashmap class to do so you will just write import java.util Dot hashmap let's get rid of all the early code and start working on hashmap okay Now to create a new hash map in Java you will have to write hash map and then just like the add list you will have to first put the type of the key so in my case I am making a hash map where I'll be storing the scores for my different subjects maybe at my school or summer so the key will be string and the value will be the scores of the subject so maybe English 98 maths 85 and so on so this will be integers and then I will name the hash map something maybe uh exams course equals to new hash map string integer that's it we have successfully created an empty hash map and since I have already discussed these wrapper classes in a previous lesson I will not repeat now to put something in this new hash map you can use the put method so exams course dot put and first we will need to put the name of the subject so it will be a string and maybe a math and then a comma and then this course I'm not that good at math so maybe 75 then we will say exam scores dot put another subject may be a sociology and 85 exams scores dot put English 95 and so on now to print out a hash map to the console you can say system dot out Dot println exam discourse dot to string just like you did with the error list okay let's run the code and see if everything works or not run excellent the hash map prints out uh so my score for English is 95 sociology 85 and math 75. uh I hope you have already guessed that the item you are putting into the hash map is not sorted so even though I have put math at first it comes out in the end so if I put some more subjects foreign and let's see what ordered this show up in the console see as they're actually showing up in random order but that's how hash maps are you don't have to worry about them now you can also print out a single value from a hash map to do so you will have to write the name of the hash map then a DOT and get then you will have to pass a key in our case the keys are all strings so I will write let's get the score for English run and yeah we are getting the score of English now apart from the put method there is also another method put if absent that first checks if a value already exists in the hash map or not and if it doesn't then it will put it otherwise it will just skip it now you can write exam scores Dot put if absent and let's try out with math math and let's put a new value here maybe 70. and then I would print out the entire hash map here string nice so as you can see the value of math is still 75 even though I have tried to put a new value for it but since the put if absent method actually checks whether math already exists or not in the hash map it didn't override the original value now if you want to replace one of the values however you can use the replace method and it will take a key in this case we are still working with math and we are updating its value from 75 to 70. what a shame so as you can see the value of math has been changed to 70. now just like the put if absent method there is another method called get or default for example if I try to get a key that doesn't exist let's say for example religion we know that it doesn't exist in our hash map let's see what the output is as you can see it says null but if we say get or default and we give it a default value of 0. or maybe -1 and run the code so the program will return -1 if the given key is not bound now like an error list you can clear a hash map by saying exams course Dot clear and this should clear out the entire hash map there you go and now if you want to check the number of elements that exist on the hash map you can do so by saying the name of the hashmap dot size this will return an integer after counting all the elements present in the hash map right now which is 0 because we have just cleared it out but if we get rid of that line it should be back to five excellent to remove an item from the hash map you can use the remove method like this exam scores dot remove and then you should put a name of this one of these keys so let's get rid of sociology and I'll put it here semicolon then exam score start to be string let's run the code as you can see sociology is not present here now you may also want to check whether a certain item exists on the hatch map or not and you can do that in two OS either you can check for a key or you can check for a value for example if I want to check if the math key exists or no I can do so by saying the name of the hashmap exam scores dot contains key and then the key I want to check against which is math in the this case and it comes out as true now if I want to check if I have this code 100 in any of the subjects or not I can do so by saying examscores Dot contains value and then the value I'm looking for which in this case is 100. now you can also put a reference type 100 here if you want to do that the value of and it shouldn't make any difference yeah it just works and I have also taught you that in case of at least when you are trying to update one of the values you need to pass the integer as in reference type you can actually pass a primitive type as well the set method will convert it to a reference type automatically but it's up to you what you would like to do and what you want finally you can check if a hash map is empty or Not by using the name of the hash map which is examsforce Dot is empty and since our hashmap is not indeed this should return false yeah it returns as false cache Maps also have for each Loop just like arraylist and now I will show you an example of using them with hashmaps to do so first you will need to write out the name of the hashmap which is the exams course in this case then you will set Dot for each just like at least you will create a new Lambda method here but in this case it will say the key comma the value then the arrow and the curly braces now the key here is the subject and the value is this Force so I'll just do it like this and then system dot out dot print Ln name of the subject Plus Dash plus the associated score let's put a semicolon at the end get rid of these empty call and see if it works or not okay I just noticed that there is a small squiggly line here that's because I didn't enclose the two variables within a set of parentheses here in case of an error list we had only one variable so it didn't need this parenthesis but since we have multiple variables here subject and score we will need a set of parentheses around them let's run the code and see if it works or not okay seems like it works now what we are going to do we will Loop over the entire hash map just like we did in case of the error list and we will update the value of each subject score just for the purpose of practice now to do that we already have the name of the subject which is the key and we also have the value which is the score to update the values we will say exam score start replace you have already learned about this then we will subject which is the key and then we will take away 10. from each subject maybe for bad behavior or something then we will say system dot out Dot println and exam scores dot blue string okay I hope everything works out fine and I cannot spot any mistakes let's hit the Run button yeah so I have indeed taken out 10 from each subject so English was 95 and now it's 85 Bengali was 100 and now it's 90 sociology is 75 from 85 computer programming has become 90 from 100 and finally math has become 65 from 75. again I would suggest that you go into the internet looking for problems that you can solve to just practice all the things you are learning in this course this will really make you confident in Java now that you have learned most of the basics of java it's time that we start discussing about object oriented programming now the concept of object-oriented programming in itself is really huge and to be very honest you cannot learn how to make good object-oriented programs from a course or a book what I can do is I can teach you the basic concepts around object-oriented programming and once you have learned them you will have to learn the rest from experience by making larger and larger software following good practices and so on now at a higher level object-oriented programming is about modeling your software around real life objects for example maybe we can build a book borrowing system where a user can come register and login check for a book's availability borrow it if it's available and they can also return it on time they can also check the list of the books they have borrowed so far now in this aforementioned system there can be two objects one the user and two the book we can store information such as the user's name and birthday and in case of a book we can store the book's title and maybe the name of its authors and so on so let's begin by creating a user class in our software and as we keep working on this simple program we will learn about the different concepts around object-oriented programming so first open up the files menu by clicking on the file icon here and click on the add file button name your new file user Dot Java in this file you will need to create a new class like we have done with the hello world file so write public class user now we are declaring this class as public because we want this class to be available within our entire program now inside the class we will store the user's name which can be string so public string name and we will also store the user's date of birth so we will say public local date which is a reference type for storing dates in Java and we'll say birthday now to use the local Red class within our user class we will have to first import it so import Java dot time dot local date uh by the way do not get intimidated about the amount of classes that Java has built into it as you will keep working with Java for months or maybe for years you will eventually learn about a lot of them now we have a new user class let's go back to our hello world class and create a new user object now creating a custom object like a user object is not very different from creating a string so you will have to write user which will be the type of our object then you will have to name the object maybe let's name it younger user because we will have a older user as well later on equals new user and a set of parentheses now we have a user but this user at its current state doesn't have any name or date of birth since these variables are declared in the class level of the user class this will be initialized as null by default so they will get default values now variables like these at a class level are called properties and since these properties are tagged as public we can actually access them from outside of the user class and give some value to them so we will say younger user dot name equals [Music] Farhan hasin Junior excellent then younger user Dot birth J equals local date Dot purse and inside the purse method we will pass 1995 0 1 31 which means 31st January 1995. now the local date.burst method can pass a date from a given string and convert it to local date type again for using the local date class here we will have to first import it so import Java dot time dot local dates then we would also like to print something out on the screen and for that we'll say system dot out Dot printf and inside the printf method we will say that modulus s was born back in modulus s then after the comma we will replace the first format specifier here with the names so we will say younger user dot name and then after that we would like to replace the second format specified with the birthday but since the birthday is not a string you will have to first convert deep string by calling the twisting method and I have already said that the twisting method usually exists in all the reference types and any local date object is actually reference type let's try running our program and see if it works or not so yeah it works just fine Farhan hasin Junior was warning back in 1995 c131 now I have already said once that using something called Methods we can actually Implement some Dynamic behaviors to our classes for example since we have the per day of the user we can use it to calculate their current age so we will create a new public method public because we want this method to be accessible throughout our entire program and then we will have to write the return type of our method which in this case is integer because age is always an integer then we will put the name of the method which is age and put a pair of curly braces now from inside the method we will calculate the age into H equals and for that Java actually has a pretty nifty class so in import Java dot time dot period now this period class has some method that you can use to calculate the difference between two local date types so we will say period dot between and inside this method called we will put a starting date which is the birthday so we will say this Dot birthday I will explain this this later on and then we'll put local date dot now now this period dot between method call will actually calculate the difference between the user's birthday and our current day and then we would like to return age dot get years because we want to return the age in years okay we do not want anything else let's go back to our hello world class and change this string to something like was born back in and he is now modulus is a module does d ears port so you say that user was born back in the birthday and he is now X years old so we'll put a comma after the twisting call and say younger user dot h and we will put a set of parentheses because this is a method and you will need to put a set of parentheses to call any method in Java let's run the program and see if it works or not yeah looks like everything has worked out just fine it says foreign Junior was born back in 1995. 0131 and he is now 27 years old excellent now what is this blue this keyword here now to explain this we will actually need two users so let's create a new user user older user equals new user and we'll say holder user dot name equals senior and then you will say folder user Dot birthday equals local date Dot first and let's put 1975 0 1 15. okay now we'll put this system out Dot printf at line 10. and we'll make a copy of it at the end of our program postponed back in uh okay all right let's replace younger user with older user let's run the code and see what happens foreign ERS Engineers born 27 years old and this is 47 years old nice now you can see that we have two different users in our program and both of these users are actually created from the same user class so when we are trying to calculate the age of the user how would the computer know which user we are referring or which date of birth we are referring to this is where the this keyword comes in you see we have two instances of the user cluster and this keyword will refer to the current object being worked on so when we are saying younger user dot age then the value of this will be the younger user object and when you are saying older user.h the value of this would be the older user object okay so let's get rid of the extra user here change the younger user's name to just user and let's start working on the book class let's go back to the files menu create a new file with the name book Dot Java now let's declare a new class public Plus book and for a book we would like to store a public freeing title and public history author yeah that's pretty much it for the book class now let's go back to the hello world again and we will say book equals to new book and then book dot title equals to carmilla book dot author equals to Shelton let's put a semicolon at the end and now we have a new book so how about we implement the functionality of borrowing books I will put it in the user class so let's close this menu as we don't need that and we will create a new method here path leak borrow and this borrow method will actually accept a parameter because this method has to know which book the user is trying to borrow right so we will say book so this method is actually accepting variable of book type then let's create arraylist of type book let's call it books equals new array list and book closing and we will also have to import the error list class so import ant java.util dot arraylist okay then we can say this dot books dot add and book so you're adding the book we have received within the borrow method to our list of books okay let's go back to our hello world class and we will say user dot borrow and we will pass the book to it I think we have made a small mistake that is we haven't said what kind of data the borrow method is returning now as you can see the method actually returning nothing so we will have to say for it which means it doesn't return anything at all there is no return statement whatsoever it just makes some changes to the books error list okay let's go back to hello world and this looks all right so far let's update this printf method yeah and h okay let's let's write another one system dot out Dot printf and it will say modulus s has borrowed these books and with some modulus s okay let's put a comma here and we will say user dot name has borrowed user dot books dot two string okay uh let's also put a new line character at the end of our printf statements otherwise they may not look as good as we want them to be okay let's run the program and see what happens then we will go through what happening in this entire system once again foreign just as I expected so as you can see it says Farhan has engineer was born back in 1919 and so on and then it says Farhan has engineer has borrowed this book's book at and then a large number but we are expecting maybe the name of the book or maybe the name of the author or something like that right but that didn't happen let me tell you why you can see that we have been using the method to string a lot right by using the method twisting a lot and I have already said that this twist string method comes with every single reference types now our book here is a custom class and whatever book object we are working with are all reference types now since we have created the book class ourselves it doesn't have a built into a string method that's why we are getting some random values here now to solve this problem we will have to implement a twisting method we can do that by saying public string to string and then we will return a string representation of this book like return string dot format here and we'll say modulus s by modulus is then a full stop and after the comma we will say this dot title and this dot author so whenever we are trying to access one of the properties within a class from a method within the same class we can use that this keyword okay let's try to run the program once again and see if it solves our issue or not let's make our console bigger foreign I think that full stop there looks pretty bad because it's going to show up like a list of books let's get rid of that and also I think this is a good time to switch back to the Stacked layout once again since our codes are getting bigger horizontally and this gives us a better look at our lights okay so what have we done so far we have created two custom classes representing our users and the books we have created a new user object we have given him the ability to borrow books from us we have also calculated their age using method we have implemented title and author for our books and we have also implemented accustomed to string method so this is really a lot to be honest but we will do more now so far we have been declaring all our methods and our properties as public but to be very honest this is not something you should be doing a lot let's learn about something called a Constructor as you can see when you are trying to create a new user you are saying user then name of the user object equals new and then you are writing the name of the class once again and then a set of parentheses as if you are trying to call a method called user well that's kind of true every single class that we have in Java has a special method called Constructor this method is responsible for initializing all the properties with their default values so what we can do is we can customize these Constructor method and make it do things let's start by writing a Constructor for our user class okay we will say user and will not write anything like public or maybe some sort of return type nothing at all we will just start by writing what the name of the class is then we will put a set of parentheses and set of curly braces so this is our Constructor method now let's think about what we want from the user when they are creating a new user object right we want their name so we will receive or ask for their name and we will also ask for their birthday now this birthday can be taken as a local date but we will take it as a string I will tell you why but now inside this Constructor method we will say this dot name equals name and this Dot birthday equals local date dot purse birthday so what we are doing essentially is we are asking the user for a name and we are storing that name in the name variable or name property within the user class then we are also asking for a birthday and we are storing that birthday in the birthday property but since the birthday property is of type local date we will have to purse the birthday from a string format to local date format now let's go back to our hello world class and make the necessary changes here we will say user equals user and we will put the name inside this Constructor call and we'll put a comma here and we'll also put the birthday within the Constructor call because now the user class is capable of accepting these two values let's run the code and see if everything works just as before or not seems like I have made a small typo here the D should have been capital foreign just like before now since we can initialize the user with a name and a date of birth right at the creation process we can actually make the name and birthday private which means we can no longer do things like user dot birthday or user dot name but we still need to know the user's name and user part derived for that we have something called getters so we will create a new method somewhere in this user class public get name and the return type B string and we will say return this dot name and we will also say public string get birthday and you will say return this dot birthday dot to string now let's go back to the hello world class and make use of these two Getters we will come down to printf and we will say user dot get name how do you say user dot get birthday and we'll get rid of the two string calls since the birthday will come back as a string by default now let's run the code and see how it works okay we also have to replace this name here and as you can see since we have made the name properties private the hello world class actually fails to access the user's name which is a good thing I will explain why let's just make it working again so yeah it's it's back to normal now since the name and birthday properties have become private no one can change their values from outside the user class which means these are now much more secret than they were before another thing that is now we can pass the name of the user and the birthday as a strings the hello world class has no business in knowing what is the actual type of the birthday is all the Hello World Class needs to know that if it passes a user name and a birthday in string format a new user will be creative this is called abstraction so what we are doing is we are hiding the complexities of the user class behind this beautiful looking Gator methods Constructor methods you can already see how cleaner the user object creation looks compared to the book object creations let's make the same changes to the book class as well so we will go back to it and change the title and author to private then we will Implement to getter methods so public get title return this title the return type will be string and then we will say public a string get author and we say return this Dot author Etc let's also implement the Constructor so we will say book we will take the title as a string and then we will take the author name as a string then we will set this dot title equals title and this dot author equals author nice let's update the creation process so we will pass the title of the book and the name of the author with the new keyword and get rid of that excellent the program already looks much cleaner now another thing that I would like to change is I would like to make the books list private and Implement a getter for that as well so let's go back to the user class and let's say foreign public and this time we will be returning string borrowed books and we'll say return peace dot books dot history excellent now the hello world class doesn't know about the complexities of the books list either we'll just say borrowed volts did I meet it private yet no I didn't so we will make it private okay let's see if the program works just as before or not excellent the program works just as before now I hope you can already see the beauty of object rendered programming and how cleaner the program actually looks in reality we still have to learn a few more Concepts around object entry programming such as inheritance now assume that our book borrowing system has multiple types of booths there can be the regular books I mean the hardcover ones or the printed ones then there can be ebooks and there can be audio books now although they have some similarities they also have some differences such as the ebooks and the regular books have page counts where the audio books have run times also the ebooks have formats such as PDF or ePub or so on so trying to implement different kinds of books using the same class can be cumbersome now you may think that you will make copies of the book class and add or remove the necessary properties methods to them but that's not a very good idea this is why inheritance comes in so we can make a default book class with the most common properties and methods in it and then we can make child book classes that will inherit all the properties and methods from the parent book class and we can also add some new properties and methods to them let's see an example first we will add the page count property to the book so we will say private int page count and for that we will have to pass the page count to the Constructor here so we'll set this Dot Page count equals page count we'll go back to our hello world class and we will say I don't remember the actual page count of the book but let's put 270. nice everything should be normal let's run that code and make sure ah that was a silly mistake I didn't accept the parameter here let's run the program and make sure excellent now we will create a new audio book class audio book Dot Java yes and we will say public class audio book extends book now since we are declaring this audiobook class as an extension of the parent book class it already has all these properties and methods we have described here so what we need to add is a runtime so it's a private int front so runtime means how long these audio books run so the runtime will be in minutes then we will have to create a new Constructor here so we'll say audio book just like before and we will accept the runtime so it's a int runtime and then inside the pair of curly braces we will say this Dot runtime equals runtime now here is a problem I have already said that since this audiobook class is an extension of the book class it also inherits all these private properties which means we will still have to fill them up somehow but the audiobook Constructor doesn't accept any of these values okay let's see what we can do to solve this first we'll copy all these parameters from the book Constructor and add them to the audiobook Constructor one of the problems have been solved we are now accepting all the necessary information for the parent book class now we will say super and we will pass title author and pitch count now the super keyword here actually refers to the parent class of our current class so when you are calling the method super we are actually calling the Constructor of the parent book class so we have successfully filled up all the necessary properties of the parent class as well let's try out by creating a new audiobook let's go back to the hello world class and after book we will say audiobook equals new audio book and we will say Dracula foreign stalker and the page count actually we do not have to pass the page count here we can modify our Constructor a little bit we do not need to accept the page counter instead we can pass 0 as the page count yeah that would be better and we can just accept the runtime so for example maybe the Dracula book would run for 30 000 minutes so I put 30 thousands here audiobook see I have made a mistake and I think we should start naming our books so carmilla [Music] okay so we have successfully created a new audio book here just for the sake of our codes Clarity let's get rid of all the code that we do not need so we will get rid of the user dot borrow call we have seen examples of that we will also get rid of the system.out.printf calls we will get rid of the user as well because for now we will be focusing strictly on books audio books and ebooks so let's create a new system.out.printf method here we will say sorry Dracula dot two string [Music] because remember that the audiobook class already inherits the two string method from the book class okay let's print out something on the screen so it's a system dot out dot print Ln and Dracula dot Google string let's run the code and see if it works or not yeah it works just fine okay now that we have a audiobook class let's create a new class called ebook chef okay King public class ebook extends and then within the set of curly braces uh actually we can copy a bunch of code from here let's copy everything to the ebook class and we will say private is string format and then we will accept everything and we will also accept the page count this time because ebooks have page count okay so input page account and then we will also accept the format so we'll say string format this dot format equals one CF nice uh yeah everything looks fine okay we have to change this to ebook let's go back to hello world and try to create a new ebook Okay so ebook so Jeeves I will create a Chiefs book new ebook carry on Chiefs written by PG old house I hope I'm spelling his name correctly then the page count would be 280 I guess and finally the format will be PDF let's put a semicolon there and let's see if the book has been created properly or not so Jeep stop to stream okay so carry on Jeeps by PG Port house so we have successfully created different kinds of books based on a parent class now this is what I had in store for this course in terms of object oriented programming I have taught you what are classes what are objects water properties and methods Constructor methods and you have also learned about inheritance now there are a lot of things that you will have to still learn like method overloading and overriding Abstract method and whatnot but I would not like to overwhelm you with all these Concepts in a single course what I would suggest that try to understand everything that I have taught you in this course uh as thoroughly as you can and then keep practicing make programs make bigger programs and try to understand whatever concept seems complex to you and as you keep working with Java as you keep making more and more fun projects you will start to understand a lot of the complex Concepts around object oriented programming and whatnot so I hope you have learned something good from this course and maybe someday I will see you in another course as well so till then stay safe and take care