 Hello! Welcome to Absolute Java Basics for Android course. In this course, we're going to learn about all the basics of Java that are required for you to learn Android. This is by a small deck that talks about Java in general and also about what this course covers. This is going to be a very hands-on course. This is probably the only video where we're going to go through slides. The other videos in this course we will actually create a lot of Java programs to learn all the basic concepts. If I move to the next page, this slide talks about what Java is. If you did not already know, Java is a programming language. A programming language is basically something that we use to communicate with machines. So in this case your computer. We write instructions using a programming language and then that gets converted into something the computer can understand and then the program executes. Java is one such programming language and it's also an object-oriented language. We won't go into much details about what object-oriented language mean. Just understand for now that object-oriented programming is one type of programming that is very popular and there are a lot of languages that follow that pattern. Please also understand that object-oriented programming gives us a lot of benefits which we will see in the later videos when we actually create programs using that in Java. But just know for now that it brings a lot of advantages compared to other types of programming. And then I added a link to the actual Oracle site if I click it. So this is Oracle's Java tutorial site. Throughout the course I will keep referring back to this one for some key concepts and I would also recommend you to go through these links because in my opinion online this is one of the best basic documentation of Java that is out there and it's from Oracle. So you know that it's authentic. This is a very useful site if you're getting it started in Java to learn the key concepts. Now if I flip back and go to the next slide let's talk about some of the basic concepts in Java further. Java is both a compiled and interpreted language. If you did not know already a programming language can be compiled and run in a computer or interpreted and run in a computer. The difference is when you compile a program it creates another file which is basically a binary file that the computer can understand. As you probably know computers can only understand ones and zeros. So when we do a compilation of a programming language which is kind of in a readable form in plain English is converted into another form that the machine can understand. As opposed to that an interpreted language is not converted into another file when we actually run the program. Each line of the computer program that we write is interpreted and executed by the machine. So those are the two differences between compiled and interpreted languages. But Java is both compiled and interpreted and there is a big reason why it's the case. When we write a program we create basically a .java file just like how you create .txt, .doc, .pdf. When we write a Java program we would create let's say hello.java. That's your program that you write and then when we compile that program we end up with something called .class. So if you create a hello.java you compile that Java program you get the hello.class and that .class file contains what's called a bytecode. So note the difference that earlier I said when we compile we usually end up with a machine code. In this case it's not the machine code it's a bytecode. The bytecode is basically what Java creates and it can understand. Before we go further on why we use bytecode let's understand one term that is used about Java. It's called a write once run anywhere program. So you can write the program in let's say a windows environment. You can compile it and then when you get the .class file you can take the .class file to a Linux environment or a Mac environment and run it without any change to the program. That's where the term write once run anywhere comes in. So the biggest advantage is your programs become more portable right and that's why we create something called a bytecode in Java to be able to create something that you can run anywhere. And after that we have some jargons JVM, JRE and JDK they all have specific purpose and we'll go through one by one. Remember we said we create a bytecode right that Java can understand. So when you run the bytecode what happens is Java creates something called a virtual machine. So it's basically a machine within your computer right that's why it's virtual. Java creates something called the JVM within which the bytecode actually is interpreted. This is why Java code is portable because that is Java knows how to create the JVM in different operating system environments. So you can create the same .class file take it to a JVM in windows or run it in a JVM in Linux or run it in a JVM in Mac so that's where the portability basically comes in. Java basically creates JVM for that environment and runs the program within the JVM and that takes us to the next point which is JRE, Java Runtime Environment. Java Runtime Environment is nothing but a bunch of let's say libraries the Java gives for different operating systems again for windows there is JRE for Linux there is JRE and for Mac there is a JRE. So JRE is just a set of libraries the Java gives for us to be able to run our programs. So using a JRE in windows you can create that JVM in windows and run your .class file similarly in Linux and Mac and then JDK is kind of like a super set of libraries. So when you say JDK it includes all the tools and anything that you need to create the programs and all the tools you need to run the program which is JRE that we talked about. So JDK is nothing but a super set of libraries that you can download from Oracle that enables you to write your program compile your program and then run your program and then connection between Android and Java. Let's move on to the next slide for that. So Android is nothing but another programming methodology or language for mobiles that follows Java. So Android is fully based on Java you will create the .java file you will create the .class file so Android is basically an extension or is fully based on Java which is why understanding the basic concepts of Java is very important because all the basic concepts are used in Java because Android programs are basically nothing but Java programs. Without understanding the basic concepts of Java or the object-oriented programming methodology in Java it would be really difficult or sometimes impossible to grasp the concepts of Android which is why we're going to go through the basic concepts of Java that's what this course covers. Java is a vast programming language it has it has a ton of things to learn. What we're going to focus on is only the absolute basics of Java that are needed in order for us to learn Android. So this course covers all the basic concepts that you would need if you are a starting Java programmer all the basic concepts that you need to understand what Java is different programming constructs in Java that will help you in learning Android. So thanks again for joining this course and let's learn Java. Hello let's get started to learn Java or to even start programming in Java you need two things one is the actual Java to be installed so you can compile and run your program the second is some type of IDE IDE stands for integrated development environment what basically is a convenient way for you to write your programs you can use the standard text editor if you are in Windows you can use Notepad if you are in Mac you can use any standard text editor program to create your Java programs but using an IDE helps you in a lot of ways because it highlights if there are syntax errors that you are making and several things and it just makes it easier to compile and run programs so since the goal of this course or what you're trying to do is to basically learn the language you want to make it as easy as possible for you to just do what you want like code and compile and run so we're going to install Java and we're going to install Eclipse which is the IDE which is one of the ideas available for Java Eclipse is one of the widely used ones so we're going to use that for this course to install Java you go to Google search for Java 8 download and then the first link would be from oracle.com which is what you need you go in there and then if you scroll down these are all different things that you can download we don't need the demos and samples now we need let's take this one 8u1 1 2 there are different versions here depending on the operating system you use you have to download the one that do you need the basic difference for each operating system is that is a 32-bit version and that is a 64-bit version so depending on the computer that you're using you would choose one of those i'm using a mac 64-bit and that's the only option available so this is what i would download i'm not going to install it because java is already installed in this machine so but all it takes is you just have to click it after you accept the license agreement and it will download and install you can just install it as you would install any of that application same thing for windows if you're in windows you would choose either this or this depending on 32-bit or 64-bit that you're using and then you would follow the setup process that you normally follow in windows and install it now once it's done that completes the java installation so i would encourage you to go ahead and complete that past this video and then move on to the next step of installing eclips now considering you already have java installed now we're going to focus on eclips installation so same way we go to google.com and then say eclips download and then go to the first link which is the eclips downloads actually if i go back it's easier to click this eclips id for java ee and then there are different download links available again that is a 32-bit version under 64-bit version for windows and Linux and there's just one version available for mac i'm going to click this and again i have eclips installed so but you would follow the same process of downloading and installing eclips just like how you would install any other application so again i would encourage you to pause the video get that completed and then once you're done move forward so considering you have java and eclips installed right now you would go to launchpad in mac and basically look for eclips it would be there you can start it once you start you can add it to your dock that's what i have done here but this is the first time this is how the first time you would access eclips so let's launch eclips and then one of the first things that's going to show up is basically a pop-up that tells you where to create a workspace think about workspace as a collection of files so if you're working on let's say a productivity program or later on you're working on a game or later on you're working on something else so different development projects i shouldn't say project because a workspace can contain a collection of projects but depending on how you want to organize things you can create multiple workspaces so right now i have in my eclips i have java basics for android that's basically the workspace name so you can use the same or you can use a different thing it doesn't really matter but if you want to just follow along just go ahead and type in your machine under your user profile eclips and then name for the workspace again you can just type java basics for android once you're done it okay this is going to open the workspace in my machine i already have some of the videos created so i'm just coming back and creating this installation video so once this opens you would see a bunch of projects here as you see so ignore all this in your machine when you open the workspace for the first time this will all be empty and that's okay this is what would show up one of the first things that you need to do depending on which machine or which type of OS you're using if it's mac you would go to eclips preferences and if it's windows you will go to window preferences so since i'm using mac i'm going to go to eclips preferences um i'm just going to make this bigger so go under java and install the jres just make sure this piece is added depending on which again which way is you're using java would be installed in different locations make sure there is a new jre added and the way to do that is you do add standard vm and then you can go directly and select the location where java is installed in your machine and that's basically that of it and then it gets added so what this is this is the jre that will be used when you use eclips to run your programs so for that eclips needs that so once it's done you should be all set with the installation of java and eclips and you know all ready to do your first program and that's what our next video is going to be our very first java program again if you have any issues with the installation online there are several sources about or even talks about how to install java and eclips for each of the operating systems so i would really encourage you to use that but the installation should be pretty straightforward it should be pretty easy to install and get started thank you see in the next video hello now that we have installed eclips and java let's go ahead and create our first program to do that right click here and say new java project we're going to name this project section one all the programs that we're going to create in this course will be categorized into different sections based on which part of the video series you are on since we are in the first section and we are going to do our first program we're going to name this project section one and let's hit finish once it's created expand this arrow right here src is the folder where all your programs will go in so right click there and say new class any java program that you create will be a class so let's create a new class where it says name is where your class name will go we're going to name it hello world hello world is a simple program that we do in almost every single programming language as our first program it's a simple program that just displays the text hello world but the best thing about that is it introduces a lot of language capabilities with just a simple program that's why people have been doing that for decades and that's what we're going to do as well apart from the name there is a package package is basically a folder structure to to organize your classes and programs that you create there are other uses for packages packages as well but for now just remember that a package is just a way of grouping your classes together it's always a good practice to give a package name let's just call it calm.java.tut.section one there is a naming convention involved in packages if you go to a website google.com the classes that they would create would go in the reverse of what the domain name is so if they have www.google.com the packages would be calm.google. whatever the subcategories are so we're just going to call ours java.tut and then section one when we go to other sections we will start naming our packages calm.java.tut.section two section three and so on creating a package and putting your class in a package is always a good practice so we'll start doing that right away hit finish wait for the class to be created once the class is created eclipse will open the class for you and as you see eclipse already populated some text for us in there the first line will denote what package the class belongs to is the one that we created calm.java.tut.section one and as you can see the class file is located inside that package and then we have a public class hello world as i mentioned earlier all your java programs would be some type of class and this is how a class definition will start we'll go into the details of what these mean in in later videos but right now just remember that any code that you write in java will go inside a class so let's start typing within these curly braces we're going to create what's called a main method a main method is basically where the execution will start so when you run your java program java will basically look for main method and start the execution there and since our goal in this program is to display hello world we're going to write a main method and enter a statement in the main method to display the text so there are so start typing public static void main and then open parenthesis and inside that type string make sure the case is right so string with s as caps and then type arguments open square bracket and close square bracket and then open the parenthesis again we'll go into the details of this in a little bit for now just follow along and any code that you write for a method should also go in within curly braces and eclipses will automatically create the closing brace once you create the opening brace and inside the main method start typing system dot out dot print l n open parenthesis and open double codes and let's type hello world end with the statement with a semicolon save it let's quickly run it before going into some details of what this program contains right click on hello world class find run as java application click that so as you can see it's launching the message disappeared but as you see this is what a console is a console is where your output the output of the program goes right and the output of our program is the text hello world printed in the console so we were successful in what we were trying to do let's just go into a little bit detail of what this program does as i mentioned earlier anything that you type in java will go into a class and then the execution of any java program starts at the main method the main method takes what's called some arguments or parameters that you can pass we will go into the details of this also maybe in a little bit later video but just remember that main always takes an array of string as a parameter for now just follow this construct and your program should just run fine when the execution starts we're telling java okay print hello world in the console so again this is the standard structure to print something to to the output console and that's what we did and every single java statement should end with the semicolon and then we have a closing of the main method and the closing of the class itself so this is a pretty basic program but as you can see we were able to quickly run a java program our first java program that actually does something so there is another print statement i wanted to introduce to you before we end this video which is called system.out.print so to to show the difference between print and println i'm going to do system.out.print and then create another system.out.print within codes now we will call it hello universe so what we're doing here is system.out.hello world and system.out.print hello universe let's run it this time you don't have to right click because eclipse remembers what you ran so you can just click this um arrow now you see hello world and hello universe are printed which is good but they're all printed in the same line it's not printed in two lines as we have coded and that's the difference between a print and println if you change this to println and save it run it again now you have hello world and hello universe in two different lines so that's the difference between print and println print does not print a new line character at the end but println does so with this you can try to change this text or add more print and println to run this program over and over see how your output differs but we were successful in doing our first java program so congratulations and that concludes this video thank you so much hello welcome to section two in this section we're going to start with learning variables let's go ahead and create a new project java project we're going to name it section two hit finish and expand the arrow find source and then let's create a new class name of the class would be variables and the package would be calm dot java tut dot section two there is a shortcut here to create the main method that we would otherwise have to type into the java class if you check this box here when eclipse creates the class for you and opens it it will also create the main method for you so you don't have to type that over and over every time you create a class if you hit finish so the java class is created and the main method is in the java class let's delete this one we're going to learn about this in a later video so right now we have a java class and the main method in it so what are variables variables are basically containers right like buckets to hold something in them that something is any value that you want to specify it could be a number it could be a series of characters pretty it could be anything right you was saying that it to a variable so you can use that variable everywhere in our program let's go ahead and start typing int and then let's call it number equals 100 so what we are saying is we are creating a number variable of type integer and the value of that is going to be 100 right now we can use this variable anywhere in our program to do different things since we know how to display or print something in the console we're going to type system dot out dot println we're going to open double quotes say number as so far we had printed one only text now there is a way to include variables in the text that needs to be printed to do that after the double code enter a plus sign and then you can enter any variable that needs to be printed so when java encounters this statement what it will do is it will know that number is should be printed and it will look for the value of number variable and print that let's go ahead and right click and do a run as java application to see what happens as you can see it printed number is 100 if you change the value let's say to 500 save it and run it it's going to print number is 500 so that's basically use of a variable you can assign value into a variable and you can use that variable anywhere in your program there are a few things to remember the variable should always be initialized when i say initialized it should have an initial value assigned to them if you don't do that java will throw an error let's remove this initialization and just declare number and try to print it as you can as you can see we have an error it says the local number variable number may not have been initialized so that's one thing let's put that back in so the error is gone the next thing to remember is the variable name cannot be a reserved keyword what are reserved keywords so java has a bunch of keywords that are reserved for specific purposes when java encounters them it is going to think that's for whatever purpose they were defined for right whatever you see in eclipse in this highlighted red are basically keywords right when you say public class it meets something to java that you are defining a class when you say public static wide main it knows that you are defining a main method so if you start using these reserved keywords as variables then it's going to be confusing so java would throw an error and prevent you from doing it let's try that we're going to name it name this variable public but public is a keyword so java saying invalid variable declarator id so we also have another error here because we changed number variable to public so java does not recognize what number is any longer so that's another thing to remember before you use any variable you need to declare it give it a type and give it an initial value let's change this back to number so that's basically what variable is and the variables value can be changed so now you can say number equals thousand here we're changing the number variable to hold thousand right you don't need an int any longer because we have already declared number is always going to be an integer and we can just change the values whenever we want now if you do a system.out.printl in here and say number is now number and end with a semicolon save it and run it it printed number is five five hundred and then the number changes to thousand number is now thousand so a variable can hold a value a variable's value can be changed anywhere in the program and it can be used in several places like printing or calculations and so on there are different types of variables that we're going to see in a in a later video but for this video number wasn't in teacher and we were able to assign different values and print them so play with this try changing the values it can take negative values also so you can you can do that and try to run it and see what you get and once you're comfortable let's move on to the next video thank you so much hello welcome back in this video we're going to learn about comments let's go ahead and create a new class and name it comments let's go ahead and check this which will automatically create the main method for us and hit finish now this is a line that was automatically generated and it says to do auto-generated methods tab what this basically is a comment which means it does not belong in the executable code when you compile this java class whatever bytecode gets created the dot class file gets created will have no reference to these comments comments are basically text that is added to the code to explain why we are doing certain things or to basically include text in the code that are not necessarily executable statements there are two types of comments in java one is this way this is called a single line comment for example if i type int number equals 20 and then i change that to 40 and let's do a print number is number right let's go ahead and run it first you see number is 40 right now if we don't want this assignment we want to keep the number to 20 but we don't want to delete this line yet you can just do slash slash save as you can see eclipse changed it to a green color which is a comment uh default color for comments so this is not an executable statement any longer if you were to run it again now you see number is 20 so this line basically did not get executed now so the single line comment is not just used for commenting out statements that you don't need you can actually use it to say this assignment is not needed any longer because of a new requirement so the what this basically says is you got a new requirement which is why you commented it you don't need this any longer so you can add text like this to your code so when you reference this code later or you're reading this program later or somebody else is reading the program comments basically help them understand why you're doing certain things in the program so that's basically the single line comment and as you can see you don't need a space after the two slashes you can if you want to to make it more readable there is another uh type of comment which is called a multi-line comment because this is was a single line multi-line comments go like this a slash and an asterisk and you close that by an asterisk and slash basically the reverse of it whatever you type between these two don't get executed so you can say number equals 40 number equals 50 doesn't matter none of them will get executed because as you can see this is all in green color anything between this block and this will not get executed again you can enter some more text here this assignment is not needed if you were to run it you would still get numbers 20 because this is the only executable statement everything else is commented out so this was the single line comment this was a multi-line comment comments are really good you know we always encourage programmers to add as many comments into the code as possible because since this does not get into the executable code you're not necessarily increasing the size of the code but you're creating programs that not only you someone else can also read later and understand so it's a very good practice to add as many comments as possible to your code so let's go ahead and follow that in our future videos also and that's basically comments thanks for watching hello welcome back in this video we're going to learn primitive data types in java as you can see we did not start with eclips in this video but if you have started with this um number sheet what i have here is the list of eight primitive data types that are supported by java and basically their sizes and ranges we will quickly go through this table before we go and create an example class and then test these out so there are eight primitive data types some of them are used for some specific purposes we'll just go through one by one the first one you see is a car data type the car data type holds one character information in the simplest term right if you want to save something like a or b or uh parenthesis or star or anything that is just a single character you would use the car data type as you can see it takes 16 bits two bytes and we have something like unicode zero to unicode two to the power 16 minus one unicodes are basically specific codes to define different characters not just english but different languages and java utilizes that but for the purposes of this tutorial let's just assume or understand that a variable that is defined as a car data type holds just one character now if we move to the next set there are four listed here and these are all integer data types when i say integer if a variable is declared or defined with one of these data types you can store only integral numbers no floating points on that and each of these data type have different ranges as we go down the range increases a byte data type supports only eight bits of information which means you you just go to the power of seven so it supports minus 128 to plus 127 and if you need anything more than that you would use shard which is 16 bits which means you would go by 2 to the power 15 and you have minus 32768 to 32767 in general programming you would not use byte and shard if you are very concerned about memory usage on defining a large array where you are storing a lot of numbers but you are confident that the numbers are going to be in these ranges you can use these two but in general programming we don't use byte and shard int is very common it is the most commonly used data type if you know when we store integral numbers because the range is it is quite decent to to accommodate any normal integral value that you want to capture in the program it takes 32 bits and the calculation goes the same way minus 2 to the power 31 to plus 2 to the power 31 minus 1 so that's in teacher long is a really long number as you can see this is the range supported by long we normally don't require long unless you're doing storing some wealth information of some you know really wealth individuals and stuff like that but normally we don't use long either we pretty much stick with int but you can use long if if there is a need so these four are the four integral data types supported by java as we move down the two that we have here are for decimal values first is float which has 32 bits of information there is a 754 standard for floating point which is supported by java but you can just assume that the difference or understand that the difference between float and double as float holds less precision compared to double double lets you store much more precision i think it's 15 numbers after the decimal point whereas float is only seven and then we have boolean boolean does not have a range because all its stores is just true or false i believe it takes about a single bit of storage in memory but it's not defined in java anywhere on how much a boolean data type takes but all we can store in it is the value of true or false so these are the four data types in java now let's go ahead and create a new java class and test these out real quick let me switch back to eclipse we're going to create a new class and let's call it primitives we will create a remain method as well so we already used the int data type in the other videos for example variables had a number that is defined as int and this is pretty much what the primitive data type int that we just saw let's go ahead and create a new byte of value sample byte equals minus 100 so that's pretty good so we created a byte let's create a short sample short equals 1000 and let's go int sample int equals 10000 and long sample long equals let's some big number type int is out of range this is because in in java a regular number is always considered an int so what we're saying is store int and long if you change this to l now this is fine if you add a l at the end of the number you're telling java that you are saying this is a long number what gets stored in sample long will not be this number followed by l what's stored in sample long would be only this l is just a way of us telling java that hey this number is a long number let's go ahead and quickly print that to confirm that theory if i do a print off sample long let's go ahead and save i'm going to right click to run as java application you just get the number so yell is not part of the number yell is just a way of us telling java that this is a long number let's do the floating point now you will see something interesting when we type float sample float equals let's say 2.5 we get an error but 2.5 should be within the range of what sample float is because if i switch back to numbers you see that floating point takes 32 bits so 2.5 is a very small number so why did we get the error if we go quickly back here and check what the error is says cannot convert from double to float what this tells us is for java any decimal number is by default a double not a float so what we're telling java here is hey take this double number which has a larger precision and assign it to a floating point variable where we might actually lose precision right so java is complaining hey i cannot assign a double number to a float now to overcome this just like we put a l here we just have to do a d here and save oh should be capital d should be small d what's going on oh sorry terrible terrible terrible so we have to tell that we're going to store the float in the floating variable sorry about that so what we're saying is hey we know this number is a float so assign it to float if you don't have it it becomes a double number and we cannot assign a double to a float without making the number itself a floating point sorry about that now i can do a double sample double equals 2.5 this is perfectly fine because we are just assigning a double number to a double variable so that's floating points and double now we need to look at car data type so car sample car equals so we just entered a single character and assign it to a variable that is defined as a car variable we can print this and say sample car is plus sample car save it and run it get sample car is c so you can save a car data type and then print it just like any other variable now the final one we want to look at is boolean boolean sample boolean equals false because the two values the only two values that are allowed for a boolean variable is true or false or we can just say sample or we can change the sample boolean to true we cannot store any other value in this so if we say sample boolean equals c we're going to get an error saying cannot convert from car as you can see if you put something in a single code java will know it's a car so saying hey i cannot convert a car to a boolean so the data types are basically a way of us telling java what are we planning to do with a particular variable when we say sample length is an int we're telling java that hey we are planning to store an integer value within a particular range into this variable so these primitive data types are the building blocks of java this is what you would use in other classes that we will build later in our tutorial but just play with it with different numbers just like you know some of them will stump you just like I had the problem with the d here I was actually saying hey it's a double assign to a float which was again terrible but play with these assignments assign different values and I'm going to add this to the to the section as well so you will have this as a reference so you can look here for the ranges and then try to assign different values to these variables and test them out it is really important to get a good understanding of these primitive data types because I said as I said these are the basic building blocks so have fun see you in the next video hello we'll come back in this video we're going to learn about casting let's go out and create a new class in the existing package and call it casting we'll create our main method as always hit finish we'll delete this guy let's go ahead and create an integer called a int and make it 20 right now let's create a long and let me a long it's equal to a int so we're basically creating two variables one is of integer type another is of a long type we are assigning the value of a long to whatever a int has and there's no problem in this code because the range for a long is bigger than an int so whatever value the integer holds long can hold it now let's do this let's create another long I'm sorry let's create another int two and say it's equal to a long we have an error let's see what it says says cannot convert from long to int since long has a bigger range a long could possibly have a long bigger number that the integer cannot hold we know that the value is 20 but java doesn't care about that java just says hey you are trying to assign a long number to an integer and that's not allowed now if we know that a long always will have a smaller number and we we know for sure that it can be converted to an int and we want to take the risk because we know what's going to happen we need to cast the type from long to int or convert the type from long to int to do that you do an open parenthesis here type int that's basically the type that you are trying to convert the value into closed parenthesis now the error is gone because now we have told java take whatever is in this convert it into an int and assign it here right so the error is gone this is basically what casting is if you were to print a in 2 let's type a in 2 semicolon save it let's do right click run as java application so the value is still 20 right now what if we were to make this value really big like something that only a long can hold not here sorry about that so let's do a long equals a bigger number all right so what we're trying to do is create an actual long number and don't forget the L at the end to denote that it's a long number so we have as in the value of a long to a really long number and we are trying to cast it to an int let's try to run it again as you can see the value is different not really what we have in a long because we have told java convert this to an int but since int has a smaller range the the value basically got converted into whatever int can hold and got displayed please keep in mind that it has a range from negative to positive so if you go over the positive range the value basically goes to the the other end of the spectrum the negative number which is why you have a negative number here this basically what casting is you would want to cast a bigger value into a smaller type only if you know for sure you're not going to lose anything or if you are positive that losing is what you need right losing the value or truncation is what you expect now casting is not just limited to integers it can be applicable to floating point as well so let's go ahead and create a double a double and say 2.6767 right so this is basically more than seven positions right that float can hold so float can hold seven and double can hold 15 right now if you were to create a float and say it's equals a double you're going to get an error saying we cannot convert now to convert it to a float it's the same logic like here do an open parenthesis type float close parenthesis right let's do a systematic out here and see what we get put it in if float is and I need to put the double quotes here and not here now let's run it you see if float is six seven six seven six seven six we have only seven here when we had more than seven decimal point numbers right so there is definitely truncation happening here also but we know that we want to convert the double to a float so we're trying to cast it by using this so that's basically what casting is you would cast when you go from a higher value to a lower value and casting is not just limited to primitives they can be applicable to objects as well which we're going to see in later videos but this basically what casting is I would really encourage you to try this out with the several other types that we have like byte and short define different variables and try to cast from one to the other to see what happens but this basically what casting is thank you see you in the next video hello welcome back in this video we're going to learn arrays arrays are basically a list of values as opposed to storing a single value in a variable arrays basically let you store a list of values so you can easily access them through a single name let's go to create a new class in the existing package we will name it arrays and create our main method we'll delete this and so far we've seen something like this right create a new number integer variable and assign the value 22 it now what if we want to store a list of values let's say numbers one two one through seven right but we don't want to create number one number two number three number four individual variables to store them but want to use a single variable to access all of them that's where basically arrays come in there are multiple ways to create arrays we're going to see the first type now int numbers right now we want to make this an array to make this an array you just need to type open and close square bracket right after the type let's say equals we wanted to store numbers one through seven all you need to do is one two three four five six seven close curly brace semicolon so what we have done here is create a numbers array of integers and we're storing numbers one through seven in that array how would we go about accessing these values let's try to print the fourth item in the array right so we want to display number four let's say system.out.println say fourth item in numbers s you would type numbers and then we have to tell what position right we want this number displayed so that's one two three four let's try to give four and see what happens right so we had numbers open square bracket number four close square bracket save it let's try to run this guy run s java application we have fourth item in numbers is five but we have the number four as the fourth item what happened here this is a very critical thing to remember arrays always start from zero right the position of arrays or the index as it's called sometimes of arrays always start with zero right so which means number one here is actually the zero position of array two would be the first position three would be the second position four would be the third and five would be the fourth right so when we say display the fourth position value of numbers we got number five displayed now if we wanted number four what we should have given here is zero one two three numbers of three change the numbers of three print now you got four right now if you say numbers of zero and run it again you would get number one well this should be the first item but anyway i wanted to show the difference so the first position is always zero in an array it's very critical to remember that now arrays are not just limited to integers even floating points can be made an array objects can be arrays as we will see later in the course let's try to create a floating point now array right and we call it salaries now i mentioned earlier there are multiple ways to create arrays we saw one way right now the other way is to just create the array first and then do the initialization later that is supply values later now to do that you would do new this is something we have not seen before we'll talk about new later but just type new type float again open square bracket let's give number three right what we are saying is create a salaries array and that array is going to have three items in total so when we say three items in total it's zeroth position first position and second position that's it right so three is the size we have not supplied any value yet but let's try to print out that print ln of float zero right not float zero sorry salary zero so we're saying display whatever is in the zeroth position of salaries right let's try to run it we have zero right this is another critical thing to remember when we initialized variables earlier we saw that if you don't initialize the variable so when we declare variable if you don't initialize them and we try to use them later in the program we got an error right but that's not the case for arrays arrays are initialized automatically right if it's an integer it's going to be zero if it's a floating point it's going to be zero point zero right so arrays are initialized automatically this is another critical thing to remember now we can say salaries of zero equals 5000 point one two and since all the floating point numbers are double by default we have to change it to a floating point before we save it into a floating point variable now if you run it so we have 5000 point one two so using this position you can either display like we did here or even as in values right so this is the second type of creating an array and initializing them the values later one more critical thing to remember before we move on to the next video is we can never go out of the bounds of an array right for example we said salaries can hold only three values like zero one two now let's see what happens if you do system dot out dot print ln salaries of five right we're asking for whatever is in the fifth position to be displayed let's try to run it we got 5000 point one two displayed but then we have exception and thread main array index out of bounds number five right we're going to look in detail about exceptions in later chapter but just remember that exceptions are bad if something like that happens in your program it almost always means that something went wrong what went wrong here is we've told java that salaries can hold only three values at zero one two position but we asked it display the fifth position value which doesn't exist so we have an array index out of bounds exception and it even gives you the value that you supplied right so it's very important to remember that we can never go out of bounds of an array we can declare like this and use only the three positions or we can declare like this where the seven positions are created automatically and the values are assigned but you can never go out of the bounds of the size that you specified i would really like to encourage you to try arrays with other types that we have like byte short care and see what you get arrays are very important because that's one of the very common things used in java programming so it's really important that you understand arrays better before you proceed that's basically it thank you so much hello welcome back in this video we're gonna learn different operators that are available in java there is a slight difference in this video compared to the other ones we have gone through already for this i already have the class created the reason i did this is because there is a fair amount of typing required to get through all the operators and i didn't want to spend time waiting on typing all these things instead i would rather go through these line by line explain to you what they are so that we can focus on the understanding part and not the typing right but i will go through very slowly line by line so you can actually understand what's going on and also maybe type it up on the side as you go through this video i've created a new class operators inside the package that we already have and the main method within that class we have two integers defined num1 which is initialized to five and num2 which is initialized to two the the operations or expressions that we have in this class are done on integers but all of them can be done on floating points as well the first four or five we're going to go through are normal arithmetic operations as an addition subtraction multiplication and division the final one is an operator that lets you find a remainder when you do the division so let's go through them one by one first one i'm creating a new variable add which is also an integer and i'm using the plus operator which is the addition operator to add the two numbers num1 and num2 and as in the result to add variable and then i'm printing it let's run it now and see the output and then we'll just reference the output as we go through each of the statements so first one add is seven five plus two seven so seven got stored in add variable and that's what got displayed so the next one we have is a subtraction which is the minus sign we have num1 minus num2 stored into a sub variable right and we're displaying the sub variable five minus two is three and we got that displayed the next one is multiplication we use a star sign or as many people call it asterisk symbol which is used to represent multiplication so we are multiplying number one and number two on storing into a variable called mu l mull so five into two is ten so mull is ten the next one is a division operator so this one finds the quotient not the remainder but the quotient right so we do the slash for it we have a num1 slash num2 so five divided by two the quotient is two so two gets stored in div variable the variable and we're trying to display that variable here so that's div is two next one is called a modulus operator or the remainder operator this one is similar to the one that we just saw but the result of that operation would be the remainder not the quotient so five divided by two we got the quotient here which is two but the remainder would be one so mod variable is initialized to number one and that's what's displayed here mod equals one so these are the basic operators that are in java as we scroll down we have an operator called increment operator so if you if you have a variable and you just want to increase it by value one just by one you can quickly use the increment operator instead of saying for example if num3 is ten if you want to increase it by one one way is to do it as num3 equals num3 plus one right instead of being that much verbose you can use the increment operator and just say num3 plus plus so num3 is ten we did a num3 plus plus and we're displaying it here num3 which is 11 so plus plus increases the value by one so the increment operator has a some variety that is a plus plus that you can add in front of the variable so here we did num3 plus plus but here we have plus plus num3 right num3 we already know as ten plus one 11 and now we are doing another plus plus num3 which makes it 12 so the result of this statement is 12 num3 equals 12 when you look at just num3 plus plus or plus plus num3 you can't really tell the difference on what's going on which is why i have further statements here there is a subtle difference between what happens when you put the plus plus as a suffix and a prefix so here we do the same increment operator but within an expression right so we have num4 which is initialized to phi and we are creating a num5 and we are saying two into num4 plus plus so num4 is five five plus plus is six and then two into six is 12 right but we have 10 how come that's because if you have a variable that it uses the increment operator as a suffix that increment is done after the expression is completed right so in this one we had two into five ten that got stored in num5 and then num4 was incremented that's why we have 10 this is where the difference between the plus plus prefix and suffix come in because we have similar statements here we have a num6 assigned to five and num7 two into plus plus num6 in this case plus plus happens first before the expression executes right so five plus plus becomes six two into six 12 so that's the subtle difference between where the plus plus is added if you want the increment to happen before the value is used in the expression you have to put the plus plus before the variable if not you you put it after the variable and just like increment there is also a decrement operator which is what i added as a comment here instead of adding more statements into this class but num3 minus minus would reduce the value by one minus minus num3 is also the same thing but the difference we talked about where the plus plus is added here is also applicable to minus minus finally we have something called a component operator this is more of a convenience thing let's say we have a num8 initialize to eight right and we want to multiply that value by 10 but we want to store that result in num8 right so normally what we would do i'm going to add the line here but i'm going to comment it out so it's easy to follow so we would do num8 equals num8 into 10 right instead of doing this there is a component assignment operation where you can say num8 star equals 10 which means we're telling java hey multiply num8 by 10 and assign the result into num8 itself which is why you see the result here as 80 num8 got multiplied by 10 and the result was stored in num8 and that's what got displayed here and just like we saw it with increment and decrement the component assignment operation can be done not just for multiplication but for addition subtraction division and the model is operated as well before we finalize or finish this video i wanted to talk about the importance of comments again that we talked in an earlier video comments really help understand what the program is doing right by adding these comments you can clearly say what that block is doing instead of having to look into the code to actually see what's written and understanding and same way if you come down here all these comments help understand what the programmer in you know is intending to do in the program which is why adding comments to the programs is very important even if you do this program and look at it later adding these comments will really help you understand the program quicker than having to go into the code and kind of try to understand what's being done i would really recommend you to try these operations i'm going to leave these out as exercise you can create this class as it is but then you can create new variables and try the decrement operator which doesn't have an example here and also all these other components in my operator just to get an understanding of how these operations work you know because when you do much more programming later these operations would be used very frequently so it's very important to get a good understanding of when to use the operations and how to use the operations um that will really help you thanks a lot see in the next video hello welcome back in this video we're going to learn about methods methods are nothing but kind of like a subroutine that you call to perform a specific function so you can reuse that subroutine whenever you want that function performed we're going to create a new class called method test in section two method test we'll create our main method and let's say we want to perform a calculation operation right we want to add two numbers let's go ahead and define two numbers right number one equals 10 int number two equals 20 we can always say int um result int result equals number one plus number two and then we can system dot out dot print a land that right this we have seen already I just quickly run it run Java application so we got 30 right but what if we have let's say 100 of these operations to be performed or 200 of these operations to be performed we don't want to repeat this statement 200 times right because later if you realize that your calculation should not be an addition it should rather be a multiplication for example you don't want to go and change 200 of those statements right it would be nice if you can keep that calculation elsewhere right and reuse that calculation so that if you have to change your calculation formula or something later it's easy to change that's basically the concept of a method right let's see how we can create something like that so after the main methods colibrace create a public static we will learn what static means in a in a later in a later video but for now just follow along we'll just say public static int calculate I'm going to explain what all this in a little bit and let's just type int number one int number two and in here we want to calculate this right so let's just go ahead and copy this guy and then paste it right here so we are doing the calculation and we need to do a return result so what's going on here so public we always make methods public not always but for now we're going to make the methods public we're going to learn about this in a later video same with static let's just go ahead and type static for now int this means the method is going to return something so what int says is this method calculate is going to perform some action right some function and then at the end of it it's going to result an integer number right that's what this is saying which is why if so the return result performs that action right it returns the value if I comment this out I'm going to get an error saying this method must return a type of a result of type int right so int says the method returns something and then we say calculate which is the method name and then we have two parenthesis right within that we're going to say what are the parameters right what are the values that the method can't receive to perform whatever action it it can you know it is meant to do in this case we're saying the calculate method is going to receive two numbers both of them are type int that's basically what it is so public static return type int method name calculate and it's receiving two parameters number one and number two of typing teacher right and a method is always encapsulated within or the method body is always encapsulated within curly braces this is very important this is not optional and you say that you will type whatever that that method is supposed to do in here we want to calculate which is basically an addition of the two numbers coming in which is going to be stored in a result of type integer and we're going to we're going to return that result now keep in mind that just because this is number one doesn't mean whatever you are passing to it is number one we'll see that in a little bit we'll comment this out because we don't need this anymore but what we're going to do is say int result equals um type calculate see what you get so i pressed control space because eclipse can auto complete it so we said calculate number one and number two eclipse populates it because it knows number one number two are the two parameters right here we already have variables named number one number two this is what i was saying earlier these names need not match you can easily change them to num one and num two and your calculation you can change to num one and num two right and even this guy you can say result two return result two right whatever you have within the method for the parameters or even the return type return variable name need not match what you are passing in right that is a key to remember so we have two numbers we're saying call the method calculate pass the two numbers as parameters and whatever is returned save it in a new variable called result of type integer right and then we are printing it if you save it and then run it again you'll get the same result because now the method was called now if you change you can change this to a multiplication and run it again now you will get 200 so if we were to do 10 of these calculations right let's say i'm just gonna for example purposes i'm going to copy this guy right so i'm gonna we don't need to declare the variable again so i'm going to take that out so now we have three of them run it you get three times right so that's the basic idea the the activity is performed only once or the code is written only once and it's reused so it's easy to maintain and you know change it later if needed so that's basically the concept of method a method is just like a sub routine that is coded to perform a particular activity um so that you can reuse it in any place that's basically it um thanks for watching see in the next video hello welcome back congratulations you are in section three in this section we're going to learn about different execution control statements in java these statements help us specify if certain statements or a bunch of statements need to be executed only on a certain condition or if a condition is satisfied or if we want to have a set of statements that it execute more than once we would use these keywords in java let's go ahead and create a new java project so let's right click new java project are we going to name it section three hit finish and once it's created let's go and expand this under source right click again and do a new package we will name it com.java.tut that section three hit finish and under the package let's right click and create a new class the first statement we're going to learn as if else statements so let's name it if else and let's create our main method as well hit finish so the new class is created and a main method is created within that now let's say we want to have an integer say 20 and we want to display that the value is equal to 20 basically in the console if the if that condition is satisfied otherwise we want to display the number is not equal to 20 let's see how we would do that you'll see say if and then open parenthesis then you would do number equals 20 as you can see i put two equal signs as supposed to one equal because one equal means assignment you're assigning a value into a variable two equals means you're checking for equality whether something is equal to something you cannot have a single equal sign here that would be an error as you can see cannot convert because it's trying to convert so it goes 20 system.out.println number is equal to 20 right and then let's say else open callibrates again else means if the condition is not satisfied then execute whatever you give within these two callibrates so if the condition is satisfied everything within these callibrates will execute so here let's say it's system.out.println number is not equal to 20 and with the semicolon so we have two blocks here and then one block is going to execute if the condition is satisfied and the other is going to execute if the condition is not satisfied and just to remember or highlight something these callibrates are not mandatory if you have only one statement in the block so when i say a block this is the if block if if this condition is true this block is going to execute now if there is only a single statement within that block then you don't need the callibrates but it's always a good practice to include it because for anyone reading the code it's much easier to understand where a block ends if there is a callibrates always so in our programs we'll always include the callibrates even if there is only one statement let's save it and let's run it run as java application we got the statement our text displayed number is equal to 20 because this got satisfied so this was true this was executed so the else block was not even executed now let's change it to 10 and this time we would want this block to execute because this condition is not going to be satisfied any longer now let's run it again see what happens see now you get number is not equal to 20 so that's how we can control based on a certain condition what gets executed and what's not what if you have multiple conditions to check right so let's say we want to check if the number is less than 20 display something if it's greater than 20 display something or if it's equals display something now we're talking about checking for multiple conditions right because right now we have only one condition here now to do that let's say if number is equal to 20 we'll display this press some enters here now we want to check if that's not true that is if number is not equal to 20 we want to check for some other condition you can say else if number is greater than 20 again the curly brace you have to end that curly brace here so now we are saying if number is equal to 20 do this else if number is greater than 20 do something else do this so that's the slight variance of else you can add an if after the else to add more conditions and more blocks so now i'm just going to copy paste this guy here and here i'm going to say he's greater than 20 right let's change the value to 50 here and try to run it again now you get number is greater than 20 what happened here is you checked for this condition this wasn't true so this block was skipped came to here checked if number is greater than 20 of course it's true so we got this displayed and the else block was completely ignored so like this you can stack up as many else as you want checking for different conditions and if none of those conditions get satisfied else will get executed that's basically if statements if else statements are used a lot in java there's there's always situation where you need to use them it's a pretty simple concept but you may want to play with it a little bit to understand it more you can try adding more else if conditions to see how it behaves and then basically get more familiar with it but that's basically if else thanks for watching see you in the next video hello welcome back now we're going to start learning about loops loops are basically used to execute a bunch of statements more than once instead of entering those statements multiple times we will just specify them once but the loop structure will ensure that it is executed in so many number of times that we want them to be there are several types of loops that you can create in java we're going to start off by creating a wide loop let's go ahead and create a new class and name it wild loop create our main method so inside the main we're going to do a program that displays numbers one through ten just one two three four five six seven eight nine ten in different lines obviously one way to do it is do a system dot out dot print l n of one and then you can basically repeat this code ten times and say one two three through ten that will get the job done but that won't be very elegant loops basically help us do this in a simple way and loops are not just to display things i'm just doing this example to show how loops can simplify something something like this let's go ahead and initialize a variable to number one because that's where we want the display to start to do this in wild loop you will type wild open parenthesis within these parenthesis we enter a condition just like the if statement this condition says enter every single statement in this loop until this condition is satisfied so now the goal of this program is to display numbers one through ten so we want to execute until number is less than or equal to ten and this is how you will specify less than or equal to in java if you want to enter greater than or equal to that will be this and if you want to enter um equals as we already saw would be like this less than or equal to would be like this and not equal to is is a little different not equal will be like this with an exclamation and equal means not equal so it's just for your information so now we want to run this loop until number is less than or equal to ten because we want to number display numbers one through ten now in here we want to display the actual number so let's just copy this guy or cut it and paste it here but here instead of displaying number we want to display i mean the number one you want to display whatever value is in the number variable if you run this let's go ahead and run it just to show you run as java application as you can see we are constantly executing not stopping at all it's a simple program but it keeps running i'm going to stop it real quick and then explain what happened here this is what we call an infinite loop because this type of loop never ends why did that happen because we came here we initialized number to one we are going to execute until number is less than or equal to ten so one is less than or equal to ten we displayed one and then the way loop works is the control goes back again here so whatever you enter within these curly braces will keep executing until this condition is true now since the value in number doesn't change at all this condition is satisfied every time around and we keep displaying and the loop is infinite we don't normally want to create infinite loops at all it is used in some cases like games and all where you keep playing until you for example die or the player dies but in general programming we would normally not create an infinite loop so you need to be very careful about it it won't do anything to the computer it just will keep running you don't normally want to create infinite loops so whenever you create a loop make sure the loop will end at some point coming to our loop the only way it can end is if the number goes over 10 for that happen we have to increment number by one each time so when we run first we'll display one the number will become two two will be less than or equal to ten so we'll display two so we'll keep going until we get to 11 where 11 will no longer be less than or equal to 10 the loop will end at that point let's save it quickly run it to see if that happens there you go because they output one through 10 so using loop we created something very simple that got the job done instead of repeating the same statement multiple times that's basically the idea of loops and as I said earlier there are different types of loops that you can create in java there's just one way of doing it in the subsequent videos we will see the other types thank you see you the next video hello welcome back in this video we're going to learn about the second type of loop called a do while loop let's go to create a new class and name it do while loop and create our main method if we quickly go to the while loop that we created earlier we basically entered a condition here and the loop executed until the condition is true right so if the condition is not true the very first time around let's say this value is 11 let's go ahead and run it to see what happens we got nothing displayed that was because the very first time around when this condition was evaluated it wasn't true so nothing got displayed so that's how while loop works this is where the difference between a while loop and do while loop comes we can create the same program here and we can say number equals 11 and the structure of do while loop starts with the do obviously and the call your brace the while keyword and the condition comes at the end of the loop so we can say until number is less than or equals 10 so the condition is the same way the only difference is you need a semicolon here because the whole thing is kind of like a statement we can enter system.println and within that number and we can do number plus plus also just like the other code save it now if you were to run this so we do a right click run as job application we had 11 displayed but then nothing else after that so for the same initialization and same condition we got something displayed in do while whereas in while loop nothing got displayed this is the one and the only difference between a do while and the while loop with the do while all the statements within the loop will execute at least once because the condition is evaluated at the end of the loop as opposed to the beginning of the loop so if you have any situation where you have a set of statements that should at least execute once before the condition is evaluated then you would use a do while loop otherwise you would just do a while loop so that's basically the difference between the two loops you can play with it now we can also create the same program that we created there so if we initialize number to one and run this again you would get one through 10 so we had the same result as the previous program as the while loop program if you had the same initialization but the difference comes only when the condition is true or not true even the first time around so that's basically the difference play with it play with different initializations and see what happens but this is basically do while thanks for watching see you in the next video hello welcome back in this video we're going to learn about for loops it's another type of loop in java let's go ahead and create our new class and name it for loop create our main method hit finish now in this video we're not going to display numbers one through ten like we did for while loop and do while here we're going to try to use arrays that we learned about in earlier section we're going to use an array we're going to put a bunch of numbers in that array and we're going to use for loop to display whatever numbers are stored in that array in into the console right let's go ahead and create a new array if you remember to create an integer array you would type int then the square brackets then you need to give a name for the array let's name it numbers and to initialize the array you would use the coli braces and put a bunch of numbers in there so 22 34 54 66 78 so there are fine numbers in the array and we're going to try to display the numbers using a for loop to do that you need to execute a loop that will execute five times and each time it will display whatever value is stored in the array in that position so if you remember arrays always start with zero position so this is zero one two three four so the loop will execute five times and each time it will display the value stored in that particular position now the syntax of the for loop goes like this it would be far and then open parenthesis there are three sections within this parenthesis for a for loop so i'm going to type the two semicolons which separates each of those sections in the first section you would give whatever you want to initialize whatever statement you want to execute only once so if the loop executes five times whatever you type in the first section executes only once when the for loop starts executing it doesn't execute five times so here we want to we want to create a counter or something that we would use to traverse this array right so let's define an integer let's name it i and give an initial value of zero because the first position of an array is zero so we want to start at zero the second part in the for loop is basically a condition just like the conditions we saw in y-loop the loop would execute until that condition is true same way here we would specify a condition until the condition is true the loop will keep executing and in this case we want the loop to execute five times because we have five numbers here we can type i less than five keep in mind it should be less than five not less than or equal to five because the positions are zero one two three four right so we don't want to execute for the fifth time there's only fourth position in the array in this array so we could do this or there is another better way to do it instead of hard coding five here we can actually derive the the length of the array or actually get the length of the array automatically to do that you would type numbers which is the name of the array hit a dot eclipse will give you a list of options you see this length here length returns the length of the array so if there are five numbers this would return five if there are seven numbers it would return seven so this way we don't need to hard code five later on if we add more numbers we would have to come in and change here otherwise if you use numbers dot length or array dot length you would automatically get the size of the array or length of the array so that's our condition we want the loop to execute from zero to four and we got that covered here the third part here is basically a statement that will execute each time in the loop right every time the loop comes back the statement would execute this would normally be your counter so right here we incremented each time because we want to get out of the loop at some point same way here you could specify i plus plus for the loop section you would hit a curly brace whatever statement you enter within these curly braces would execute for each iteration of the loop and in here we want to do system dot out dot println numbers open square bracket i and then end it with a semicolon let's save it so just quickly run through this the first time when this executes i would be zero zero would be less than numbers dot length five so zero would be less than five that time i plus plus does not execute the very first time it wouldn't execute so when it gets to the loop body we're going to display numbers of i so numbers of zero which would be 22 and when the loop goes back up the statement would not execute but this statement would so i would become one one would still be less than five so we're good now we would display numbers of one which would be 34 so one and so forth now let's try to run it to see if we get that output so right click run as java application there you go we got 22 34 54 60 and 78 displayed in that order now you can change numbers here or add numbers since we use the numbers dot length you don't need to change anything else save it just run it now you got all those numbers displayed so that's why numbers dot length is much more convenient and flexible than entering the actual size here so this is for loop but actually there is another type of far you can do when you want to traverse an array it's called an enhanced for loop we will look at that also here and you try to use the enhanced for loop to achieve the same output right i'm going to go ahead and quickly comment this out because we're going to try to do a different type of for loop to get the same output i'm going to clear the console now i'm going to type a comment to say this is enhanced for loop the enhanced for loop goes like this it would still start with far there are only two sections in enhanced for now this is an integer array right so let's go ahead and type int number and then a colon not a semicolon and then numbers i'll explain what this is in a bit let's open a curly brace and close it and within that we're going to just display number this time of number let's save it quickly run it to see what we get there you go we got the same output from 22 to 79 whatever we got earlier but this enhanced for is much more simpler than this one in here what's going on is we're defining an integer number and this time we are going to use it not as a counter like we did earlier but actually to get the number from the array right so when java executes it knows this is an integer array and this is an integer so for every iteration of the loop it's going to assign that position's value from the array into number so the very first time it executes is going to assign 22 to number and it displays that the next time it would be 34 and it displays that so on and so forth until 99 so java automatically knows what position of the array it is in for each iteration and it will assign that particular value to this and we're trying to display that value so we get the same output as earlier so to traverse an array you can easily use enhanced for and write simpler code that would basically take care of counters and everything for you and this is not only limited to integers you can use for any type of array even an array of objects it would it would work just fine so that's basically for loop try to play with both these types of loops because this would you would use when you want to traverse an array for every other situation you would use this for loop so both of these for loops are very widely used in java so play with it make sure you are much comfortable with it because for loops is something that is very frequently used thank you see you in the next video hello welcome back in this video we're going to learn about two statements in java called break and continue we're going to see how they're used in loops and what is the difference between the two of them let's go and create a new class and we'll name it break and continue create our main method and in here first i'm going to create a for loop that displays number one through ten right so it goes like four and then parenthesis the first one is your initialization which would be int let's use the number i number one so we want to display number one first the second part is the condition if you remember so that would be i less than or or less than 11 or less than or equals 10 the third one is the expression that executes each each loop iteration and we want increment i by one right and in here we want a display value and i of i right so if you quickly run this you would get numbers one through ten hopefully there you go with it i'm going to expand this a little bit now let's say for break we don't want to display anything more than five right to do that you could technically just enter five here but we're going to see how to do it with break so once you encounter five we don't want to display any longer if that's the case and if you want five displayed you would type the code after the system is not out but if you don't find one five you type it here let's say we don't want five so if i equals if you remember the equality is two equals five we want to break let's quickly run it to see what happens so you got one through four and then nothing else so what happened here was when i become becomes five this condition is true and what break does is it totally breaks out of the loop where it's coded when you highlight break eclipse highlights which block it belongs to so break basically takes the control out of the loop right again like i said depends on where the break is the program would execute that way but all break does is take it out of the loop so if you run it now you would get number five which displays here first but then we check for equality and then we break so that's basically break if you encounter a particular scenario in the loop where you know you don't want to execute the loop any longer you would use break now this is where the difference between break and continue comes continue basically just keeps that iteration of the loop but still keeps the control within the loop whereas break completely takes it out let's do an example to see what we're talking about so let's take the code and put it back here where it was now let's say our goal is to not display five you want to display everything except five which means when i becomes five we don't want to do the display but we want to take the control back here to increment i to six because we want six through ten displayed anyway right so if you hit comment this out and say continue let's run it to see what happens so you got one through four there is no five but six through ten that's the only and biggest difference between break and continue break takes the control out of the loop continue just keeps that iteration so when i became five continue was encountered the rest of the statements in the block for that particular iteration only is ignored and the control goes back here where i become six right and when it comes here i equals five would not be true any longer six would not be equal to five so continue will execute only one time when i is five and we are skipping the printing so that's the difference between break and continue you would use one or the other based on what your needs are try to play with this you can you can change the counter here or you can add other conditions to see if you can skip some iterations or you want to you know break out of the loop try different scenarios make sure you are comfortable with it but that's basically break and continue thanks for watching see you in the next video hello welcome back in this video we're going to learn about switch case statements switch case statements basically let you check if a value stored in a particular variable is something and if it's true do some execution or execute a bunch of statements and then if the value is something else do something else so in that case it's kind of similar to if else but if else let's see you check for different conditions but switch case basically let's you check for only equality if the value is this but switch case makes the code a little more readable if you have to write a lot of those equality conditions you would keep writing if you do it in if else you would have a lot of else if blocks but switch case lets you do it in a more readable way and it gives you a little bit of flexibility too which i'm going to show let's create a new class and name it switch case and create your main method and in here the goal of this program is going to be to take an integer which can have a value of one through seven and if the day is one we will display it's Monday if the day is two we'll display Tuesday and so on now let's see how to do it with switch instead of the if else the syntax goes like this you type switch just follow along i will explain a little bit and then within parenthesis you will display what is the variable you are checking in this case it's day so type day and then as always you have curly braces to define the switch block now inside that this is where the second part comes which case right the case so you type case and say one and a colon in here you can type system.out.println it's Monday you need a break here i'll tell you what it's for in a little bit and then you type case two system.out.println it's Tuesday now from and then a break obviously and from now on i'm going to just copy paste so you don't have to wait to see me type the whole thing four five six seven i'm going to paste again i'll explain a little bit why and this is going to be three as you can see you're going to check for the same case java alerts you cannot add a duplicate case so four five six seven and this is going to be something called a default for now just follow along make sure you have all this code i'll explain what's going on here Wednesday it's Thursday Friday Saturday then Sunday and in here i'm going to say please enter a valid day from that state when you probably guessed what default does but let's try to run this program see what we get and then we'll go into the details so right click run as java application so we got it's Monday and the day is one so we got the output let's change it to four run it again it's Thursday which is good so it works so what's going on here we said switch day so it's going to look for what value stored in day variable and we're saying if the variable has one that is case one display these statements if the day is two display these statements and so on and so forth now if you change this to 10 and then run it you're going to get please enter a valid day so if none of these cases were true then default would execute but if any of these cases were true default wouldn't right so that's what the default is it's basically like the final else block that you write without any condition which would execute if none of the other if conditions were satisfied and why do we need the break so the way switch case works is once one particular case is true it would just start executing all the statements that are coded here right if you don't have a break so let's change this back to one or let's change it back to five right and we want it's Friday displayed but let's remove this break and see what happens run it oh now you got it's Friday and it's Saturday what happened here was when case five came true Java just started executing all the statements it executed this and then there is no break so it executed this so at that point that is when a particular case becomes true Java starts checking for cases and it just starts executing all the statements so if you don't have a break it will just continue executing everything it would even execute what's in default until it encounters a break or encounters the end of the switch case block itself this can come in handy for example if the goal of this program is once a particular day becomes true display what are the remaining days in the week right so once Wednesday becomes true display Wednesday through Sunday what are the days that are qualified in that case you could easily do this which you cannot do and if that's the flexibility I talked about by just taking out the breaks you can just display Friday Saturday Sunday if that's your goal right but if it's only Friday that you want then you just include the break and the program will automatically start executing that way so that's basically switch case and we used integer here you could use characters which is the single character variable or strings also you cannot use any other type in switch case but switch case helps in a lot of ways to create readable code it's it's very flexible as well if you have special special requirements like executing multiple blocks once a case becomes true so that's basically switch case thanks for watching see you in the next video hello welcome back now that we have learned about loops I just wanted to do a video about nested loops nested loops are basically loop within a loop I wanted to make sure we do at least one program that way so you can understand loops don't have to be just a single one out there and let's see how or when we would use a nested loop let's go ahead and create a new class and name it listed nested loop with the main method now I'm going to show you first on what we are going to try to do so you don't need to type I'm just going to do this to show you what is our goal in this program so I'm going to just add a comment here so that's our desired output right first line would be one asterisk second line would be two asterisk third line would be three four and five right and you can go to 10 20 doesn't matter but that's our structure now to do it you could obviously do five system dot out dot print a lens and then the first one would be one asterisk second would be two and so on but what if you wanted to do this 100 times you don't want to type that min system dot out and this is where we learned earlier loops come in handy but if you see what's going on the first line executes one time the second line executes two times third executes three times how can we achieve this with loops so let's start with a for loop for an open parenthesis and we want to start with the variable initialize to one because there's one asterisk here and this is the first line and we want to execute five times so let's that equals five right and then we want to increment i by one each time i plus plus right now we want to display one asterisk in one line two in second line which means for each of these lines here we want to execute something multiple times because the first time it runs it will display only one but the second time we want something to run multiple times to display the asterisk that many number of times so here's a clear example of where you need a loop within a loop because the goal of the first loop is to keep track of the number of lines but the goal of the second loop would be to keep track of how many asterisks are displayed in each of those lines let's go ahead and create another loop for now this time we will use j right we will initialize that to one right but in this case we don't we want j to execute the so many number of times where it's equal to i what do we mean by that so let's say i defines their lines right one through five and j defines the asterisks now second line has two asterisks the line has three asterisks right so if j denotes the asterisks j cannot execute more than what the value of i is if i is three j can execute only it's three not more than that i'm hoping you understand what i'm trying to convey here let's go ahead and type let's down equals i which is executed and then we can go into much more details and we want to increment j also by one each time now in here let's do system dot out dot print ln or actually print it should be print because after each asterisk you don't want a new line right only at the end you want a new line so let's just display an asterisk i'm going to execute this and then show you without a new line how it looks let's right click run s jav application we just had asterisks in a single line that's because we never told java where we want the new line where do we want the new line we want the new line after each line of asterisks is completed right and each line of asterisks would be completed when this loop is completed so if you want a new line print ln we just want an empty string displayed because we don't want anything displayed on the screen we just want a new line on the screen let's run it again to see what happened there you go we got the output so i is one through five which is the number of lines but j keeps track of the asterisks and we got the output that we want now if we can change it to anything we want we can change it to 50 and run it and you would get that many so you can see how loops are pretty cool from this you just had to change one line or just one counter and you can alter the output any way you want so that's basically nested loops which makes it easy for us to iterate and then do whatever we want instead of typing statements over and over and this is where nested loops are used where you have multiple activities happening and you want to keep track of multiple iterations you would use nested loop so i would really encourage you to try different variations of variations of these and try different possibilities of nested loops to to to basically understand how these work so that's basically nested loops thanks for watching hello welcome back congratulations you are now in section four in this section we're going to start learning about object oriented programming concepts and how they are done in java so far we have created classes in other videos but we have not really learned what a class is for what its true purposes for and what are objects and we're going to be starting to learn those right now let's go ahead and create a new java project for this section we'll call it section four hit finish and we're going to create a new class we're going to name it employee and we're going to create a new package java to that section four we're not going to create a main method i'll explain why hit finish so what we have done is we have created a class call employee what exactly is a class a class is nothing but you know there are different terms blueprint a template something that's like a model like a type and an object is is a real world thing right there could be multiple employees john tina and so on right but all the employees have some common properties like name their job title their salary and so on so what a class lets you do is to define those properties right that belongs to all objects of that type class right so that using this blueprint you can create any number of objects right you could create even thousand objects thousand employees that all share the same template that you define in the class there are two main parts in in a class they're called fields and methods are you know in in normal terms it's like a state and behavior right what it basically feels fields are the properties that we just talked about we're going to start typing private in the later videos we're going to learn what this private means but just for now just follow along private string name so what we're saying is any object of type employee will have a name right so we can also say private string job title each employee has a job title and all these properties need not just be string right you can make it private double um salary because each employee can have a salary so we created a class employee with three fields that define or that belong to an employee right all classes have something called a constructor constructor is a special type of method so public employee note that the name of the constructor is the same as the class name right that's what makes it a constructor we'll we'll do the parenthesis and then we're going to say string name string job title string salary i just noticed that this was a column before so okay there you go so public employee has three parameters that match the three fields right so it's basically a method which can receive these parameters and the purpose of a constructor is to initialize the object right so if you were to create a employee object john you will call the constructor and pass the name as john pass the job title as analyst and so on and pass the salary like five thousand ten thousand or something like that so when these are received we need to set them to the fields now if you do name equals name it wouldn't make sense you will get a warning say is dozen meant to variable name has no effect because we're not there is there is an ambiguity here because the property is also name and the string parameter that comes in is also name right so how do you differentiate there is a special keyword in java called this so when you say this you're talking about the object that you're working on right so this statement means for the object that you're creating set the property name to the parameter that came in right same way you can do this dot job title equals job title and then you can say this dot salary equals salary so that's basically what a constructor is um type this match oh sorry about that there should be a double um very sorry because um salary is a double so the parameter should also be double sorry about the mistake so that's basically what a constrictor is now apart from the constructor right a constructor is basically called when you create the object we're going to see that when we create an object of this type employee but for now just remember that but once you create the object if you were to change the value um of of an employee change the name of an employee is change the dot title of an employee or if you want to retrieve the value right what is the current objects um name and stuff like that we need we need methods to access these values right that's what we call a getter and setter a getter basically gets the value and a setter basically sets the value now in eclips there is a shorthand for version or way to get it if you go to source generate getters and setters so you i did the right click went to source generate getters and setters right eclips automatically gives you the three fields that you are working with just do select all and then hit okay so eclips created some methods for us let's see what they are so for name it created a get name which nothing but returns the name itself which is where the written type is string um there is a set name which receives the parameter name and says this dot name equals name same like here right but the written type is void because nothing is being returned so similarly we got the get job title and set job title and get salary and set salary so these are the methods through which you can access the fields right so any class you create will have a set of fields and set of methods to access them so that's basically class class lets you create a template with properties and methods so you can create any number of objects for them so if you made it this far that's great um in the next video we're going to create some objects from this class and see how to call these methods and so on but that's basically what a class is thanks for watching see you the next video hello welcome back in this video we're going to create some objects of the employee class that we created in the previous video um we didn't create a main method last time because this class has nothing to be executed right we just created a template which is why we never created a main method we never intended to actually run from this class but in this video we're going to create a new class we're going to call it employee test so this is a class that we're going to use to test the class that we created which means we need the main method so here for the employee class or employee type we're going to create some objects and the syntax goes like this starts with employee which is the class name we'll name the first one EMP1 to denote employee one right just like how we did in arrays you would need a new so which means we're creating a new object right and then type employee and let's see what happens employee two parenthesis then semicolon we get an error what does it say the constructor employee is undefined now if you quickly switch back to employee class we created a constructor that accepts three parameters right we never created an created a constructor that can that you know receives no parameters which is why java is not able to find it so the the only way this would become valid is if you actually pass the values let's say we are going to create an employee object for john and the second one is or the second parameter is the title and the third is the salary so let's call make him an analyst and let's give him a 10 000 salary i make the same mistake again it's not a string it's a double so the employee john is a new object who's an analyst with a salary right now if we quickly go back here we created some methods to get the values right we can do a get name get job title and get salary so let's try to get the name of emp1 and display so system dot out dot println emp1 dot get name as you can see eclipse is automatically giving you the options it knows what are the methods defined in employee and it gives you those options we want to do a get name and with a semicolon right let's try to quickly run it run s java application john so we were able to create a new employee object from class employee and give it some parameters and use the method to get the value right now we also had a sit name now if i were to change emp1 that sit name to tina and now if i try to do a system dot out dot println emp1 dot get name and run it again as you can see the name was john but then we use the set method to change the name now emp1 name is tina so that's what setters and getters lets you do basically set the values and then retrieve the values now if you write a type emp1 dot you see all these methods but you never see the parameters that you define here because that's the significance of marking something private if you mark something private you cannot access it directly from another class the only way to access those values set us set or get those values is using the methods right that's something to remember if you mark something private you can only use the methods to access them you cannot directly access the access them from outside same goes for methods also if you make a method private you cannot access it outside um so you need to remember that now what happens if we try to display the entire object so just like how you create when you created an integer variable you would just put it in the system.out and it will display the value let's try to do system.out.printl and emp1 right we're not calling any method we're just giving the object itself run it it has java to its section 4 employee and then some number this is basically the reference value or the memory locations stuff like that um java doesn't know what to display when you just give the object here right it doesn't know how to how to display the parameters what are the parameters you want displayed did you want just the name displayed or did you want all the parameters displayed java doesn't know right you need to tell java what to display now that is a special method to do that if you go to employee class you can create a special method to display whatever you want to display the syntax of that is two string so this is the syntax two string that is a shorthand way to create it if you right click in eclipse go to source find generate two string it's going to ask what are the fields you want included in the two string or what are the fields that you want returned now we want to display all the values when the object is displayed so we'll just hit okay so it created a two string method that returns a string right so this is the return type string and what this does is basically concatenates or puts together some string and then the actual value name and then some string job title and then the actual parameter or sorry field and then salary the actual field salary all we did is create this ignore this at overwrite for now we'll explain in a little bit but now if you're ready to run this you got employee name equals tina job title analyst salary equals 10 000 just like that all you had to do was create a two string in class when you do that java automatically knows when you try to display an object to call the two string and basically get the value that is returned or get the string that is returned and display it so that's that's basically two string which will be used a lot when we try to see what's what's in an object you just call the object that but you define the two string so that's called automatically the same way you can create emp2 emp3 and so on i would really like to encourage you to create you know several employee objects using this class try to play with the with the methods and then see see how they behave but that's basically object an object represents something real right an actual employee and you can create any number of objects when you have a class defined that has a set of properties and methods that that define an employee that's basically object in the next video we're going to go into a little more detail about some of the things we did not explain because the focus of this video was just to understand objects and how to how to interface with them but that's basically it i would really like to encourage you definitely to play with it but that's basically it see in the next video hello welcome back so we learned how to create a class and create objects using that class in this video we're just going to go a little leap into some of the things that we wrote so that we get better understanding of that before we move forward and learn more advanced object oriented concepts right the first thing i wanted to explain is this thing string that we used we did not learn what string is before right we've learned about primitive types so string is nothing but another class just like employee so employee is a class that we created string is a class that is already there available for us to use right it comes with java by looking into this you will get understanding of you know how you can create classes that you can use over and over right so string is a class if you right click and do open declaration eclipse will open it for you and it will show you the class that was created in java already right that we are using this is a class that you can use to store like we already saw a string value a series of characters right so that's the type we used in stuff int double we used a string type because name and job title can be a series of characters as opposed to just a single character right so that string class we will do another video where we will look in detail on what string class has to offer but at this point i just wanted to show that string is another class that we can use and it's one of the most widely used classes and i wanted to kind of explain that since we did not see the type before so we can close this but if you're interested you can look through this to see what are the methods that are defined in this class so that string the second thing i wanted to show is the constructor so when we try to create let's try to create an emp2 right emp2 new employee right let's not give any parameters and see what happens we saw that that we saw an error right the constructor is not defined because if you have a constructor defined with parameters but you are trying to create an object and want to call an empty parameter constructor right you may want to do this because when you create the object you may not know what the name is going to be your job title or salary right so you may want to just create the object and set the values later using the set methods but for that the empty constructor is not available to be able to do it you need to go and create it you can have eclipse created so if you click this create constructor so eclipse will take you to the employee class and it will create the constructor for you now if you come back here the error will disappear so if you have a parameterized constructor this empty constructor is something that you will have to manually create but if you'd have no parameterized constructor or if you have no constructor defined at all then java will automatically create this empty constructor right for you you won't put it in the code but it's it's implied so if i just quickly comment this out right i'm going to comment out all the constructors right i'm going to save it i'm going to quickly switch back to here where we're going to get an error because this constructor is not available anymore but you don't get any error here that's because if you have no constructors defined java will create this empty constructor automatically for you it's kind of implied only when you create a constructor with parameters deliberately you have to create this also java doesn't create the empty one at that point so that's a difference i wanted to show because a constructor is not a mandatory mandatory thing that you have to create right if you know that you will never set the values when you create the object you will only set at later point then you don't need a parameterized constructor or any constructor for that matter so that's the difference i wanted to show so i'm going to quickly remove the comments since we kind of like learned about it now the error is going to go away because the class is now or sorry the constructor is now available um apart from that these private things and public they are called access modifiers these would be much more easier to understand when we learn about inheritance that's that we're going to learn soon but in the coming videos we're going to learn about these access modifiers and how how they they kind of control you know how the things are visible or not visible so those are the things that we could not do in the previous video kind of learn so i want to do this video just to explain those things in the next video we're going to learn about more advanced object oriented concepts but this is basically it thanks for watching hello welcome back now that we have learned about classes and objects we're going to learn another important concept in object oriented programming it's called inheritance so inheritance in object oriented programming is when you inherit a class within another class just like the regular inheritance meaning where you you get some stuff right for free when you inherit a class from another class you basically get whatever is defined in the main class which is also called the parent class into what you are inheriting into which is called the child class right so if you have an employee class defined here employee has name job title and salary and a bunch of methods defined for the class you could inherit this class into another class like directors or managers right who are also employees so whatever properties you have here still makes sense for them but if they have some additional stuff like bonus if it's applicable only to directors and managers and not employees which would suck but for example sake if they have stock options right if they have an office stuff like that right if you have additional parameters that are applicable to somebody but still these common parameters are still going to work for them you can inherit manager from employee so that manager will get all the parameters and methods automatically so you don't need to recode them right that's that's where the reusability comes in where you can inherit from an existing class but add more stuff to the to the child class so let's go ahead and create a new class called manager so we'll name it manager now here you have something called super class we are not going to use it now but i just wanted to highlight it here you you can very well go to the browse and then choose employee right because we are inheriting from employee and the eclipse will automatically create the code for you but we'll just type it out i just wanted to show you that option where eclipse can do that for you right and manager is not a class we're going to run which is going to create the subclass or the child class so let's go ahead and hit finish we have a manager class created now to tell java that you want to inherit from another class you would just type extents employee so extents is the keyword to tell java that you are inheriting from this class right just by doing it now manager will get to know about everything that you have defined in employee right and you can just add more stuff to it you just add private double bonus pct right so we're adding a new new field to manager where they have a bonus percentage right let's go ahead and create the constructor we'll just do the automatic creation from eclipse to show what it creates so go to source we want to generate constructors from superclass let's click it hit okay let's see what gets created now we have two constructors created one is the empty constructor like we discussed before and the other one takes a bunch of parameters right let's go ahead and delete that to do but then here we have a new keyword called super right we know it's a keyword because it's highlighted by eclipse so super is a keyword just like that this keyword we saw if you will switch back to employee we saw this this keyword right it's similar in the sense that it's also a keyword but there is a big difference between the two this reference says the object that you're talking about right so you can access the fields and stuff but super here just references the pattern class it doesn't talk about any specific object so that's a big difference between the two so when we say super off what this means is when the code comes here call the call the constructor in the superclass which is the pattern class so these are the terms pattern class and super class mean the same and child class or a subclass mean the same so a super super off calls the constructor in the pattern class now here we have a manager constructor right that has only three fields and using the three fields we are calling the pattern constructor or pattern classes constructor that takes the three fields right but for a manager we have in fourth field bonus pct which we would want to pass in so let's go ahead and create double bonus pct and just like how we did in in employee class we would want to do this dot bonus pct equals bonus pct so we're saying for the parameter coming in just assign bonus pct field to that value right that's basically it now we have created a fully functional manager class that has all the fields that we have in employee and also a new field bonus pct that is applicable for manager let's go ahead and test it let's create a new class and now let's call it manager test we obviously want to run it so we'll create the main method hit finish now here you can go ahead and create a new manager object so manager mgr1 equals new manager off so manager can be paddy top title is let's say senior manager um your salary could be 30 000 and then bonus percentage let's say 10 percent right that's basically it just by doing this we're calling the constructor here which in turn calls the pattern classes constructed to initialize the three fields and then initializes the fourth one to this this is this value that we passed in now we can do a system that out dot println mgr1 dot you can get you can call any of these fields right or you can try to display the entire object itself so let's try to run it so do a right click let's do a run s java application as you can see we have the three fields displayed right name job title and salary but not the bonus bcd that's because as we know when we try to display an object java will call the two string that is no two string defined here so it calls the superclasses two string which displays only the three fields right now if you want to display more information right or whatever is defined in the manager we have to create another two string here so let's go out and right click go to source generate two string let's go and create it for bonus bct hit okay but then right here you can just say you can just concatenate more stuff so i'm going to just do a colon to separate things out right and then just like how we used a super to call the constructor you can do a super dot two string hit save just to quickly recap we are returning manager information plus the the employee information right so the entire string is going to be returned and displayed again let's run it see what we get there you go now we have a manager which has a bonus of 10 and the employee information is displayed here so just by reusing the methods that we already had and fields that we already had we were able to create a new manager object just by adding only stuff that is newly applicable for manager but be able to use everything that is defined already so that's the power of inheritance so i would like to encourage you to create new manager objects and see how it behaves but in the subsequent videos we will go much more deeper into inheritance and other keywords that are applicable to inheritance but that's basically it i hope you were able to appreciate the reusability of it thanks for watching see you in the next video hello welcome back in the previous video we learned about inheritance in this video we're going to take a quick look about some things that did not go over in the classes in these classes but also learn a new concept called polymorphism which is another important object-oriented concept and we're going to see how that applies to java programming language here but before that let's go to the manager class there are a few methods that we did not create earlier we're going to create that the first obvious one is we did not create a gator and setter for bonus pct so let's do that so let's do a right click go to source generate gators and setters we'll select this guy and hit okay now that's done so we have the gator and setter for bonus now we're going to add a new method in manager right because now we have the bonus pct which is the bonus percentage it'll be nice to have a method to calculate the bonus for a manager right so we could do a public we want to calculate the bonus and return it so we want to return double and name the class calculate bonus or name the method calculate bonus sorry about that so in here we want to calculate bonus so we'll name it double bonus equals we will need to multiply bonus pct by 100 or divided by 100 into the salary right now we have the salary method or get salary method defined in employee which we can just call so you can just call get salary that's it and we want to return it right return bonus so we were able to use the get salary method that we are inheriting and just use the new bonus pct field to calculate the bonus and return it right now here after the manager object is displayed you can just say system.out.println and just say bonus for mgr1 mgr1 and just say mgr1.calculate bonus so this will basically call the calculate bonus get the value and then display it right so we have a 10 person here which means we want to display 3000 let's see if it works right let's do a right click run s java application there you go bonus from gr1 is 3000 and so we were able to call this method and get the bonus calculated right now we can actually type like this employee emp1 equals new manager now we know employee is a different class but manager is also a different class but you can use the pattern classes variable right type as a reference to a child class object this may be kind of like hard to understand but you can you can think about it as a parent type can always reference to the child type but this will not have access to all the methods that are in manager for example if you type emp1. there is no calculate bonus right because calculate bonus is defined in manager it's not available in emp1 but if you want to call it if you want calculate bonus to be available what you could do is go to employee right and then let's do a public double same method right calculate bonus but since there is no bonus bct here you could just say return zero right there is no bonus for the employee right now if you come back here and try to say emp1 dot you have a calculate bonus so if you have the method defined in the pattern class right and you also define it in the child class but you actually change the behavior that's what overriding is we already saw something like overriding in tool string right so we did the override because we are basically taking the tool string method from the parent class but redefining the behavior in the child class that's the same thing we have done here whatever you see here it's called an annotation which we will see in a later video but you could basically type the same thing just say we are overriding calculate bonus because it's defined in employee but we are overriding the behavior and giving new behavior here right now if we were to go back to manager test right we have an emp1 an employee type variable referencing a manager object right now let's try to do the system.out.println again here right so i'm going to copy paste we don't need this guy because we want to display it emp1 right so let's name it emp1 so bonus for emp1 is we are calling calculate bonus on emp1 right we obviously want to initialize some value here so let's give john now let's say this guy is a manager and the salary would be let's say 25,000 and a five percent bonus right let's try to run it see what happens we have it calculated perfectly right that's because java knows that although you have an employee type here the actual object is of manager type so to call the calculate bonus on the manager instead of the patent right this is the polymorphism concept where based on the object that the variable holds java knows which method to call instead of depending on the type of the variable so that's basically polymorphism you could define other methods in employee and overwrite it in manager and then try to call it but that's basically it the only thing to remember is the employee this variable cannot access anything that it doesn't know right if you did not add calculate bonus here emp1 did not know what calculate bonus is so it needs to know about the method or feel that you are referencing but as long as it knows about it java knows that the object type is manager so it has to call that particular method that is calculate bonus on the manager object and one final thing to to note about override in here if you do a override it makes sense because calculate bonus is an employee and it's overwritten in manager right but if you go to employee and you have an override annotation for two string it may be confusing because that is no extents here right we don't have anything extending we're not extending anything in employee so what does override mean here that's because by default all classes in java extend an object a class called object right so if you type extents object it's redundant because employee already extends object which is a class so you can just do a right click an open declaration it will open the class named object so this this comes shipped with java and automatically by default all classes extend object you don't have to explicitly mention it right now if you go to outline tab here which is a very nifty thing in eclipse it kind of gives you an outline of what a class what the class has as you can see there is a two string here so object class already has a two string right which is what we are overriding here so you might as well delete it because it's by default happening we're extending from object and that's basically what we are overriding here so this this is what i said earlier that we will discuss later and that's why we have overwrite here you don't need to specify it but it's good to have it to show that you are overriding this this method from a parent class and in this case the parent class is the object class and that inheritance happens by default so i hope that made sense i would really like to encourage you to add more methods in employee and then extend it in manager and see if you are able to access it but that's basically polymorphism thanks for watching see in the next video hello we'll come back in this video we're going to learn a little bit about packages because we've been creating packages so far we're just going to discuss about them a little bit and then we will learn about access modifiers right i'm going to open all these four so packages are something that comes as a first statement right and it kind of like is the folder or namespace like i mentioned in one of the earlier videos packages help group your classes like organize them right into different sections but they also come into play a little bit when you try to access classes right from some other package now what i mean by that is if you have another package here let's say a new package now let's call it comm dot java2 dot section 4 dot pkg2 right package 2 hit finish now we have another package i'm going to create a new class in here i'm going to name it package test right and i'm going to create the main method hit finish now in here let me try to create a new object of type manager right manager which is already a class that we have defined right in one of the earlier videos so i'm going to call it mgr1 equals new manager we're getting an error and it says manager cannot be resolved to a type so java doesn't know what manager we're talking about we did not have this problem earlier when we created an object of type manager in manager test that's because manager test and manager are under the same package so java knows where the manager class is but package test is a class in a different package so we need to tell java which manager class we're talking about because this manager class could be anywhere it could even come with java like pre-installed like the string class right so to do that we need to do an import as you can see we have options that eclipse is giving if you click this you will have this import statement we have not seen import before so it's pretty important to understand what it means we're basically importing the class manager right from a different package to tell java okay import the class from calm java to section four manager because that's the class i'm trying to use right so this is where package serves your purpose where package defines the namespace where the class is defined and you use it in conjunction with import to import classes or access classes defined elsewhere so here you could call the same methods right now you have so if you do it's called mg1 sorry mg1. so the calculated bonus is there you can access everything now that you have imported there's no difference between manager test and package test any longer because we're talking about the same manager class right so that's basically packages now i said we were also going to learn about access modifiers right if i quickly jump back to employee class we have these private defined we all have public on the methods right so these are called access modifiers what that means is it basically help control where a particular field or method is visible right so when we say private we're saying that method is visible or sorry that field is visible only to this class because if i go to employee test and then try to do a emp2 dot access the name we cannot access the name because name is private we were able to do git name right or set name because git name and set name are public which we can call but name job title and salary are all private so it's not accessible and if you make them public if you make this public and then go back here and then try to do a emp2 dot name that works right because now it's public you can access but that is really really bad thing to do we never want any of our fields to be public right the only time you can make something public is if you also make it final now final might seem familiar to you final is a keyword that we used earlier when we created constants right so if you want to create a constant at this class level so you can say public static we'll learn about static later final and then you can just say final we'll call a string um company name equals a b c right just for example purposes now note that i typed everything in capitals because that's the naming convention for constants so the only time you would want to make something public is if you are creating a constant or if you're creating methods right but you don't want any of your data fields public so that's the difference between private and public if it's public it's accessible only to this class if it's public it can be accessed from anywhere now there are two other access modifiers it one of them is protected so in here you can type protected uh watch another field you could call string um department right you could create a protected one um when you make something protected if you go to manager right so in here from let's find the constructor so here's the constructor let's try to do this dot name job title and salary are not accessible because they are private like we said private ones are accessible only within the class but department is accessible here right so that's the difference between so you can say department equals zero zero one let's say that's the only department right so we're able to set the department sorry department is a string protected so what's the error here can i be resolved this dot department oh we need to save employee sorry about that so now this dot department equal to one i did not save employee so java did not know what department i was talking about so this dot department equals zero zero one this works fine because a protected data field is accessible in the child class as well right you don't need to go through the method um there are some some scenarios where you would want to make something protected but ideally we would want all of our data fields to be private uh that's the third type so there was private public unprotected the difference is private is accessible only within the class public is accessible everywhere protected is accessible either within the class or in the subclasses right or the child classes the fifth one is um default right we don't type default because if you just type int what is what is something something else that we can type to an employee um let's call string location right we did not give any access modifier here which would make it a default right default is the fourth one if you don't specify an access modifier it's it's default when you have something like this it's accessible by all classes within this package right so you could go here and then type mgr1 dot department right so if you have something default it's accessible by every class within the subclass right i'm going to save all this to show the difference i'm going to go to package test right now i'm going to type mg1 dot and see what all i can access here as you can see i could not access anything when i say anything i could not access any field i could not access department i could not access location or anything because we are all together in a different package when you're at a different package you have no access to any of the fields right but if you are within the package you could access the default ones so that's the fourth one and default is also something that is not very uh frequently used ideally we would want to make all our fields private but if you know you have another class within the same package that would need access to a particular field you can go ahead and make it default right but there is no difference between making that or making something private and giving the methods so ideally we would want to make everything private and give methods to access it but that is the fourth type of access modifier you have which you don't have to specify but that's the default type and whatever you have default is accessible from all the classes within that particular package so that's where the significance of package comes and you know especially in relation to the access modifiers so hopefully that made sense please play along with it play with it add add more add more fields to manager make it different access modifiers and see that it's accessible but that's basically the four types of access modifiers that are in java thanks for watching see you in the next video hello welcome back in this video we're going to try to learn arrays of objects we have learned arrays in the earlier in an earlier video that we created an array of primitive types we can also create an array of objects we're just going to see how to create that now we're going to create an array of employees right so let's create a new class and we'll name it employees test just to show the difference between an employee test that we already have and create our main method and to create an array of objects it's pretty much the same syntax as the array of primitives so you would type employee square bracket to say that we're creating an array employees equals we will have our new keyword employee right and within square brackets we need to say how many employees right so five employees so that's basically it we're creating an employees array right and we're creating of length five right so you could just say system.out.println employees so same things that were accessible earlier like length are accessible here as well so just quickly save it and then let's try to run it run as java application there you go five right now we want to create these employees now if we cannot say employees of zero i hope you remember that array start at the zero index right so zero dot get name let's try to print this and see what happens right this is out if you type this out and control space you will get system.out.println so we're gonna copy this guy and then try to print it so we're trying to print the name of the first employee let's try to run it we get a null pointer exception we talked about exceptions where it's a bad thing something bad happened so here we get a null pointer exception because although we created five um five length of employees array we have not told java what those employees are we have not even created the employees objects we just created an array of five length now to initialize these you have to say employees of zero equals new employee of for the constructor you need to pass the values right now without doing that if you run it again you just get null because at least you don't get the exception but you get null because now you have created the object right you're not trying to invoke the get name method on a null object right earlier it was null so when you try to invoke get name you have you got an exception now employees of zero is a valid object and we're calling the get name on a valid object but the name itself is not defined so you just get a null so this is not an exception it's just a null value or no value has has been assigned to name yet now we can pass values so we can say john and then the second one is title analyst and then the third one is the salary 10,000 save it now if you run it you get john right so first we just had the array declared and then we had the first element or first index of the array right now defined to an actual object with values and we're trying to get name it works you can just call employees of zero which would automatically call the two string so if you run it again you get the two string right similarly you can define employees one, employees two, employees three and the employees four right so there are only five positions from zero to four you cannot for example you cannot say employees of six and try to run it you'll get an other index out of one's exception which we saw earlier because that is no sixth position right but up until four you can define um so you can just say employees of one this is something you can also do in a loop but i'm just trying to show how to define these employees one by one so you can just say employee now this time it could be mary who is a developer 40,000 right and then you can just say system.out.println or type sysout and control space employees one now let's try to run it we have john displayed and mary displayed so that's basically arrays of objects you will first declare the array and then you will initialize every single object in the array to an actual object and then you can call any method that you want to call in the object just like if you would call it if it's just a single variable instead of an array so that's basically arrays of objects um again try to create a loop try to send different values to them and try to print them but that's basically arrays of objects and how it works thanks for watching see you in the next video hello in this video we're going to learn a little bit more about the string class we use the string class of string type in our employee class for example we defined fields of type string the string class is one of the most widely used classes so i think it's good to spend a video just learning about that so we'll close this we'll create a new class and we will name it string test and the main method hit finish i'm going to define a string so as we saw the syntax before it's the type name the string let's call it name equals john so we can define another string string title equals programmer right so they are two different strings um when you create a string what happens is a particular memory location is allocated to store the string and the reference of that is stored in the variable right so if you create a string result equals name plus let's add a space here plus so what we're basically doing is concatenating the two strings right so this essentially creates a brand new string in memory and stores it to result so at this point there are three strings right created and stored in memory and we have references to to each of them we can print the result print a line of result if you save and do the right click run as java application you'll get john space programmer right so that's how string performs string is basically what we call an immutable type so if you create a string it never changes if you concatenate or you alter the string it always creates a new string in memory right we can test it by by doing this so let's create string um new result equals result right so what we are saying is create a new variable of type string a bit basically as in into the same string that we had earlier right now at this time if i change result equals one two three so result at this point has john space programmer and we are making new result point to result right same as result now we are changing result to one two three right let's save it and print so we have one two three now at this time if we person print new result let's see what we get so i'm going to copy paste this guy but this time i'm going to print new result run it as you can see new result still is john space programmer right just because we made this association right if you change result that does not change new result because it's an altogether new string because strings are immutable whenever you perform any operation it creates a new string right that is very key to there's a big key to remember right apart from these there are some methods in string class that are very useful for example if i do result or let's say new result because it's a longer string dot eclipse will show you all the methods defined in string class that you can use and there are a ton of methods so the same concatenation we did here with the plus sign you could do with this concat you could um you could check if a string ends with a particular um set of characters right if you can check if two strings are equal um things like that so there is also a length we saw earlier arrays had a length um but this is a length method that you can call so i can say system dot how dot print ln new result dot length right if we run it get 15 so john space programmer is 15 in length so the length method is is a very commonly used method just like there are several methods um that you can use i would really like to encourage you to um just play with some of the methods to see how they perform we did see the um equals so we're going to test that real quick because it's very important now we want to check if new result equals the result right earlier we learned the i'm going to create the if block we know that to check equality we did result equals equals new result right this is what we did earlier when we worked with integers right numbers and stuff but when it comes to string you cannot do this because when you check this it just checks if the two of them are pointing to the same memory location it's not really checking the equality right to check equality we will have to use the equals method that we saw right equals so this would be the right syntax so you're going to have to use the equals method i need to close the parenthesis here so you need to call rest result dot equals new result then you can print print ln results are or the strings are equal are the same something like that right if you run it you won't get anything output because we had changed result right now if i go ahead and comment this out and now i run it you get the strings are the same right that's because they're both pointing to the same location you can also say result equals john space programmer still the strings are same right so the equals method actually checks if the two strings have the same set of characters if if they are truly equal you cannot do a two equal sign to check um because that's a common error people make you need to remember to check equality for strings you need to use this method and not um and not the two equal sign and so there is another method called equals ignore case which as the name says it doesn't check um it checks if the strings are equal but it ignores if you know if one of them is cap in caps and one of them is in lower case we can quickly test that as well so we're going to do the same check on equals ignore case of new result but this time we will change it to john programmer right and run it you would get the strings are same now if you had used the regular equals you will not get the output back because the actual this equals also checks for the case but the equals ignore case basically ignores the case that's basically string like i said string has a lot of a lot of methods that you can play with to see how they perform it's one of the widely used classes and many of the methods defined in string string class will come in handy when you when you code you know bigger java programs in future so um i would really like to encourage you to try that methods out make sure you're comfortable with this class because it's one of the most important ones in java that's basically it thank you so much see you in the next video hello welcome back in this video we're going to learn about another class called string builder string builder is slightly different in the way it it functions compared to the string class which is going to see a quick example and basically learn when to use string builder so we'll create a new class in the same package and this time we'll call it string builder test with the main method hit finish so in here we know if you have to create a string it will be string name equals john right so string builder would be something like this string builder we'll call it name two equals new string builder as you can see there are multiple constrictors right that are available for string builder we'll use this one because it takes a string in we're going to pass the name that we created right so the way you create a string builder is slightly different compared to the way you create a string but the advantage is if i want to add you know the title to this name right like the programmer title that we saw in string test you can just say name two dot there are a bunch of methods that you can use right you can you can use this append and say space programmer right let's try to print it see what happens print a line of name two so we'll right click to run as java application we get john space programmer so we got the output same as what we did in string test but the difference is as we learned in in our string class whenever you create a new string with any operation concatenation or anything right it always creates a new string that is that is not a very good way of manipulating strings if you if you have if you have a requirement or a need that you have to do a lot of string manipulation where you will constantly create new strings manipulating existing strings string builder gives you a better option because you are basically manipulating the same set of values in the same memory location whenever you are performing the operation with string builder so you will not end up with creating multiple strings in memory you are always working with the same set of characters right in that way string builder is much more efficient in manipulating strings as opposed to string right which is why it's very good to learn this class because there would come a point where you you have you would have requirements to manipulate strings quite a bit at the time knowing about the string builder class and what it has to offer will really help right also if i do a name too just like this string class this has a bunch of methods right you can even append an integer anything that you want to append this class has a variety of methods that you can use to to do almost all types of string manipulation that are that are commonly done right it also has the length and everything that string has so you're not losing anything but you get the benefit of performance and you know efficiency where you're not creating ton of strings in memory right it even has it even has methods like reverse where it just basically reverses what what you have we could call name to that reverse right um and see what happens let's try to run it there you go programmer as you can see it doesn't return anything you don't have to you don't have to save the result elsewhere because it works on the same string when you say reverse it reverses and keeps the strings the string there so it's much more efficient than having to reverse the string by yourself assigning it to a different variable which ends up creating multiple strings in the memory so that's basically a string builder just like the string class i would really like to encourage you to try the different methods that that are there in string builder because many of them will come in handy when you do other programs in java in future so that's that's basically it thanks for watching see in the next video hello welcome back so we are learning different classes that are available in java like string string builder and so on so in that in that line we would want to learn about primitive wrappers we learned about primitives earlier which are the int flow double and so on so primitive wrappers are basically class equivalents for that right when I say class equivalent for int that is an integer class so int is a basic type integer is a class just like string so for for double that is a double class so in this video we're going to learn a little bit about those primitive wrappers because they will definitely come in handy so we would definitely want to learn them let's go to create a new class and we'll name it primitive wrappers and we'll create our main method let's start with int so if you want to know create an integer variable you will create int number equals 10 right that's an integer so there is a there is a there's a class called integer so which basically stores the same type of value but it stores within a class so you can say integer i equals there are two ways to create or multiple ways to create create these objects you can say new integer let's do a control space and see what eclipse gives us so as you can see there are two constructors that are available one takes an integer value other takes a string value right the integer one is pretty straightforward so let's try this guy so you can inside that you can say two so what this basically creates is an integer object but stores the value two in it so this string is basically converted to a number and stored same way you can let's try the other constructors also j equals new integer of three right so this creates a j object and stores the number three in it but there is another shorthand way to do it the concept is called auto boxing auto boxing right what that means is you can create integer k equals three that's perfectly fine because k is an object right of type integer class but instead of doing a new integer of the number you can give the number directly so what happens is a concept called auto boxing java knows okay you're trying to assign an integer number to integer object it creates the object for you when stores it's just a convenient way of creating an integer object instead of doing a new integer off you can print this so you don't have to convert or anything you can just say system.out.println k right just like how you would display an integer if you do a right click run as java application you get three perfectly fine so that's that's that's basically primitive wrappers if you do a k. there are a bunch of methods again just like string and string builder you have a bunch of methods that you can use this these classes come in handy when you want to create an object that stores the value because you want to perform object related functions on them and you cannot you cannot use a primitive at that point so these definitely come in handy so we learned about auto boxing right there is another concept called unboxing which is basically the reverse of it you can say int k2 equals k so we are creating a primitive right variable k2 of type n but we are assigning an object right java knows okay you are assigning an integer object to an integer primitive type it unboxes the value and instead of sorting the object it stores the actual primitive value or the actual integer value in this primitive type so this auto boxing and unboxing will come in really really handy when we have to convert between primitives and and wrapper types just like integer we have other ones too so you can say double double d2 equals 3.4 that's perfectly fine right you cannot do double d4 equals 3 or 2 it will say you cannot convert right it would have to match the type will have to match but all the methods that we saw all the auto boxing unboxing any method that has that is there an integer is also there and double also and same way we have float boolean all the primitives have a wrapper type and one more important thing to remember our important thing to kind of like know is all these methods have a parse method that come in really handy so here we created a integer object right but if you want to create an integer primitive type from a string you could do for example int result equals integer dot type parse as you can see integer dot parse int returns an int right so you could also use this method and parse number four and do a system dot out dot print ln result so if you print it you get four displayed so parse int integer dot parse int just like that we have double dot parse double and so on so forth to convert strings to an integer type or primitive type so the parse methods also come in handy when you have to convert from a string to a primitive type so that's basically wrappers there are other wrappers available for other types play with it make sure you you're comfortable with it and make sure you're really comfortable with the auto boxing and unboxing and what it does because it'll be very important it'll definitely come in handy when you code more programs in future so that's basically primitive wrappers that see you in the next video thanks for watching hello welcome back congratulations you made it to section five in this section we're going to learn some new class level concepts some method types and something called interface we're going to start in this video with something called static methods we have seen static methods before in this video we're going to learn what they are for and how they are used let's go to create a new project we will name it section five hit finish and also as always we'll go to source do a right click new create a java class we'll name it static methods we'll also create a package java.section5 we need a main method to test this out we'll create a main method hit finish we've seen the static keyword right what does static mean static means something belongs at a class level and not an object level what do i mean by that when we created employee classes earlier we created methods that are just public wide right that are never static something that was because we were creating objects for employees and we were calling those methods so any method that you invoke from an object are the are the other methods that you create in class the non-static methods but if some methods do not belong to any object but belong at a class level and you don't need you don't need an object to invoke them that's when you will make a method static let's see how it works right let's go ahead and create a new public or let's go ahead and create a new class we have not done this before so it'll be a good learning experience so far whenever we have created java classes we have had only one class in it right and a main method mostly a main method in it but you can actually create our right two classes inside the same source file you can call class operations right and inside that you can say public static let's create a let's create a another method that adds two numbers and returns it right let's int calculate sum and we can say int num1 and int num2 we've seen methods before so it's not it's not different we're creating a method by name calculate sum that is going to return of type int public because we need public access to it and static is what we are learning by making it static you would be able to call this method without creating an object and we're going to see how right so we have num1 and num2 as parameters we're going to create int result equals num1 plus num2 and we're going to return that result we're getting an error here because we are not returning anything yet now if you say return result it goes away so before we call this let's take a moment to understand why we have two classes and why it's a load right we've learned long back that every java class that you're trying to run or every java file will need to have one public class right you cannot have two public you have one public class let's let's see what happens when we create make this public it's going to say public table must be defined on its own file right what it means is if you're making something public create a separate file for it but if only one of them is public it's it's a load which is creating one class and then another class which is public right when we try to run this java is going to look for the public class and the main method and it's going to start running there and in here you don't you can call this method and you don't need an object for this class you can say system dot out dot println um you can do operations which is the class name it's not an object it's a class if you say dot eclipse will show you what options you have available as you can see calculate some shows up and here you can say 22 44 semicolon see there are no errors this is a valid statement we're calling calculate some method using the class name and we are passing parameters let's straight up run it right click run as java application 66 so we got we got the output we were successfully able to create a static method and call it using the class and no object this this may come in handy several times where you you really need a method that can be called just the class and you know you don't need to specially create an object for it one classic example of this is uh is the math class that is available we've been looking at string string builder and so on just like we have a math class so if you type math dot um see java dot lang dot math all the string string builder math they're all defined in java dot lang package and java dot lang package is automatically available you don't need a separate import statement you don't need to explicitly say import java dot lang dot anything right because you can say dot star when you say dot star it is going to import all the classes that is available in the package but you don't need to do it because java dot lang is automatically important for you so coming back to the math class if you say math dot as you can see there are a bunch of methods that are available that you can call because they're all static let's take one example right if you want to create math dot uh max right you want to find the maximum number of two numbers you don't really need an object for it why would you create an object store the store the two doubles and then call a method to perform the operation when the whole purpose of the method is to take two numbers check which one is max and then return the result to you right so that's a that's a great example for for a static method so just like that you may encounter situations in your java program programming where you need a method to perform a specific function it doesn't have to perform on an object it just has to perform the the function on whatever you pass it that's when you'll use a you'll use a static method and coming back to again math class as you can see there are a bunch of methods available any type of math operation that you want to do i would really recommend to check the math class first before you go about coding it to your own because if you want something chances are the math class would have it would have a static method to perform that so that's basically um that's basically static methods so i hope you understand what static methods are for because they will really come in handy that's basically it thank you so much see in the next video hello welcome back in this video we're going to learn about abstract classes abstract classes are those where one or more methods are not defined yet let's go and create one and see see how it how it looks let's go out and right click create a new class so you would do the same way it's there is no other option like abstract class you would just create a new class let's call it shape right we're going to create a create a class that is just a basic class for any shape like circle square um any type of shape right but this is just going to be a generic type or abstract type shape and in here we may want to say the shape has string um fill color because each shape can have a fill color right and then you can also have public string border color we can also go ahead and create our gitters and setters so do the source generate gitters and setters select all select both of them and then hit okay so there you go you got the gitters and setters as well now let's say we want to add another method called public double calculate area right so i'm going to create a method that basically will calculate the area of the shape and it will return it in a double right but i put a semicolon here and not the curly braces that would define the body of the method and that's because at this point we're talking about some arbitrary shape right uh we don't know what shape it is it could be a circle rectangle we don't have a way to calculate the area for a shape itself because we don't know what shape that is so we cannot really define anything if we have to put a semicolon here we have to make this method abstract when you make something abstract you don't have to give the body right um that's what abstract methods are but we still have an error and the error says the abstract method calculate area in type shape can only be defined by an abstract class there is an error here as well let's see what that says it says the type shape must be an abstract class to define abstract methods so it is what it says right here if you make any method abstract within a class you have to make the class as well abstract because think about it this is a class that has a method calculate area but does not really say how to calculate the area right which means the class itself is not a fully defined class a fully defined class would be a concrete class a concrete class is where everything is defined fully right but the shape class has a method that is not fully defined which would make this class as well abstract because it has one abstract method now if you if you write a type abstract here as well the error now goes away so we've learned two things here one if any method is abstract we have to make the class also abstract but within an abstract class you could have methods that are fully defined it's not it's not a rule that for an abstract class all the methods should be abstract you could have methods that are defined if you know what would go in there here for a color and fill color and border color you know you can set and get the colors right so that's basically abstract class abstract class is basically an idea right the ultimate base class right from which child classes can inherit and that's basically what abstract classes are used for you define whatever the basic things are in this parent class and then you can create child classes that inherit from this for example you can create a class for rectangle that can inherit from shape right but then with with rectangle you would know how to calculate the area so you could go ahead and implement calculate area in there let's go to try to do that right let's go right click create a new class we will name it rectangle hit finish we may need a main method also so let's create the main method hit finish here we have created a new class rectangle now we know from earlier to inherit a class we have to type extents shape right as soon as you type that you have another error here let's see what it says it says the type rectangle must implement the inherited abstract method calculate area so java knows that you are trying to inherit from an abstract class so it's going to look for methods that are abstract and it is going to force you to implement them because any class that is concrete should have everything defined now by extending shape rectangle class now knows about calculate area but calculate area has no definition in shape so rectangle will have to define it now just to show you if i were to declare this abstract as well the error will go away because when rectangle is made abstract there is no rule that you have to define all the methods right you could have one or more methods and defined so once you type abstract the error will go away but again this is going to be an abstract class you're going to have to create another child class that will implement it so that's how the that's how it goes now let's go ahead and delete it which means we have to define that method now eclipse has a shortcut so if you go here it says um add unimplemented methods right if you click it eclipse will automatically populate an overridden method calculate area right and it's going to put in return zero because return type is double so eclipse it's a short shorthand form in eclipse or a quick way to create all the overridden methods because if you are inheriting from shape and shape happens to have let's say 10 abstract methods you don't have to type them up one by one just by clicking that add unimplemented methods eclipse will automatically populate all of them for you right now let's go ahead and define rectangle class so i'm going to bring this main method down and in here a rectangle would have a length and breadth right so you could type private double length and then you can say private double breadth right now one more thing we are learning here is we can extend from abstract class but we can go ahead and define new data fields and new methods in rectangle apart from the ones that you are inheriting so for rectangle we have length and breadth that is defined so let's go ahead and create our constructors as well our constructor public rectangle and we're going to get n double length and then double breadth curly braces and then if you remember we gotta do this dot length equals length and then this dot breadth equals breadth so there you go our constructor is ready now in calculate area we have to say um return let's let's create another variable in now double area equals two in two length in two so is that the formula i believe so so and then we can return area or i think it's length of the breadth sorry yeah that was terrible now you can tell i failed math class so in here now you can call that method so we can say rectangle rect equals new rectangle off let's say phi two and then we can say system dot out dot println of rect dot calculate area save it let's right click run as java application there you go 10 so we got the we got the area displayed but the calculation was another point of this exercise the point was to extend from abstract class and override method that is abstract in that abstract class gives give a body and then be able to instantiate the child class because this is a concrete class and then call the method on it so we talked about instantiation just now so one more thing to remember is if you were to do shape yes equals new shape you're going to get an error saying cannot instantiate the type shape and that's because shape is abstract an abstract class can never be instantiated only concrete classes can be just to show you if i go here and just delete these two abstracts just to show you and then come back to rectangle the error will be gone because the class is not abstract any longer that was just to show you i'm gonna undo so that is a you know big thing to remember abstract classes can only be used you know to extend in a child class and you know be given definition for all the methods you can never instantiate an abstract class so that's basically abstract classes hope you were able to kind of understand the concept behind that why we would define abstract classes i would really like to encourage you to create more child classes for shape like circle or square you can define fields that are applicable for those shapes and then try to override the calculate area method and basically call it and try it out but that's that's basically it i'm going to comment this out save it but that's abstract class thank you see in the next video hello so this video is going to be a continuation of the abstract classes discussion that we had in the previous video definitely understanding this by doing another subclass of the shape abstract class would definitely would definitely help so we're going to extend shape again but this time we're going to create a circle class so let's say circle as we know we could use this superclass section we can say shape and select it and we can even say inherited abstract methods right this is selected by default so if you hit finish eclipse will automatically create the extends shape and it's going to add the override for any method that you can override eclipse knows that calculate area is an abstract method so it added the override already now for circle we can go then define double which is private you can say private double radius we can add a constructor so we can say public circle double radius and then we'll say within the curly braces this dot radius equals radius so so the constructor is there we can add our getters and setters for radius so we can go ahead and say source generate getters and setters for radius hit okay so now that's done so we extend the shape which is an abstract class we did an override of the abstract method which we're going to fill up here we added a new data field and getters and setters and constructor for it right so let's calculate the area so double area equals so the area formula for circle is pi r square right i mentioned earlier when we looked at the math class for any math operation that you do it's always good to check the math class to see if it has something for you in this case it does because pi is a constant value 3.14 and then there are a bunch of decimal places so pi is a constant so if you type math dot you can see there are two constants defined already in math class so instead of typing a number you can just say math dot pi you can even see the declaration so if you right click and go open declaration so pi is already defined in math class that comes with java so you don't need to type all this up yourself so that's handy and then we can say pi into radius into radius and then we have to return area so we successfully did override at this point we have overwritten an abstract method but like i said earlier you can also have fully defined methods like this in an abstract class so let's go ahead and add another one so we're doing this video just to get more understanding of abstract classes and how we override methods and stuff so definitely it's good to add more and learn so just say full void display shape name so let's say this method all it does is displace the name of the shape so obviously we are in shape so we'll just display system dot out dot println i am a shape and obviously we would want to override it in rectangular circle in this video we're focusing on circle so let's do a right click go to source instead of that there is another handy way to do it so if you just type display and then control space eclipse will give you an option display shape name override method so just double click there you go we just added another override using eclipse shortcut way to to add now here we don't want to call the super calling the super is not a mandatory thing you can call it if that is a purpose in this case there is no purpose to display i'm a shape because we are in a circle class so you can just say system after deleting that line you can just say println i am a circle and end with a semicolon now we can add our main method and test this out so we can say circle circle equals new circle off let's say 22 so double so let's just say 0.0 but it's not needed from here we can say system dot out dot println circle that calculate area or we can also say circle that display shape name right let's go ahead and right click and run it so circle right click run run as java application so you have the area calculated in display and i'm a circle display so java knows you we are working on the circle object so it calls the display name on that one and one more thing to show is in shape we defined two two data fields and added getters and setters for it now since we are inheriting shape into rectangle and circle even those methods would be available so you can say circle that set border color and set fill color and then once you set it you can do a get same way get border color get fill color so any method that you already have in an abstract class would obviously be available or you can override them as well or any abstract method you have you would override them in a concrete class and use them so that's basically it so this video was again to to increase the understanding of of abstract classes because abstract classes and the whole inheritance concept will come over and over in any java program that you do so it's very good to understand this i would definitely recommend you to create some more child classes for shape you know try with different overriding methods and make sure you understand it really well but that's basically it thanks for watching see in the next video hello welcome back in this video we're going to learn about interfaces interfaces is another concept like abstract classes but before we learn interface there's one more thing to cover in inheritance that will really help to understand where and why interfaces become very helpful so if you were to create a new class you don't have to create it you can just you know follow along i'm going to say some weird shape hit finish and i try to extend multiple classes so i can if i say extends circle and shape java does not even recognize it right say syntax error um what i'm trying to say is you cannot extend multiple classes in object-oriented concepts it's called multiple inheritance so there are other programming languages object oriented programming languages that support multiple inheritance java doesn't because we talked about you know methods being overridden in in subclasses but one of the main concerns is if you have a class extending two other classes and both of them have concrete implementations of a method then when you invoke the method on an object of this child class the language may not know which which method to call right so which which superclass takes precedence it's kind of hard to define that so in java that multiple inheritance concept itself is not supported in other words you can always extend one and only one class you cannot extend more than one class but there may be situations where you may you may want to have multiple abstract classes right defining abstract methods that you would want to override in a in a subclass to solve that um and for other reasons java has a concept called interface so i'm going to delete this i'm going to delete this class because we don't need it anymore i'm going to create a new interface so we have used only class so far we're going to create a new interface now and i'm going to again create shape um interface actually i'm going to create shape but in the new package so i'm going to say section one dot pkg2 finish i named it wrong turn so instead of doing that i can just say right click it'll be good to understand this so if you do a right click and go to refactor you can do a rename so this is much better than rename me the class yourself because java will update all the references of the type you're updating so this is a much safer way to rename something compared to you doing it manually so if you right now we don't have any anywhere it's used but let's say if this interface is used elsewhere eclipse will update all the all the references automatically so it finished now even the name is changed here that's good so we're going to define an interface shape because if i go back to the shape abstract class we had some methods defined the concrete methods defined and some abstract right but what if there is a scenario where you need to define something like an abstract class but you cannot define any of the methods you just want to create the signatures so these are called signatures you just want to create the method signatures you don't know what to implement right you there is nothing to be implemented in these methods in those cases you can create an interface and say again here we can create public double calculate area so all the methods in an interface should be public and you cannot create any data members if you say private int num you're going to get an error and it says illegal modifier for the interface field shape num only public static and final are permitted so anything that you define in an interface should be public static final so all the fields should be public static final if i say public still get the error if i say static still have the error final let's see what it says now the blank final field may not have been initialized and you need to initialize so when you initialize it what does it look like it's a constant so the only things that you can define in an interface with respect to fields or constants you cannot define anything else so that's important to remember i'll leave it here this is not going to be useful for us i'm just going to leave it here but this since this is a constant you want to have to make it all capitals that's the best practice we talked about earlier now we have a method again the method cannot be anything other than public so if i say private double i'm going to get an error so only public is permitted so what we have defined here is an interface and say this interface has one method that is public double calculate area right we're not giving any any definition you can also you cannot also give any body to it if you say if you say this you're going to get an error as well abstract methods do not specify a body note that we did not say abstract we did not type abstract here this is because all the methods signatures that you create here are by default abstract because you cannot give a body so that's interface interface basically helps you create not a blueprint but basically a structure it's going to force anybody that is implementing this interface to actually provide a body to the method same way like abstract classes if you if you inherit an abstract class you have to override the abstract methods similarly if you implement i say implement because when you add this to a class you want to say implements let's go ahead and create a new square class now you're going to say square and in this section you can actually add interfaces so let's go add shape you can actually select it so let's select shape hit okay and then hit finish so as you can see public class square implements shape so in case of inheritance class inheritance we'll say extend in the case of adding an interface we have to type implements that's the keyword so when you say a class implements a shape that means the class is going to give concrete implementations of the methods that the interface defined so in this case we have calculated area so i'm going to close this abstract class so it's not confusing we're just talking about this interface we just created which is being implemented by this class and we are overriding the method that we are supposed to override so in here since a square you can say double it's double which is private sorry should be private private double side right our length and we can add our constrictor so public square double length yes this dot length called length and we can add our gitters and setters as well we're going to right click core source generate gitters and setters for length and okay so we have successfully implemented an interface and same way we can create a main method and then calculate the area let's calculate the area as well double area equals length into length and then return area so we have that implemented we can obviously create a main method and then call the calculated area on the object for square which we know one more thing to understand about interfaces is we talked about how we cannot extend multiple classes you can inherit only one and only one class but in the case of interface you can implement as many interfaces as you want for example i can create another interface and call it something like position finish and then say public void something like display position so that's going to be our abstract method inside the interface and then i can go back to square and then say implement shape comma position just like that so now the class is implementing two interfaces we have an error here because if you go here you'll say the type square must implement inherited abstract method display position because this interface has that as abstract so when you click this guy to create the method the error goes away so this is how in java you can implement multiple interfaces and give concrete implementations for those abstract methods in the subclass or in this class and in java that's how that's how you kind of achieve multiple inheritance you're not inheriting a class but you are implementing multiple interfaces so you could have different signatures and different interfaces and you can implement that in a in a child class and give concrete method bodies for that so that's basically interfaces interfaces help set a standard right say say whenever you create a create any shape square or something if you implement this interface this interface will tell you what are the methods you need to implement and it's going to force you to implement it because otherwise that class will not be a concrete class so that's basically interfaces interfaces are again very widely used one of the best practices is to create an interface to kind of like dictate what are the methods that need to be implemented when that interface is actually implemented in class so i hope this video was clear i would really like to encourage you to create at least another interface and then try to implement that in a concrete class see how it behaves but that's basically it thanks for watching see you in the next video hello in this video we're going to learn about final classes final classes are those that cannot be extended that is if you mark a class as final nobody can create a subclass extending from that class basically the inheritance is stopped there are many reasons you know why we may want to do that maybe because we know whatever class we have created is concrete and we want to protect it we don't want anybody to extend it and add the functionality or override methods and change functionality right in that case you can make a method sorry a class final so nobody can do that we actually saw the math class earlier i've not shown this icon here if you click it you can open anything that you have defined or anything any class that is available for eclipse you can say math right and then open math class directly if you open math class you see that math class has been defined public final class math so that means we can never extend math class so that's basically um what a final class does let's go ahead and create one just to kind of like play with it so we'll call it final class we don't need the main method and then let's just go ahead and add make it final we're gonna add a number which we're gonna make private we can add a constructor maybe public final class which takes number and then it will set this dot number equals number right and then maybe we will display public wide display value which we just system.out.println number so we just created a method just to keep something in this class because we would never be able to extend this class and give functionality so we just give one method that just prints the number right now i'm going to create a final class test so again a new class final class test let's try to see if eclipse gives that option here so let's try final class it does give it let's go ahead and select it hit let's create our main method and hit finish as soon as it's created we're getting an editor in eclipse and it says the type final class test cannot subclass the final class final class so we can see that it's it's prevent that same goes for math class if you try to extend math class you will get the same error fine let's try to extend string class you get the same error so um the classes that are defined as final can never be extended and the reason could be um we we know that final class for example only needs this functionality we don't want anybody to extend it that's when you would mark something final these these classes can be instantiated so nothing's wrong with that so we can go ahead and delete this and then say final class f1 equals new final class of 20 right that's the constructor and then we can call f1.display value i'm gonna save it i'm gonna try to run it job application we got 20 displayed right so this method got called the value got set and the method was called and the method was displayed so if final class can be instantiated you can create objects as many number of objects as you want but you can never extend it or inherit it so that's basically final class um it might come in handy when you create a program in future a class in future where you know you have to restrict extending that class you can just mark it final and that'll take care of it that's basically final class thanks for watching see in the next video hello welcome back in this video we're gonna learn about inner classes inner classes are those situations where you create a class inside another class they're also called nested class let's go ahead and create a new class we will name it again let's say employee hit finish now let's say you want to create an object called name right you want to create a private name object and let's say the name is going to be another class which is a combination of first name middle name and last name right now you can obviously define them separately here but let's say you wanted to create an object so that you can you can have just one variable to um to access all those names you can obviously create this name class outside but let's say let's say you don't want anybody to be using the name class right you just want everybody to be using the employee class not the name class at all so you want to define the name class but you want to make it invisible to others right to do that you can define the class within the employee class so that only employee can access that name nobody else can right let's see how to do that let's go ahead and create or start typing private class name and inside that let's say as you can see as soon as we created it they went away because now java knows what name we're talking about now inside this you can say private um string first name private string middle name and then private string last name so we can also define constructors um you can say public name um you can say string first name string middle name and string last name we can even assign that then so this dot first name equals first name this dot middle name equal middle name and this dot last name equals last name right so what we have created is a class inside a class and this is basically the nested class concept and we're doing it because we want only employee to have access to this name nobody else right let's just go ahead and create a test um we'll just go right click a new class let's call it employee um let's say inner test we'll create our main method and inside that let's say we want to do employee EMP equals new employee that's fine no errors right let's try to find name um here's a control space you're saying several names because name is a very common um common class type but they are in different packages right you don't see the comm dot java to that section five at all because name is an inner class we can never um we can never directly create an object for it now how would we how would we define this then so we can create an employee constructor right let's just make it public employee constructor and let's say this is going to be taking string first name string middle name and then string last name now once we do that we have to create a new object for the inner class so for that you would you would say let's try to type name here and see what we get so we obviously can't see name here comm dot java to that section five that employee because employee has the name defined so you can say name or we can say this dot name equals new name off that's it so we have a constructor here for employee and from there we are calling the constructor of the inner class to instantiate it so this way only employee has access to the name class and only employee can use it nobody else can and here we can say john a apple seed so nothing's going to run but we can just um nothing's going to display rather we can run it it will run just fine so there are no errors that's basically the concept of inner classes where you are um you're basically defining something inside to restrict access to it that's one and also make it more concise you don't have to create another class third class name just to be able to use it in employee you can just define it inside so if somebody is looking through your code they can look at what's defined they can see the name is an inner class and you know they can see the definition right inside here so it it also improves the readability of it and make make the programs more concise so that's basically the inner classes you can obviously define other methods to get the names and you can use it at the employee level right but another thing to remember is if we were to make this public now we know public gives much wider access than private right um so if you have it public now you can create instances of this outside let's see how to do it right now it's public since public is much wider than private whatever we have here to pass constructor make this private is that that still makes sense but what this enables you is to what making this public enables you is to create objects for employee outside and let's see how to do it again we cannot just say name equals let's say name name equals new name let's say um mark a johnson let's see what it says no enclosing instance of type employees available so what this means is you cannot create an instance of an inner class without somehow referencing an instance of the outer class in other words since name is defined inside employee you can never access name directly you will have to go through employee to access it now to do it the syntax is a little strange but here's what you could do emp dot now the error is gone because you can um that's what the error says let me go ahead and remove this and let's look at the error again it says no enclosing instance of type employee is accessible right so you have to give an instance of employee to be able to access name if you just say emp dot then you're talking about a specific instance of employee and then you're creating the name object right and you can also do this and it's actually a good practice to do this you can you need to say employee dot name then you know that you're talking about anybody looking at your code or even you looking at the code later would know that okay we're talking about the name inner class right that is inside employee so if you make something i mean if you make your inner class public this is how you can create instances directly um by using the outer class and outer classes instance um and that's basically inner class so that's how the public and private kind of controls how the behavior is it's it's usually a standard practice to make an inner class private so that its access is restricted from outside but there might be situations where you want to make it public so you can instantiate the inner class also somewhere so um that's basically inner class it it definitely helps in a very concise a code creating a concise code and when you code a lot of programs you would automatically start seeing situations where you would want to make a class inner class so that's why understanding this concept is important so that when you have that type of situation you would know java has a method or java has a way for you to implement that so that's basically inner classes thanks for watching see in the next video hello welcome back in this video we're going to learn about anonymous classes anonymous classes are those that you create by implementing an interface but you don't necessarily create a class with a specific name or something let's go ahead and try to create one and see how they work and then see how useful they can be let's right click in the package and create a new class we're going to create something called a machine well actually let's create an interface let's go ahead and create a new interface and say machine hit finish and in the interface we're going to define two methods so public void start and then public void stop right so this is basically a machine interface which can be implemented by any machine could be a car could be a manufacturing plant machine and all of them would need a start and stop right so those are the methods that the machine interface declares and now we're going to create a new class and let's just call it machine test we'll create our main method hit finish now let's say you just want to create one car right one car object you don't need multiple car objects you just need one car object and you want to be able to call the start and stop on that car object right one thing you can do is you can create a public class car that implements machine and then you can define the methods right start and stop because if you implement an interface you have to define all the methods that are declared in the interface right to create a concrete class so you could do that and then you can then create a car object now that is a shorthand way to do it you can type car or machine right car you can always use the interface name right to declare the variable but then you cannot really do a new machine right if you say new machine java will not like it because interface cannot be instantiated you need to create a class this is where anonymous classes comes in you get a few type machine and then hit control space eclipse gives you an option machine anonymous in a type right just select that and see what happens so this is what anonymous classes you had just created a class by implementing an interface but there is no name for the class right because all we are saying is machine which is the interface name so we didn't give any specific name for the class but we had just created the class sorry and we had also instantiated it so we are not only declaring the class we are actually instantiating the class as well and assigning to the car variable right so this is kind of like the shorthand way of creating a class and instantiating it where it helps is if you don't necessarily want to create a class and create multiple objects all you want is just one object to do what you want you could go ahead and define it like this so the code is much cleaner easy to follow for anybody looking at this code they can see that okay you have created an anonymous class right a class right here by implementing the interface and you are also overriding the methods that are declared in the interface right so you are you are also following all the rules where you are going to give concrete implementation so here you can say system dot out dot println and say car stopped and same way here you can say system dot out dot println car started so we have given I need a semicolon here so we have given concrete implementations of the methods we had also created the class and instantiated it now you need to pay close attention to this syntax because we had had Eclipse automatically created but the syntax is very important you are doing a new machine with the two parenthesis and a curly brace right because you're defining basically a class so anything that you define within the class all the methods going to a curly brace that defines the class and you just define the methods in here which is not any different but then you need to end this with a semicolon because although we are creating a class here this necessarily is a single statement right all statements in java end with the semicolon so this semicolon is also important you cannot delete it you'll get an error so you need to pay close attention to the syntax um and then here you can just say car dot start and then say car dot stop so since we had already instantiated the class and we have the car variable right you can call the methods on the object so let's go ahead and right click run s java application and you get car started car stopped so we were able to declare the class without any name to override the methods and basically call those methods right um this this is going to be very handy when you code um mostly the um ui screens where you have buttons and stuff if you have a button on a particular screen that button does one and only one job right it can do whatever it is coded to do now in those cases which is called even handling in those cases this will come really handy because for each button you don't necessarily need to define a class and instantiated you could just define whatever that button needs to do right there very very you define that method right or declare that um declare that button so in even handling anonymous classes will come in really handy so it's really important to grasp this concept you know make sure you understand it you can add more methods to more methods here and then try to override them here but make sure you understand anonymous classes very well because it will it will be very helpful so that's basically anonymous classes um i would really encourage you to add more methods try to override them and see how they how they are called or perform but that's basically anonymous classes thanks for watching see in the next video hello welcome back congratulations you are in section six in this section we're going to learn about exception handling exceptions are situations where something bad is happening in the code right the program is going to error out so you can handle exceptions or find the problem and fix it right so let's go to create our new project for this section we'll name it section six and we're going to create a new class so right click on source we're going to name it exceptions test and obviously we have to create a package as well calm dot java toot dot section six let's go ahead and create the main method as well hit finish so there are two major types of exceptions in java one is called checked exception the other is unchecked exception let's learn about checked exceptions right so there is a class in java that lets you read a file right any flat file a text file or something that you have locally it's called a file reader if you hit control space eclipse will import it for you so we've seen packages and import statements before so just like we've seen java.lang package that is a java.io package that comes with java which happens to have a class called file reader it says convenience class for reading character files right that's what the this text says so we can use file reader to read a file but the goal of this exercise is not to read a file we're trying to see or learn about checked exceptions so let's go and create a new object file there is a constructor for file reader which would be new file reader and it expects the name of the file right let's just go ahead and say test dot txt we'll end with the semicolon we have an error let's see what it says it says unhandled exception file not phone exception so what this means is for file reader if you give a file name that doesn't exist there is a chance that the program will fail so file reader has been coded in such a way that file not found exception is a checked exception that can be thrown so we cannot successfully compile this program until we somehow handle it because if we were to run this program where that test dot txt doesn't exist it's an error condition the program would not know what to do so there is a checked exception of file not phone exception that we have to handle right how do we handle it so obviously when we give the file name and the program runs that's when we would find out whether the file you know exists or not the program would find out and it's going to error out if you see the two options that are given here there are ad throws declaration and surround with trycatch we're going to learn this first so if you go ahead and click it i'm going to delete this to do code so what's happening here this is the statement that we tried right i mean that we entered there is a try added here this is the try block right so anything that is entered in the try block the program is going to try to execute right it's going to try to run that that code so that's the try block and then we have a catch block so the whole thing is called trycatch block right so what we're telling java is hey try to run this code if you get an exception called file not found exception catch it right why would we catch it so if we catch it or if we handle it this way then the program can run whatever is in the catch block and still continue executing for example i can have a statement here system.out.println done right so if i don't catch it or handle it obviously i cannot execute it but another thing is the program is going to error out there right just failed right there it cannot even proceed but if i do a trycatch and handle it what java is going to do is try to open the file and let's say test.txt doesn't exist it's going to come in here and then print the strike trace but then continue executing let's go and run it to see how it behaves so we'll right click and do a run as java application as you can see we have a strike trace this is what is called a strike trace what happened here is it tried to run main right from there we are calling file reader so it went there which is calling here which is calling here right so it's a stack of methods right that tried to execute but could not execute because the file does not exist so this is what called a strike trace error is right a program normally should not throw a stack tracer right even if you handle it it might be better to say something like system.out.println file test.txt could not be found right let's go ahead and run it again so now you have a graceful message right display the file test.txt this could not be found but then the program still continued executing right so that's the purpose of try catch blocks right or how to handle the checked exceptions you know the exceptions might happen so you write code in the program to handle it right to basically handle the error do whatever needs to be done and then continue executing that's basically try catch block one more thing to know is since in java we inherit all the classes and everything right file not found exception if you open declaration it extends io exception right now let's go and open this guy it extends exception exception is is the um is is a super class that many other classes extend if we were to go to let's say let's go to a browser go to google and then say java 8 exception right it will take you to um oracle site where there is a java api documented and you have exception which is the class here and this shows the hierarchy of object is extended by throwable and throwable is extended by exception and then you have direct known subclasses right as you can see there are several classes that extend exception because exception is kind of like the super class of all exceptions although there are there's throwable and object exception is kind of understood as the super class that all the exception classes inherit right so io exception for example which we saw extend this guy extends exception so if you go there io exception has a bunch of um subclasses which we saw file not found so that's the exception hierarchy right so all these are checked exceptions now going back here to the code let's go to exceptions test if you were to say um and then something like um buffered so this is under the class to read the file so let's say buffered reader control space again right um reader equals new buffered reader we have to give the file reader so that's the that's the syntax as you look through the api I shown here right for different classes you would know what are the options available I just happened to know the buffered reader one so buffered reader has a constrictor that needs an input of file right all file reader so file that's good and then now we can say reader that read line which reads line and then this is what I was expecting but let's try to print it first so what reader that read line does is read a line and then we're trying to display it but what I was going to try to show is now read line has unhandled exception type io exception so just like how this one had file not found this one has io exception right now we have to handle it somehow so what you can do is catch io exception then say io ex and then say system.out.println or sysout control space cannot read file so the reason we wanted to do it is because the catch can be stacked as well right you can add a bunch of catches because you could have different code in the try block right each of them could be throwing different exceptions which means you need to have a bunch of catch blocks to catch them all now one thing to remember is since all these are classes and subclasses right you need to make sure the superclass is always at the end not at the beginning because we learned polymorphism right where a superclass variable can actually point to a subclasses object right now if you add sorry about that now if you add let's go here and then say catch exception right you get error and says unreachable catch block it is already handled by catch block for exception and then here you also see unreachable catch block because exception is the ultimate superclass right so if an exception is thrown any type of exception is thrown in this code exception object or exception this reference can catch it this variable can catch it which makes this code meaningless right so this is key to remember when you stack catch blocks you need to make sure the superclass is always at the end right for example io exception was extended by file not found exception which is why io exception needs to be here if you move this to the top again you get an error so that's definitely something important to remember your superclasses will always be at the bottom you need to have the subclass exceptions first before you go to the superclass ones so that's how you can add a bunch of catch blocks so that's basically unchecked exception I mean cat checked exception sorry about that we're gonna we're gonna continue this in the next video but hopefully that gave an idea of what checked exceptions are and how to do a cat try catch block thanks for watching see the next video hello welcome back we're going to continue learning about checked exceptions and these try catch blocks because there are a couple more concepts that need to be learned here we added try catch blocks we added multiple catch blocks right and we also learned that the superclass should be um coded after the subclass otherwise if the superclass catch block is before the subclass right the superclass will catch any of the tail class exceptions as well because of polymorphism and we don't want that happening now let's say we have a message um that you want to display here right system.out.println completed, completed reading the file right we know that the the test.txt doesn't exist right so we're gonna have throw exception right here let's try to quickly run it again so the exception was thrown caught here this message was displayed and then was displayed right now this never executed because as soon as the exception happens the control will go to the catch blocks and then proceed from there right but what if we have a statement here that we always want to execute regardless of whether there is an exception or not if the code is here it is never going to happen right so what we want is to put this code in a place where it will execute regardless of whether an exception was thrown or the code was running fine to do that there is a block called finally so after you define all the catch blocks you'll say finally and then use your curly braces and put your statement here now let's put it here save it now let's run it as you can see we threw the exception we caught it here but we also displayed this message and then continued right now if we were to just if you were to define this files here let's go and create that file new file so we want to prevent that exception from being thrown text.txt finish right i'm gonna some text vcde now let's try to run it to see if you're able to read that file successfully right there you go so there was no exception thrown here we were able to instantiate a reader and then we were able to read the line from the file which is abcde and print it which means there was no exception so the catch blocks never executed but the finally block did get execute all right we got this message displayed so as you can see the finally block always runs what do you want to do with the final block normally normally you would want to use it to do any cleanup we try to display a message here but in this example we have a reader that we that we open right we have to close it we can obviously say reader that close right now let's say if this code executes and then this read line which throws an io exception let's say this throws an exception at this point we have the reader opened but not closed at all right if we were to throw an exception here this close operation will never happen right that is not a good thing that's what we call leaks in in java so we don't want any of these memory or any type of leak happening if you are opening a connection you need to close them right you need to close it so instead of putting it here if you put it somewhere like here obviously the close the close also throws an exception which we need to catch here right reader cannot be resolved because we have to define the reader outside the block because if you say buffered reader here it's visible only in this block so java doesn't know what this means so we can put it here equals null because we need to initialize it to something right and then we don't have to define it again here and here we want to say if reader not equals null because we don't want to run it if if we did not even open the reader right so we want to make sure it's not null and we need to put a try catch for this also so run with try catch and we don't need to do anything because this is the exception this is an example of an exception block that doesn't do anything because when we try to um let me finish this formatting right so this block is empty this block is empty because we are trying to close the reader the only reason where this exception can happen is the reader was never opened to begin with which means the code could have failed here right never even got here so we don't have a reader open so we don't I mean we don't we're not expecting a submission here at all right or we don't want to handle anything because there's nothing to be done so you could it's perfectly okay to define empty blocks if you know that there is nothing that needs to be done right now let's go ahead and run it after we fix the error here so this is the try catch obviously for the if block that is a code embrace missing now let's try to run it yep we got the same thing um maybe cde completed reading the file and then we successfully closed it and then completed the program right so a final block is where you put um some statements that you know that they have to execute right regardless of what happens um finally is a very important block if you write any type of connection opening or anything that you do here that you know you have to clean up it is very important to put it in the final block to make sure it runs always so that's final statement there is there's one more concept that we need to learn here which is the throws we are going to learn that in the next video but at this point i hope um you can realize why finally should be used or the importance of it i would really encourage you to kind of like play with it um you can you can you can try to read another file see what happens and stuff like that but that that's basically it that's basically um finally a block thanks for watching see you in the next video hello welcome back in this video we're going to learn about throws um throws is a keyword in java that basically lets you throw an exception from a function or method that you can catch where that method is called we already saw an example of that if we were to go to for example file reader which we used you can see when we used the constructor for file reader we had to catch file not for an exception that's because this is throwing that's the throws keyword i mentioned throwing an exception the reason you would throw an exception from a method is because you if you want hoover calling that method to handle the function exception instead of it being handled in the method itself that's when you would throw it one example is this file reader constructor could be used in thousands of places right wherever you want to use it and in all those places you may you may want to handle the exception differently so this constructor or any method right need not really think about what are the ways the exception can be handled you can just throw the exception from the method and let the caller decide how to handle it that's basically the concept we're going to try to define similar thing in our example program to kind of understand that better so if i go back to section six instead of using the program that we already have i'm going to create another one new java class this time we'll call it throws test with the main method obviously hit finish i'm going to create a method here so public we can keep it static and then let's say file open file so file is the is the variable or the class that we used earlier sorry it should be file reader file reader so if you hit control space you will get the import automatically now let's say this method wants to take in a file name right and then it will open file reader fr equals new file reader of whatever the file name that's passed right so we want to create a utility method that will basically open the file instead of keeping this code everywhere right you're just putting it in a method that you can reuse now this guy obviously throws an exception we need to handle now this method can handle it but if you have this open file method used in like hundreds of places right you may want to handle them differently in different places so you can just say throws and then file not found if hit control space eclipse will automatically do the import and add it here now let's see what it says this method must return a type of file file reader all you need to do here is return fr that's it so anywhere you call this open file you're going to have to handle this let's try it so let's do a file reader fr equals open file off we already have a file created from our earlier video test.txt if you don't have it all you need to do is right click here and then do a new file and then you can just create a you know test.txt i just have some text in there so well let's just say text.txt save it semicolon save it so now it's going to say unhandled exception and here you cannot really throw it let's say if you say throws right this is the main method if you were to run it run as job application nothing happened because the main is trying to throw it there's nothing to catch it right it doesn't make sense to throw for main because this is where the program is executing you may want to handle it and then and then display a message or something for the user so you can say set on with trycatch and then you can just say sysout control space within within code you can say file not found or you can say file test.txt not found now if you were to run it let's see what happened here so we are catching so we are opening the file reader turning this is a oh because the file exists so if we change it to test1.txt and then run it you're going to get file test1.txt not found that was terrible sorry about that because test.txt already I mean existed so we never got the exception but now since test1.txt doesn't exist we are calling the method with that test1.txt we are trying to execute it this obviously results in a file not found exception which is which is thrown but is caught here and handled so that's basically the throws block you would I mean throw statement you would use it in a place where in a method where you don't really need to handle the exception you just want to throw it so whoever the caller is can handle it that's basically what throws is used for and you can also add multiple things so you can say throws I owe exception too right which you're going to handle you're going to have to handle here so you can add multiple throws because if you have multiple statements here and each of them throws a different type of exception you can you can put them all here separated by commas so a method can throw multiple exceptions too so that's basically the throw statement it will come in really handy when you have methods that are doing different things or something in different exceptions but you want the caller to handle them that's basically throws thanks for watching see in the next video hello welcome back so we're learning about exceptions right and obviously one of the things that you can do because that is inheritance in java is to inherit from exception class which is the super class we saw right so you can extend exception class and create your own custom exceptions let's go to try to create one and then also understand or learn when we would want to do something like that so i'm going to create a new class that is going to be the new exception that we are creating right i'm going to create a separate package for it because this is how i'm going to type an exception so this is how you would have your classes kind of like organized if you have a bunch of exception classes custom exception classes that you are defining you may want to keep them in a separate package right so i created a separate package and then let's call it custom exception you don't need a main method hit finish now just like the same extends that we saw earlier you just say extends exception now exception being a concrete class not an abstract class you don't need to overwrite anything but it doesn't make sense to just do this right that the whole point of extending from exception is to be able to define something that is custom for our application let's say one of the things is an error code right private int error code so we want to throw a code that makes sense for our application but be one two three or hundred two hundred doesn't matter some error code that will uniquely identify a problem right and then we can also say private int error message so we have two um sorry it's got to be a string turn private string error message right so we have two fields that make sense to just our application which is why we extended exception class and define them now we can go ahead and create our constructor we can say generate constructor using fields hit okay i'm gonna create the gitter and setter so right click source generate gitters and setters select all and hit okay and we can even add a two string right source generate two string hit okay there we go we have the custom exception class defined where we're gonna have our own exception that has an error code and error message now we can try to use it we're gonna go back to the section six package right right click new class and let's say this is custom exception test we'll create our main method because we want to run this class right hit finish i'm going to create a method that is going to open a file for us right same like we didn't throw test so we want to say public static file reader open file and that's going to be a string file name as a parameter whatever we want to open and in there we can say file reader fr equals new file reader of file name we have to import this guy so file reader control space the import is there java.io. file reader now let's say what the RSA is unhandled exception we know that the constructor throws this exception let's try to catch it but instead of printing a stacked trace we're gonna use our custom exception right we already saw the throws that you add to the method signature here now for a custom exception to throw that you would say throw not throws it's throw and custom exception is a class we need to create a new object so a new custom exception right now we know the constructor needs two parameters an error code and an error message let's say i want to use the code 100 and the message of file file name not found the space here and then a semicolon so we are throwing new custom exception so it is cannot be resolved to a type that's because it's in a different package right so you can say import there you go import it so since custom exception is defined in a different package we need to do an import for java to know which custom exception we're talking about now we have another error let's see what it says unhandled exception custom exception so we're saying that this method is going to throw this exception we don't have a place where we are catching our throw defined the throws right so you need to match it with the throws here throws custom exception now what the other error says this method must return file reader right so we don't have a return statement we can say a return fr let's define or declare this outside and then remove this guy okay we just have to initialize it turn null here return there you go so we have open file method defined that is going to throw custom exception and the actual throw statement is here so what we are doing is we are catching an exception and throwing custom exception let's just talk about why we would want to do something like it right so if you are creating an application with tons of classes you may have different exceptions that are being thrown if you may want to have a consistent way of handling the exceptions right you may want to know you may want to display an error code for every message or every error so that with that error code you can uniquely say identify okay this is the place where the problem happened right so that's one reason where you may want to create your own custom exception and use it everywhere so that there is a consistent way problems are handled in the program so let's try to go you know use that open file now let's say file reader fr1 equals open file i'm going to give a file that doesn't exist right test2.txt we already created test.txt but we want to see if the exception handling works and then this is going to throw a custom exception which we need to catch and here you can say system.out.println of e right we're giving the object here because we defined a two string which is automatically going to be executed when we try to print an object let's try to run it see what happens so right click run as java application so we got a custom exception right which is our exception with an error code and error message right this is much more meaningful from a from a debugging perspective or troubleshooting perspective but it is throwing an exception that you know with an error code so if you have thousands of lines of code but using unique error codes if you see error code 100 you know where it failed right so that's basically one of the reasons why you would want to create an exception by exception class by extending the exception class that comes with java so that's basically inheriting or extending exception to create your own custom exception you can go ahead and add more fields that make sense you know that that you want to add to the exception class and then try to basically pass it when you're creating the object for it right I hope that made sense thanks for watching see you in the next video hello welcome back so far we've been learning about checked exceptions right the ones that you have to do a catch and handle it or do you know use a throw statement to pass it up to the other method that was calling it so that's how you handle checked exceptions the second category of exceptions that are in java are called unchecked exceptions or runtime exceptions that you don't necessarily normally handle because they are problems in in your program that have to be fixed right if you go to google and then say java eight exception we're going to go to the api so we saw earlier exception is the superclass that has a bunch of exceptions child class right subclasses if you see runtime exception and select that guy so this is the runtime exception that we are currently talking about it has a bunch of subclasses as well like null pointer or a restore exception or arithmetic exception right stuff like that so these are all runtime exceptions that you can catch if you want but this actually if you if you handle it or catch it or do it right it kind of masks the actual problem so it's not normally good to have runtime exceptions if you have runtime exceptions you have something wrong in the code that you need to fix so we can see something like some example of it if you go back to eclipse and then we will create a new class and let's just say it's called runtime exceptions test it finished now let's say you want to create an array so let's say int numbers equals one two three if you say system.out.println numbers of five so we're trying to display a value in a position that doesn't exist so if you do a right click run as java application you're going to get an array index out of bond's exception right let's click it or let's go to this the symbol open type we're gonna say array index out of bonds which extends index out of bonds so let's open that declaration that extends the runtime exception right so anything that extends runtime exception you don't necessarily do a want to do a try catch because this statement did not force us to catch anything right earlier when we saw open file or file reader those methods threw an exception that we were forced to cut right but this is not throwing anything right it's not forcing us to catch which is why they're not checked exceptions but what this tells us is there's something wrong in the code where we are trying to read a position that doesn't exist right or something like this string name equals null and then let's say we want to say system.out.println name.length right we're trying to call the length method on an object that doesn't exist all we have is just a reference to nothing right if i comment this out because we don't want to end here right if i run it it's going to fail with the same exception i want to skip that part so if you run it again now you get a null pointer exception right let's see what null pointer exception has null pointer extends runtime exception right so runtime exceptions are those that you were not forced to cut but when they happen they actually tell you there is something you know really wrong with the code that we need to fix so runtime exception is not really normally good to have if you're getting runtime exceptions it means there is something wrong that you need to fix in the program right but you don't necessarily have to catch it there's nothing wrong in catching it for example if i comment this out again and then say try here we can say catch or index out of bonds exception ex say system.out.rentln index out of bonds if you were to run it we're going to get index out of bonds right so we were able to handle it there's nothing wrong in handling it right but if you if you're getting runtime exception um you normally don't catch here you would fix the problem in the code that actually ends up causing you know causing that causing that problem right um one one way to look at the difference between a checked exception and unchecked exception is you can make anything a checked exception if the program can recover from it right let's say you have a bunch of statements in try block right if something fails you're able to recover from that error if the program can be recovered from the problem by handling that exception you will make it a checked exception right if there is something wrong with the program um throws an exception which it cannot recover from then you will you will make it a runtime exception let's say you're trying to open a file from a disk right but the disk itself doesn't exist let's say there is a hardware failure where you're not even able to read the disk right that would clearly be an example of a runtime exception because the program cannot recover from it if it wants to read the file if it has to read some file for the program to continue but then that disk itself it doesn't exist that would be a runtime problem that needs to be resolved right so it would not make any sense to check for it handle it in the program so that's the difference between a checked exception and a runtime exception um and that's basically how you would think about the problem to decide what type of exception you would want to use in your program so hope that made sense um that's basically the second type of exception that is in java which is the runtime exception or unchecked exceptions thanks for watching see you in the next video hello welcome back in this section we're going to learn about collections collections are nothing but a list of objects in in that regard it's similar to arrays because arrays also let you hold a group of numbers or objects but the collections let you manage those those list of objects much better than arrays it lets you add items easily and remove items easily so collections are definitely widely used i have the oracle site opened on the interface collection so this is where kind of everything begins that it's an interface defined call collection that comes with java which has a bunch of sub interfaces um the thing that we're going to look at in this video is list so if i click list list is another interface which has some implementing classes and one of them if you see is array list our list is one of the most widely used collections because it it really helps you um easily manage objects so in this video we're going to focus on array list we're going to learn how to create an array list how to add objects to it and manage that list so if i switch back to eclipse we're going to create a new project and name it section seven hit finish and then we'll go to source and create our new class we will put it in the package comm dot java toot dot section seven i have another package by that name but i think it's okay list test so let's call the class list test and put it in a package comm dot java toot section seven and we'll create our main method hit finish now as we know we can have the variable declared with the interface so type list which is the interface and then hit control space sorry sorry about that control space and we want the one in java.util not the one in java.awt so hit enter and you see we have something here with a less than greater than symbol you have something called e this is where the type would go in if you want to hold a list of string you will it will put string here if you want to hold the list of let's say employee objects you will have an employee type defined and that employee would go here now we want to hold a list of string so we'll type string here and names and just like how you would define any object you will type new but we want to define a realist now you obviously know you cannot give list here because list is an interface and you cannot instantiate that but a realist is a concrete class implementing that list so you can now eclipse is showing an error because it doesn't know what a realist is because we need to import it just like how java.util list was automatically imported when you hit control space here we will hit control space again and select java.util and eclipse populated string automatically because it knows you're trying to create a string of list you just need to put the parenthesis and then semicolon there you go so we have a names array list defined to hold a list of string now you can do names dot you have a bunch of methods available in the array list but we're going to use the add one so hit add and we can say john now let's go ahead and use another method that is available in the array list names dot size as you can tell from the name it's going to tell you what is the size of the list how many items are held in the list so let's go ahead and save it we will right click run as java application so we got one so we already have used two methods that are available in the array list so let's go ahead and add one more or a couple of names say kate and then names dot add peter so we will save and run just to make sure the size changes yep so we got three we got three names and then we got the sizes three so those are just two methods there are other very useful methods available one of the most useful methods is let's say if we want to remove kate from the list we don't want to you know have kate in the list we just need to have two names you have a remove method that takes an index so just like arrays index always starts with a zero so john is index zero kate is index one and peter is index two so if you want to remove kate from the list you will say remove one hit save try to run it there you go you have two now because we we had a john kate and peter but we removed kate now the list is back to do this is a striking difference between list and arrays if you had a if you had an array of string that had these names you have to manually remove kate which is the second item in the array but then you will have to move peter ahead so that there is no gap in the list so with arrays you have to go through a bunch of steps to do what you are able to do with just one method so this is this is one of the most powerful things about lists it lets you manage the list much easier than you know what you have to go through with an array and there are other useful methods i really would like to encourage you to explore all these methods the other one i would like to show is add this one took a string and we we give the names but this one takes an index so it is just like how we removed something from the list it's pretty easy to put it back in the list as well so if i say add one and then add let's say kate back hit run now we got three again so we made it two but then we had made the list again three now if you were to print system.out.println names that another useful method is get you can also get something on a particular index so i can say get one so i'm asking for the first item in the list which is not the first item the index with one the index one to be displayed run so we got kate again so we removed kate we added her back to the list and then we were able to get it so just like the remove to add something in the middle of an array you would have to go through a bunch of steps but now with just one method call we're able to add an item back into the string string list so that's the power of our list or any collection for that matter like i said earlier i would really like to encourage you to explore all these methods because several of them will come very useful when you're coding much more complex programs but whatever methods i've shown are very frequently used so make sure you are very comfortable with the methods shown here because these are used very frequently in most of the programs but that's basically our list there is another way to go through all the items in the list i mean stop doing a get for for you know each index but that is going to be in the next video it's called an iterator but the next video will be dedicated to iterator to understand how you can easily traverse the list to get each item that's basically it see you in the next video thank you hello welcome back in this video we're going to learn about iterator as i mentioned in the previous video iterator helps you traverse through a list easily you stop doing a for loop and going through the list so in this video we'll try to create an example for an iterator and see how it works let's go ahead and create a new class in our section seven package and we'll call it iterator test and we'll go ahead and create our main method so here we're going to create a new list our list control space so that we can import java utility list automatically and then it's a list of string call names new control space again so your auto poplates semicolon to end the statement now let's go ahead and add some names to the list so names dot add john names dot add matt names dot add kate and then let's add one more names dot add peter so we have now four names one way to go through the list is to do a for loop where you can get each item and then display but now we're going to try to use an iterator so just like how we added our list let's type iterator and then hit control space which will do the import automatically we want the java.util.iterator so both iterator and our list are inside the java.util package so it's an iterator of string equals now instead of doing a new let's name it names iterator equals instead of doing a new we can do names so which is the list so if you do um names dot the first option that's shown is iterator so let's just hit enter put a semicolon to end the statement and then kind of like I'll try to explain what it does so every list has an iterator method what it does is it creates an iterator object of all the elements in the list and then returns that so we're just assigning that to a new reference names iterator which is of type iterator that can contain string so what this does is creates you an iterator object that helps you easily go through the list instead of doing a for loop now to do to do the traversing let's do while now the objective is to go through the list until there are no further items right so let's open and close this block and then we have to put a condition here there's an easy way to do it so just do names iterator dot if you go through these methods there is a has next so go ahead and hit enter so what has next does is it returns true until there is one more item until there is a next so if there is another item in the in the iterator it is always going to return true so that's what we want to do right until this is true until there is one more item to read we want to go through the iterator and when you reach the end of the list that is the iterator has next will return false and at that point you would know you have to stop reading it so this is much better than doing a for loop doing a get and then check until it you get a null because you are moving past the list this is much easier has next um you know has it covered for you you just have to do has next in here and it will return true until there is one more item for you to read as long as that one there's one more item for you to read so now we we want to get the next item in the list right so for that let's do string name equals names iterator dot next so eclipse automatically gives the best option for you as the first option right so next there's a difference between has next and next has next just checks if there is one more item for you to read next actually fetches the item so if you think about it as a list of four iterator has the four four elements when you first execute next john object will be referred and then when you do next again mad will be referred then kate then peter after that you don't want to read anymore because there are only four items but you won't even get here because has next will tell you there's no more items here and you will break off of this while so that's that's the whole point of iterator now we can just go ahead and display stem dot out that println name that's it no for loop no if conditions nothing um iterator basically make sure you are only reading until there are items to read let's go ahead and run it to see the output run s java application so now we got john mad kate and peter in the exact order so has next next keeps checking if there is one more item it keeps returning true so you are while was executing over and over until all the names were displayed and we use the next to fetch it right first the actual object and display it so once we hit peter and we displayed peter here in the next time around has next returned false so while never executed and then we broke out of while and then the program ended so as you can see it's much easier to get through a list through when i using an iterator instead of having to loop through the list manually and iterator is one of the very commonly used classes to go through list you would want to make sure you really understand this better because there is no other better way to go through all the items in the list you know than using an iterator so hope that i was helpful thanks for watching see the next video hello welcome back in this section we're going to learn about one of the most fascinating concepts in java which is multi-threading multi-threading is being able to run more than one thing within your java program at the same time so in that sense it's similar to multitasking where you run more than one process or application at the same time but multi-threading is within within a java program being able to run multiple flows or threads at the same time to get started let's create a new project for this we're going to name it section eight and once the project is created let's go ahead and create a new class and also a new package at the same time so we're going to name it comm.java.section8 and the name of the class we're going to name it runnable test we'll create the main method and hit finish and before we get started i'm just going to add a statement just follow along you don't need to type this i'm going to try to divide by zero and we all know that's not good but i wanted to show something and we'll just do a runness java application and see what happens and as expected right we got an exception because we cannot divide by zero it's it's not permitted but if you see the exception closely it says exception in thread main so like i said multi-threading is being able to run more than one thread within a java program at the same time what this shows you is there is already a thread going on without us you know doing anything special there is a thread called main so any java program at least has one thread which is the main thread and multi-threading is being able to add more threads so that alongside a main thread you can run multiple flows or multiple thread at the same time that's basically the whole concept of multi-threading in java and one of the ways to create multi-threaded program is by implementing an interface called runnable that's why we named the class runnable test so let's delete this line and then go to the class and try to implement runnable and you don't need to import it because runnable is already part of java.lang so it's already imported for you but let's see what this error is and it says we have to implement the unimplemented method in the interface which we know and let's click this what we get is one method so run runnable interface has a method called run which is not implemented which we need to implement whatever we type within this run method can technically be kicked off in its own thread let's see how this works so within this thread i'm just going to put a system.out.println just to show us that this is running in a new thread so in new thread and with the semicolon and let's go back to the main class which is where our program starts executing now in order to create a new thread there is another class not an interface but a class called thread which we need to instantiate so let's just say thread t1 equals new thread and this constructor takes in an implementation of runnable and we already have an implementation of runnable which is runnable test so we can just say new runnable test and with the semicolon so just to recap what we have done is created a new thread and passed it passed to the constructor and implementation of runnable and from here is just a simple matter of calling the start method on the thread so just just note that we didn't call run directly we need to call the thread start method which will eventually call the run implemented for the runnable test you can never call run directly it doesn't work that way so let's just run this just to see what happens runness job application we got the we got the message in new thread but this is this is not anything new because we have several times called methods right from our main method that does the same thing and just to show the difference let's just put a system.out.println in main thread now in main thread so normally if you remember from our methods that we have seen in the previous videos when you call a method the control or program control basically goes to the method finishes that completely and then comes back to the calling method and continues right so in the same way if we call a method here it should go here and display whatever is in the method and come back so in short in new thread should display first and then in main thread should display next that's how normal method calls work let's try to run this to see what happens runness job application look at that but we got in main thread first and then in new thread next so what that tells us is once this is run so basically that thread is started the main thread doesn't stop executing the main thread continues to execute while the other thread also executes in parallel which is why in main thread displayed immediately otherwise if this were a regular method call in new thread will display first so hope this shows how parallel thread kicks off you know at the same time as the main thread and two threads are executing at the same time and that's basically the concept of multi-threading using a runnable interface in the following videos we'll look at some more concepts in multi-threading but this kind of is the simplest implementation or even the most popular implementation of multi-threading in Java you would very frequently implement the runnable interface which is the simplest way and and the most frequent way we implement multi-threading in Java thanks for watching see in the next video hello welcome back in the previous video we looked at an implementation of runnable to implement multi-threading so we created a class implemented the runnable interface which means we need to override the run method and I also said this is the most common way of implementing multi-threading in Java but I also mentioned that there is another way to implement multi-threading which is what we're going to see in this video and I'll also explain why that is not the most common method let's go ahead and create a new class this time we'll name it thread test and we will create our main method finish and then instead of implementing something this time we will extend and if you remember from the previous example we created an implementation of thread class so all we're going to do is extend thread so we are basically creating a subclass extending thread and once we do that we can override any of the methods in thread but in this example we're going to override run so enter run and then do a control space and then choose the first option which is overriding method from thread so from here onwards we're going to do the same thing so we're going to display something here say system.println in new thread and with the semicolon and back in the main we're going to extend thread test which is this class t2 equals this time we're just going to thread two sorry thread test so if you go back here we did the same thing we created an object of class thread but we passed it a runnable interface but this time we're just going to create a new object of type thread test and then we can just do t2. Start remember we don't directly call the run method we should always call the start method from the thread and eventually run will automatically get called and let's also try to display system.out.println in main thread so we'll save it and we will run it run as job application so we have in main thread displayed first and then in new thread what happened was we created a new thread here we kicked off thread.start and at some point so this kicks off a new thread right but the main thread continues executing which is why we got the in main thread first but then in the thread that got kicked off parallely start was called and eventually run got called and then in new thread displayed later so this clearly shows that there are two threads executing at the same time one is the main thread and the other is the the other thread that we created this is not the most common way of doing it because we are extending a class and if you remember from our inheritance class or video that there is no multiple inheritance in java and as you create more and more java programs a creating subclass will be a very common thing to do so if you extend thread you cannot extend any other class so if you have your own class for which this subclass needs to be a child off you cannot create that because you're already extending thread class you cannot add any more classes right that's why implementing runnable is the most common way this gives you the flexibility to to extend any other class that you have but also implement multithreading so that's one of the main reasons why implementing runnable is the most common way to do multithreading in java although there is nothing wrong in pursuing this this just limits your options of what other class you can extend in your program but this is the other way to create multithreaded examples or programs in java i highly recommend you to create more threads create other classes add other run methods and kick off multiple threads to kind of see how multithreading works in java this this is a very key concept as you do more advanced programs or even games where you will always have multiple threads executing at the same time so understanding multithreading is really important in these subsequent videos we will look at other thread concepts like sleep and so on but this is the basic example of how you create multiple threads thanks for watching see in the next video hello welcome back we're learning multithreading in java in this video we're going to learn a new concept which is making a thread sleep and we're also going to create more than one thread apart from the main thread we're going to try to create more than one thread and just see how those threads execute let's go ahead and create a new class and we'll also learn why we would want to make a thread sleep so create a new class and we'll name it sleep test and also as always we'll create our main method let's finish and since we are going to create new threads we're going to implement runnable implement runnable we're going to get an error because we need to implement run so let's click this which will create our overridden run method and in here let's create a new thread that will be thread t1 equals new thread and if you remember we have to pass to the constructor a runnable implementation which we already have which is going to do new sleep test and from here we can just do t1.start and in the same way we're going to create another thread t2 following the same methodology so we're going to say new sleep test and we're going to start this thread as well and in between let's just put some system out in main thread after creating t1 and same way let's do one of the sys out here in main thread after creating t2 which is going to see how all these threads execute when we get the messages and that will help us understand what really is going on when multi-threading is done in java so in this method which is the run method we're going to just do a sys out first if i can type and say in new thread before sleep and to make a thread sleep we again are going to use the thread class you just have to type thread dot if you scroll down there is a static method in thread which is called sleep so as you can see it takes a long millisecond right so we can say 5000 which would mean the thread will sleep for five seconds and let's talk about why we would want to make a thread sleep so let's say we have a lot of threads running in our program and at some point a thread no longer needs to execute or you want to make the thread wait so that other threads get a chance to execute right you're just basically passing the thread for a certain period of time because you want to give priority to other threads or if you think of a game example right um let's say you are the player enemy hits you and then you want to just um not move the player at all for let's say five seconds because the player just got hit so these are some of the examples of why we would want to make a thread sleep and we're getting an error let's see what it is it says we have to surround with tri-cache because we are not handling an exception called interrupted exception so let's click this the basic concept is the same way we can make a thread sleep we can also interrupt when it's sleeping so let's say a thread is sleeping for a minute but then in 30 seconds some condition gets satisfied when the thread should come out of sleep immediately so at that point we can interrupt the thread that is sleeping which is why we have to catch the interrupt exception here we're going to make the thread sleep for five seconds we don't have to do anything here but just because the sleep method is throwing interrupted exception we have to catch it which is why this is needed um and after this we can just say system.out.println in new thread after sleep so we have a lot going on here let's just go ahead and execute and then see what we get right click run as java application so we got the main thread um you can see the program terminated after some time let me just run it again so let's clear this and then run it or before that let me make it 10 seconds so we actually get time to talk about what's going on and then to run as java application so we got in main thread displayed and then in new thread this got displayed we have two threads going on so for both those threads we got something displayed now we are in a wait for both threads and then the 10 seconds passed and then we got in new thread after sleep in new thread after sleep we got it twice because we have two threads going on so clearly the program got through the in main thread came here for the thread one and then it displayed in main thread thread two and then displayed this for thread two and then both threads kind of went into a wait for 10 seconds and then they both came out of the sleep and then displayed this which is why we got two messages displayed here so we clearly see what sleep is doing uh it basically passes the thread for the said duration which is in milliseconds um this is a very trivial example but this is also a concept that you would very much use especially if you're doing game programming later on multi-threading and you know when to make a thread sleep when to bake it up those are all very critical concepts so i would highly recommend to create more threads or even create another class that implements runnable that is more than just out right and then basically play with this make sure you understand how the threads are kicked off and also how to sleep a thread and because these are all very um critical um critical things depending on what you go on to do with your Java programming later thanks for watching