Java For Beginners | Michael Rascon | Skillshare

Java For Beginners

Michael Rascon

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
9 Lessons (7h 33m)
    • 1. 01 Course Introduction and basic setup

      17:02
    • 2. 02 Creating a Simple App

      34:53
    • 3. 03 Variables, Data Types and Math Operators

      30:46
    • 4. 04 Conditional Logic Looping and Arrays

      49:55
    • 5. 05 Representing Complex Types with Classes

      39:53
    • 6. 06 Class Initializers and Constructors

      27:04
    • 7. 07 A Closer Look at Parameters, Overloading

      30:35
    • 8. 08 Class Inheritance, Equality, Abstract

      46:30
    • 9. 09 Inner Classes, Exceptions, Pacakges, interface

      176:08
17 students are watching this class

About This Class

This class assumes no previous experience, and takes you from the absolute beginner concepts. Java is one of the most popular programming languages. Java offers both object oriented and functional programming features. If you’ve never programmed a computer before, or if you already have experience with another programming language and want to quickly learn Java, this is a perfect course for you.

Following topics are covered in this course:
- Introduction and Setting up Your Environment.
- Creating a Simple App, Variables
- Data Types and Math Operators
- Conditional Logic Looping and Arrays
- Representing Complex Types with Classes
- Class Initializers and Constructors
- A Closer Look at Parameters, Overloading, Class Inheritance, Equality, Abstract

Prerequisite for this class

- basics of Java language

Transcripts

1. 01 Course Introduction and basic setup: our focus throughout this whole course is really give you a strong foundation in the Java language. The teacher. What? You need to work effectively with Java programming language. I'm gonna do that as a very hands on approach will be writing lots of code as we go through and seeing what happens. We write and change that code. And our focus here really is on this again the idea of the language right to Java, sin tanks, the language constructs the concepts and how to use all those things together to program effectively and we're really trying to do is give you the language skills you need to work effectively in any job based environments. The topics recover here are useful in traditional job itself to call John a standard edition, but also, when working in enterprise level applications, even job a smart client applications right that carries on even down to small devices with Java, Michael Addition and Android. Right? So we really got that whole thing covered and think it's interesting to note, is that you know, even though Android is really kind of the most popular phone platform uses Java, that doesn't mean job. Unlike tradition, isn't important, right? Although job, unlike tradition, is not a big part of phones anymore, it still plays a really important role in smart devices and the Internet of things, right? So understanding Java programming language really gives you what you need to work across all all levels of computers, right from desktops all way down to, ah, small devices, all the backup, two great big servers. The goal of this first module is to give us the information we need to start working with and learning the Java programming language. So first we look at is just take a brief overview of what job is, what one of the parts of it, what's made up of. They're gonna talk about the Jerry versus the J. D. K. To Turner's People's for around pretty freely in a job, a world. I don't understand what those are and what they mean. We look at the details of actually setting up your job development environment and then looking at your job, integrated development environment, the tools we use to build job programs, and we're gonna kind of endorse or focus on any job or any specific job I D. In this course but I want to talk about what the options are out there and help you to choose which ones right for you. The first thing we need to understand that it started is exactly what is job When someone says Java, what are they talking about? Well, Java is a programming language, but job is also a run time environment. It's actually both of those things. So we got the programming language as things like the syntax that data types control flow like looping and conditional statements and being optic oriented, right, doing inheritance and so forth. And then a run. Time, of course, has to support those things but also provides things like configuration security, a threading model, input output. That's everything. So when someone says Java Day could be referring to approving language or the runtime environment or the whole thing Now in general, the run time environments was talking about when they just say jobs, which often referred to his job. A standard edition. That's kind of the basic job environment. But Orca provides other environments to drive from that Enterprise edition, Gentle Micro Edition and job FX. So those are all either super sets or subsets of this main thing, which is just the job Standard Edition. But the thing that just need about job it's so flexible that there are even run times that are not tying to the job of one produced by Oracle, right Androids, kind of most well known. One. Andrew provides very different runtime, then the standard Java runtime from Oracle. The thing is, though, that all those environments support effectively the same Java programming language, right so that one language equips us the work in all those different places. The J R. E in the J. D. K. Or two terms. You hear people mentioned very frequently in the job a world and what they are is the two parts that we need in order to run and create job applications With Jerry is the Java runtime environment. J T. K is the Java development kit, and so the jerry is what you require in order to run job applications, and users normally install the J. R. E right that one's gonna run a wraps. The J. D. K provides the tools that we need to create jobs abs. So normally developers the ones who install the J decay on their machines and in order to develop action, you to run them. So jaded Cancellation includes a Jerry. So how does all this work together? And if we sit down and we type up Java source file with our program code inside of it and we want to get and run that in some host environment, how do we do it? Right? Host environment would be Windows Lennox Sremac could be a browser. Might be a phone running android. How do we get from that source code? We've typed up to something It can actually run on that other computer? Well, that's where the job development kit comes in. Using the job development kid. We can feed our source code into it, and it will produce our job application now. John was not like a low level language like C right. See, when you compile a C program, it produces an application that can run directly on the host computer job. He uses an abstraction called Blake codes. That's platform independent. It allows us to not be tied to a particular host environment but actually have something that can be run in different host environments. And that's where the job of run time environment comes in Java, runtime environment provides What we need are Java app display codes, executing any host environment. And so that's why and users install the Java runtime environment because they just need to run. That cared. We have developers installed. JT came to give us the tools to produce that application. Let's go and install the J. D. K onto our machine. Now that you are all I have on screen, the bit Lee PSG DK download is set to point to whatever the current version of the J. T. K is. As I'm recording. It's The current version is J. T. K eight. So that someone all install If you watch this course into the future and another version dedicated nine or 10 comes out that same, you're all you see will take you to the appropriate place to download that current version . And so here we are at the current download page, or I should say, here at the page where you can get the current job downloads, you notice here on the left, we've got one here for the J. D. K, also called the Job of Platforms were going click on that here we are on the J. D. K. Download Page is going to scroll down here a little bit. Do you see that? Here's all the various version. Begin download and basically just download version for whatever platform you're using. Right from Lennox. You to get that one. Of course. If I was on my Mac right now, I get the Mac one. But this case on currently on 64 bit Windows machine. So I won't install that version right? When to 64. One thing gonna make sure you remember to dio is, except it's license. If you don't accept the license, that won't allow you to do the download. Right. So we're ready. Which getting click on this to download the file. So my down let's complete it. I'm gonna get just run the installer gonna get in, double click on this guy. And now here we are, inside the installer. Right. So you're gonna get in. Let's install, get started here, go ahead and say it good and stole everything and you'll notice that one of things that has here is that the jerry of the Java runtime. So it actually puts that in their forces. So you have to do that. Here's your dinner promises again for a destination folder Because again, this is the folder where the java runtime is gonna go. I'm gonna get just accepted to fall for that. So say, next. And with that, we're done. We now have DJK at along with Jerry installed on our computer. If you wanted to, you could build your job. Applications haven't only installed to J. T. K. You couldn't use some arbitrary text editor the type in your program code. And then you could use command line tools to do all the compiling and executing of your programs. And and that would work fine. And people did that for years. And some people still do that. But in general, we're developing. We want to use a more productive models in that we like these things called integrated development Environments that allow us to you're typing are code compile it debug everything all in one place. Now Java has lots and lots of ideas available. Two of the most popular are net beans and intelligent, and both of these are available for free net beans is the i D that oracle themselves provide so they provided a four free, and it's pretty flexible in the sense that it can comes in different configurations, and configurations of it are available for all the Oracle jobs, right? So Standard Edition, Enterprise Edition, my tradition, Java FX and you can add all those in at no additional cost. The one kind of popular job environment that does not support is Android. And so, just to be aware that if you were doing android development and other job development, you wouldn't really use net beans for the android part of it. One kind of nicety is that Oracle does provide a single installer that has both to J T K and the job SC Bundle of net means, in other words, that version of net beans that let's work on Java SC programs. And that's just a really kind of nice. You're nice convenience if you're installing a new machine and you just want to kind of get the J. T. K on there and have an I D all in one Install just makes setting up a machine easy. Another very popular I D for Java is intelligent. I really like intelligent is my preferred job environments. Now the intelligence community edition is a free version of a commercial product. And so, you know, a company called Jetbrains actually builds and sells a full blown installation of Intel Ajay. But they make this communication available to us for free. And what I like about it is that the condition supports Java, Standard Edition and Android, As you can use one i d. For both of those environments, which I find really convenient. If you decide to get and go with the commercial, a version of Intelligent you would pick up additional features. There's some other development features. Its sports. Javy doesn't cool server debugging stuff, but you don't have to go to the commercial version. The community addition is quite substantial and certainly is good enough for everything we do in this course, you'll find that most things you're likely want to do are supported in the community edition. Let's go and walk through the installation of the Net beans I d. Now, as I mentioned, you can download net beans with the J. D. K um, and that same euro we used earlier to get the most recent JK works for getting the most recent packaging of Net beans and the J. D. K. So that same bit Lee PSG Decay Download If you want to actually kind of pick which configuration of net means you want, as opposed to getting the one it's got J T. K built into it. You could go to the Net Beans WARG website on their download page. You actually pick out exactly what configuration that means you want. Here's let's go through the steps. So here on the Oracle download page, you see the big logo there it says net beans and says Net beans with JD Case. That's getting go there and see what that looks like. So click on that and you notice here that right here in the center of the page, it actually says they here to J T. K with net beans, and it's got all the different platform installations. But look to the right here. You'll see there's actually a link that just says Net beans, I d. E. So let's take a look at that guy real quick. So angry that page that puts everyone to net beans. Ah, website itself scroll down a little bit and you can see there that these are all the different configurations that we can download for the different platforms, right? For just sc support or if you want e support as well and other ones. So if you want to control that and pick that picture configuration, you can do that from here. But I'm gonna do those head back to the page we're on, and I want to go ahead and install net beans with J. D. K. Remember the earlier demo I installed to J. D. K? It's all by itself because that step was already done. I don't actually have to download this package version of it. I could actually get net beans by itself. So we're going here and get and get the version for the current computer, which is again a 64 bit Windows download that. So I have to download. Now that's good. And run that rates. A rainy installer is gonna click through that. Now we have accept the license for some of the tools here. So J Unit is a ah testing tool and that it starts part i d. So it's gonna didn't accept that license Click next again telling it where to install the JD case, we'll say yes, do that and now wants to know whether install net beans and some J T K support suffered net . Beans will get click next on that and the last one here is that Do you want to check for updates? And I leave that check so couldn't cook. Install, hurry, stars set up is complete. That lasting, it's asking us is just We want to go ahead and contribute to test statistics back into the projects. They can see what we're using. All right, So I want to leave that box checked and say Finish and I now have to net beans I d installed now. One thing to be aware of his M the net being installation is a fairly length against the least. I want a pretty new machine here, and, uh, it probably still took between three and four minutes for that. Installed a run so it takes a few minutes to run. Don't be worried about let's go fire up net means now and see what looks like you're down here to my windows. Just get down to where my programs are. Scroll over here like my net beans. There's not being so. It's gonna run that guy. And there we have it. We've been nothing's installed and it's running for us. Well, actually built a program within the next module, but I want to make sure it installed ran correctly. And it does. Let's walk through installing the intelligence community. Addition, your own screen there, the bit Liro will take you to whatever the current version of Intelligent is. Currently, that happens to be 14.1. But even as the versions involved that you are else would still remain valid, grow down a little bit here, taken some sewer rant. You see, this one page has got both the, um, the commercial addition and the community addition want to make sure we get head and down with the community edition. So getting please click on the download button here. Once the download's complete, we just go ahead and run the installer. It was Just step through this. Now's off. Start a click. Next, I'm gonna get and accept that the fall installation folder. Now I'm gonna go and create a desktop shortcut to make a little easier to find. And also, I've got these associations, so I'm gonna get unassociated with dot jobs. So that way, if I just double click on any dot job of final, it'll automatically open it up inside of intelligent click. Next, I'm going to keep all of the fault here on the groups. And now it's often installing my installations, complete someone go here here, and just click this box that says, Go ahead and run intel. Ajay, when I get when I exit so I click finish, I'm gonna tell to not worry about important and importing any previous settings. So it was OK the first time you run, it wants to ask you to How do you want to set it up? Do you want to customize its appearance or anything? I'm gonna say, Just skip all that and just set to the faults. See, now I'm at the starting window. So we now know we have intelligent installed as well, and again in the next module will actually start using this and billings from code with it . But we now know we have a successful install to wrap up. The key thing remember here is that when we talk about Java, Java accident comes is both a language and a run time environment, and there may be some variations in those individual run time environments. But the cool thing is that the language remains pretty consistent, right? So by knowing the Java language, well, you've got the ability to work across a very wide range of platforms now, in terms of installations, and users only require the jerry rate that Java runtime environment. As developers, we want the J T. K as well. Remember that the JD cancellation installs the jerry for you so you can get and run this applications that you're creating. And although Dee Jay Dickey is all we actually need to create our applications, we probably want to use an I. D. E of some sort. And there's a whole bunch of ones out there again. You pick the one that you like best other 1 to 2. I showed you have won his net beans, which is the one that work will provides the other when I should be intel. Ajay is again very popular as well, and there's no magic to it. It really comes down to you. Just pick the one that you like best, and with that, we have everything we need to set up our environments. So in the next module will start coding 2. 02 Creating a Simple App: Let's go ahead now and create our very first Java project will good and just use the intel . Ajay, I d To do this one have a short cut to intelligent on my desktops. It's going just double click that guy to start up. So once in tell A. J. Starts up here takes me to this initial window. You know, what I would do is just create a new project. So click on that. Now it takes me into the Wizard to create the project. Now, one of first things we have to dio is of course, choose. We wanna have a job, a project summary intelligent, worked for a variety of things. And then we also have to associate the ah J d K version. We want to use the one you need to do this step once, but we do you use that word says product sdk news that there are none now there's nothing to choose. All right, so we're gonna do is just click on this new button here on the right. I'm gonna choose to set up a project sdk, which is the J. D. K we're going to do now is just navigate to where we installed a J. D. K. Writes it for me in here. It's on program files, Scroll down Java and then makes you choose J D. K not to J. R. E. You want to J D k say okay. And now that we've done that, we can now create projects with that J. D. K. So now one thing. Just a little bit of challenges that this wizard screen doesn't render well on the resolution that we record at. So it's gonna pull this up here just a little bit. There is that that the bloods across the bottom, right? So I'm going to click the next button to move onto the next step of the Wizard. So click on the next button. So now says, What template do you want to use or do when he's a template? All we're gonna say you're going created from a template, and what that does is just create some initial file layouts for us. That's things up so we can get started easily. We're gonna create a regular command line application, which is just the most basic kind of job application. If I put a dialogue up, I'm gonna click that next button down there at the bottom. So now good in one of name thinks so. In the kind of in the life long tradition of ah, Programming in part, of course, is gonna create a hello world app. It's just getting call this project name Hello world. So I've named it Project Hello, world. I'm gonna go here where it says based package and we're gonna delete that away for now. We'll come back to that a little bit later, and I'm just specifying where I wanted to go Was gonna put into a folder under my demo folder for this module called Hello World that Pull this guy up. News down at the bottom. Now there's actually a finish button. That's what going to select this time is the finish button. So is it starts up, it brings me into the project. One of the features of intelligent is it actually has kind of the tip of the day just to kind of show you different facts about working in their environment so forth. Gonna close that up. He knows Here it's generated source code file for me, You know about the left here. I've got my project explored just just kind of the hierarchy of the files it's created. If I expand Hello World and this source folder here, there's the mean That's Thea class file. It goes with the class of created took a whole bunch more about classes later in the course . This based just comes the start of her application. Now intelligent, always creates this initial class as class name main. That class name doesn't actually matter or took a lot more about class names a little later . What does matter is inside here. There's what's called a method right. That's where code actually runs. And for job applications, the start up of your application must be in a class that has a member called mean That looks just like this. What has to be public, I mean, just publicly accessible. We'll talk more about that modifier leader. The modifier static void has to be called main and has looked just like this. So whenever you run, your code in Java is gonna look for this is an entry point. I don't just delete this line away here, and we'll do the classic hello world applications. I'm gonna use object here or time called System and I'm Gonna years Something called out and print line. And this is just a mechanism in Java. We used to print things out to the council, and we're It's a hello world, so we have that there. So this is kind of the most fundamental application we can build right now. The way we run this an intelligent is that we go up here to the run menu. Click on that and we choose run. When we do that, we'll see the intelligent will go ahead and compiler code for us and then down here at the bottom, it shows a console window and actually shows the output of application. So in this case, it says Hello, world. Now our focus here is on job and not on the development environment, but just to say a couple things that makes it easier. We saw how to run it from the menu. Once we have this window down here, if you would say Want to change something, I'll say Hello, world. We'll just say again. I want to get rerun the cud. I could go down here on the bottom. Where have this little green arrow click on that it will just run the code over again, compiling and running force. And now we see hello world again. So we've successfully run our very first Java hello world program. That's what through a demo now of running our program from the command line, In other words we want to do is look at how we can run our program without having to use a developer tool like intelligent to do it in previous demo, when we wrote her application where we did all the work here inside of a developer tool in this case in Tell A J, and that's did are compiling and even that ran it for us. Now developers, we have that tool. But how and users run a program housing end user, execute the program without having won his developer tools? And that's what we look at now I think, I remember, is that the main class for our application here is called Main. It didn't didn't have to be, but that's what is called here, and we have to remember that when becomes time to run our program. Remember that we say that and users have to install the Jr era at the Java runtime environment, and let's take a look in there for a second. Here I am on the C drive of my windows computer I won't do is get onto your program files and insiders. Forecourt, java right inside there. That's the J. R. E. Right? That's the execution of irate the Java runtime environment. We said that that's what actually runs our programs, right? Java programs don't run directly. They run within the job environment. If I go inside of this folder, there's another photo called Been You notice Inside of your first scroll Down a little bit , there's actually a program called Java. That Java program is what actually runs our program right now, if you're on letting our Mac, you could basically used that Java program directly. If your windows you want to make sure that it's actually in your path right so that you can actually type just a word Java and will find it in this folder so we want to do is keep track of this location where we found the job, the job, sixties. We're going to copy this and again. What we do is we put that into the path of our machine. So I got overhears Control panels were getting open to control panel and your control panel Gonna find the system entry, open that guy up. And what I want to do is get to advance system settings. And from here, I want to go to environment variables. When I want to do years, I wanna go ahead and add that to my path. Right. So I'm gonna add to my you my user path. Now I happen to have no current user path set up on your machine You may already have in entering here That says path. If you have existing, when you gonna highlight it and say edit? I want to create a new one because I don't have path yet. It's gonna call it path. No longer do is paste in that location where the job dx iwas right when I say OK, now we see path listed here, right? And so just kind of clarify if you win you open environment variables. If you already saw pass, you would highlight it and click edit because I didn't have it already. I had clicked new All right, so we'll get to say OK and OK, and close these guys up. And so now I have the folder where my job of programs located in my past so I could just type it from the command line. So now we want to do is run our program. So what I wanna do now is go to the folder where I created our applications project. So when I created our applications project I created in this demo folder and I'm are called a project Hello World was by going here in a hello world to see a series of folders. Now, the exact loud of these folders is specific to the way intelligent does it. But any environment you're using, you're going to see something similar to this. So well, we want to do here is good are out folder and again, a name out specific to intel. Ajay, whatever tool your using would have something like that. And so we go out and see production is another folder inside there and then inside of here we see Hello, world. If I go inside of there, we can see in this case our class file. This hello world folder under out of production is the result of compiling our program. And again, the names out and production are specific to intel, Ajay. But whatever environment you're working from, you'll have some folder structure like that. The key is we wanna have where the output was placed, which is our hello world. Right now that we're here, we can actually a bit of a command line and run our program. So I'm gonna do is it's going to appear Just type cmd open of a command prompt in this location. So I've got a command prompt here, and what I'm gonna do is just tape Java life inversion. And he knows their outputs. That it's Thea gives me the version number of java, and basically, this really tells me Is that my job of commands working? If that doesn't work for you, if you have something like command not found or you get a version different than when you were expecting, which you may have to do is just log out and log back in because user level environment variables don't take effect right away. All right, so if you get again, if you get the part, I'm not family to Java. Just log out long back in it should then work when you have your next command prompt. If it doesn't, just go back and make sure you've got your path setting to the right location. To where? That job that, Yes, he was located. It's not a runner program. Going to say Java and we want to do is give it the class name that that actually had that main entry point. And remember that in our case, our class name was actually mean. So it's gonna get and hit, enter and then we see hello world again. All right, so we see that we actually successfully ran our program without having the use any fancy. I d right. This is how would running in and user environment. They would have your class file think we produced when we built the program and just using the Java command goes ahead and launches it. Java programs are made up of statements now. A lot of different things can go on in a particular statement, and we'll talk about those things throughout this course, but fundamentally programs afraid of statements. Now each statement ends with a semi colon. Right job is a language where you know the new line, and the enter key doesn't really create a new statement, right? Actually, relies is still in the semi colon. They're coming from any of the sea based language. Is that something you're very familiar with? Other languages, like visual basic actually used the end of line. The market statement In Java. It's the semi colon, and the parts of a statement could be separated by zero more white spaces. And a white space could be many different things. It could be the space character could be a tab. And because statements don't end with New Line, even the new line itself is just a white space in Java. John is a language that gives us a lot of flexibility with white spaces. Remember, he said, that the parts could be separated by zero or more right spaces, so it allows us to format things in a way that works well for us, right? So I have a statement like this where all the parts are pushed altogether with no white spaces between them. But then I can have the same statement. Words. Put a space after the print line space after the parentheses, space before the other princey. That's the exact will do the exact same thing. I can put multiple spaces in there, and that's still does the exact same thing. I remember that because the new lines considered a white space. I conform at it like this right now. This is kind of a crazy way to format, and I wouldn't suggest you do this. But it's all just white space, right? So after that print line, we've got a new line followed by a bunch of the space characters. That's fine right after that. Prentice. See, we've got a new line again. You're after Hello, world. We've got a new line, another new line that a whole bunch of white spaces, right? So Arsenal, which is space character. And so it just shows us that the weight space allows us to you in Dan format put line breaks in a way that works well for us, right? The weight spaces or just separators is that semi colon, the marks the end of a statement. Java, like most programming languages, has the ability to include comments and comments are just basically text inside of your source code that the comm Potter doesn't see right there, and they're really kind of just two general uses for comments. One is that it allows you to add human readable notes to your source code real at last type things in the source code so that when you look at it later, what someone else looks at it deters, leaving notes to understand what you were doing there. It's also useful for a hiding source. Cool without deleting. It may be your testing things out, so you want to just gonna take some things away and types of new stuff, or there's something you don't want to anymore, but you think you would do it again in the future. So comments Ally to take that stuff out. So the contents in your source code, but the compiler doesn't compile it. There are three types of comments in job. One would just call line comments a lot if you base it. Just put a double slash basic compiler ignores everything until the end of the line. And when I said by the end of the line, it's actually until you hit the Enter Key, the new line character. It's not like other statements were realizing the semi colon right, so just compiled to skips everything until the next new line. Then we're called block comments, where he used a slash start to begin the comment and a star slash to end it. So combine skips everything between those notations. They can be happened in the middle of a line or they can span multiple lines. And the last kind is a special kind of comment called a java dot Comment, which starts out slash star Star and then ends Star Slash. There's a utility called Java Doc that allows you to generate documentation. Using this special comment format allows you basically to write your code documentation right inside of your source code. And when you run the Java doc utility, if you follow the appropriate structure in your comments, that utility will generate documentation right from the source code. File the details of Java docker outside the scope of this course, but I've got that you are l. If their on screen for you. If you want to dig into java dot com to learn more about it, let's take a quick look. Now it using comments in our code. Here I am back in the program we wrote earlier, and let's do you? Let's just take this line. We rate a Hello were again. Let's copy that and put it back in a couple more times. Just say hello. World 12 and three. Never go and run our program down here. We'll see that all three of those lines get written out. Hello, World one to entry. So using comments where we can add information into our source code and so I mean, we use up first I use a line comments or just do a slash Slash. Say, this is a comment and this comment only exists until I get to the new line, right? You know, Stephen, the ideas using a different color text. Just make the comments stand out there. But if I run this, it's had no impact on my program. Does all right? Still says he still says a little world 12 and three. But if I go down to the next line here and I put a double slash in front of that right, that line is now ignored by the compiler, right? So if I go ahead and run this get out of the world one a little world three. Right? So it allows us again to just kind of have this commenter only exists for a single line. And of course, these comments can also be on the line by themselves. Or if I had a line here, I just typed something like this is a standalone comment. We're gonna go ahead and run this guy again. All right? No change the output, because again, the comment last until the end of the line. Right now, blocked comments actually have distinct starting and ending point. Right? So before this method here, if I put a slash star that they that coming exists until the star slash right? So I can say this is the first line of a comment, right? They could even get another line. Say, this is the second line of a comment that could have as many of these lines here is. I want to write because a comment doesn't and until gets to the star slash using that same technique, block comments can start end in the middle of the same line, right? So if I wanted to just change this text here, but not lead us, I do a slash star. I put a star slash at the end. Now I put in here This is different text Everything between the slash star and star slash is ignored. But then once we hit the end of the block comment CA fire looks at it again. All right, Arch, instead of Kamar sees the text again. Right? So I go over and I run this. Now I get a hello world war, but I get the This is different text And so the really key thing there is that thesis slash slash Comment just exists until the very end of the line. The block comments have distinct starting and ending points. One thing to be aware of a block comments is that you cannot nest them. Right. So I've got a block coming here at the top with this is the first line of comment is the 2nd 1 of comment. If I put a slash star in here, you notice that when we have that second star slash with one at the bomb now shows up is an error because the compiler doesn't have a distinct idea of for every starting block comment . There's an ending block basically assumes it sees the very first encounter of star slash all the comments or ended so you cannot nest block comments. Now it is okay to put line comments in subtle block in it. So I put a slash slash line comin in here. That's not an error. You wouldn't intentionally do that, really, because you're ready to comment blocks of weapon line comment in there. But if you happen to have an existing line comment and you wrap it in a block comment, that's still safe. The bottom line here is that comets allow us to put Texan's ever source code that we don't want to be seen by the compiler right, whether it's notes toe to ourselves for another human being, or we just want certain source good to be ignored for some period of time. Let's talk briefly about Java packages. Packages are a very important concept in job, and we can actually talk a great deal more about them later. We have a whole module dedicated to them, but one look at just a couple of simple things about packages right now to get us started. Now, if we look at our source good, all the source code we've written up until now has just kind of our class definitions, and that's kind of by itself. But you look at most Java source code out there. You'll see that at the top of the source code files to the word package, followed by some name right and what this does when we had his package concept, it's provides organization within a Java program. Now, again is a lot of aspects of that. But one of you could just kind of two basic aspects of it to get us started. One is that the's package names follow a standard naming convention, and they actually affect our source code file structure. Now, in terms of naming convention, one very simple rule is that package names are all all over case. That's just a convention to Kamata. What actually allowed not to be a lower case? But that is the convention that Pakistan's air all over case and one of them's we're trying to do would packets names is create a sense of uniqueness. So one aspect of uniqueness is on a global scale right throughout the entire world. So in order to assure package name uniqueness on a global scale, what we generally do is use the reversed domain name, right? So, for example, that parole site owns portal site dot com, right. There's actually authority out there that make sure that no one else buys the name portal site dot com. So we do is that we start off our package names using a domain name, right? So any package created by plural site would actually use the name com dot parole site against reverse. Or is the top level of its calm and then plural site, so that now assures that as long as everything we do close, I'd start with that naming structure. No one else will name a package like that. And again, there's nothing that enforces this rule. It's just a convention that we all follow to keep things from colliding with one another. And then we want to do is that we have further qualifiers beyond that to assure uniqueness within a new organization, right? In the case of a company or some group, if we're creating packages of long to climbed up puerile site, each of our individual packages would have a another part to it to just identify some project. So in this case, it's, you know, my project, and that's kind of the simplest way. There was short uniqueness, right? Is that each project and have its own kind of last note, Part two that are last part of the package name. It stays unique. As organizations get larger, you may have to get a little more sophisticated about your package names, right? Because if you have multiple development groups within an organization, if you only have these three parts right, the top level Kanda plural site and in that last part, all the groups would have to coordinate to make sure they didn't collide with one another. So what often happens that as you get into larger, larger organizations, you'll add another standardized part to it. So we have calmed up plural site, but a florist They had their own development group for the accounting department. You won't agree that well. Everything created by the development group in the account department is calmed. A parole site thought accounting and then say if there was another group instead of portal site and say that was the group that took care of course management, that was their own development group. They would then agree that, well, all the packages they create or conduct parasite dot course management. And then there's no concern about colliding because then when they name their individual projects, if they need them both my project the Reason of Pakistan collision because the earlier part that was qualified by their group created the uniqueness again. These are all conventions. There's nothing enforcing all this but these air rules that we follow to make sure our package names don't collide. Now, as you put members in tow a package, those members, of course, become part of that package, right? And And that package becomes part of the members name, right? So we just build a class called mean. Well, the name of that class is just me. But now, once we put that class inside of a package right, the package name becomes part of the client overall class names, so the classes no longer known is just mean. The classes down, known as com dot prole site dot my project dot mean and that becomes again, a unique name. And because we all follow these naming conventions, we now know that anywhere anywhere else in the world can create class called me because it's qualified by a package that follows a convention. The class name itself is actually unique when qualified fully by the package. Now, when the most significant things affects us about packages at this early point in talking about Java is that it turns out these package names actually affect the source file structure. Now. What's interesting is that Java itself requires no correlation between your package names in your source code. File structure, in other words, doesn't care how the packages air named it doesn't force you to position or structure your source files on any given way. That's Java itself. The thing is, most I d ease do require your sub folder structure to match up to the parts of the package name. So you think is that even though Java doesn't require it, we kind of almost ignore that, because in practice, most tools that you work with are going to require that your source file structure match up to your package names. So what does that look like? Well, if we built a class, as we have earlier, where we didn't put inside of a package with the way the idea expects that to go is that you've got your source code folder, and then your job a class file just goes right inside that same source code folder. That's exactly what it expects. But if we now have a package definition or source code file, the presence of that package name now enforces a structural rules on the way. The idea expects the source could be laid out and basically is that each of the parts of that package need to either. I should say easily part of that package name. I need to be their own sub folder. So under source, the I D expects a calm sub folder to match the first part of the package name then under that expects a plural site sub folder and then an examples of older. And then finally, our main dot Java is expected to be inside of there. All right, so as you have different package names this hard, he's gonna have to match up to all those again. This is true and intelligent. It's true, and net beans a true in most ID's. Let's take a look now at how packages affect our application. So here we are in Tell A J. It's going to create a new project. It will, of course, be a job. A project? I can't remember that. The buttons at the bottom or office. The screen here at this resolution. So what? Get clicked at next button just accepted the falls here. I'm gonna go ahead and create the project template as a command line. Go down here and click the next button. So now would create my project project. He was going to be organized. The name that is a project. But now I'm going to give this one a package name. Right. So we're gonna follow that rules we talked about. Com stop Pearl ST and they're going to go ahead and add our final qualifier. Let's just call this one. Get organized. So our project name organized is a i D e. Concept rates. Just what we're calling the project in the I D. But this package name calm. The pro site that get organized is the package name were using with a job. A sense very often. The package, the last part of the package name is the same. Your project name. But I want to come different. In this case. It's a show that they're not directly related. All right, just going. Just finish this. So you were on the application now, right? We've got our source code, our senior class and police just like we did before. But now we have that package declaration at the top. I wanted two years. Let's go ahead and delete this line away. And let's go ahead and write some output. But this time will say something like Hello. Get organized. Where is this going to run this? Make sure everything's fine. So we're gonna just like we did before. Run, Run! We see there in our output our consulate of shows. Hello. Get organized. Everything ran just like it to be force within the I d. Nothing drilling any different. Let's take a look now about how that change to a package affected our source code Fire key . Right. So I created Project organizes the Fuller created it in. So it's inside of there are SRC our source code area. But now notice that we have a calm plural site and then they get organized, right? So that's where our main that Jonah is so create our folders just like we thought it would . But let's see how it affects our class name now, right? So we go back up here to the organized level, we're gonna go to the output floor, so out production and then organized. So I'm going there. That's got a bit of a command line here. Now, you notice right away that you don't see the main that job in their effective media jobs. Dexter down very down to get into this com folder structure. But I want to focus on that. We'll talk more about that aspect of it later in the course, but I want to do now is open at the command. Prompt. Right there. So we've got our command prompt, and we're gonna get to run the program. They're married. And we said when we run our programs, we actually identify the class name recently. Say, Java. We run a job program, going to say, calmed up. Parole site. Don't get organized. All right, That's our package name dot mean, so now when I run that we get our hello good organized. Because remember, we said by putting it in the package our class maim riel name is now the full, fully qualified name within the package. Kanda parasite get organized dot mean so by running that class name quality with the package or application ran correctly. Up to now, we don't all of our I d work inside of intelligence. So let's take a quick look at using net beans to create and run a project. Have a short cut to net beans right here on my desktop, so it's going to start that up. So here we are, inside of the Net beans, I D. Says, creating new projects which would say file new project When we come here, it does. That's what kind of project. So I want to be someone's going to be a job of project. It's gonna be a job application. So that's all fine, says Click Next. So now it comes in here and we first wants to project name. So we'll going cause we just call this our hello Net beans Project surges like intel. Ajay, the project name is really an I. D e concept. All right, so we want to do now is go through it, identify where we want to go, so it's gonna put it in the same demo fold I've been using for the other parts for the other demos down here. The creative main class. Right? So remember that we have our main entry point into our application now, in Net beans, you actually specify the package name and the class name all together. All right, So what if I the same rules of comped up for all site, So I've got that mean tot the top level of the package name was gonna make the next level to say example. So at this point, that's to my package name and then would give it that initial class. Remember said that although intelligent, always called it mean, we can call it anything. We want someone going Call it at Maine. So what this is really saying is that my initial classes called app mean and it's in the package calmed up. Parasite. That example. Let's get click finish. So here we are, inside of the source code. And what again closes output window for now. Just get it out the way so I can see more. Who knows? They're over there on the left. We've got our our says our source packages, and that's our app mean dot Java, which is the source code file we're in right now nears there at the top. It creates our package decoration, Kanda prospective example and was your class definition. We've got our main entry point, which is the public static, void main. And so that's where our co will run from Initially, you know, is also that net beans even put some initial comments in. It was a block comment at the very top there, just telling us a little about working with the idea itself. If you notice there's the slash star star above the at mean, that's actually a job, a docks comment. So it's even initially laying it out so that we have Java docks in place for the APP main and even for our main entry point. Let's go outside and inside of here. And let's just add a little code output something. So we've added the code now just to print out Hello, Net beans. Let's go up here and try running. It would go for my run menu. She's run project so we can see their output window that we've got to Hello, net beans. Put it out. So we were able to run our since a compiler runner application that easily, Very much like what we did in intelligence. What we saw there were some some basic differences in terms of how we created an initial class name created the project will, fundamentally, all the ideas work in very similar ways. Now, let's take a look at if we want to actually run this application from command line where we would actually find the folder so that we could actually run it. Remember that I mentioned earlier that each of the I. D. E. S kind of sets up its output folder structure a little bit differently. So here I am in my demo folder and here's our Hello Net beans four that we created for this project. Go down inside of there. You notice here that in net beans instead of having an output for we actually have this build folder. Let's go in there and there's a classes folder, right? And that's we're gonna run our application from the command line here in the net A Net, beans, projects. We're gonna go ahead and just open of command from just like performance a java to runt and we're getting give the package call package qualified. Class name. So conduct pro site Done example and then our class name, which in this case we called APP Main ffolliott. Enter. We go there, see your output. Hello, nut beans, Right? So we still ran it exactly the same. The only difference was that the i d e for net beans create a slightly different output file structure than intelligent had to wrap up. Remember that we used the Java command execute our Java programs from the command line. But the key thing there is that it allows us to run our job programs without having to have a full I. D right. That's actually our job execution environment. When you run the program, we specify the class name, including its full package. Neighbors were not. Ring a fireworks during the class on windows and order. The access to Java command, which want to do, is make sure that you have your Jerry's been folder in your past environment. Variable as we saw a program for made up of statements, statements and with semi colons, and the parts of a statement are separated by a zero or more white spaces, that gives a lot of flexibility and how we want a four matter source code as we saw that on some of the examples that could get really ugly, especially, start using too many new lines. You want to be careful about how much weight space use, but use enough to keep things clear and easy to read. Comments are useful tool for adding notes to our source code, as well as hiding statements that we don't want to be seen by the compiler. For example, just when I take some code out to test something or may preserve some code for later, as we saw packed his provide organization where they help us assure uniqueness in our class names. And we also saw that most ideas were actually tie the source coach file structure to the package. Seems so that eats part of the package. Name is a separate sub folder, as they mentioned earlier. Packages are really important part of job, and we're gonna talk a whole bunch more about this later. In fact, they get their own module 3. 03 Variables, Data Types and Math Operators: In order to do anything interesting in the program, we have to have the ability to store and manipulate values. What allows us to do that are what we call variables right now. A variable. Simply put, it's just named data storage. Now, Java is a strongly typed language. What that means is that when we declare a variable, like in this case, we have a very well named data value. We have to specify the type of that variable in this case is what we call an ant something in store managers. So that means is that the data value variable can Onley store things that are compatible with the type. And as we go to the courts will talk about this idea of one type being compatible with another. Now we declare a variable, of course, then a sign of value to it. Rights are variable. Data value now holds the value 100. Now we use variables. We can do it the way we've done here, where we declare it, then assign it, or as a matter of convenience, we can declare them and assign them in a single statement. Java is a language, allows you to modify the values stored in a variable. You can store an initial value in a variable, and throughout the course of your program, you can modify the value that stored inside that variable. When it comes to naming variables in Java, we follow a combination of rules and conventions. The rules allows to use letters, numbers, the dollar signs and the underscore who by convention we only use letters and numbers. Rules require that that first character is not a number. But since conventions say that we never use a dollar sign on underscore, that means that we always end up starting it with a letter. So some examples are like If I wanted Claire available called Total Right T o T a l right, That's valid or grade for because the four is not the first character. That's a valid variable name. By convention, we followed the naming style known as Camel case, but that means is that the first layer of the variable name is a lower case letter. We started each word after the first with an uppercase letter and all other letters or lower case example would be bank account. Balance it. The first word is bank that starts with a lower case. Seconds accounts. We have a capital. A next word is balance its capital b Another example Level two training first word level is all lower case. We still have the number two in there. That's valid. But when we start to next word training, we use a capital T. Let's take a look now, at a simple case of using some variables. So I've got a program stubbed out here with my entry into my main method. I'm gonna get declare variable here called My Hvar has Type int. We could also call this a local variable just because it's local to the method main. We'll see some other ways to store information. They're not local. Throughout this course I've been here at least local variable my var. And if I got and trying to use my far right now instead, try the print that out. That would actually be an error because local variables don't automatically get a value. There's nothing to find stored inside of them. So we don't want to do that before we actually use a variable. Want to make sure and put something inside of it, right, so in this case, I have stored value 50 inside of my bar. So of course, now if I print that out, I'll get the value 50. I can go and declare another variable here. I'll call another far. He knows that my variables don't have to all declared the top. I could declare them anywhere in my flow of logic that I want to. All right, so my and another of our has the value 100 stored inside of it. If I print that out, of course I get 100. I can assign one variable to another, so I've assigned another of our to my var. What I'm saying is that I'm saying the value in another bar to my var. So if I print out my var, I get the value 100. One thing that's interesting to notice that if I go out here and I change another far, so I assign, that's a 200. If I printed out, it has 200 in it. But if I print out my var, it's still only has 100 in it. Basically, we're doing what's called copying by value. There, we'll talk a little bit more shortly about what's actually happening to the covers. Two allows the sign between one variable another without them staying link. But the key thing to remember here is that you declare variables. You assign values to them. We can modify our variables, and we can assign values from one variable to another. So as we've seen, when we declare our variables, we give them a type and the most fundamental types and job, or what it called primitive data types. And these are the data types are actually built into the language. Now, when you hear the term primitive data type, you may think there's something kind of lowly about them. You have something kind of, you know, less than modern about them, but that's not true at all. Print of data types are actually very important there, really the foundation of all other types that we use in Java. So they really that's the kind of strong foundation we're going to build on for any other data types we use in our programs. Now there are four categories of primitive types in Java. There the energy types, floating point character and bullion. So let's look first at the energy types. Now there are four different imager types, but the difference then really is just the size of storage that they take up. But that difference in the size of storage they take up affects the range of values that could be stored there. Right? So the smallest Intertype is the bite type, right? So it takes a eight bits looking only store between minus 1 28 and positive 1 27 And so we see when declaring which declare a variable of type bite. And we did the sign, the energy er is giving energy literal to it. All right, so here we have a blatant number of English letters equals 26. The next larger type is short, which takes up 16 bits. Right, Let's let you start, um, store between negative 30,000 posit. 3rd 2000 All right. Using exactly the same way. So we have here short feet in miles 5283. Probably the most common leaves energy type is one called Aunt. That's a 32 bit integer and being 32 bits, that's a store between minus two billion and positive. Two billion. And then the big energy type is what we call a long right. That's a big, 64 bit manager, and you see it in store huge values in it. Keeping an notice, though, is that when you use a long, literal value, you have to put that capital healthy end of it. Now. Java also has floating point types. Now the floating point types conform to the eye Tripoli standard for floating point and that may or may not be meaningful to you. When it really comes down to is that floating points allow you to store values that having fractional portion to them. Basically, it's sports positive, negative zero values that have some fractional portion. There's a lot of nuances to the way floating points work, and they're kind of outside the scope of this course. But I've got that you are on the screen there for you. If you want to know a lot more about the details in terms of how footing points working kind of the oddities of them encourage you to check that out. But basically we have are two floating point types in Java. First we have the float type, which is a 32 bit floating point value knows that when we used the flow type, we have to put the F at the end of any constants for its. When we declare this float called Miles in a marathon 26.2 F, saying it's actually a floating point value and then we also have double, which is a 64 bit floating point value. If you just use a literal that has a desk wanted. The compiler assumes it's a double, which can also make it explicitly a double by putting a D at the end. So we look here. We have double Adam within meters, you see that 0.1 d denotes that that is a double literal, and our last two primitive types are character and buoyant and a character or the exit. A carrot type stores a single Unicode character, and basically you didn't note the liberals of these by just using a single apostrophes or single quotes around the constants rights. If I say care, the regular U equals and I put a pasta you apostrophe that assigns that car into it. I know this is different. Them strings. We'll talk about strings later. Carriages, a single character value. And because the carrot type supports Unicode, you can actually specify any valid Unicode character in there. So if you want a sign a Unicode character that you don't have in your keyboard, you can use the Unicode code point by using that slash you notation right. So you see here I've got this car accented you with the apostrophe slashed use ears or D A says that that is actually a you with an accent on it. And then finally, we have our bullion types pulling types store true and false. The liberals for that are true and false. So if I say Boolean, I Love Jonah equals true Java, primitive types are stored by value, and that's important, understand, because it affects the behaviour applications. When we assign values from one variable toe another, let's take a look here if I declare an initial variable called First Value and I signed by 100 to it, what's actually happening under the covers is that an area of memories being allocated that's named first Value and the Value 100 is stored inside that memory. So now if I declare another variable in this case, other value on a sign first value to it again a Maliki an area of storage. I'm giving it a name, other value. And when I make the assignment, the value 100 is being copied from first value into other value. And when that means is that there's a distinctly separate copy of that value 100 being moved over into other value. What that allows me to do that is that if I make modifications to first Value, for example, assigned the value 50 to it, that 50 replaces what's in first value. But it leaves the very well called other value completely untouched, right? And that's what mean by being stored by value that each primitive type variable has its own separate copy of the data. Something we commonly have to do in our programs is perform arithmetic operations. Java provides three basic categories of operators for performing math operations. There. The basic operators, like add, subtract, multiply and divide called free fixed and post fix operators, and they never called compound assignment operators. The basic math operators are just you. Just what you would expect things like add, subtract, multiply and divide. The operatives were used for these or again things were very familiar. Or if I'm adding a U A plus sign, right and when I do things like ad doesn't really matter what I'm using a floating point or a manager, right? So if I say one plus two, the answer is going to be three. All right. First Tractor used the minus sign again. It doesn't really matter whether using floating pointer imagers if I subtract four from five, I get one from Multiply was an asterisk. Four times two is eight, and all that stuff is really straightforward. As we get to the Divine operations, though, there are some differences between floating point and integer. Right? If I take 13.0 and divided by five points here, right, that's a floating point Operation. 40 points have fractions, so I will get 2.6. But now, if I take the energy er 13 divided by five and that's an integer operations managers don't have fractions. So actually get just to it doesn't matter what the fractional portion would be. It's just dropped. There's no rounding or anything. It's just the whole number of times that you can do the division right, so five goes into 13 to hold times. There's another operator called the modulates Operator, also known as the remainder operator, and that gives you the remainder of the divide. All right, so let's look at the energy first on this one. If I say 13 module is five, that's the percent symbol. My answer will be three right five goes into 13 to hold times, leaving three right five times to his tense. Affect him from 13. You get three, and you can do a mindless on floating point as well, right? So I do 13.0 modules, 5.0. I'll have a remainder of 3.0 as we look to prefix and post its operators. They allows toe operate directly on a value. The plus plus symbol is the increment right increments value by one at the minus minus. Simple documents value by one, whereas if you look here, if I have a variable, my vow and I said it to five. If I say sprint out plus plus my vow, that's the increment operator because it's before the actual variable. Two plus months before the variable. That's a prefix, which means that the operation is actually applied before we get the value back. So if we result of this Prince statement is actually six right to five was implemented, so we print out of six. If I print my Val again right, it's still six. But now, if I move the operator after the variable, it's no post fix operator. And what that means is that I get the value back and then the operations performed right? So I look at someone or code here where I have my variable. My Val. I said it to five, but this time, when I put it out, I say my vow plus plus don't so I'm gonna post fix increment. The value printed will be five, because that five was returned. But my vow is now incriminated. If I print my vow now, I will get six. The last category of math operators will be called compound assignment operators. What these do is they combine an operation and the assignment, so basically it looks at the right side of the operator, takes whatever that is and applies the operation to the left side, and then stores value into the left side. So let's see what that looks like if I gotta have my vow and I said it equal to 50. If I say my vow minus equal five. All right, so the right hand side value is five, right? The left hand side value is currently 50. It applies the operation, which is the minus sign, so it's attracts five from 50 and then stores of value back into my Val. It's if I print out my Val. My Val has 45 and they're available for all five basic math operations. In my experience, I used the minus equals, and the plus equals foreign away the most. But you do find occasion to use the other ones as well. It's looking at another example. If I have ah, unusual result equals 100 and I have two more variables. Val one equals five and Val two equals 10. Find out, say result. Divi equals Val one times vowed to remember. That's going to get the complete result of the right sign, right? So if I look at Val one times vowed to the result of five times 10 is 50 and then takes the existing value in results, which in this case is 100 and then it then takes that operator. It's a divide and performs that operation between them. So it's going to divide 100 by 50 and in store that back into a variable called results. So we print out the value of two. The operators are evaluated in a well defined order. If we look at them. Basically, the post Rex operators are evaluated first, then prefix operators, then the moment multiplication. I've operations, multiplication division and modular us. And then finally, the additive operations rate, plus and minus operates of equal presidents are evaluated from the left side of the equation, moving right and you can override presidents by using parentheses. And if you have nested parentheses, those princes were evaluated from the inside out. To get a better sense of how operator presidents works, let's take a look at some code. We have a simple program here, with four variables declared at the top. We want to do is kind of set up some math operations and see how the order of precedence affects the result we get. That's going to clear an imager for a result. So you call that result one want to do here is one. Take the verbal valet, and I'm going to go ahead and so attract Valbe from it. And then I'll divide that by Val. See for instance here and then just duplicate that now. So another one just like it call this one result to and I'm gonna do is put a set of parentheses in prison. Apprentices around valet and Valbe here. All right, where this Prentice's in place. So the last thing I would do is just go ahead and print these guys out. All right? That's good. Run it. As we run it. We see that we get two very different results, right? The 1st 1 result one gives value of 19 2nd one result to give us a value of five. And what's happening there while in the first line were set result one. Remember that multiplication of operations take precedence over additive operations, right? So division is a multiplicity of operation. So basically, value B, which is six, was divided by value see, which is three, which gave us a result of two. So then we subtracted that, too, from value A, which is 21 giving us 19 the 2nd 1 result to because of the parentheses. We overrode that that normal water of operations. As a result, we first attracted six from 21 which gave us 15. And then we divided that by three, which gave us a result. Five. All right, so we overrode that normal our order of operations by adding Principe's. So let's look at another case here we'll go in and pick us up. Another equation was a result. Three here and for results three will do Is was that value? A. We'll divide that by value. See, there were more by that times Value D and then finally add in value Be, I said, sets up once it's getting copy this now and will duplicate it. But then we'll modified a little bit, so we'll call a result result for we'll use them parentheses. So first thing I'd do is put frenzies around this addition here, value D and value be. And then when I do it for another set around value see and the result of value D plus value be so I've not got nested parentheses, I said, With that in place now, what I want to dio is this. Go ahead and print these guys out as well. Okay, we're all set there. That's good. And run it And it was again. We get very different results, right for the result. Three, we get 13 for result four. We get the number one. What's different. Or again, remember that multiple of operations come ahead of additive. And then when two operations are on the same presence there left to right, So in a result, three. The first thing that happens is value. A is divided by value. See, Evaluate has a value 21. But you see has a value of three. So give us a value of seven, then that's multiplied by value. DE, which has a value of ones that still seven and then we add in Value B, which has a value of six. And that gives us 13 but down result four because of the parentheses were changing that order of operations. Right? So we have nested prints, you go into the innermost one. So first we get value D plus value. Be very D is one that you be a six. A one plus six is seven. We multiply that times values see, which is three, which is 21 and then we divide value A, which is 21 by 21. Giving us result of one operations in our applications will commonly involve multiple data types. Because of that, we have to deal with type conversions. Now there are implicit type conversions and those air type conversions that are performed automatically by the compiler. To see a simple example of that, we look at something like here we have a ninja rival that we've assigned value 50. If I didn't say long El Valle Eagles, I've al the compiler has to convert that 32 bit in a drive out into a 64 bit injure as it's stored into Elvis. And there are also explicit type conversions and these conversions that I explicitly perform in my code. And I do that using a cast operator we see here. If I have that long, El Valle equals 50 now, so I'm now assigning a 64 bit imager, the value of 50. If I want to sign that into this, I've out a 32 bit imager. I have to explicitly cast it. I have to tell the good part of that. I want to go from that 64 bit injure into a 32 bit integer, and I do that by using the type I wanna convert do in this case and putting it inside of parentheses and put it next to the value of when a cast. So this, says Thean Prince, He says, take the L vow and cast it down to a 32 bit integer. If we looked at these implicit type conversions, these air generally we call widening conversions, and these could be done automatically because we're moving to a wider data type. So if I have a 32 bit integer and I want to move to a 64 bit injury, that's wider, right? So if the value can be safely moved. So those to be done implicitly and the compiler has to make decisions about how to make these conversions and the rules are pretty straightforward. If I have expression with multiple imager sizes in it, all right, maybe have a short and the long whatever the largest emitter sizes is what things will be converted to. So I do an operation with a short and the long the short will be implicitly cast into alone by performing operation with mixed floating point sizes. So I have a float and the double. It will always go to the double because double is the largest floating point size. And then, if I have an operation that uses imager types and floating point types compatible cast to whatever the largest floating point in the equation is there is value in operation with a long and the float. The longer we cast toe afloat by doing operation with a long and a double lung would then be cast to a double explicit type. Conversions are the ones that we explicitly perform in our code, right using this cast operation. When we do that, we're taking responsibility for whatever happens. As a result, that type conversion. Because of that, we can perform both widening cat conversions and narrowing right so wide in going from a 32 bit to say 64 bit. Now we're going from a 64 bit down to a 32 bit. We just want to be aware that we know what could potentially happen and if we do an explicit cast from a floating point to an imager, while floating points can have fractional portions editors can, so any fractional portion would be dropped. When I cast that flute down to a manager, you want to be careful when performing a narrowing conversion. But if I have a 64 bit imager, it has the ability to hold values that are too large to fit into a 32 bit editor. So I cast that 64 bit to a 32 bit. The program will actually do it, but if the value is too large to fit into a 32 bit, you'll get some odd results from that. You want to make sure that when you're casting it, doing a narrowing cast that you know that what you're doing is safe. And the last one is just that. You want to be careful when converting from an injury to a floating point. Because if you have an energy with a large number of significant digits because of the way floating points are stored, you could lose some of those significant digits. The deep details of how these type conversions occur are beyond the scope of this course, but if you'd like to understand them in more detail, I've got that your own screen for you. That actually points to the job of documentation that talks about those details. If you check that out, you'll particularly one look at the sections on widening primitive conversion and narrowing primitive conversion. Let's jump into some code now and see these type conversion behaviors in action. We have a simple program here that has, um, declarations at the top float double byte, short and long, and the variables reached name to help identify what they're types are like. Floaters float vow long as long vow, and then problem just prints out of a success message if it runs. So you see how some of the type conversions come into play here. So it's first of all, it's just going to create a variable will be of, ah, short. Just call it results. I think it's going call a result one, and we just do a simple assignment. So first we just a sign The blade vowed to it Now, as we expect for if I couldn't run this run successfully, we know that's a valid assignment because a bite could be assigned into a short because that is a widening conversion. Now, if I take this bite Valdo and I make it a long vowel instead. So now it's actually along. If I run this alright, I get the an Aramis, you're saying incompatible. Telia's possible loss conversion from long to short. So what I can do here does that I could do it. Explicit cast was put short in front of this, so now it's valid so I can run into. Of course it works because the long could not go into the short because that was a narrowing conversion. But by putting the explicit cast in front of it. Now it's valid. If I want to, I can put a cast notation and into my one if I want to be very explicit and say that you know, I know. Although Blake conversion is legal, I want explicitly show that I'm casting it by putting the short cast in there. I can do that and that's completely illegal. So let's take a look at another scenario would create another very well call result to and result to is a short as well, and when I want to do years, there's gonna take my bite value and I want to subtract the long value right now. we know that's not legal, because the result of the expression is going to be the size of the largest energy or in it right, which is the long right. So if I run this exc in air saying that it's not valid to convert a long to a short, but it's that I want to get and keep that result was a short while, I need to do a cast. But what I want to cast this time is the value of the entire resulting right. So I'm gonna do is put the short cast in front of it here. Then what I'll do is go ahead and wrap the whole thing in parentheses. Right? So now we're saying, Is that the result of blight found minus long vow which will be a size long? We want to cast that down to a short rights over on this. Now it will run successfully. So now let's try another one. Good. Declare another room call result three. But I'll declare this one is a long so I've got a result three. And what I'll do here is I will sign that are long vow minus our float valve. There's no if I run that. Erin now says that it's a loss conversion floating, converting from a float to along right, because whenever we have a energy type and any floating point type, the result is going to be the floating point type, says Good and convert our result now toe a flute. It's about making that afloat actually get run it and it runs successfully her. But now, if I take the flow of AL here and I converted to be a double thou and if I try to run this , I get the error because it says the result is going to be a double, because again, when you do an engine of floating point, it's the size of the largest floating point in the equation, right? That's good and make this result of double. So now you're on it. All right, let's look at one more, so I'm gonna have another result that I'll make a long And so this result were calling results for and what I'll do here as I'll just take the short value and subtract the long value from it. We know that's valid because the largest type in there is long and results long. That's OK, But now let's go ahead and add in the float valve, right? So if I run it now, how could an error message saying What doesn't convert a float to along? Let's go one step further. Now let's go ahead. Also an ad in our double Val and now they're on it. We'll still get in there. But now it says unable, convert a double to along. So as we see our result, here are errors air changing based on the types that are involved, right when it was all an injures, it was the size of the largest and injure. There once was a floating point involved. It's a size that largest floating point, right? So when it was a short and a long whose along it was a short along and afloat, the result became a flute and then was a short along afloat in a double result became a double. So the run this that's good and cast this whole thing to be along, so mixes along. Can we wrap the whole thing in parentheses? And now we feel to run it just fine to wrap up here that variables air strongly typed in Java and the foundation. The job type system are the primitive types. We saw that there were four categories of those managers floating point character and bullion. But then, within the energy and floating point types, they're even types of varying sizes, Right, so images to be a small is a bite with only eight bits are as large as a long with 64 pits , so money floating points had float with 32 bits and double with 64 bits. We have a really rich list of math math operators, anything from the basic operations like add, subtract, multiply and divide to the post fix of prefix operators allows to increment and decadent values to the compound assignment operators that allow us to apply an operation to the value invariable and store that result back into the same variable her do that our math operators, following a well defined order of precedence, I remember that you can actually affect order of precedence by using parentheses, and then it comes to type conversions. We often have to move between different types because our programs, as they get more complexity, will likely involve multiple data types. The compiler can handle type conversions that are widening, moving into from one type to another that can hold larger values. But you can also use casting to explicitly perform those type conversions that the compiler can't perform automatically. 4. 04 Conditional Logic Looping and Arrays: adding additional logic is one of those simple things we do on our programs, but they're really central to them behaving well. When we talk about attic additional logical, all we're saying is that our program will behave differently. Based on differences and data values. There are four things we need to understand to do. This one is relation all operators. That gives the ability to test different values something called conditional assignments, which allows to assign values differently based on conditions. The if statement, which allows us to change our code path in our application and then logical operators that allows to combine different conditions together. Looking first at relational operators, these allow us to test values against one another that these air very familiar if you're coming from any other programming language, would just go fill quickly. The 1st 1 is greater than is the first value larger than the second value look at an energy example. Five is greater than four. We get into character data values, but this doesn't this uses the different Unicode code points. If the code point is larger than the sort order comparisons considered larger, so C is greater than a There's no way to do a greater than with the bullion. I think there's great they're equal to which says that if they're the same or the 1st 1 is larger, all right, so five is greater than we could before. But four is also greater than or equal to four because it's the same. Our character ones that you see is greater than or equal to A and A is greater than or equal to a less than is the 1st 1 less than the SEC. 14 is less than five, right? A is less than C, less than or equal four is less than or equal to 54 is also less than ever before. Now we get to equal Teoh right now equal to is the equipped is equivalent. Are the values the same right? And we use to equal sign to do that right. So five is equal to five. Right and C is equal to see that makes sense, but we get to the bullion. Basically, they're equal. If both sides are the same, right, so true is equal to true, so that makes sense, but also false is equal of false right. So if you have to false values compared for equal. That resolves the true because those values are the scene and then finally not equal to is simply are they different? Right? Four is not able to five a is Michael to see and true is not equal false. A conditional assignment allows us to assign value to a variable based on result of some condition. If we look at setting setting up an assignment here for external divine things into multiple parts, where we have a question mark and a colon, well, that lets us do is have a condition, and then we test that condition. Condition is true. We returned the value immediately after the question mark, but the condition is false. We returned value after the colon. Great to see that in action. Have some civil code here. We've got two variables or V 1 to 7, and V two is five. And now I set this up so that my V max equals V one greater than V two. Rights were doing that condition. We test that condition is seven greater than five. Since it is V, Max gets back the first value of the V one, which is a seven. It's a true value. Look at another example. I set this up. I have students, is 30 and rooms is four. If I say that students for room equals the condition is rooms equal to zero? Well, if it was true, we returned zero. But if it's false, which it is, we go into the equation of dividing students by rooms. So the value in students per room is 7.5. The result of that equation. The F L statement allows us conditionally execute another statement, right? So rather just return a value. We can execute an actual statement. So basically, we start with just keyword if followed by parentheses and inside of the parentheses, we had a condition and then following that we have this statement we want to execute. If that condition is true, what condition was false would just skip over that statement. Right. So to see that in action, have some Cody arrived. Two variables fee one is 10. V two is four. I say if V one is greater than V two, print out V one is bigger, so basically just evaluates that condition as long as it's true, which in this case it is it prints out for you. One is bigger if statements can optionally have an else clause attitude them which says what you want to do if the condition is false, simply put else followed by whatever you want that action to be on the false side. So our code here we should say, else printout V. One is not bigger. Oftentimes you'll have more than simply if this condition is true or it's false, you may have multiple things you need to evaluate so you can actually change if else statements together. And when you do that, the system would just keep evaluating them until one is true. As we set that up with our regular, If statement is that we did before you followed by the else but everything else we can put another if and another condition. And if that condition is true, we have It's true statement, and we could repeat this as many times as we want, right. We could have 20 or 30 days in a row if we wanted to. That probably would be a good coating practice, but it's completely legal, and you can optionally have just else D and to say, Well, if none of those were true, what should I do? In that case, where did you see that? In code. Then we have Our V one is 10. V two is 40 he said. Well, V one is greater than V two. Frowned V one is bigger else. If V one is last in V two, Fran out V two is bigger. And if near those air, true, then pronounce if you want to veto recall. So in this case, the system would first evaluate the V one greater than V to its Not so it jumps down to the next condition. Is V one less than V two? Oh, it is. Go ahead and print out. V two is bigger thinking about our if statement where we said that an if statement conditionally executes another statement. And if you think that we never saw any kind of end if for anything like that. So how do we execute multiple statements? Conditionally? Well, that's where a block statement comes in a block. Staving groups individual statements into a compound statement. So we have a series of statements that we want to group together what we can do is ramped them in an opening bracket and a closing bracket, and that now makes them a compound statement and enables and be treated as a single statement. So we look at this in code. Bassam Cote set up your wife got V one equal 10 V to ical four and a variable def. And I say, if V one is greater than V two and I put in difficult V one minus V to print out V one is bigger and then def. The way this code is currently written, the assignment of def equals V one Minds V two is conditional on whether V one is greater than V two, but there to print statements. Their viewing is bigger and if will print every time, because only the single statement of the assignment of def is a tied to the condition. So that's where blocks David's come in by putting a open bracket after the F and in a closed bracket after that print of def. Now that becomes a block statement, and so the if now condition is tied to this entire three statements. Similarly, I could do that with, like, an else if I've got else's V to greater than V one, although by the way of my code indented, it looks like all three of these statements, the diff assignment to pronounce or tied to that fee to greater than V one. Currently on Lee, the diff assignment is tied to the condition again. I need to put an open bracket and a close bracket to bring those into a block statement, and I could hear asked at an else nothing to notice that blocks a what kind of independent from one another, right? So if you haven't if in an else if and announce if you wanna have block statements on part of them like I do on the if in the else if but just single statements on other parts like we do with the else, that's just fine. Just one other thing I want to bring note to as well in this code noticed the very first line of code. I'm doing it Variable declarations in a way I haven't done before. Noticed that on one line I'm declaring multiple variables of type int normally, and all of our other co we've done is on individual lines. I just want to show you here that you can actually do multiple verbal declarations on the one line like that. So we're saying that V one is an ant that has a value of 10. Initially, V two isn't as a value of four initially and deficit aunt. That's not yet initialized. Let's take a look. A demo re nest one if statement inside of another. We have a simple program here where we have two variables declared students, which is set to zero and rooms unless they want to do a very simple but a code where you say, if students is greater than zero. If that's true, I want to print the average number of students in each room. And then if it's students, is not grated 20 I don't get in print out the fact that there are no students. Okay, that's pretty simple, right? That's good. And run it and we run it. We get the message, we expect no students prints out, so that could working well. But now, if we look at this code, you know, I realized that you know, I'm dividing students by rooms. What would happen to rooms with zero? Well, just like in real mathematics, you can't divide by zero. Well, in Java you can't divide by zero either. All right, so if we're gonna really be, you know, good defensive programmers here, we would actually check to make sure that rooms was not zero before we actually trying to do this division. All right, so when I do, you're just out of line here. Just says, Well, only do this if rooms is greater than zero. Alright, so I've got that test in there That's good in dentist so that it matches up with our style here of in Denning underneath the EFS. That's going to run this now. And you notice that when we run it, we don't see are no students message. What happened? Very that worked before. Why is it going now? Well, because the else is matching up to the closed. This if to it. Right. So in this case, the else is matching up to the test for rooms being greater than zero. Even though we really want to test again. Are matchup began students greater than zero. So how do we fix that? Well, we can use the block statement style. What weaken Dio is take the if here put open bracket before it, and then another open bracket here and now that closes up that if block right, so that that prevents the else from matching up to the if for rooms we've closed that if for rooms with Anna Block under the if for students that way the else matches up to the if that we wanted to or so I couldn't run this. Now our program now performs correctly, printing out the no students message as we use these blocks statements. What happens if we declare variable inside of a block? Well, it turns out that variables they're cleared inside a block are only visible within that block. They're not visible beyond the scope of that block. And in fact, this idea of where variables visible is known as the variable scope. Let's take a look at some code. So I've got codes that appear right initialized students to 30 and rooms to four. So I put it, if stayed in a place where I want, just make sure that rooms is greater than zero, and I opened it up with my bracket, meaning I want to create a block so I have a closing bracket to close the block, and inside of that I print out students and rooms. And then I declare afloat called average, which as a result of students divided by rooms. Now, if I then outside the of block, attempt to print out average, actually to compile error, because once I leave that block average no longer exists. But notice that variables can come into the block, right? I've got students declared before the block started, and students is valid to use within the bloc. All right, stand thing is true for rooms. And so the way it works is that variables that air in scope when the block starts remain in scope, But variables that are created within the bloc go out of scope at the end of the block. So the way I would have to fix this code, I'd have to do one of two things. I'd have to declare average before the start of the blocks and move it up before the if, or I can move the print statement inside the block. While average is still available, logical operators are useful for arriving in a true or false value by operating on other things to provide true or false values. They could be Boolean variables, but more commonly logical operators. Air used to work on the results of other relational operations, right? So there are basically four fundamental logical operators and or exclusive or and call negation. And we look at this is that the and allows us to take two things can be resolved to true or false. And if both of those were true than the end returns. True as we look a little code here, I have three variables. Declare A B and C and I say if A is greater than be and B is greater than see print out A is greater than see what this does is that first we do the comparison of a being greater than be. In this case, it is very 20 is greater than 14 so a greater than be resolves the true. Then we operate on be greater than C 14 degrees in five that resolves true and then we and those two truths together and true and true equals true, it's one and resolves the true Onley. If both sides of it are also true, then we have an or or compares the two sides and only one side needs to be true, right? So if the first one's false and the second side is true, then that resolves the true. If the first that is true in second side is false. That still goes off the true. And even if both sides true the or resolves to truth now that's different than the exclusive war and the exclusive or exactly one side needs to be true. It could be false or true and then true or false, the case of exclusive or it just can't be true or true, and the last one is negation. Negation basically reverses the result. So basically, when you use negation, not false is true, right? So if we look at that and could battle boy invariable done, I say Done is false. Well, if I go if not done print out, keep going. Where we look at Dun Dun is false, but then the not of done are not of false is true. There are two special logical operators called conditional logical operators. There's a conditional and and conditional or now conceptually these resolve the same way as the other ads and wars we we looked at. The key difference, though, is that they Onley execute the right side of their test if they need to do that to determine the result. So in the case of an end, for an both sides have to be true. So a conditional logical and Onley executes the right signed If the left side was already true because the left side was false, we knew the ants going to fail Anyway, there's no reason to even run the right side of it in the case of the conditional logical or it only excuse the right sign if the left side is false because if the left side were true in that case, we already know we were done so we wouldn't need to execute the right side. So looking at the conditional and we still need both sides to be true for that to resolve the true. But when doing a test, if the left side had resolved the false, it would never even run the right side because we already know the result of the and would be falls began to traditional war. The left side is false, but you or that with a right side of true that resolves the true. But you do a conditional war in the left side is true. It never even runs the right side because we already know the results going to be true. Let's take a look at a demo comparing the behavior of a logical and to that of a conditional lodge gland. We have a simple program here where we have a two variables declared at the top. Right students equals 100 50 rooms equals zero. And let's say I want to put it a condition here where I want to print the message crowded. If there are more than 30 students to a room, I was gonna run me. If statement I'll just take students. Divide that by rooms. And then, if that's greater than 30 I'll go ahead and I'll print out my message. So the result of students about their rooms is great and 30 I print that crowded message. Of course, one of the issues I have is that well, what if rooms zero right again, you can't legally divide by zero. So I really want to say is that well, if rooms is greater than zero and students divided by rooms is greater than 30 then up around that message. So I'll do year it just put in your rooms greater than zero and then and students five rooms greater than 30. So that way we'll do both tests. Right rooms is greater than zero, so it will be a valid division. And then the result of the division writes. It's going to run this and notice what happens there. I'm getting an error message, right, because it's not legal to divide by zero, because what happened is that it first did rooms greater than zero now that tested to false , because rooms is not greater than zero. But then it tried to do the right hand side of the and as well. I try to do the students five my rooms, which created the air because you can't legally divide by zero. But now, if I go ahead and change this to the double air percent, making it the conditional logical and now we'll Onley do the right hand side if the left hand side was true or conditionally does the right hand side conditionally. Now, if I run it, I don't get their message. It ran successfully now. It didn't print the message out right, because the combined value of the test was false. Right rooms was not greater than zero, but we ran successfully, so we were able to conditionally execute the right hand side of the and based on left hand side. If the left hand side had been true, we would have also run the right hand side to see if it was true. But once the left hand side was false, we never been bothered running the right hand side. That's to another demo. Call our Cal King engine demo. Well, doing this demo is we're gonna create a simple application that can go through various just mathematical calculations as we're starting in this module, but will be using it throughout the course, enhancing it with the various things we learned. We'll start out by creating a brand new project. I'm going to use him. Tell a J for mine would use whatever you prefer. We'll create a new project. I remember that, as I mentioned earlier, that just because the screen resolution we recording you can't see the very bottom of this wizard screen. So you scroll appeared knows there's a next button down at the bottom. I was gonna get and create a job, a project by clicking. Next, go get and create a command line project again down there to bomb. There's a next button, so good and click that. So I'm gonna call this project Calle que Engine. And then for my packaging, I'm gonna be calmed up Pearl ST and I'll call it Dark Calkins. So I've got my project. Name my package name. Now I'm gonna click to finish button down there at the bottom. So now we have our application created Going to go in here and just get to this comment line another way throughout this project. Throughout this course, as we build this project, we're going again. Just do some mathematical operations and have the program kind of just to kind of smarter and smarter things for us. We're gonna initially start very simple, just doing very to member calculations. You adding two numbers together, multiplying two numbers together. That sort of thing we're gonna do is declare a couple of variables here at the top. First of all, so one of Clara two variables enter double vow one and vowed to I've got those two variables was gonna have another double for result. So now have the ability to have two values operate on store. The result. And what we'll do is that we use a concept glycolic op codes. We're just going to use, um, one letter code to indicate the mathematical operation we want to execute, like a for ad, ask for, subtract that sort of thing, going create a caravan Arable called off code, right? That's that's my basic ability to set the values of what I want to dio. And so I'm gonna go through now just up If statements to perform this operation is the 1st 1 will be at So that's going to the op code A. You could say if and then off code equals a right. So the op code is a What I want to do in that case is add the two numbers together and assigns a result. Right, So it's that simple. So I've got ta in place now for add and I want to do it, ask for subtracts. I'm trying to an else. If this case off code equals s and of course, in that case, it's gonna subtract value to from value one. And we'll do the same thing for D for divine and M for multiply. And finally we want to do is just print out the value of results. Renowned notice here that throughout the program the ideas is kind of underlining on my variables. They're showing me that there must be something wrong, and what it is is that we're trying to use all these variables without having initialized. Right. So we need to do is good finish line. That's going to set a vow 1 to 100 vowed to 2 50 So we've got there's initialized. Let's set our first off good here. Let's just make that a for ad. So now we've got all the variables were using initialized Right now we're going to assign result, But, you know, it's possible that maybe would set the op code wrong rights of it being a proper very like A s. Dear m. Maybe we actually put some like X whatever. So we'll do years that on the end of a else if Aladdin else just if it's not any of the values we expect, we're gonna get and set the results. Zero All right. So now we have, ah, very civil programming place, right that we can actually, just setting off coats that two values and get the result, right? So right now I'm said to add 100 plus 50 says getting around it on display 150 writes What did the math correctly? Of course, all I have to do now is changes from an A to a d right now will divide instead. So if I run it, I get to 150 is, too. It's were off to a good start here. Now we can make things a little better here, and we get this bottom window out of the way. Now when we have this bad op could just showing a result of zero could be confusing. So what, we probably does mean couldn't put an error message here. Right? So it's going print on error message. It says air invalid. Off code. It's a now, if we put in a bad value, would actually just display a message and make sure something useful, right? So I currently have a good value here. They're the op code is D, so that's still fine. But scared running. Make sure everything's OK and you'll notice that when I ran it now, right, I didn't get the proper after two point. Oh, I got zero, right? And that's because I need to make this a block else, right? Are blocks even with this else, right? Because remember, the else only had ties to the one line here. So by actually adding this print statement here, I'm forcing it to always that result zero, no matter what is done before that. So that makes us a block statement. And now, of course, it will do the right thing because it only sets results zero. If we're inside the else blocks, of course, Now offer on it. I get my 2.2 point zero displayed again. You know, One other thing, right? We're still exposed. Our divide to a divide by zero. Right? So good programing Practice, of course, is the always check to see if to divide the bottom. Valued adviser zero. Right. So what I would do here is say that if vowed to is not equal to zero, that in that case I'll do the division. Otherwise I want to set that equal, said the result equal to zero. All right, so now if I run it leaving Val two as 50 it displays 2.0. But if I change, vowed to to be a zero and run it. Now I get zero, which was doing the right thing. Now, one thing to note here is that and they have statement like this where you simply do a condition and then set a result. The one thing or another. Great. That's a great time to use that conditional assignment idea. What I can do here is, instead of that, if else like that, I can simply say results equals Val to not equal zero. And if it's not equal to zero, then go ahead and divine vowel by vowel to otherwise return zero. All right, so that one line replaces all of this because we're gonna comment that out. So now if I run it, it still runs correctly. My serve zero. Because Val to a zero I changed vowed to back to 50 running again rights now to point out now, one thing to note here is that it appears that we have multiple lines under this else, if for up code equals D, but remember that there's last four line to commented out, right? So it's still treated as if there's only one line under the else. If writes, we didn't need to make the block statement with a situation like this, where I've got code hanging around that you just kind of can be confusing because it just may seem odd that I've got all these statements there and Alison applied to the else. If it's often useful to go ahead and use a block statement just to make your code more readable, and so we do it, just put this in a block. Even though it's not necessary for the freedom to run correctly, it makes the program much more readable. Let's take a look now to three basic ways to write loops and Java First is a while loop than a do while loop, and then the four loop a while. Loop is really the simplest way to resolute. It allows you just to repeatedly execute some statement as long as the condition is true, the while infrastructure. So the condition is checked at the start of the loot, so basically used the while keyword. We have our condition And then we have the statement we want to repeatedly execute now. Because the condition is checked at the start of the loop, it's possible that the statement never executes. All right, let's look at an example. That's right. A simple But it could that will use to do a factorial function. Right? Factory was just You multiply a number times East number bullet Right? So five times, four times, three times, two times one that sort of thing. So we set it up with a while and we want to say that our value Cavell is greater than one. Right? So cable starts out of five. We're gonna keeps inside this loop as long as cave Al is greater than one. We then say R factorial is equal to itself. Times Cavell. Right? So the first time into this loop effect for it was one cave Alice five So factory becomes five, right? Five times one. Then we reduced Cavell by one. Cable Moniz equals one. We concave out For now, read it goes back up to the wild statement. So now checks four is greater. The one we do the factorial times cave ouster. Now that's five times four is 20 Que val becomes three. Give backs of Luke Frank three Still greater than one. Factorial is 20 times three, which is 60 k Valbe comes to to still greater than one factory that is 60 times to 120. Cavell now decorates down the one when we check our wild one is not going to the ones what falls through And then it would print the value 1 20 News for reasoning blocks even here in a while because the while up itself will only accept one statement Unless you put it in a block to kind of give an example of that there's a way we could actually write this same code to do the work without using a block statement. If we set this up right again, Cave Alice, go five Factorial is one. We do our loop Cavell greater than one. And then the statement we executed simply factorial times equals K vow minus minus to decorate Operator. In this case, renowned is performing the exact same work. But we didn't have to use a block statement because now we could just get and put it out so it repeatedly execute that factorial times equals K. Val mines mines until Cavell gets down to one another four of loop is a do while loop the do wallop repeal excuses statement as long as the condition is true. But unlike the while loop, it checks condition at the end of the loop. So we look at the layout for we have the do keyword The statement would execute with wild keyword and then the condition now because it checks the condition at the end of the loop, The body of the do while always executes at least once. So I see some code here. If I set this up and I have some integer value I've house at the five, my due in place. Now I'm gonna execute multiple statements. I'm going to set up a block did inside of here. I'm gonna go ahead and print out. I've Al you know, it's now most time. Up until now, we've called print line Print L In this case, we call just print. And what that does is when we print the value out, it prints it and doesn't go to a new line. All right, so now if I pray out after that star two equals. You like to put that on the same line. So I go ahead and calculate I've out times equals two, which now makes I've out 10. When I print line that now I get 10 displayed and next probably be on a new line. So getting clues, My loop here. Now I'm just gonna walk this loop over and over again. The last thing I need to do, of course, is include the condition. So I'm going to stay in this loop as long as I've hours less than 100. So that we knew. Currently, I vows tents next passed through the loop. It's gonna print out 10 times two equals 20. So I vows not 20. So less than 100 20 times two is 40 40 is still less than 100 40 times two is 80 80 is still less than 100 and now 80 times two equals 1 60 But now I've al has is now not less than 100 secreted 100 1 60 So our co dents now the key difference here from the while loop is that it will always execute at least once, right? So if I initialized I vow. Instead of being five, do something like 150 where it will still go through the loop one time. Putting out 1 50 times two equals 300. The last the basic loops we're gonna look at here is the four loop, just like the others. It repeatedly executes a statement as long as the condition is true and conditions checked at the start of the loop for it, very much like the while loop. And really, what is the four Loop is more of a convenience layout for a while. Let's look at a very common wild loop behavior that we want to several while live to first we do is initialize some value. In this case, it's, I vow, And then that while loop we would check a condition. This case I've out less than 100. Well, then do some work inside that live, like print something out. And then we would update our loop control variable, right? We'd actually, in this case, times equals two. Well, that's what we do very, very frequently. So the four loop provides a simplified notation for this scenario. We use the for loop. We used the four key word. Then within the parentheses, we initialize things. We have our condition for being in the loop and we have a place toe update the loop control . And then, of course, that excuse air statement. So you see that an example of that. We start out with our four keyword in the parentheses we do. The initialization, I vow, equals one. We have a condition. I've at less than 100 knows that each of these sections are separated by a semi colon. And then we have our update. I've out times equals two, and then the body of the loop we print out, I've All right, So this wild Lupin, the four loop both do the exact same thing for the four lives. Just makes that standard behavior of initialization condition enough date a bit more simplified. Just is all the loops if you want to actually execute multiple statements and put it in a block. All right, So just here for notation we could have an opening bracket and a closing bracket, and we could please many statements inside. There is we need to a razor, a really important part of job. Their formal definition is that they provide in order collection developments. What that really means is that they allow us to store multiple values of a common type under a single single name. So if we do something like float the vowels, but you notice that we've got that square bracket where it after floats, that indicates that we're declaring the vows as an array. So that allocates out of name now that can access on a ray. And then we use is cured, new and then float. Three, once it says is actually allocate space to store three float values, and they're all accessible under this one. Name the vowels. Now each of the members or elements of the array or accessed through an index and the index zero based. So basically, the index's run from 0 to 1 less than the number of elements, right? So in this case, we have our 1st 10 right, then one, then two. So, using that we can now put values in and get the values from the array. If I say the vows, Sub zero equals 10 that stores 10 in the zeroth position, then the vast one is 24 20 in one position and then the vows of two because 15 points 15 in the number two position. So that's what we want to do something like Go through this array and add everything up. Well, we're gonna Adam off advocates from space to store The result, called some The beauty of a raises, makes it very easy to move through these values using loops. And when the question, of course, is we have to know how many spaces the walk through well, a raise expose value called length to tell us how Maney elements air in there. So I can write a live like for int I equals zero is on his eyes less than the vows dot length without a walk through each element. Slums anchoring. I buy one each time What you've done here, so I can some of the values of disarray by simply some plus, equals the vows. So by each pastors loop, I'll go through a different element 0th 1st and then a number two element that I can, of course, print out that some. Now you notice here that this process of allocating the array and initializing it is pretty cumbersome. It takes a lot to do that. And that's something we might want to do very often in a program. So job, it makes it very easy to create. A shorthand for that is that after we declare the uranium, we can use an open bracket and then just list the values Clinton close it. And that has the same effect that all likely allocates the right number of spaces in this case three and initialize the value in each one of those faces. One of the most convenient ways to walk through the members of an array is the for each loop. Awesome. That is an enhanced four loop and what it does. It takes care of just executing that loop with statement within the loop wants for each member in the array. So basically, it's just a four key word. We have parentheses, but rather than having explicit conditions and are ran nationalisations, we actually just put the array in their preceded by colon. And then we declare a variable toe, hold an individual over a member, and then we can walk through the body of our loop. We'll go through once for each member of the array, and it takes here having the details of getting the length of the array as well as accessing each of the values later in the course will see that Afford Stoop can also work with other special data types other than a raise. But of the types we've talked about so far, a raise or the only thing that works with now the see it in action imagine we have this scenario again, where we've got an array of values. In this case, we get three values tim 0.0 20.0 and 15.0, and we want to sum them up just like we've done before. Well, rather than rain, that explicit four loop where we set up on an index variable increment ourselves, keep testing his condition with the for each loop we just have before so that well, I know that a ray has floats in it, have the colon, and then we have the vows. We simply have the array name there and now, inside the body of our loop here, we can simply say some plus equals current vow. And what will happen is that the first time through that loop, current vow will have a value of 10.0, which would make some temple in zero. Next time you come around the loop, current Val have a value of 20.0, making your some 30.0. Next time through the loop, current vow will have a value of 15.0, making her some 45.0. So we would print out 45.0 switch transfers, control to bricklayer statement based on a value and really what it's purpose in life is. Is this simplify the idea of testing against multiple matches. So you said of the switch keyword, You put in the value you want to test. No, this is not a condition, right? It's the value you want to test, and then you go through inside a set of ah brackets, the word case and the different values you wanna match against. And then this statement you want to run if matches against that value in the word case again in another value on a magic ants and those statements repeat that as many times as you like now. Of the primitive types we talked about, only care and imagers can be used with a switch later in the course will learn other types that we worked with a switch of those we've talked about so far, only care and injured types could be used. One thing to notice that a match can execute more than one statement. Notice that under the case t 5. 05 Representing Complex Types with Classes: Java is an object oriented language. That means, of course, that it follows the tenants of object oriented programming. And so obviously these things that encapsulate the data operations and uses semantics, in other words, is that what you want to work on and how you work with it are kind of package up, this idea of on object. I just allow the storage and manipulation details of things to be hidden right so that when someone's working with an object, they focus on what they wanna have done. It's not their concern on how it's done right. The class implementer of the object implementer actually focuses on the how to consumer or user just focuses on the Watts is That's a really powerful idea that allows us to build more conflicts, programs the way we get the objects in Java is through classes. Classes provided structure for describing in creating or objects that the classes are the things that we used to be able to describe our objects and then be able to in stanciute them, bring them into existence. To be worked with basically, a class is a template for creating an object. So the idea is that we want toe declare class. We use the class keyword followed by the class name. Normally, when we create our classes, we put him in their own source file and that source file will have the same name as the class itself. There are some caveats, so that that will talk about shortly. But but in most cases, your source felony, which will be the class name dot Java. Now the body. The class isn't just contained inside of brackets. You have an opening bracket and the closing bracket. And that's where the contents the class is gonna go all inside of there. Now imagine that classes have both the state and what we want to do with it. All right, so the idea is that a class has data inside of it and all of its excusable code. So this captured one of three general ideas, or is that the state itself is in what we call Fields. As we look at our class flight, we've declared here, it's got to fields in right to both senators, one for passengers and one for seats. Classes also have methods. This is the excusable code that's going to manipulate the state and perform any operations . And so, in this case, our class has a method called Add one passenger. And basically, when someone calls that and make sure that there's enough seats available on long as there is because it adds another passenger, and then there's what it called constructors constructors are a special case external code . This is code that gets run during the creation of an object, largely to set the initial state. So we've got here a constructor that basically starts out by setting seats to 150 our passengers to zero. So basic means that when we created a flight, that flight has 150 seats on it. When you're ready to use a class, as you would expect, you would go ahead and declare variable the thing we're gonna be aware of, those that declaring of variable simply allocates space to store will call a reference to the actual optic we want to use to actually create an instance of our class of the resident is an object. We have to use the new cure. So we do. We've got our variable N Y C T S f. We assign that the value of new flight. What that then does is the called a new flame, allocates the memory associate ID with that class and then returns back a reference to it. So that means it is that that variable NYC tassef is not the object itself, but a reference to the object. Now, each instance that we create will be separate from one another. And you see here that I've actually declared the variable and then assigned the object to it in two separate statements. We can, of course, do that in a single statement. So I've got a variable SLC to Dallas, equals new flight, allocates out the SLC to Dallas, which is the space for the reference creates the instance of flight and assigns the reference to our variable. So each of these air two distinct instances of our flight object in each of their own variables, and we can then call a method on one of those instances in this case would call add one passenger on our SLC to Dallas for calls. Are passengers to go from zero no one. As we saw him, we were using our classes and creating class instances. These objects we saw the variable wasn't the object itself and said it was a reference to the object that tells us that we're working with reference types and as important implications when it comes to working with objects. So we look at some code here if I declare a variable flight one that points to a new flight that allocates out the variable flight. One allocates last the instance of our object and puts a reference to that object in the Flight one and do the same thing for flight to write. That creates a separate object incised into a separate variable flight to So there's two objects are completely separate from one another. And so, if I call, add one passenger on flight two. The African since pointed to my flight to will have its passengers implemented from 0 to 1 . So, of course, if I print out Flight two passengers, it prints out one. Now if I assign Flight 12 flight to that doesn't copy the entire object pointing to from by Flight one in the flight to all that does was reassigned the reference So that flight to know instead of pointing to the object, it currently points dio well now point to the same object that Flight one points dio. So now, once that object, pointing to buy flight to or previously pointed by, Flight two is no longer reference, that object goes away and flight to in Flight 1.2 now to the exact same object. If I now printout flight to dot passengers, it prints out zero because that's the value of pastors in the objects pointing to. So now, if I work through Flight one and I say, add one passenger or the increments pastors from 0 to 1, Of course, by then caught add one passenger again on Flight one that increments it from 1 to 2. So now if I print out flight to Don passengers, I get out the value to our print out the value, too. Right? So it's important. Understand that we make these assignments. We're signing references around not entire object, right? This is very different from what we're working with primitive types where the values were actually copied around. So it's really important understand that that as referenced types, assignments causes to point to the same optic instances as opposed to making complete copies. Since Josh has an optical in language. We want to use good object oriented techniques. We build our programs. You hear that? One of things we talked about, that when you consume an object or when you use an object, you won't be able to think more about the what of what you're doing, not the how of what you're doing. That's one important idea in there is that as we build our objects, the internal representation of those objects should generally be hidden. Theme user of an object shouldn't have you know a whole lot about the way that object is built. So the idea of hiding this internal representation is an idea we call encapsulation. And in Java, the way we achieve encapsulation is by using access modifiers. Let's look at some of the most basic access modifiers now. The most basic access modifier. It all is to have no access modifier, and in fact, that's what we've been doing up until now. If it class or a class member does not have an access modifier on it, that's considered what we call package private, only usable within its own package. We'll talk more about that when, later, in the course, when we spend more time on packages now, one of once we commonly see is the public access modifier. And if a class where class members marches public, that means it can just be used anywhere, anywhere, in all in the program. And the last we're gonna talk about for now is one called private. If a class member is marked as private, it's only accessible from within the class. Where's declared now? Top level classes, the kind of classes that were working with right now cannot use the private access modifier Little later in the course, we'll talk about some scenarios with nested classes where we can use the private access modifier. Let's take a look at how the Axis modifiers affect the uses of our classes. Class members. I have your base of the same class we looked at earlier in our class flight as some fields declared the top pastors and seats as a constructor, then has a method add one passenger, and I've also added another method to this called handle Too many that gets called from ad one passenger, the idea being that when we call out one passenger, if there's none of seats, Adam Pastoral call handled too many to do whatever we want to have happen when we have too many passengers. So let's take this and we'll go ahead and add a public access modifier to class flight. Know what that means, Of course, is that we're now allowed to access class flight from anywhere so we can go out there and declare a variable called Flight one of type flight. I'm gonna get head in Mark. The constructor is public as well, which means I'm also allowed to now create instances of this class. We'll talk more about constructors shortly. The key thing here is that we are allowed to create instances of the flight class. Now let's take our two fields, passengers and seats and will mark. Those is private now is private. They're accessible from within the class. So inside of a constructor were allowed tax system Inside that method, add one passenger, are allowed to access them. That's fine, But if from outside the class we try to do something like we did earlier, like print out the value of pastures that's no longer allowed, right, that would actually be a compile time air, so we wouldn't be allowed to have that code in our program, accessing it from outside the class, looking at our methods. Let's say we mark add one passengers public and handle too many as private. Well, from outside the class, I'm free to call. Add one passenger or that causing to add one passenger. I want Pastor if it checks the number of seats. If there are already full, it actually called down to handle too many. And that would be just fine because we're accessing able to many from with inside of our flight class. But it from the outside we tried to call handle too many again. That would be a compile time error, right? Were not allowed to access it from outside of the class. No one thing the new now their classes marked as public. Remember there earlier, I mentioned that the class file four class normally has the same name as the class. Well, once we mark this class is public, that becomes a requirement. Public classes have to be inside of a source file with same name, So a public class called Flight has been a source file called Flight dot Java. Now it's not marked his public that requirement is not in place are your last name file. Whatever you want. You always want to be careful about choosing the name, the class file, something different than the class. There are legitimate reasons to do so, but just consider that carefully. This is a great time for us just to take a minute and look at the rules and conventions for creating class names. No glass names have the same rules as variable names in terms what characters are allowed, and they actually even follow most of the same conventions. They still use only letters and numbers. The first character is always a letter, but one of the key differences in conventions. They follow a naming pattern called Pascal Case, which says that the first letter of every word, including the first word, is upper case, although the rest being lower case. So we have a class name like bank account, both the be in bank and the A and account or both capital. Right? If that was a variable name to be, would have been lower case, and what we want to do is that we were naming our classes. We want to use descriptive noun so I want to say things like a class called person, right or class training video. And in general, we want to avoid abbreviations. We want to use full words now. The caveat to that would be any scenario where the abbreviation tends to be more widely used in the word itself. Like people rarely say Uniform Resource Locator. Using your AL is much more common now. We've mentioned that methods are basically just excusable code that we can use to manipulate the state of our objects were in perform operations. Basically, each method has a name. Now the rules for creating method names are the same as a word variables. One things we normally do from a stylistic standpoint, though, is use a verb or some kind of action statement to ah Neymar methods. Their methods have return type and in job, but there's always a return type. So if a method doesn't return anything than that, return type is void and then a method can have parameters, and so parameters start with parentheses. After the method, name you. Then list of parameters close friends see, and then the body of the method is enclosed in brackets will, however, many statements it takes to build your method. No, no, these brackets are not a statement. Block right there always required even your method only had one statement. That statement goes inside of brackets in a method. All right, so to see an example, that's great. It really simple method here, and we'll have it not return any any values when we could avoid method. Let's say we'll call this guy shows some Let's say we want this method to Dio is maybe take two floating point values, add them up, and then we'll print out that value multiple times. It'll be three parameters here as we have our open perent. So they have a float X Akama to separate it from the next parameter afloat. Why a common separated from X parameter and then it didn't count. So the ideas that will add extra why and then print that result out count number of times. So it closed parentheses within. Put our brackets in place for the body and they won't do the work, so we'll add X plus y to get some will create a loop two counts from zero and an in preventing I each time as long as it's less than count and then prints that value out. So when it comes time to use this method, the first would do is go ahead and just wrap it up inside of a class cause all methods are inside of classes. We'll go ahead and make her method public so we can access it and then put together some code will first create an instance of our object. And they were to say, object instance Name, which is M dot shows some right calling the method we're gonna pass in 7.51 point four and three races, 7.5 will go into ex. The 1.4 goes in the why, and it's three goes into count. All right, So what would happen then is that some will become 7.5 plus 1.48 point nine. They were going to go inside of our loop and print that out three times so we would see a 30.9 printed out three times looking at that method we created in the last clip. Basically, we call into the method. The method runs until it's done, and then it exits Well, there are actually, three reasons a method will exit one is that it reaches the end of the method, which is the case in our show. Some method here. You can also put a return statement in to indicate that you want to exit. And there's 1/3 scenario, which is when an era occurs. We're gonna talk a lot more about the way the area situation is handled. When we get to the module on exceptions for now, we're gonna focus on these 1st 2 scenarios reaching the end of the method or having returned statement. So when a method is done, it returns back to wherever it was called from, right? So in the case of a little show, some function here we have our code where we create the class instance and then we called Show some. We have another instruction after that to print out a message like I'm back. What's gonna happen is that when we call m dot show some that's gonna pass control into our show some method it will do its work, which is print out that 8.93 times and the control is getting passed back up to the caller , which will pass control to that print line. I'm back, which then prints that message out. Now, if we wanted to, we could put a return statement here at the end and would actually work exactly the same in that case will be extinct. Is that the return instead of the end of the method And in this snare, it doesn't change anything. But the return statement does not have to go at the end of the method. Manage, If we had a slightly different call here is that we call show some instead of fasting. Three is the last parameter we passed a zero. Well, what would happen in that case? Whereas we'd calling to show some we would do the work that the numbers together and then our Prince David wouldn't do anything. So basically our shows, some method would actually have no real results. Now, in this case, we're just doing something very simple, adding, but in many methods, you may be doing a lot of work that you end up not using. So it is often used to check your parameters the very beginning of a method and a certain criteria aren't met. You just go ahead and exit. And so if we actually get to make a little more room in our method here, well, we might do at the very beginning and say, Well, if count is less than one, well, we know we're not gonna do anything. So what, you're gonna get head in return? All right. So in this case would happen is we call show Some control is passed in the show. Some we checked count, which is zero. So we simply exit back out and print around back where we end up not doing all that work that we weren't going to use anyway. So the return statements could be placed anywhere inside your method to make sense for the work that you're doing. When a method returns that methods not void, that it actually returned to value. Their method always returns just a single value, and that value could be a primitive type, like a float. A short of bullion can also be a reference to an object. And it could even be in a reference to an array because in Java, a raise our objects. So let's take a look. That flight class we've been working with, you remember that it has two fields in it, pastures and seats. And for now, I'm not going to show the other methods we've seen already. Don't focus on. Some new methods were going to adhere. Let's say we have a method that we want to check and see that is there room to combine two pastors from another flight with those passengers on this flight. Soon as we pass in a parameter, which is the other flavor call F two and I returned. Type is bullion. So we say here is that we'll figure out the total number of passengers. So how many passengers do we have with how many passengers of the other flight have? And then we check and see what that total is less than or equal to the number of seats we have. Well return true. Otherwise we'll return false. Where is that? In this case, it's a massive returning back of boy. Invariable knows the code were using for return value here. If total less cynical deceits resolves to true, we then return true. Total Lesnik receipt resolves the false. We return false Well, rather than actually have the if then the return, why don't we just use that value directly is what we do is we were in place that if statement by simply saying return total lesson ago, two seats, whatever that resolves to it will be our return value. So let's make a little more room here. Since we have covered some of that code, let's create another method here. This method we'll call, create new with both, and you notice that this one returns back a reference to a flight object. And the idea here is that it will actually create a brand new flight that combines the pastor accounts from the current flight and that Flight F two that's passed in So we'll do here because we'll create a new instance of the flight object. We will then say the number of seats in that new flight is equal to the number of seats that are current flight object has, and then number of passengers is the combined of our passengers and the other flight, and then we'll just return back. This newly created flight were returning back, a reference this new flight that we created. So to use this in code, we'll do it. Let's go ahead and declare one flight instance will be inflates. Look to L A X to Los Angeles will be a flight l a X one. We'll create another flight to Los Angeles L E X two, and we'll say that we just run some code that adds passengers to both of these flights. So, upon some point when we get past this comment both L. A x one and Alex to has some number of passengers. So it does create a new flight reference. But as I'm not going of flakes, just a flight reference and why I want to do now is check to see that. Well, if there's room to combine L E X one and x two passengers, I want to go ahead and do that. So what do you guys have? An if statement a place that says, Well, if l a x one dot has room l E X to where that calls over to our has room method. When we get into the has room method because we called has room against the L A X one flight instance, and it will refer to the class more variables, passengers and seats, whether unqualified, that means you're referring to the values they're currently in L. A X one when we refer to passengers using the F to reference right, that's actually L e X twos passengers, because that's when we passed into the primary, right? So when we run this method of basically agile together and then if there's room, it'll return back. True. If there's not a return back false, so then we can go ahead and say l a x three equals l a x one dot create new with both passing L E X two. It's now gang controlled transfers over to to create new with both again because we call this against L. A X one. Anywhere we use seats or passengers unqualified, there's a the L E X one seats. F two passengers will be the L E X two passengers. So in this code, we go ahead and create that new flight instance. Assign it a number of seats from L. A X one right to flight reference we were called against, and then passions is set to the value of L E X. Once pastors plus L a X twos, passengers and then we return back that new flight. So l a X three will receive a reference to that. Newly created flight instance returned back from the Create New with both method job includes some special reference variables. They're important for us to understand now. One of these is the this reference and that this reference allows you to refer to the current object So it's useful for any time you want to be very explicit and an indicate that you're referring to the current object. It's also used for four cases where an object may need to pass references to itself toe other methods. We'll see this used a lot throughout the course, but it's looking a simple example. Remember that we have our flight class and we had that method we just wrote called Has Room Now. The hazard method uses data from the current instance, and it also uses data from an instance past NF two as we have our F two dot passengers, which refers to the passengers of the instance passed in and then our other passengers refers to the current instances passengers, and this is completely valid the way we have this written, but we wanted to make it more explicit that we're referring to the current instance. Pastures. What we could dio is we could actually put this in front of the pastors on the left saying that we're referring to this one inside of the current instance, right? So it allows us to get rid of that ambiguity and maker Cudmore clear There are other cases that maybe we had a local variable or something that maybe had a name collision with a member field. We could also use this to disinfect You ate that. We'll see an example that shortly later in this module, another special reference is the null reference. And this is a literal and now refers to on uncreative the object, and you can assign it to any reference variable. And you want to really just use it to say that Hey, this reference variable isn't pointing anything yet. So we take a look at some code here. Remember that we wrote that code earlier where we declared our two flights L a X one Alex, too. And then we're gonna have our other flight l a x three that if there was room we would have signed a new flight instance to with a combined combined passengers of L A X one that likes to Well, this code is it's written kind of creates a problem right now. Is that our flight, L E X three? Well, if there wasn't room to combine them, l a X streak could end up plant potentially set to nothing. We learned earlier that local variables cannot be un initialized. So we need to initialize L e x three to something, and we want to initialize it to no object. So that's where it all comes in. So we can do here. Is that simply say, flight L A X three equals No. So now it's initialized 2.2. No object all. So let's say that later in our program we do some work and we want to know if l a. X three was actually assigned a flight or not. Well, we can actually compare l A X Street to know we're saying, Well, if l x three is not equal null. In other words, at l a X tree, no longer pointing to nothing. Does it point to something? Well, and if it does, we know the flights were combined so we could print that value out. That's revisit our Calkins and demo and update it to use classes and methods. Here we are in our count engine program. As we left it at the end of the last model, remember, what we had done was create four parallel rays when the left values with right values with the op codes for the Operation one perform and then a raid, old results and the way we created commonality across these arrays was that we said that well, the first member of each of Ray corresponds to the first member in every other array seemed for the 2nd 3rd and fourth members. A much better way to represent this idea of related values is to use classes. Let's go ahead and add a class to our project here. I'm gonna get in use the I. D. E. S ability to create class. Worse, all it's going to do is create a class file and put the class definition side of it all. The major i d support this concept and they all pretty much do it almost the same way longer. Two years go to my package name, right, Kanda Prosthetic talc engine. Right. Click on it. Say new take Jonah class and give it the name of the class. So it's car class math equation gonna get and just tell it to get and create it. And what that does is create a source file, name, math equation dot Java and put a public class decoration inside of it. Right now, what I want to do inside of your is create fields for each of the values that I need to give track of, right. So if I go back to me and for just a second here, basically, I want to create fields for left vows, right, valles off codes and results. It's a good back inside of here when you do is make the space to do that. And so first I'll do left found. So I just made a public double called it left. Found very similar to what it was called the old program to the same thing for a right vow are up coding a result. So now I have the ability to store all those values together inside this one class. Let's head back to the main program Now. If we look to me and program inside here, there's this great big switch statement, and this is this is kind of broken in terms of the fact that the program has to know a whole lot about how these operations worked. Realities. Burger just wants to have the work done. So this switch statement could really be moved out of here. And let's move it into our class and so we can wrap it up inside of a simple method, right? So gonna get head and cut that away, Go back to my equation. And that's at a public methadone here called Execute. I know that I've marked a method void. Singing doesn't return any values, in fact, is not going take a new parameters either. So it's gonna go ahead and put the code block inside of here. What I'll do now is outpaced that switch statement inside of this excuse method. Now, what I want to do now is just updated to work on its own values, right? So the idea is on for the 1st 1 here for a it's going to get rid of the sub scripts because I want to use Op CUD has declared inside the class same thing for a result. It's gonna make that result same thing for left. 1000 right? Vows. So I get my results Equals left vowel. Plus right, Val, that's using all the members here appear on the op code. I need to take that s sauce with matches. Right. So now the op code matches Oppa's well, so I'm now using the case of a all of my member variables op code for the switch. The result, that vow. And right, Val, I'm gonna do the same thing for all the different cases on the default down here. So now my excuse method knows how to perform all the operations using the member fields. So now the next thing I need to do is go and start creating instances of my math equation. Right? So we go back here to the main program we're gonna do is get rid of all these arrays appear was getting commenters out. And what we'll do is instead is Korean array of our math equation class. So we're gonna declare math equation, put the array indicator on there. We're getting called this equations and said he equal to a new array of math equation. Now we've created the array of math equation. Now that creates the array itself. But I still need to create the individual math equation instances for each array member. So I basically need do is say something like equations Sub zero equals new math equation and then go through and set each devour each of the fields. Right, left vows, right fouls and op codes that, since I would have to do that four times, is another great chance to use a method, reckon use a method kind of encapsulate all that work of creating a new instance and setting all the values. So we're getting create that here inside of my main class. Yes, I want a great a new method here I was gonna get and call the, ah method create. So Marcus Public. This is a modifier called static that we haven't talked about yet. Will visit. We'll talk about that one little bit later in the course. That's just getting put it in for now. And when our create method is going to do is return bank in new instance of math equation. So it's returned type is math equation again. We're gonna call it create, and what it will do is accept a parameter for each of the field you want to set, right? Left fouls, right. Vowels and off codes. Yes, we have all the parameters there is gonna put the brackets in place. So now we're going to do inside of here, is creating new instance other math equations or would declare math equation will called equation and then new up to math equation. So that gives us our instance of the math equation. And we want to do just grow down here so I can see a little better, right? We're going to do is go through and set all of the fields the correspondence of for Amber's . So for left families see equation dot left out equals left, Val. So it takes whatever that left Val parameter is and sets the left vow field on equation. We'll do the same thing for right. Valen on coun with all the value set dancing left do is return back our equation. So what That all set? What we can do is up here in the main part where we create each one rather than explicitly create them. We could instead call that create method. So I'll do your is just called create and then passing the values I want to use. So for left foul in the first male use 100.0. Then I used 50.0, and then the up care de now do the same thing for the other three members. So now we have our math equation array created. And then we also have the individual math equation instances created in that, each one of the arrays. So I'm going to get rid of this four statement here. We don't need that one anymore when I'll do your Is that where we had us for each Where we're going to The results before we can do now is go to that magic math equation array I saw Go ahead and declare is math equation. Call the variable equation and what it will loop through is equations. So now what I can do inside of here is for each one. I can simply say equation dot Exe cute. Well, that'll do. That's what I call equation dot execute right for each one. Each of the sets of values will go into math equation. Call X cubed, check the op code, perform the appropriate operation store that in result So I get bank here. What? Aiken didn't then print out a simply equation dot results. And so now I have a much more encapsulated application here, right in the sense that I have the idea of what I want to perform modelled into my class math equation. All right, so what has the fields for each of things I need to perform that out. The operations, The X Q method Does the actual work to go back to the application? The application doesn't care about any of those kinds of details. It simply creates each math equation. Instance, loops through them, tells each one execute and then displays the result. So we go ahead and run this. We get our appropriate results. Out there is that 100 divided by 50 is too. 25 plus 92 is 1 17 2 25 minus 17 is to await and 11 times three is 33. Most of the time, we do not want to allow access to the field within our classes from outside of that class. We want to hide those kind of details because the fields are very fundamental part are very kind of low level part of the way a class solves a problem, and they're very likely to change over time. So we don't wanna have this kind of details exposed outside the class that that doesn't mean that we don't want to allow interaction with the information ciders fields from outside the class. So we do is we generally use methods to control access to our fields. As you would expect, this is an issue that we have to address very frequently. So it con pattern called the access or Mutar pattern has arisen to deal with that. Now, if you're not feel about the term pattern, all that means is it's just kind of a common way we solve the problem. Let's take a look at our flight class we've been working with when we have a couple fields inside of here, passengers and seats. Let's say that we decided that we'd like to allow interaction with the seats values. Now again, we don't want to give them direct access to see if we don't make that public. So we'll do is we use methods to address that. So we do is we use what's going access er to get to the field value. It's often just called a getter. And what we do is we create a method normally that has word get followed by the field name . Right. So the access er for our seats would simply be get seats. Notice that the return type is the same as the field itself and also noticed that the method is following Camel case. Write a lower case G for the first word in uppercase s for seats. The second word, right. Even though the field started with a lower case s, that doesn't matter. It we're going to use consistent camel casing as we name things and know the access or does is just return seats so easy for the consumer, the class to get to the value. But we've got control. If we ever change the way we manage seats, that will not affect anyone who, using this class to allow the value of seats to be modified. We use what's called a mutate er, also known as a center. As you might have guessed, the way we name that method is simply set and the field name so a mutated for our seats. Field shows have public void set seats noticed that the return type is void because the Senate doesn't return anything back and has a parameter to receive the incoming value. So now, inside of set seats we want to do is set our field seats to have the value of that parameter. Now we have interesting challenge here, knows that we're saying seats equals seats Well, because on the right hand side, we want the one that's parameter in the left hand side. We want the one that is the field. This is a great time to use this for putting this in front of the seats in the left that says that I want the field seats to receive the value of the parameter seats. But if we go ahead and set up some code would create an instance of our flight, I want to set the number of seats. I simply call R S L C to NYC reference against set seats passed in 150 that would set the value of seats 350 to get the value back. I simply call get seats against S L C D N Y C, and returns back to value. We set 1 50 in this demo will add accessories to mutate er's to our count engine app. We're looking how to deal with situations will remain when I was provide the ability to see a value but not modify value. So here we are, back in our count engine app, and I'm hearing the math equation class. We have our four fields at the top, right that are all currently public. The first thing we want to do is go ahead and make these guys all private. So with the values all private, now we can go ahead and other accessories and, um, you taters and that's going to really straightforward. That's good. There's a first in doing for left vow for left foul. Good. Make it public return value will be the same as left challenges double we call it. Get left vow and all that does is simply return back. Left found. Where's that? Gives us an access for left Val for our mutate. Er again will be public. This time will be void, though, because we tears don't return. A value would be set left Val and we'll accept a parameter of type double will call left Val and then from there, we simply assigned the parameter to our field. That's pretty straightforward. And we're gonna do that for a right foul and off code as well. So this accesses imitators in place. We can set the values of any of those as well as act system. And that makes sense for left out, right, Vallon off code, but results a little different. Result is the result of this class doing what it does executing an operation. So it doesn't really make sense for anyone to be on a modified result from the outside. They certainly should be able to see it but not modify it. This is a case where we may wanna have a access, er but not, um you Tater. What it does is, in effect, make our result a read only value. So we'll do is for our results. Will go ahead and create that access. Er, but we're not gonna have a mutate, Er and so with that, we can now just got an update our application and get and use the accesses from you. Tears we've created. So down here we're creating math equation. 6. 06 Class Initializers and Constructors: remember that we talked about the fact that classes are made up of both state and executed all code, so it's reasonable to expect that when an object is first created that is going to be in some useful state. Java will provided the fault state when the object is first created, but that may sometimes not be enough. You may need to actually set this value yourself or even execute some coat. Java gives Theobald City to set the initial state of an object. It X provides three separate mechanisms for doing so. One is what it called field initialize er's where we assign a specific value to a field. Another is called Constructors, where we actually can you potentially pass in parameters and run code to set the state. Another one's called initialization blocks allows is to run code that could be shared potentially across constructors. You'll recall that when we talked about variable declarations, we said that variables always had to have an explicit of value assigned to them. That's not true for Fields. Fields will get a default value automatically as part of the object instruction. The default value will always be what I call the fields zero value. And what I mean by that is it's kind of whatever the kind of empty state of that field is. Based on this data type, we take a look here like, for example, all the energy fields bite short and long. The value is actually zero. Same with the floating point. The value is zero for the carrot type. Zero value is basically kennels ears kind of the null character for bullying. It defaults the false and for reference types they default on all. So we have all these kind of the fall fights that they get and there's there are reasonable defaults. But as your obvious get more sophisticated, those the fault values may not be the right thing for your objects. Initial state. Now the good news is we don't have to accept those default values. Java provides what it called field initialize er's the field additional. Isar allows you to specify the fields initial value as part of its declaration. Imagine we have this class. We're gonna call the class Earth, and it has a field called Circumference in miles, so we want to go ahead and set. That's when initial value right initial value of zero doesn't make sense. We know the Earth actually has a circumference. So what we can do is just do a simple assignment that set its initial value basically saying circumference of miles equals 24,901 By creating an instance of the Earth class, that field will have the value 24,901 now simple. Simon's air. Good start. But that may not be enough. You can also use an actual equation. So if we had circumference and kilometers, well, we could calculate that. Calculate that out by hand. Or we can simply say that Well, I know if I take 24,901 and multiplied by 1.6 that'll give me this or comforts in kilometers, as we can actually have that equation. Remember, though, that the equation has to be a valid equation. Right? So right now, this wouldn't compile because although 24,901 is an Intertype, when I multiplied by 1.6, which is a double, that result will be a double that I can assign directly into the long circumference and kilometers. So he's got to put a cast in place and that now becomes a legal assignment. But if we look here, you see that we're duplicating that 24,901 in two places would be nice to only use it once . Well, we can actually reference other fields in our field Initialize Ear's so we can take that 24,901 and replace it with the field circumference and miles, so the equation would then use the value of their comforts in miles when it does the calculation. So things are getting better and better as we go along here. No one thing. The interesting to note, though, if we calculate out 24,901 times 1.6 value, that that calculates to is 39,841 0.6. Now we can't that toe along. The cast is just going to truncate it. So the value of circumference and kilometers within being 39,841 a lesson ideally accurate . The better answer for that would be 39,842. Well, the good news is we can make any method calls that we need to in here. So one of these we could dio, is there's a built in method called math dot round. So if we call math dot round, that'll take the result of that equation 2 39,000 and 41.6 and actually round it so that we then would get 39,842 into our circumference and kilometer. So, you know, sees thes feeling. They're sliders. Air really powerful because you can do as much as you need to Anything from a simple assignment. Two equations all way up through method calls. We talked about constructors briefly in the last module, and from that we know that a constructor is exposed. Execute herbal code that used during the creation or object to set up that initial state. I remember that we worked with our flight class in the last module, and we saw that the flight class had a constructor in it. No, I think it's interesting to note is that a constructor is not a method. It is like Cuba execute herbal code, but it's not a method. You'll notice that constructors don't have return type. It's just a code we want to run during the construction of her object, and every class has at least one constructor. But interesting to note, though, if we looked our flight class, what's going on the side of our constructor isn't really necessary. We see setting passengers equal to zero. Well, that's not necessary, because we know that EMTs are automatically zero when their fields in a class and the set seeds Eagles won 50. We could have actually put that up in the Declaration of seats, so we didn't really need tohave an explicit constructor here. So what happens in the case where we don't really need to have an explicit constructor? Let's take a look here and have to deal with that. That's going to choose another class. Call our passenger class In the past, your class is gonna have three fields, and these are all related to checking bags. We get on a flight. We have the checks bags field, which is how many bags of pastors checked. Free bags indicates how many bags are allowed to have for free, and then the per bag fee is what is the cost of each bag beyond the number of free bags and let's assume that we've provided access. Is Ammu taters for checked bags and free bags so they can interact with that data. Well, as we can see, this class does not have a constructor. Yet. If I write, could going creating new passenger and assigned to Bob that code will run well, How is that possible? If we said that every class has have at least one constructor? Well, it turns out that if you don't have an explicit constructor, Java actually provides one you wouldn't see in your source code. But when the classes built job, it generates a constructor that doesn't do anything different. Makes it possible to create an instance of your class without explicitly writing and constructor. And there's nothing special about that. Class will behave normally so you can interact with all of its methods and so forth, but classes can actually have multiple constructors. Now the parameter list has to defer free. Since constructor. That's an idea we call the signature. We'll talk a lot more about how signatures work later in the course, when we talk about methods and more detail, the key thing is that just the number and types of the parameters have to differ across the various constructors. So let's say that we have a new trigger where we want to be able to create passengers, and it's part of creation indicate how many free bags they're allowed to have. So that constructor would do is accept the parameters that number free bags and assign that to the field. What that would allow us to do is to write code like this, where our pastor, J. Nichols, new passenger to that calls, are constructed that accepts manager and that sets number free bags for Jane to to. Of course, we can then set the number of checked bags for her from there. The thing is that once we introduced this new constructor with it accepts the image of free banks, the line above there where we X could create Bob's. A pastor would no longer compile, because what happens is that once you write any constructors, you're now responsible for all the constructors, so that constructor that was created by Java is no longer there. The point there is that Java doesn't assume that your class need to construct with no arguments. Once you write any constructors, you're not responsible for all the constructors. So if we still will allow users of our class to create instances that don't provide any arguments, we're responsible to go ahead and write a constructor that doesn't take any arguments, doesn't have to do anything. Which is by putting that there were saying that that code that creates an instance about preventing parameters is now valid again, Looking at our passenger class I want to focus here on is just the constructors for a second. So we'll assume that we have any fields and methods we saw in the earlier slides. Remember that we have a constructive that takes no arguments. We also have our constructed. It accepts an imager, which is the number of free bags that we set. Of course, that allows us to go out here and do something like create a reference called Jean to a new passenger. On we create. We say that James allowed to have two free bags, and then we can call them at that set checked bags, the salmon eBags she's checked. Now, if we find it is a scenario that comes up a lot where we create a passenger who has a number of free bags and a number of checked bags, it might make sense to introduce another constructor allows its combined his operation so we can get and creates a passenger and in one call say that they can have two free bags and they've checked three bags. All right, so the right constructor like that is really straightforward, right? We just introduce another public passenger with two entered your arguments, one for free bags, one for check backs. Now, one way we could write this began. We just make the assignments. We have signed free bags into the field, Free banks we've signed check bags into the field, checked bags, and that would work. The thing is that we're now getting some duplicate logic, right? Is that that assignment of free banks is now happening in to supper constructors. Now, in this case, that logic is really simple. But if time goes on and the logic around the management of free bags gets more sophisticated, we would actually have to change it in every place that we currently assigned free bags. So it would be nice to be able to chain thes constructors together. It turns out, we can do that one constructor is allowed to call another constructor, and all we do is use the this keyword followed by the parameter list. So if we look in the constructor that takes free bags and checked bags, that line will reassign free bags. We can replace that with this and then our free bags parameter. What that will do is then call into the constructor that accepts the single manager free bags and run that constructor. The one qualifier is the call to the other. Constructor has to be the first line in our constructor. So now we create this passenger gene. It calls into the constructor that takes two arguments. As part of that calls up to the constructor. That takes one arguments, which says the free bags. And then when that returns, we assign checked bags into our checked bags field with multiple constructors. We may want to start thinking about the visibility of our constructors because just like any other members with constructors, we can use access modifiers to control the visibility of this constructors. Well, that's allows us to do is limit what code can perform specific creations. It's sick, but an example here, let's say that we introduce a constructor that allows us to identify the per bag fee for passenger. Of course, all that does inside is a sign whatever that parameter is into our per bag fee field. But thinking about is that if the logic around setting bag fees is kind of meant to be part of our class, we probably don't want a program to easily go in and change that right. We don't want cheap Joe to come along and just create himself is a passion here, where he pays a penny a bag. We probably don't want that broadly accessible. So we want to do here is that for a constructor accepts the baggage fee of being public good. Make that guy private by making it private. It can't be called from the outside. It could only be called from within our class. So maybe we want to do here is say that well, based on the number of free banks of pastors allowed toe have we will set the baggage fee, the idea being that a passenger is a sign of certain a free bags based on kind of the level of customer they are so customer who actually has allowed more free bags. May also is part of that. Get a lower per bag rate for the ones who have to pay for. So if we look at our constructor here that accepts free bags, we make a little room in here. Maybe we want to. Dio is make a call down to the other constructor based on the baggage fees and passing a different value based on number free bags. Customer has so we can do here is called out to that and say, Well, if free bags is greater than one, they paid $25 per bags me on the free bags. Otherwise it pay $50. Right again, The idea being that a customer gets more free bags is also gets a discount rate on bags they pay for. So what that allows us to do now is have our baggage fee rate tied to the number free bags . Passenger gets right, So if we have one call here, we can create a pastor Fred, who gets two free bags where that goes directly to the constructor that accepts the free bags parameter. As part of that, it chains down to the constructor that sets the baggage fee. We have another pastor recreate who accepts the two parameters right to free bags in the checked bags. Well, the calling to first that constructor that constructive chain up to are constructive accepts number free banks, which then in turn, chains down to the constructor that sets the baggage fee. Let's take a look now at how we can use field initialize, er's and instructors to improve our Calkins an app before we start changing anything in their class. Let's imagine what it's like for someone who's using our math equation class for the first time. I think about whenever you start working with the new class or class library, something you often do is just gonna right the simplest thing you can and see what happens . Right? So let's imagine what that will you link with our class? Someone declare available called test equation of type math equation. We'll go ahead and new up math equation. And, of course, what's the simplest thing you can do with our math equation? Weaken, go our test equation and call execute, And then what you would do from there is just print out the result. So with that we see kind of the simplest thing you can do here, right? So it's gonna comment out our other code for just one second. We'll go ahead and take these this area code and comment that out. So it's going to run this now and see what the experience would be like for someone who just kind of exploring our class. You see what happens here is that they see a message says Invalid, Hopgood writes. Right away, they've kind of negative experience, because what's happening is that there were allowing them to create our class in a way where class has an invalid initial state basic. What's happening is that I go into the math equation class well, the value of op code is that the null character right? The all zeros character if we get down here to our excuse method, since it's not one of the valid op codes, we right away print an error message. So I think one kind of the best ways to kind of deal with this is actually allow the optic to be initially created in a valid state, and there's a couple ways we could do this one way to do that. Is this good? Cynthia PKU. That's something that's valid, like in a way that way, when they run it, what we'll do is we'll add two zeros together a little proud. Zero won't do something useful, but it won't give them a negative negative experience, right? So now we're run that code. It just prints out zero. And that's a reasonable experience for someone who is exploring our class. So we only want to make sure that our classes are being created in some kind of reasonable state. Let's have accurate. I mean, that's going coming out that test good. Let's bring back our original code to get uncommon. That stuff. So now remember, what happens here is that the way we do is we create this array for math equations and it goes through and we call create to create a math equation into each one of the array instances where that we've got this create method down here. But I think it's kind of ugly about this is that the application is hand had to handle all the details of setting each value, setting the op cud. We don't have to do that. If that's something it goes on frequently. That's a perfect chance for a constructor. So let's get back to work our class here. And that's think that some constructors that we could right now one very reasonable constructor, I think is the have one that accepts Justin op code. It would make a lot of sense. I'm gonna create an equation, and I know what kind of operation I'm going to perform on it, but I don't know the values yet. Let's go and create that constructor. So make a public math equation. We're going to give a single argument a care off code, and then all we're gonna do inside of here is a sign that parameter to our field op code. So now we support the ability to create instances of math equation with specific op code. No, I think is that doesn't solve our current problem, cause we know that we want to create instances, toe have the op code and both values. Let's go and create another constructor, and this constructor will accept the op code as well as left and right values. But we had it all set up now inside of your let's first look at storing the left and right values. We're gonna just assign each of those to the appropriate field. So we have that in place now. We could do the same thing with off code. Or but since we already have a constructor that accepts up good, that's a perfect time to get in. Chain up to that constructor would say this and pass in the op code we've received. So that way we just call up to the other constructor that already knows how to do that. Now, before we go any further, let's just gonna run our program and make sure everything's OK. If you look at what's happened here, we've broken the existing code. You see, we're back here in Maine and where there were we executed, create just math equation were not able to anymore because remember that we were getting at the fall constructor before, when we didn't provide any constructors. Once we provided the constructor we're now responsible, provide all the constructors. So we want to do is head back to our math equation class and go and create that constructed . That doesn't take any arguments. And so with that, we should get a runner code now it's going to run it. And now the code works against or we've now kept her old code working, and that's something we want to dio. But now it's looking how we can improve the code. And now that we actually have a constructor that accepts the op code in both values, if we go back to our main app here, we should need this create method anymore. We feel do all that looks instructors. So I head up here and why each of these places where I call create I can instead call the constructor or is going simply new up math equation. And when I knew it up and make sure the proud order mashes So in our constructor we have the op code first, then the values. So we'll cut that away, put that in the beginning, and now we're using constructor to create that zeroth instance of the array. Gonna do the same thing for the other three elements. Now we're using a constructor that create all the array elements so we can actually scroll down here and just get rid of this create method, and with that, it's good and run and we get the same results we haven't getting, which is good. But now the key thing is that we're using constructor to set up the object, get the up to the appropriate state so that we take that burden off of the program that's using the object and keep those kind of details and housekeeping inside the object itself. Constructors are not. The only way to run code is part of the initialization of our classes. We have another mechanism called initialization blocks. What they allow us to do is create cooed that shared across all our constructors, and what they do is they run the code as if that Cove replaces the very beginning of each constructor. Let's revisit our flight class for a second over. Their flight class has some fields in it. We know we have that. Passenger fields got a good look at another field here called flight number. We'll talk about the second that I've added, and of course, you have our seats field when it's just another new field here called flight class. And the idea is that flight number in flight class or two different ways to identify flight so flaky that created within individual number or is created with a new individual characters as a flight class to kind of group. It somehow remember that constructed that we wrote earlier. It took no arguments and said Seats the 1 50 our passengers were set to zero. Now we've learned a lot since you originally wrote this constructor. We know that passengers will automatically be set zero, so we don't need to have that code here. We also know that we can initialize about with seats field right up there in the declaration it's we'll get and move out of there and we no longer needed inside of our constructive. So now let's add two more constructors, one that accepts our flight number. We'll go ahead and initialize that another one accepts our flight class. And that initialize is the flight class field now is we're enhancing our class. Let's go one step further. In addition to having these different ways to identify our flights, let's keep track of the seats a little more closely, right? Right now all we have is his ability have the number of seats. You know when earlier we come to keep count of how many pastors we had. Let's kind advances a little bit and say, Let's keep track of it If each individual seat is available and we've got this new ray here is seat available, that's an array of bullion right now, if we just declare this array of bullying, all the values they're going to default to false, we of course, don't wanna have all the seats available set the false that would imply that they were unavailable where it went to be available are set to true. So now, based on what we know so far away we would do, that is we would go to our no argument constructor here. We would go ahead and allocate the array for his seat available, and then we would do is loop through each one and then said each one the truth. And that's a reasonable thing to Dio. What what would do, of course, is that in each of the other constructors we call up to that constructor, right? So our constructor, based on flight number and our constructor based on flight class, would both call up to the no argument constructor, and that's a reasonable thing to do. But in cases like this, where we have code that we want to share across all the constructors. That's a perfect place to use initialization blocks, and all we have to do is take that code that we want to share and place it within brackets outside of any method or constructor. Let's take her no argument instructor and take all the code out of it, and we'll move it down. So now it has no actual cute code inside of it, and it will take that code. We wanna run and wrap that in. Brackets knows there's no constructor name here. There's no method name. It's just the brackets and the could that turns that code into an initialization block, and we'll automatically be executed as if it's at the beginning of each one of our constructors. So our flight number base constructor no longer needs to chain up to another constructor as well as our flight class constructor. No matter how someone creates this class. Now, the code to set up our is seat available will always run because it's in that initialization block. So it's a great way to share that code across constructors. It's really useful in something we're going to talk about later called anonymous classes. Another thing just to note is, if you do put multiple initialization blocks in the class, they're executed in the order they're encountered from the top. I would be really careful about that because that's really easy to get out of hand with, just something to be aware of throughout this model. We talked about a number of different ways because that airfield values, as part of the creation of our objects we won't understand is the order that those values get set or the order of these operations occur. As you'd expect off creation occurs in a predictable pattern order, predictable path. So it's imagine we have this class here to just be called are over initialized class. We'll put a field in here called the Field. Let's go and give it a getter. When the first ways we learned about how we could initialize a field is through field initialize er's right, and that is actually the first step in the creation of an object. So we take our field here, called the field, set it equal to one, find them in a program, created instance of this class and then print out the value of the field. I'll print out the value one. The next phase is to run the initialization blocks. So if we take the same class and now we had an initialization block that sets the value of the field to even though we still have a field initialize er that sets with one when we run the code that prints this out, it's now going to print out, too, because the initialization block ran after the field initialize er's ran right so it would overwrite that value. And then the final phase is construction. So again we take our same class, and now we add a constructor that sets the field to three. When we run the code apprentice out, it will now pronounce value three. Now you're looking at this. You obviously wouldn't want to do what we do here. We actually, you know, said it set of field to something in a field, initialize er, then change in initialization block, then change it in a constructor. You're not gonna do that. But as your classes get more sophisticated, you'll find that your fields start to depend on the values and one another, so it's important to understand this order as you use the field and set up two field inside your class. The most common mistake I see people make is that they'll do work an initialization block that was invalidated by works. It occurs later in a constructor. So just keep this order in mind that you're setting up your classes. Some of the key things we want to remember from this module. Keep in mind that we want to make sure there are objects are always created initially in some useful state. We don't want to allow user to just know open object and have it in an erroneous state. Now they may not be able to do something meaningful with it, but it should at least not be error base. When he first created in terms of how can initialize are objects we saw, there's a number of ways. The simplest ways field initialize er's allows to just associative value of the field is part of its declaration as we associate code with the object creation that we have constructors and every class has at least one constructor. If we don't provide a constructor, Java will provide one that has no arguments on it. we can provide multiple constructors and remember that once we provide one constructor were now responsible, provide all of them right? So if we provide a constructor that has arguments if we still want to allow you to create an instance of our object using construct with no arguments, we then have to provide that constructor as well. We can change our constructors together, which allows us to unify code and constructors so that we can pass parameters from one constructor back toe another constructor t use that code. Remember, though, that when we do chain constructors together, the call from one instructor to another has to be the first line of that constructor to have code that gets executed, no matter which constructors called. We have initialization blocks. Remember that syntax? And that's kind of weird. It's just a set of brackets with code inside of it, not part of any constructor where method and given all these different ways to initialize, are objects and getting constructed up to make sure we always keep the order in mind. Gonna remember that field initialize the first that initialization blocks and then finally our constructors 7. 07 A Closer Look at Parameters, Overloading: in Java. When you call a method and you pass parameters into it, those parameter values are actually copied down into the parameter is something we call passing by value. What that means is that because a copy has actually passed down there, any changes you make to the value of the parameter inside the method are not visible outside of the method itself. Let's see how that affects is more working with primitive types. So let's imagine we have a method here. We're gonna call swap swap except to winter parameters. I and J no set up some code to call it so. And are could it cause it will first have available declared called Vow One that we set to 10 which, of course, allocates at some memory the value of 10 inside of it to another one vowed to set to 20 again allocates memory with value 20 in it. Of course, if we print those values out, value of al one will be 10 and value of AL two will be 20 now if we call that method swamp passing in vow one and value when control gets passed down to the spot method memory for the parameter eyes allocated and the value of al one is copied down into that memory. For I Same thing for J the cop The value for value to gets copied down into the memory allocated for J. So now, if inside a swamp we do something like allocated local variable con que and a science value of I Okay, well, then get the value of 10 rights value currently held in I. We then say I equals J. That means take the value that's and J 20. Put that in the eye. I becomes 20. We then say J equals K. The values in K 10 goes in to J, which is now becomes 10. So down inside demented swamp If we print these values out, the value print out for I will be 20 the value that's currently there Same thing is a proud Jane value pronouns 10 to value that's currently there. Notice that all the changes that occur within the method are occurring inside the copies associate with the parameters, not the original values. Right. So we exit out of this method and pest control back all those copies air cleaned up, So vow one and vowed to still have the original values race. If I print this out, Val one still has 10 valets. Houston has 20 records. Again, things were passed into the method as copies. Now, what about classes, Right. We know classes behave a little bit differently than primitive types. Remember that classes work with references, right? So let's say we have a class here. We've worked with Flight and let's just focus in on its field flight number, and we'll assume we've got an access certain mutate, er set up for that. We've got that constructor. That, except the flight number, of course, sets the field with it. Now we're gonna worry about any of the other members in flight right now is really focused on flight and flight number here. So now let's again. So we have a method called Swap, but now our method swap accepts flight references, Right. A flight first ones I write second is J. So now if we want to call it from our code will allocate Alley Val one, which is a new flight with the flight number set to 10. All right, So what's that going to do? Well, it's gonna allocate out memory that's are variable. But then we remember that we allocate out the class instance itself separately and then assign a reference into the variable. So we have another flight instance here, Val to it again allocates out to place the hold the reference the actual flight object itself and then associates that reference. So now vow one in vowed to are not the flights themselves, their references to the flights. So, of course, if I print those out things or what we expect vow ones flight numbers 10 vowed to flight numbers 20. But now we call in the swamp. We pass vow one and vowed to its What's gonna happen is actually the same as what happened with our primitive types. We're gonna have that memory called I that's allocated. We're gonna copy what's in vow one. Well, what's in vow one is the reference. That's what's gonna point to that same object flight number for vow to will convert that into J get we're comping the reference which points to the other flight with flight number 20. We look at our code now we do the same sort of thing. We allocated a local variable con que and we assign what's inside of I. Well, it's inside of I is a reference to that first flight object, one with value 10. We then say I equals J. Well, I now stop pointing at the original flight and point to the same one that J points to the one with the flight number 20. We say Jake was K won't j. Stop pointing to the one with 20 points, the one that K points to which is the one with 10. So inside of our method here we print out the flight number of the 1.2 by I. Right, That's 20 1.2 by J is 10. But notice that we're swapping the references around. We still haven't affected the original vow one and vowed to rights when we exit out of swamp Vow one still points to the one. The flight number of 10 vow to still points the one flight number 20. So we print those out. Nothing has changed. Found one is 10 Val two has 20. So we're copying these values into the parameters, causing us not to be able to change them inside the methods. So that tells us that changes to the values of parameters have a method don't affect the original values. It doesn't matter whether it's a primitive type or a class instance. But what's important realizes that although we can't change the actual parameters themselves, we passed classes in any changes we make to the members of classes inside of method do stick. There's do take hold. Those are visible outside of the method. Let's take a look at why, If we look here, that same thing we're doing before, right, we're gonna create an instance of our flight class. The value of 10 right sets of things just like before. Vow one is a reference pointing into an instance of flight with a flight number of 10 vow to points to another one. Rates of out to is a reference point. One instance with flight number of 20 we print amount. Everything's the same as before, right? Val? One is 10. About two was 20. Our method. This time we're gonna change its name to swap numbers, and we want to do inside of your wrist swap the flight numbers between the flight instances . That's what we call into this guy again. We're still copying the values of the parameters, right? So I still gets a copy of the reference that was inside of Al one. J still gets a copy of the reference that's inside of Al, too. But now in our code here, we're gonna change the members. So if I have an imager called K this time we call, I don't give flight number. Well, that takes the reference on by I goes up to the object instance that appoints Dio and that gets back the number 10 and puts that inside of K. So now if I say i dot set flight number and I passes a parameter J don't get flight number . Well, let's look at that from the inside out we call J don't get flight number. That takes the reference that stored in J follows it up to the object. Instance, gets that number that's in there, which is 20 and then we work to the outside. I That set fight number takes the reference. It's held and I goes up to the object, insisted points to doing currently with 10. But when we cost that flight number, it becomes 20. So you see that we didn't change the parameter at the parameters still a copy. But because we're find the reference, it's in the parameter. We can change the object at its point to. So if we now say that Jadot set flight number of K What we get divides in K, which is 10. We take the reference that stored in J filed up to the object that it points to and we said its flight number. It now becomes 10. So inside the method, if we print he's out, things were changes. They've always been the flight number of the flight instance points of my eyes, 20 1.2 by J is 10. But the key is because we found the references and then change the actual objects. As we exit out of here. Even up will recall the method those changes now stick. So the flight pointed to by vow one has the value 20. The changes occurred down inside the method of flight point. To buy Val to also has to change the value of 10. The changes occurred down inside the method as we were working in different classes. Throughout this course, we've seen that given class can have multiple constructors and that same idea could be extended to methods where a class can have the same method name appear multiple times. This is a concept called overloading the ability. Use different parameter lists with a given method name or the constructor. Now the system has to have some way of identifying what constructor, or what methods you want to use and when he uses a concept called a signature is that each constructor or method must have a unique signature and signature is made up of three parts . The one part is the number of parameters and we saw this previously. We're working with our passenger class writer past. Your class had multiple constructors. The first constructor here has no parameters at all. Wait. Another constructed had accepted the number of free banks that I had just one parameter. And then we had another version of the constructor accepted free banks and checked back. So it had two parameters. So the system was able to figure out which construct we one of the used based on the number of parameters we passed to the constructor. Now we're not limited to just a number of primers. The signature is also affected by the type of each parameter, and we got to see this earlier. We're working with our flight class. Are flake class had again constructed. It took no parameters. A constructed it took just the flight number. So that was an image of parameter but only one parameter and another constructor that also has a new one parameter. But this was a care for the flight class. So it's not just the number of parameters, but also the type of the parameters and the final part to identifying the signature is the name. Now, when it comes to constructors, the name doesn't really matter so much because it always has to match the class name. But when it comes to methods, the name is actually really important part of that because a given class can have multiple methods, each with their own unique name. But that one method name can also have different numbers of parameters and parameters of varying types, and we'll see some examples of that in our next clip. Let's take a look at our flight class and see how well you might be able to use overloading to improve this class. Remember that we have the idea of our seats or 1 50 we keep track of the number of passengers. And we've had that method. We were much earlier in the course called Add One Passenger. We're just make sure that there's enough seats for one more passenger. If so, we Adam. And if not, we go and just handle that, which is just gonna report an error as we look ahead to maybe making this flight class a bit more sophisticated. This idea of checking whether there's enough seats to add another passenger is something that we we may have to re use a lot. So why don't we go and make that its own methods? We have a method called has Seating, and inside of there will just put that check in for the number of passengers less than the number of seats available. And we'll do is we'll update our add one passenger good and use that has seating method. Now we're keeping track of what's going on with our flight One things you might want to keep track of is the number of total checked bags, and we're not going to limit the number of checked bag, but we're gonna keep track of it. But something that we might wanna limit is the idea of carry ons. So we're gonna do is going to set the maximum of carry ons to whatever twice the number of seats are right. No one's supposed to have more than two carry ons, and we're getting keep track of that total carry ons. Let's go in at a method to just allows to check to see that based on number carry on. Someone has Is there space for them? So all we'll do is just take how many total Karen's already have. How many Karen's they're trying to bring on? As long as it doesn't exceed our maximum carry ons, we're gonna let him do it. Then, of course, we have all the other members we've seen previously. I want to focus in on the idea of Add one passenger because now that we're keeping track of things like total check bags and carry on, the idea of adding a passenger is gonna be a bit more sophisticated. It's good. Move this off to the side. Now we're still the same ad. One passenger bridges looking at. Nothing has changed their butts. Adult more space to work here. So now if we think about overloading, add one passenger. Well, keeping track of checked bags is gonna be important. So it's at an overload that except one injure. And that's the number of bags and the logic inside there would be, Well, we'll call our existing, add one passenger, do that work, and then will Adam Marie bags. They've checked to the total check backs Now. One interesting thing about what we're doing here is that it's possible that we tried to add that passenger wasn't of seats available, But in this case, we'd go ahead and increase the total checked banks. So we can do is get a wrap our code here so that we check the has seating before we do any of that other work. And this shows is a couple of things. First of all, noticed that we wanted to access the overload of ad one passenger that took new arguments. There was no special syntax for that, but it wasn't like we constructors where we had a special key word. Here we just call the method name with the right number of parameters. I also noticed that when you're calling from one overloaded method toe another overload of that same method. There's no rules about where it has to be. Remember when we were talking about constructors, the Cheney of Constructors had to be the first line in the constructor here. It's just kind of a method call. You can call it anywhere in the body of your method you need to. So now remember that we also have the idea of a passenger class. Well, if we're writing a method that add one passenger, it's a probably accept an instance of the passenger class. Now we never get anything special here. All we're gonna do is called the ad. One passenger did accept an imager for checked banks, so we just call on our pastor, get checked bags and past that in this year's. Another interesting thing about method of reloading. Our add one passionate, accepted imager number of bags right? That was adding new functionality that was functional, that we did not have before the idea of keeping track of the total number of checked bags. But our add one passionate accepts just a pastor. Instance, we certainly could have required someone who's using our flight class to simply call get checked bags themselves on passenger. But that's something we do very commonly. Is that overloaded sometimes are just used to add convenience. All right, so the one that accepts the pastor references a convenience overload. So someone didn't have to call get checked bags themselves. The one does, except the energy number of banks actually adds functionality. So as we look at adding functionality, another thing I want to keep track of is this idea of carry ons. All right, so we haven't overload here. Now it takes the number of checked bags and the number of carry ons, so we'll check to see if we have seating will go ahead and call the ad one passenger to accepts an injured number of bags and then we'll add the functionality to increase the total number of carry ons. No one things. We want to do your courses that before we add the passenger, not anyone checked for available seating. But we also want to make sure that we have space for their carry on. Right. So, again, this isn't ever lose its adding new functionality, validating that we have spatial to carry on and then keeping track of that total number of carry ons. And then we'll have another convenience overload. Here's it except passenger reference and a number of carry ons. And all that's going to do is call up to the implementation of AD. One. Passenger accepts an energy number of bags, a number of carry ons. So our classes got a lot more sophisticated here now, right? The idea of adding a passenger can do a lot more things as it was, just keeping count of number of passengers, where to keep track of the number of checked bags, the number of carry ons and even limit how many carry ons can get onto that flight. So let's focus in now on not just the implementation, but kind of just the signatures. Murder has the signatures, that thing that determines which implementation of an overload gets called. So focusing it on just the signatures of these let's go ahead and make some room here. So I just pushed them all together. So these the same exact methods were just looking at it, just as five overloads of ad one passenger and let's see how life get used in program. So it's and some code here that goes ahead and creates a flight that's first creative passenger were passing in zero and one to the constructor. Reminder is the zero is how many free checked bags I get. So in this case they get zero none. And how many bags are checking, which is one. Create another passenger that gets zero free bags, but they're checking two bags, so we've got this all created. So now if I call on flight, add one passenger. Well, this is the one with no parameters. So it's nice and easy to know which one that chooses just calls the implantation of ad one passenger that accepts no parameters. Michael at one passenger passing an imager. Okay, well, there's only one parameter here, so there are two possible overloads that can handle that right. The one of deception, Danger and one of steps passenger but central Passing it manager. It will use the image overload. Similarly, when I call the ad one pastor passing any reference to a passenger it will call The Overloaded accepts a passenger. But let's go another step. Let's declare a local variable of type short called three bags that we set to three now when I call, add one passenger passing in three banks is the first parameter a short and then two and energy is a second parameter. Well, there are two possible overloads here. Did accept two parameters, right? The one that, except to imagers one except a passenger and manager is there is no overload that accepts the short. So how has this system decide which one to call? Well, it starts looking for the automatic conversions that's able to perform. Remember, back in module three, we talked about kind of these idea of automatic type conversions. Well, very similar rules are applied here in order to determine how to find the overload. So what happens is that since the system knows out to convert a short into an end, it will go ahead and call the overloads. It accepts an injures the first parameter, and then finally, because add one pastor passing in a passenger and energy, of course, calls the appropriate over for that one of the sub state passenger and an integer in this demo would take a look at how we can use method overloading to improve our Count Kenshin program. Here in our math equation class and you recall the creators with three constructors one that accepts no parameters, one to accept just eop code, and one that except op code and both values we want to operate on. Now. The way this works is that if when you create a math equation, if you know the op code and both values when you create it, things are nice and easy to use. But if you only know the arm could it's time you create it and then later, when you're ready to execute you, then have the values were a little bit cumbersome to use. Could you have to create with the constructor of accepts EOP code and then have to call set left phallic the left value set up our call set right values of the right foul when we scroll down here a little bit, then finally you call execute what seems very likely to be a lot of situations where we may create an instance of our math equation with a particular op code, and then what Simon excuse would have both of the values we want. So it would be nice feel to go ahead and just pass in those two values as part of the execute is this is a great opportunity to provide an overload of her execute method. So we have with one currently that takes no parameters. Let's add in execute method that accepts to prowlers the left down the right foul. Yes, that's we really used for us to do here. There's going to clear public void execute And they were simply gonna have parameters for the left down the right Val, they both those parameters is going Put the body of it here and all we need to do inside of year is set. The field left Val to divide the parameter left Val, do the same thing for the right now and then call the other Execute implementation. So now, in this scenario where we have the opportunity construction time but the two values of time , right, execute, we could do that kind of all in one step. So it's going to remain program here, and we've got the existing care that we worked with before. But I want to, first of all, before we do the actual work was gonna put a couple of print statements in here just to print out a message in the output window so we can differentiate what we've done with the Array previously. With the new work we're doing with the overloads, let's go declare reference for math equation class. We'll call this one equation ever lewd, and we'll do is we just knew open instance of the math equation with the dividing off code we've got that they're now before we use that. That's going to declare a couple of doubles up here. So have a variable called left double set to 9.0 in a very called right double, said the 4.0 we want to do here is that Go ahead and perform the actual calculation right now, as I said before, we have to do is call set left, value inset, right value. Each time Now it gets really easy. You just say equation or veloute. I say, don't execute. We're going to do is pass in 22 values left Dublin right double. And of course, from there we're just going print the values out. So we simply call X Q Paschen the values and then go ahead and just get the result back as we print it out right So if we run, this is gonna work just like we would expect it. And we see their inner apple window under using revolutions. We see result of 2.25 writes. That works just as we had expected. But now what happens if instead of using doubles here, I declare a couple of managers instead. So they're just basically the same values that I had before with the dumbbells, right? So if I confidence lines that we use with the doubles and when I want to do years where I have left double and right double, let's switch that the left and and right in. So now the question is, will that work? Since I've declared my X Q method to accept doubles, I'm passing an answer. Is that going to work? So it's gonna run and see what happens, and we see that it does work raise. Our result with the energies is also 2.25 and the reason being is that that's what we call a widening conversion. Remember earlier in the course when we talked about calculations house, there were some automatic type convergence that can occur since a double is wider than an end other to double can hold anything. It's inside of an ent. The system can go in for that conversion and go and call them at the accepts doubles. Even though we're passing it in its now, there is one thing that's kind of curious That right? I mean, just run this again real quick. Our results of dividing the energy or nine by the energy of four is being printed out as 2.25 We remember that in our imager arithmetic that we learned earlier in the course that should actually just be too. When you divide to energy or values, you don't get a decimal point. You don't get the whole portion of that. So to make our math equation class more effective, But we should really dio is provide another overloaded execute that accepts to imagers. So I go over here and what again? Copy this one we have here now that accepts the doubles. I'm gonna getting pace that in again. And what I want to do here is convert each of these doubles to be ins. So we now have a never alluded accepts managers. But now if we were to run this right now, nothing would be any different because even though we're passing energies end at the parameter level. When we make the assignments of the fields, they're gonna convert two doubles again anyway. Well, what happens when you do division with energy values, right, You get a truncated value So we can do here. Is that after we call executes, the value is going to be a result would be 2.25 Well, if we could truncate that, then we are math equation class would provide the right answer for imager division. So what I can do here because I can take my current field results. I'm gonna sign it the value of result. But what I'm gonna do here is cast it to an int. And what that does is it takes that double value of 2.25 by casting it to an end. It gets truncated becoming too that to think it's assigned back into result as 2.0, because again, results of double. So now what should happen is that when I go back to my program here now, when I run this second call that executed, it passes and imagers I should get a proper answer for energy. And you know, is now the result is to now it displaces 2.0 because it's being stored as a double but is giving us the right behavior for dividing two integers. Let's go one step further now. So I want to get in comedies seem three lines here again where I passed the integers in. So I copy that. I'm gonna get head and peace that in. So now in this third call, what I want to do is I'm gonna go ahead and cast this 1st 1 toe a double. So now what happens? There is I'm now calling execute with a double as one parameter and into as another primer . Well, which one's going to select if I get back to my math equation class for looking my executes , Well, I can't has a double into an end because that would be a narrowing conversion. That's not legal. But I do know I can pass it and into a double. So the system will actually choose the one that accepts two doubles because that's the only one that can accept all the parameters. So now if I go ahead and run this. We see we get 2.25 for that last one. The system had to pick the best overload of all those that were available, the one for which there was a valid way, the past, all the parameters in practice, the mechanism that Java uses to resolve method auroras. It's pretty intuitive. In most cases it's going to pick the one that you expect. But the implementation of how that is resolved is actually quite complex, cause there's a lot of kind of nuances of what can go on if you're interested in all the details of exactly how the system chooses a particular veloute. I've put a euro on the screen that references the specimen case for job on exactly how that works. It's really kind of interesting. It's actually quite complex if you're interested in kind of learning more about it, encouraged to check out that you are ill as we've seen, overloading allows us to pass differing prowar list to a particular method name. But what happens if we don't know exactly how many parameters we need to handle in a method ? Let's take a look at our flight class now up until now, whenever we wanted to add passengers to a flight, we always had to add them in one of the time. But what if we went to had a method called ad passengers that accepted however many passengers? We need to add a time. Could be one passenger. Be, too. It could be fine. Well, it seems that the most logical way to handle that isn't a rain. So we'll go ahead and have our ad pastors method except an array of passenger. Now, one thing we need to do is an extra helper method here. Up until now, we've only had to check whether one more pastor could be added. Now we need to check and see if multiple pastors can be at it. So what create our own private overload of has seating that now accepts account? And all that will do is just make sure that there's room, the ad that many more passengers. So the first thing we're doing our ad pastors method is just call has seating passing in the length of that array containing the pastors. So I will do inside of here. Is that what will increase the number of passengers on the flight by the length of that array. And then we'll just get and loop through the array, adding up to check banks for each pastors. We have the complete list course. If there wasn't room, we'll go and just handle that. So now what's it like to call this method? Add passengers rights. We sent the code here and we create a flight. Let's say we create Janet, who is a pasture, has one checked bag and we have John has passed your to check backs. We're gonna get add them together to call our flight and passengers. But we now have to package Janet and John open to win a race. We have to add that could where we actually create a new passenger array and initialize it with Janet and John. No horrible thing, but notice if you look, we've actually type more characters to create the array than we did actually name to do parameters. Janet and John. And if that carries on that scene now, we want to add a family of three people Fred, Sarah and her daughter Susie. Well, again, we got a call, add passengers and then again explicitly creating array containing Fred, Sarah and Susie. It would be nice if we get simply, just list each of the pastures we want to add. It turns out that we can actually do that. Methods can be declared to accept a varying number of parameter values, and doing it's actually quite easy. All we have to dio is when we declare the parameter just putting the lips after the type. So you see her. We have passed dressing array. If we change that to now, be passenger dot, dot, dot at the Ellipse that now says that list will be a varying number of passenger references . One thing to notice that when we use is the lips notation. It can only be used on the last parameter for a method. Now, in our case, our method only has one parameter. But if we had other parameters, we went to accept. Besides this list of passengers, they don't have to occur before the list of passengers. Now here's what's really neat, though. Is that a lips notation? You're actually still receiving Honore? So all the code that we wrote to handle the array stays in place. We have to change any code in this method, the value comes in is that it actually simplifies calling the method. So we take a look at that. Cool. We created the call in tow. Add passengers. The code is we have a written right now would actually still work because the variable number parameters actually handle is an array inside the method. We can pass them to the method as an array. But that's not where the value comes in. We take a look. The first call the ad passengers with Janet and John we can actually replace the array creation with simply passing Janet and John and what'll happen is that Java will take care of creating that array for us. The same thing where we call for fresh air and Susie Weaken simply pass in Fred, Sarah and Susie. So this now gives us that flexibility of handling an array inside to method, which allows they handle anywhere from zero arm or passenger references. We'll still have the convenience of calling it by simply listing the values we want to send to the method. The key things you want to remember from this module, remember, the parameters are immutable. What that means is that any change made to a parameter within a method are not reflected when you exit that method and doesn't matter whether it's a primitive type order reference to a class. But you can make changes to members of a class because remember that the parameters actually pointing off to that object instance so those individual members can be changed. A constructor or method can actually have multiple versions of it. In other words, you can have differing parameter lists. We call that overloading. Remember that the each one needs to have a unique signature. That signature is made up of its name, the number of parameters and the type of each parameter. And finally remember that methods could be declared to accept a varying number of parameter values. Basically, you process it just like it's an array, because it actually isn't. Array is just the job environments taking care of creating the ray instance for you. The one key restriction is that could only be done with the last parameter received by that method or constructor 8. 08 Class Inheritance, Equality, Abstract: as an optical rated language. Java allows one class to inherit from another class, also known as having a class derived from another class. The way we do that is when we're declaring the new class. We used the extends keyword and identify what class we're extending. Our we're inheriting from what happens is that that derived class has the characteristics of the base class, but then can add its own specializations to create more capabilities and to see what this looks like. Say, we have a class here want to call it our cargo flight class we wanted to do is to have all the same basic characteristics as our flight class. So we simply say, extends and then flight. And so now the cargo flight class will have those characteristics that come from the flight class, thanking, of course, at its own right. So is a cargo flight. Maybe things will keep track of is how much cargo space we have. So we'll say our Carter flights have 1000 cubic feet of cargo space, and of course, we'll keep track of how much that we're using. That's what's going down some methods to this, so we'll say that won't. We haven't method to make sure we have enough space for whatever the size is what we're trying to add. So we just make sure that if we add that to how much the space we've already used, make sure it doesn't exceed our max cargo space. We haven't method for handling. When we do try to exceed that, this case would just display a message saying There's not enough space. And then, of course, we'll have a method here, says Add one package, and that method will accept two dimensions of the package the height, the width and the depth of that package. So what we need to do then scientists method is that one receive a package, will calculate the total size, simply multiply the height times of with times the depth, and then we'll call our has cargo space. And then if that returns true, we'll go ahead and add the size of that package to how much space has been used otherwise. Well, good and handle the situation of not having a space, which again just prints out a message. To use this. We can go out here, just declare a Carter flight reference and new EPA cargo flight. Then we can, of course, at a package to it. And so, in this case rating package with a height of one foot with 2.5 feet and then a depth of three feet are giving us a total size of seven cubic feet. We add that into our Carter Vly, Remember the since our cargo flight extends, flight is gonna have access to the characteristics of the flight class. So our flight class has his add one passenger method. So with a cargo flight, we can go ahead and new up an instance of passenger in this case, Jane, and still add one passenger Jane to the cargo flight. So we've got these extended capabilities as well as the base class capabilities. As we work with a derived class. Instances of that derive class can be assigned to references of the base class type. Right. So if we take a look at some code for that Mary that we still have our cargo flight here that extends the flight class well, we can go ahead and create a reference of type flight F and then new of a cargo flight and assign it to that reference with that means is that as a flight reference, it can use the flight capability so we can know a passenger and, of course, add one passenger jean right to that flight. The thing is that we only have access to capabilities that are visible to the flight class . So if we try to do f dot add one package even though a cargo flight knows how to add one package, a flight doesn't so that wouldn't be a valid call because we can only access methods that are visible to the reference type. The value of this capability, though it allows us to perform flight based actions without being concerned about the specific type of the instance that's we think about a situation like this. Say we create an array of flights will call it Squadron. It makes room for five flights. We could have the first member of that being instance of flight class. The next member means that the cargo flight class and keep mixing that up. So we have another Carter flight, a flight and another cargo flight, and then we can loop for through this, doing all the flight based stuff for the Carter flight ones. We may want to do some extended things for Carter flights, but it allows us to very easily group these actions. Well, we're adding behavior toe a drive class that Dr Classical, of course, have fields as we've seen. The thing is that if the derived class adds a field that has the same name is a field in the base class, it will actually hide the base class field. Let's see what that means. Look at her code here. Remember that we have our flight class. And as we've seen, our flight class has a method called Add one passenger now inside of her head one passenger . It will check to see if we have enough seating. If so, we had the passenger. If not, we handle the case of too many, and away we check and see if we have enough seating is that we have a method called has seating. What has seating does is based looks and sees that as long as the number of passengers is less than the number of seats, then we'll say we have seating. So our flight class has a field called seats with a value of 1 50 So if we create this is very flake class and add it to a flight reference called F one, if we print out the value of F one dot seats, we will, of course, get 150. Have we take our cargo flight class that extends the flight class, right? Inherits from it. If it adds its own field called seats with the value of 12 which would make Central Plains a cargo flight, it may have fewer seats. We didn't go out here and create an instance of the Carter flight class and assign it to a reference of type Carter flight called CF. We pronounce the value of CF dot seats that gives us the value of 12. The Carter flight seats field is hiding the flight seats field, but now something unexpected can happen By doing that. Find now, create an instance of the cargo flight class, and I assign it to a reference of type flight. We've called F two when we print out F two dot seats, but we will actually get is the value 150 because the seats value of 12 is Onley visible. When the instances being worked with as a cargo flight. Because the reference here F two is of type flight, it doesn't know anything about the seats. Value of 12 atoning is about the seats value of 150 that becomes really important as we start using methods from the base class is a vital take f two dot add one passenger. When that cause into the method, add one passenger which then in turn calls, has seating. When it checks the value of seats, it's going to use the value of seats to find inside the flight class, which is 150 which would allow us to add 150 passengers to a plane with only 12 seats. And this is not limited to the scenario where the references of type flight if we were to say, cf dot add one passenger and CF is of type cargo flight again because at one passenger calls has seating and has seating is implemented inside the flight class, it would still use the value of 150 because within that method it only knows about the fields to find within flight. So you can see this idea of hiding fields is a very dangerous things were getting highlight That and read now, while we work of methods is a little different. Methods can override based class methods. So if you have a derived class and has a method with the same signature as a base classmethod, it will override it. Remember, the signature means it has the same name and the same parameter list. Let's see how overriding differs from hiding. We have our class here, cargo flight deriving from flight. Same exact Cobey saw before. But we're going to do here. Is that where we set seats? Equal 150 as a field we're gonna do is get rid of that field seats. I'm gonna change it toe a method called get seats. The returns of value 150. Of course, that means that our has seeding method has to be changed to get rid of seats and instead called get seats. And there are derived class cargo flight will get rid of its field seats and added a method called get seats. The returns 12. So now if we work with this we got here, we have our flight reference F one assigned the value of a new flight instance. Course. We print out get seats. It's gonna print out 150 if we have a cargo flight reference. CF pointing to a new instance of Carter flight. When it prints out get seats, it will print out 12. But here's what we see The difference if I now have a flake reference called F to a signed to a new instance of cargo flaked when we call get seats because they get seats. Method from conflict overrides the get seats method from flight. We will now get the appropriate value of 12 3 Method and derived classes overridden the base classmethod, and that's really important as we start to do further work rights. If I take my F two reference of type flight call, add one passenger. It calls into the at one passenger method inside of at one passenger. We calling toe has seating when we get in. The has seating when it calls get seats because the instances of type cargo flight the implementation of get seats inside of Carter flight is actually what gets called returning the appropriate value of swell, so it only allow us to add 12 passengers And that works whether we have a reference like F two of type flight where Reference CF, which is a appropriate type cargo flight. The method in the base classes actually overridden, assuring that the appropriate method incantation gets called based on the type of object created, not the type of reference used. If you come from other object oriented languages like C Sharper C plus, plus something it may stand out to you here is that you'll notice that we didn't have to do anything special to be able to override that get seats method and Java. All methods are automatically over rideable. Unless you do something special to say that you don't want them over ridden, we'll talk about it. Do that a little bit later in this module. No one things that may come to mind that was that. Well, how do you make sure that you haven't excellently made a mistake in terms of maybe not matching the signature correctly? What John provides is the override annotation and what this tells the compilers that it is your intention to override and method from the base class so the compiler will actually check and make sure that the base class hasn't method with that signature, so it's kind of just a sanity check to make sure that the method you're declaring really does replace a method in the base class has no impact on run time. It's only used at compile time. One of the built in classes that Java provides is the object class. The after class is the root of the Java class hierarchy. When, that means is that every class in Java, whether it's a built in class or when you create, has the characteristics of the object class. What that means is that using the object class, we can declare references that can point to any class type, as it could be. Variables feels parameters and because a razor classes object claiming point to a raise so dry kind of this kind of universal reference type. But it's more than that. The object class actually has methods that are defined on it, so that means that their specific characteristics and capabilities that are common to all classes. So if we look at the idea of inheriting from the object class, every class inherits either directly or indirectly from the object class. Let's look at some of the classes we've written throughout the scores where we have our flight class. All right, so if we were diagramming this, we might just gonna draw a box representing the flight class. Then, of course, we have our cargo flight class, So draw box for that. The murder that we declared the cargo flight class. We said that it extends the flight class right away. We're diagrammed as that. We just drawn our up two flights saying that cargo flight inherit from the flight class. Now look at the flight class. There's nothing about extending anything. But what's implied in that class declaration is that class flame extends the object class. And so, by not seeing what it extends, it implicitly extends the object class. So the diagram that we would have the object class and flight inherits from that you could actually write extends object after the flight class. It just wouldn't change anything. Having nothing there has the same effect. So we look at our passenger class, right? We don't say it extends anything, but when we diagram it, it's still extends. Object. So we see here is that whether classes air related to one another or not. They always extend the object class mean that we can treat any class as an object, right? So to put that into practice, so is declaring array will call stuff right? It's type is object, and we created this response in it. So maybe the first element holds a reference to witnesses of flight. The next one holds a reference to a passenger instance, and we could even add another one. That's a cargo flight to see what it's like to work with object references. Let's go here and declare object. Oh, the points on intensive passenger. Once we do that, that same variable oh can also be used to point to on array of flights. Be very clear on the left, we made an object of rate. It's pointing to lots of different class types on the right here recently saying that because raise our classes, we can assign an array to a variable of type object. Now we wouldn't have access to any of the array characteristics of it, but we can hold the reference are we now take that same oh and point to an instance of cargo flight. But again, the reinforce that idea. Remember that when we have a reference of a given type, we can only access the capabilities that are visible to that reference. So if I was to try and take oh, and call, add one package a method that specific to cargo flight. But that's not gonna work because the reference O doesn't know anything about this idea of ad one package. Now, does that mean that the optical created cargo flight is any less cargo flight? Because the reference oh can't get to the Carter flight capabilities. Of course, the answer is no. All right, let's see what this means in terms of what's happening here. Where that we declared our reference o of type object, we knew it up a cargo flight. And of course, oh, that holds the reference to cargo flee. So even though only knows about object capabilities, it's still pointing to a cargo flight object. So we should be able to get back to those cargo flight capabilities, and so we can actually do that so we could declare a variable will call it CF and a sign it what's in? Oh, now if we tried to use this code as it is here. We would execute an error because the compiler would look at that and say, Well, wait a minute. Oh, come point to many different types. There's no way for the compiler to know that they'll actually be a cargo flight in there. So we can do is add an explicit cast. It says No, I know there's a cargo flight in there Now we want to make sure that it's true because it wasn't true would execute an error at run time. It's what happens when we make this assignment. We've got our reference CF, but CF understands cargo flight and it ends up pointing to that same object was in no cargo flight. So now, using CF, we can call add one package. And again it reinforces point here is that we want to make sure when we made that assignment that there really was a cargo flight in Oh, there's any doubt about that. We can verify in code. We can ramp this in a condition that says, Well, if o instance of cargo flight, what that will do it run times will actually look at the object pointed to bio and make sure it actually is a cargo flight. If it wasn't, we wouldn't have run the code near that, assigned it to the cargo flights. CF Now looking at our object class, the optical as is not just for references that actually has characteristics, actually has methods that are built in that we're not gonna go into all these in detail right now. But I want to make you aware of them. One of the built in methods for the object class is the clone method that allows an object to create a duplicate of itself. There's some caveats to working with that we're going to talk about later on in the course . Another method that's available to the object class and therefore to all classes, is hash. Koot returns back a hash coat that's useful, working with things like hash tables and other types of rely on hash tables. To get classmethod returns back type information about an instance. The finalized method is part of resource clean up. In most cases, you won't do very much for the finalized method. Then we have the two string method that returns like a string of characters representing the current instance. Rex, don't talk about that one Maurin. The next module and the last one is the equals method, which they use to compare one object instance to another rights. Gonna talk about that one in the next clip? Let's look at the issue of equality when we have two references. Toe objects. What does it mean when we ask, Are they equal and you enter? That is actually, well, it depends. Show you what I mean. Let's have some code here. It's first created instance of the flight class. We'll give it a flight number of 1 75 and assigned it to the Reference F one. Then we'll create another instance of flight class. Give that one a flight number of 1 75 as well. In this case, we assign it to the reference F two. So F one and F two pointed to separate instances of flight class, both with the flight number 1 75 So if I write to, Could to say, if F one equals F to using the equivalents operator, the equal equals the comparison there will resolve to false because the equals equals operated performs what's called a reference equals test. Other words do both of these references point to the exact same object. Instance, when you use this equals equals operator, it only resolves to true with reference types if they're both pointing to the same object. Remember that we've been talking about the object class, and we meant that the object class has an equals method on there. So maybe that's the answer to how we compare these to see if they're equal. So do it. If F one dot equals passing in F two, If we run this code, what we'll get is false again. Did the fall implementation of the equals method, in other words, the one that we get from the object class also performs a reference equals test. In other words, it does the same thing as the equals equals operator. It only resolves the true if both references point to the exact same object instance. But the good news is that because our flight class, like all classes, inherits from the object class, we can override equals method, so it's very overflight class here. Remember that our flight class provides two different ways to identify a flight if we can have a flight number or you can have a flake class. We don't set both as we set one or the other. And so the way it would work is that we would have a flight number with no flight class or a flight class with no flight number. So we're gonna say that we're reckons there two flights to be equal if they're identifying information is the same. They both have the same flight number without a flight class, but they both have the same flight class without a flight number. So we're gonna do is override D equals method. Now the Eagles method returns back a bullion. So have a boy returned type R equals method name. And if we look at the definition of equals in the optic class at the equals method has one parameter, which is an object, then we're gonna do. You're gonna mark this with the override annotation just to the composite will double check us and make sure we've got our signature correct for the equals method. So now we call f one dot equals passing in F two f two will be passed into that parameter. Oh, I remember that because oh is declared as an object, it will only have access to members that are known by object. It won't have access to the flight members. So we need to dio is take that. Oh, cast it to a flight important into a reference of type flight. So that will be our other variable here. So now other will have access to the flight information from F to surround dear than to have the test. Is that well, if the flight number for the current instance which is F one matches the flight number from the one passed in which is have to and the flight class from both of those match, we're gonna consider them equal rights with The idea is that if the flight number was set, so both have the same flight number. But flakes class, we have that the fault value, which is the no character. The flight class was set the both of the same flight class, but flight number will have the default value, which would just be a zero. So we're just gonna return back that value, right? So that now we call equals. We're now comparing the two flight instances based on their identifying information. Now, this is how we've defined equals in this particular situation in your individual programs, you're gonna have to identify what equals means, because we might have decided that well, for two flights to be equal, not either they're identifying information have to be the same. But maybe the number of checked bags also has to be the same, right? It's up to us as we define our problem space and the problem we're trying to resolve. So now, relying on this idea that as long as the identifying information is the same there equal, if we go back now, look at the code right First, the if f one equal equal f to where that still could resolve to false. Because that's still a reference equals it's only true both f one f 2.2, the exact same object. But now our if f one dot equals passing in F to that now resolves to true because both F one and F to have the same flight number. But now let's have another situation. What if we go off and create instance of a passenger and then we say, Well, if F one dot equals passing in the passenger since eagles accepts an object as its parameter type. It's valid for P to be passed into that parameter. Oh, but what's gonna happen now when we try to cast oh into a flight, right, it's gonna go and create an error. So one thing you have to do is make sure that in our equals method, we don't try to compare against any type we can't validly be compared to. Well, we know that we can take that. Oh, and check to see if it's an instance of the flight class. Well, we want to do here is say that Well, if it's not an instance of the flight class, we just want to get out of here. So we'll do is just go and wrap that instance of comparison in the not operator. And then, if it's always not an instant flight, we're just gonna go and return falls. Are there comparisons that, compared to flight instances won't be changed. But this situation we're trying compare a passenger who can't really be compared to the flight that will now return false. The key thing to understand here is that we need the override equals to provide our definition of equal and the specific definition of equal is going to be specific to your problem space From our discussions of previous modules, we know that Java offers references that have special meaning like No, and this another one of those special references is the super reference. Like this. Super provides access to the current object, but we're super is different. Is that super treats that object as if it's an instance of its base class and allows us to access to feature the object, as if our car class has not ever written any of those features. This comes in really handy when we're implementing something in her current class, and we want to get to the features or a method exactly as they behaved in the base class. Let's take a look here at our flight class and as you were coughing a previous cliff, we've overridden the equals method to compare to flight instances based on the flight identification information. The flight number in flight class. But it's look at some code here. I say we go ahead and we created its to flake with a flight number of 1 75 and assignment to F one, and then we declare another reference F to an a sign it f one. So now F one and F two are pointing to the exact same flight instance. So now if we say if F one equals passing in f to it, that's gonna call into R equals method and now what's it going to do it? It's gonna go through everything we've written inside of equals where he's going first, make sure it's actually instance of flight, and I'm gonna cast the flight passed in, and they were going to compare the values of flight number and flight class. Now, in this case, the work that we're doing there is not that substantial. But in some cases an equals method may actually have to test a lot of things in a complex object. There may be a number of fields compare and other operations you have to go on. The thing is them. We know the base class object implements a version of equals to just checks to see if two references point to the same object. And reference comparisons like that are actually really inexpensive. So it would be great if inside of our equals method, maybe we could do your say Well, if the reference passed in points of the same object that we currently dio, well, we know they must be because of the same object. Let's just get out of here. So that's update our equals method to do that. So it's good to make a little room in cyber equals message here. And what we'll do is what if the very beginning, I will simply say, equals passing it. Oh, and if that returns true, will then in turn return true. Of course, the problem. Years as we've written this, when we call equals inside this if statement where we're gonna dio we're gonna call back into our own equals method, which will then again call back into our own equals message and just do that repeatedly. Actually, until we crash with an error we really want to do is at this point call equals as it was implemented in our base class. And that's what the super reference comes in. We gotta move that equals over, and we put super in front of it. What will happen now is that when we call into the flay implementation of equals, the first thing that we do inside that implementation is calling to our base class implantation, which compares to see if both references point to the same object. If they do, we just exit out of here. If we didn't, we then go through and do the other tests that we've built inside of our equals implementation. So we've been able to access that based class behavior when we wanted to, but still have our over in behavior when we needed it. As we've seen Job, it makes it very easy to extend classes and override methods. In fact, by default all classes to be extended, and when you inherit from a class, you have the option of using the methods as they were written in the base class or overriding them. But sometimes I mean what you want. Maybe you want to put more controls on that. It turns out that a class can change these defaults. It can control what it's allowed to be extended and how overriding methods works. One way it does that is using what's called final final allows us to prevent inheriting of an entire class or the overriding of certain methods. Let's take a look. That's why we have a class here are passenger class we've seen before. Let's say we've decided that you know, we don't want to allow any specialization of the passenger class. We don't allow anyone to extend this class well, all we have to stick to pasture class and market as final. I'm working in his final. Simply put, you cannot inherit from it anymore. You're not allowed to extend that class. One thing to note, though, is that the order of public and final here doesn't matter. If we want to weaken, switch the order. Those so has the exact same effect. So marking classes finals a very simple thing. It's simply blocks extending that class. But very commonly we want to do is allow a class to be inherited from, but have certain methods. We do not want to allow them to change. Let's take a look at our cargo flight class here, say we want to get in that allow people to inherit from cargo flight and specialized Carter flight. But we want to make sure that they don't change the way that adding a package works. So what we can do is take our add one package method and just mark that method as final by marking the Methodist final. Now you can inherit from cargo flight, but you cannot override at one package you Conoco and override other methods that might be in a class if you have access to them. But in the case of cargo Flight, there are no other methods that you couldn't override because add one package is final and has Carter space and handle no space or both. Private, so deriving class couldn't change those now. Methods that are inherited from flight could be overridden. Rights work just very selectively blocking what can be overridden. In the case of Final, you'll generally either mark the classes final or an individual Methodist final because once a class's final, there's no reason to mark individual methods. Is final because you can't have write anything if you can't inherit from it. So final is a method or class situation. Now there may be another situation where, instead of trying to prevent inheritance, you want to go ahead and require inheritance. And that's where abstract comes in after it allows you to require the Class B inherited and require that a particular method be overridden. Let's see what that looks like Let's create a new class here, will call it pilot, however pilot class and will go ahead in a pilot can fly of flights will have a current flight field. And we had a method called Fly that accepts that flight. And what will say is that Well, if the pilot can accept that flight will go ahead and assign the flight to current flight. If they can't, we'll go and just handle that case that they can't accept it for handle can accept. We'll just do. We've been kind of doing is simply printing out a message. But when it comes down to the idea of whether the pilot can accept the flight or not, that's gonna depend on what kind of pilot it ISS. And we want to leave that to the classes that inherit from pilot. So we'll do is we'll go ahead and mark something is public. I'm gonna say now abstract and then we provider standard method signature. So it's a public method called can accept returns of bullion, but but saying it's abstract were saying that we're not going to provide in implementation now is that we're not gonna provide implementation. What we do is that rather than preventing a method body, we just put a semicolon at the end. So we're simply saying that the class pilot has a method court can't accept. We don't know what's implementation that method is, but it has that method. What that allows us to do is use can accept in other methods in the class, like, in this case, the fly method. Now, once you mark a method as abstract, that means the entire class must be abstract. Will go to mark the classes abstract as well. So when it comes to abstract, if you have an abject method, you have to mark the classes abstract. It's possible the market classes abstract and have no abstract methods, but that's not very common. Normally you'll have one or more abstract methods in any abstract class. So now the way we work with this right, let's go ahead and define a pilot will call our cargo Onley pilot that extends our product class because extends our pilot class. It has to provide an implementation for can accepts. We'll go ahead and set that up, will go and use the override annotation and what will say inside of here is that a cargo only pilot is not allowed to have passenger, so we'll take the flight called Get Passengers and we only return true for can accept if there are no passengers at all. May we have another class called full license pilot and he's got of our super pilot, where he's allowed to fly any flight. So what override can, except for him, go ahead and marked with the override annotation and he simply gonna return true all the time, saying he's allowed to fly any flight. It's what allowed us to defy basic characteristics and behaviors in the pilot class, but then require specific specializations in any derived class, an issue that's very important. Understand, as we look at the idea of inheriting one class from another, is that in Java constructors are not inherited. Each class is responsible for defining its own constructors derived class, though, must always call one of the base class constructors. So as you define the constructors inside of your derived class, there's always gonna be a call back toe a base class constructor. Now that call does not have to be explicit. If you don't have an explicit call toe a base class constructor that it will use the base classes. No argument, constructor, but you can call a specific instructor if you want to. You simply use the super notation, followed by the list of parameters that correspond to the base class constructor that you want to call. You do have to make that the first line in your constructor, though. Let's see what it looks like. One coat. Now we've looked at our flight class. We've done a bunch work with that until now and want to focus in on the no argument constructor. And it's constructive. That exception flight number and that allows us to create code to create since of a flight , in this case, creating a new flight would flight number 1 75 Now our cargo flight class that has a number of members inside of it has no constructors defined. That, of course, means that we can create an instance of cargo flight using a no argument instructor because Job provides an organ instructor force by default if we haven't specified one. But if we try to go off and create a cargo flight with a flight number, that's not gonna work. We get an error because even though are based, class flight has a constructive except the flight number. Cargo flight does not. So if we want to create cargo flights with a flight number, we need to define a constructor in Carter Flight that accepts the flight number. Now we don't have to do that work herself. As we said, Weaken, delegate that to the base class by simply using that super notation and passing in flight number. And so now we can go ahead and construct a cargo flight with a flight number. In this case of 2 94 that calls into our cargo flights constructor accepting a flight number which in turn calls the implementation inside of flight. Now we can, of course, extend behavior beyond the base class constructors. For example, our cargo flight class keeps track of the idea of the maximum cargo space so we could go often to find a cargo flight instructor that accepts flight number and a value that we want to use for Max cargo space. Now inside of the cargo flight instructor, we can enforce set max cargo space if we want to get and call up, though to the base class instructor, We again use the super notation, but it has to be the first line of the constructor. So this would call into the flight instructor steps of flight number and then set Max cargo space. But in this situation, rather than call into the base class, we've already done work inside of our class to create a constructor that accepts a flight number so rather called super. In this case, it will be better again. Use this so they have a golfing or create could. It says I want to create a cargo flight instance that accepts a flight number and Max cargo space. It will call our Carter Flee Constructor that accepts those two parameters. Well, then call up to our Carter flight constructor of accepts the flight number and then that calls into the base class constructor to accept slight number. Now, something that's happened is that as we've added these two constructors to cargo flight, we've broken a line of code, right. The line of cool where we created the car deflate passing and no parameters no longer works . We wanna have that. We need to go ahead and add that to our cargo flight class. So now this code would build again. And when we call into our cargo flight constructor, it will then call into our flight classes. Constructor, That takes no arguments. Right? And that happens because we did not specify any base class constructor. That's what's so We add another constructor to our cargo flight. This one accepts Onley cargo space, and all we do inside of here is set Max cargo space. So we now create a lot of code that news of a Carter flight passing and only Max cargo space. What does this do? Well, it calls are constructor. But before it executes the body of our constructor, it will call up to the flight glasses constructed that has no arguments and then run the rest of our constructor. Right? So it always calls into a base class constructor. Even we don't specify one. In this demo we're gonna use, we've learned in this module to see if we can make our calculation program a little bit easier to manage and maintain. Here we are inside of our count engine program. And what I want to focus on is this math equation class. We take a look this class. It has a number of distinct responsibilities, some that are common to all operations than some things. They're specific to an individual operation. Well, look here. First of all, it declares all the fields necessary to do the work. Then it has to have getters and centers for all those fields. Then it has the variety of constructors, and then we scroll down here towards the bottom. We get to this excuse method which actually is doing a number of different things. And when I found is that when you see code like this, we've got a Syria big condition like this and there's individual tasks inside of there. As a program gets more complex and you start to work inside this method, this is a police were very often enhancing or modifying. The program will introduce errors because I got a bunch of kind of loosely related could kind of clump together. This is a great opportunity for us to use the class inheritance features of Java to have a better division of responsibilities. So I want to do is go here. I'm gonna get add A new class were to call this class Calculate base is gonna get knew this guy up and, as I mentioned, will call this class calculate base and based on his name, you can tell that it's probably going to be a base class, so other classes are going to inherit from it. That's not a requirement. It's just something I tend to do when I know a class is going to be used only as a base class. This class will actually act as a common point of inheritance from all of our separate operations. So the thing is going to common. All these operations is the Siris of fields. We need to declare it left. Vow right, vow and result. In addition to that, we're gonna have getters and setters free to those fields. So that takes c 9. 09 Inner Classes, Exceptions, Pacakges, interface : earlier in the course, we talked about the carrot type, which allowed us to work with individual characters. In practice. We tend to work with sequences of characters Maura than individual characters, and that's what the string class comes in. Stores, a sequence of Unicode characters, the stories I'm using. The UTF 16 encoding, which basically means that the job is drink class, can store pretty much any character you're likely to ever want to work with. Working with strings is really straightforward. Literal strings are enclosed in double quotes, so that's they wanna have a variable called name, a sign and a literal strength. We simply declare it as string and a scientist. Little String Jim Enclosed in quotes We can easily combine string values using the plus or plus equals plus combines two strings and gives you back a new strength. Plus equals adds a string onto the value of an existing string. So if I want to get do something like print out Hi Jim, I can use our print line method. Put the little string high and then at a plus sign and name after that and that will print out that value. Hi, Jim. Now One thing to be aware of is that string objects are immutable, and what that means is that once the string object is created, it can never be changed. So anything that changes that value requires that a new instance of the string object recreated. So let's see what that looks like. That's a good declare, a variable called greeting and a scientist literal. Hello, of course I've got my variable that a string is allocated out in memory, holding the value. Hello, of course. The variable greeting then references it. But then, if I do something as simple as greeting plus equals space now all I want to do is at a space onto the word Hello. In order for that to happen, a whole new string up has to be created, holding all the existing values, the hello plus the space and then greeting is re pointed to that new instance. So it'll feel like just a space was edible into the end. But actually a whole lot more is going on. So if I then announcing greeting plus equals world again, allocates at another object holding Theo entire string and re points greeting to that. So we want to be aware of this idea of strings being immutable because we can end up doing things really inefficiently Now. Later, in this module, we'll talk about how we can use other mechanisms to work with this string situation like this mawr effectively. Now the string class has a number of methods on it. We're not going to talk about all of them, but it's gonna plant some of the highlights here when the methods would commonly uses the length method. Which gives us back the length of the string is how many characters Aaron that string. Very often. We want to convert non string values in the strings like we haven't maybe the energy value 100. We want to get back to characters. 100 The string method value of will do that. The string class provides methods for creating a new string from existing strings. Can cat combine C string values to creating the string bass? It seems the plus operator police to lower case to upper case in trim. Create a new string based on modifying values of an existing string. The split methods useful for cases where you have a delimited string like a list of common delimited values will give you an array of strings back of the individual values. Inside that original string, we can do string formatting. We can extract a sub string from existing string. We can check for the presence of a sub string in an existing string. And, of course, we can do comparisons compared to and compare it to ignore case check to see if one string is greater than equal to or less than another string based on the Unicode character sequences. His empty tells us whether we have a zero link string equals equals ignore case. Honestly, check for a quality equals checks to see that we have the exact same character sequence in two strings. It was ignored. Case does the same thing, but ignoring the case, of course, the thing is equals actually raises some interesting issues that we need to talk about, which we'll talk about in the next clip. To get the full documentation on the string class, just check out that your l A have on screen. Let's take a look at the issue of comparing strings for equality. Let's say I have a string of call s one and I signed the value I space love Then add on space Java to the end of that they have another string Call s to I said to the value of I and add on space love, space job. So we have two strings s one and s two and both them had the value I space love space, Java So now if I compare them for quality using the equal equals operator what I'll get is thoughts and let's see why that's the case. So I look, it s one. It contains the value as we said I space love, Space, Java And of course, the variable s one references that and we look at as to what it also has I space love, Space Java. It has two references that but remember that the equals equals operator compares values based on whether they both point to the exact same object. Instance if we see here is that s one points the one instance and has two points to another . So they're not equals by the definition of the equal equals operator because they don't point to the same object incidence. And that's where the equals method comes in the equals method does a character by character comparison. So as long as the character by character comparison of the two values matches, then in that case we get true. So in most scenarios of comparing strings for equality, we're going to use the equals method you know. Something to consider, though, is that reference based comparisons are actually quite inexpensive, whereas character by character comparisons can be very expensive, particularly in very long strengths. So it would be nice if we had situations where we're going to a lot of comparisons of particular string value. It might be nice to take advantage of that inexpensive nature of reference based comparisons, and that's where the intern method comes in. The intern method gives back a cannot ical ized reference of a string value. That's what that means. So let's say I declare another string variable s three and I a Science of value of s one dot in turn again into returns back economic allies value. And that's a fancy way of saying when you call the intern method on a string value, it will always return back the same exact string object for a given string value. So we co s one that in turn we get back economical ized reference to I space love Space Java as three gets assigned a reference to that. So now if I say string s for equals as to done in turn as for will get a reference to that exact same object instance. So the intern assures that two strings with the same value will reference the exact same object. What that allows us to do then is used that very inexpensive equals equals operator to do the comparison so as three equals equals as four returns. True as you might expect, there is a bit of overhead to in turning a strength. So in general, when you're doing a series of one off comparisons of strings, you'll use the equals method to do that. But when you have situations where you expect to do a lot of comparisons to a given set of string values, that's where the intern method comes in. You often in turn a syriza string value, expect to search over and over again and put those into an array or some other collection. And then as you searched that collection, you will then, in turn, the incoming values and use that very inexpensive equal equals operator to see if you can find the value in that array or collection of intern string values, we often need to convert non string types into strings. Having a value is a string makes it easy to do things like build a message or display output to a user. The string class provides a helper method called value of provides overloads that will handle converting many different types. Two strings and using is really straightforward. So we have something like an energy here. I vow that we set to 100. If we say s foul equals string dot value of, I vow, as I will get the string 100 The value of is useful when you need to do those explicit conversions, But very often Java will take care of doing convergence. Two strings for you automatically. Let's say we have some code here where we have to imagers. I has a value of two, and Jay has a value of through. But I say result equals I Times J and I now want to display out to the user a full string showing the operation and the result. So I say I followed by Plus and the strings space Astros space. When Java sees that I'm taking an injure with a plus and the others a string, it knows that I actually want to string representation of I. So now if I go on to say plus J plus basically space then plus results Java will go through and convert I J and result two strings for us and then can cabinet them all together. So we get that complete string to space time space three space, Equal space six bills that string together forests and took care of those conversions. Now, in this case, we're dealing with a very simple type. Write a primitive type manager. But what about things like more complex types, like classes where the string representations not so easily known? Well, that's where the two string method comes in. Remember, we talked about that. The object class provides from standard methods that all classes will have to string is the one we used to get the string representation of a class. Let's take a look at some code for that. Remember that we have our flight class we've been using throughout the course. So here we created flight class instance with a flight number of 1 75 Find out, say, print line. My flight is and then we simply can cabinet on my flight. What job is going to do is call to string on the object reference by my flight. Now we have an implemented to string in the flight class, so it's going to call implementation from the object class. And what that will do is give us results that looks something like this. Where, of course, you have that literal string. My flight is, but then we get is the fully qualified class name, including the package that's in followed by an aunt symbol, followed by whatever values returned by the hash code method. So I give this kind of a unique representation of this instance, but it's not really very helpful. All right, so we can improve that. So we look at our flight class or that our flight class had two ways of identifying flights and fly could be created to have a flight number or a flight to be created to have a flight class. So we want to do now is have our to string method represent a given flight instance in a meaningful way. So go ahead and override to string. We'll do. Here's what check and say, Well, if it's a flight that has a flight number we're going to do is return back to string flight space hash and then add on the flight number. It was a flight that has a flight class. Instead, we're gonna say flight space, class space and whatever that class character is. So now if we take a look, this code over here when we call print line we're gonna actually get out is my flight is a flight number 1 75 So now we're getting back a more meaningful string representation of that object instance. And that's what we want to do. Inside of our to string method is provide that meaningful representation of an instance as a strength as we've talked about strings air immutable, and it means that any modification to a string results in the creation of a new string, and that's just not efficient. But there are, of course, times we need to be able to efficiently manipulate strengths, and that's where string builder comes in. String builder provides us with a mutable string buffer, providing us with an efficient way to manipulate strings now, although you don't have to when you create a string builder, instance you'll get the best performance if you pre size the buffer. Yes, we will get some code here, declare string builder as B. It's a new string builder 40 With that allocates out an instance of string builder that has room for 40 characters inside of it. In fact, we really call the sp dot capacity method. On that instance, we'll get back to value 40 now. The string builder will grow automatically if you exceed the capacity. But you want to minimize how often that happens because there's a fair bit of overhead. Each time the system has to grow a string builder instance, String butter has a number of methods available, but the ones who used most commonly are upend, which lets us add new content to the end of string builder or insert, which gives us the ability to add new content within the body of the string builder. Let's look at some cooked, so we have our flight we've been using here have flight number 1 75 we'll have a string called location with the Value Florida. Let's leave one a bit of a message, but again, say sp dot upend. I flew to space well that as it to the end of the string builder was its string builders empty. That adds it to the beginning. So then we say SB upend location takes a value location Florida as that on to the end, the little strength space on space that gets added onto the end. There is a SP Don't upend my flight. My flight is a class so getting called to string on it. So we get flight number 1 75 So we've been able to build these four values together, doing it all in a single buffer. But it's only come along little further program. We realized that we actually have access to the time of this flight as well. We want to go ahead and add that into the message. We want to put it somewhere into the body of the message that they want to do it just before the space in the word on. Now, since we know how many characters we've written into this buffer from the beginning. We could just count how many calories it takes to move over to get there. But let's say we didn't know that. Let's say that all we knew is that we've added content inside of here and we've added the word on and then the information from our flight class, and we want to calculate where the insert point is going backwards. So from the end of the current values, let's see how we would do that. So we declare a variable position minutes ago, say SB dot length. And that tells me how many characters are currently in the string builder instance. Remember, Capacity said, How much space is allocated? Length says how much is in use and will say that we want to go back the length of that literal on now. Honestly, I could have used the energy value four here, but I just wanted to show you that we can call string methods on string liberals, and then we'll use our my flight to string that length. That now tells us how far back we have to G o to get before that space before the word on. So now, without that, I can now say something like SP Done insert, Give it to position and then what I want to answer, which is space at space. The string little were do is move over that on flight number 1 75 and then right the at in there. If I say SB, insert position plus four and then add the value of time in the position post floors is I want to get past that space and space. No, it's a time, is it manager? But insert will take care of doing the conversion. So now it'll move over the on flight number 1 75 and right that nine in there. So now we've got our content build exactly as we want it, but it's not quite a string yet. The way we get to string out is the way we get to string out of any other class. We simply call the to string method so inside of here. If we say string message equals SP dot to string message will then get the actual string. I flew to Florida at nine on flight number 1 75 so string, but it gives a really efficient way of building and manipulating strings throughout our discussions in this course recently, we've been talking about classes I think we see when we talk about classes, that classes provide convenience when the conveniences is that all classes inherit from the optic class, so we can use object is a standard way to interact with all class instances, So that's a good thing. Classes have fields and methods that are specific to that type, so it means that we can have values and operations directly associated with the type. And so that's a good thing, one of things we need to be aware of. Those classes also have overhead. Every class instance has a certain amount of memory that's always taken up just by the fact that it's a class, and that's before even has its own specific values inside of there. So, general, we consider that little bit extra overhead worthwhile. To get those conveniences, I think, is that primitive types focus on efficiency where we use them alive. So we want primitive types in general to be very lightweight. All right, so the idea is that if you have a four bite and it's simply occupies four bytes, nothing beyond that, so that's certainly a good thing. But now, in order to get that efficiency, we have to give some things up. We can't have fields or methods of social, primitive types, and primitive types cannot be treated as objects. And most of time, this division between classes and print of types gives us kind of a really effective way to work. But there are times where we're working with prune of values that we're willing to give up these efficiencies in order to get the convenience that we have with classes. And that's where the primitive rapper classes come in. The primitive rapper classes give us the capability of classes, but they do also incur that overhead. But they allow US toe have those capabilities when interacting with primitive values. Now the point of classes are indeed classes, as with all classes they inherit from the object class, and each of the primitive types has a corresponding rapper class, so the bullion primitive type has a rapid class called bullion. The only difference is capital B. For the class lower case be for the primitive type. The camp front of type has a class called character, and when it comes to the new Mary classes. They all have a common base class called number Number is an abstract class that all of the numeric primitive rapper classes inherit from. We have four classes, one for each of the energy types, and we have to one for each of the floating point types again, these are all real classes, right? So they could be treated as object. And they have fields and methods associate with them that are particular to that type. One thing to be aware of. All the primitive Robert classes are immutable, so a given instance always has the same value inside of it. So if you have a reference to a instance of one of the primitive rapper classes and you do something that changes the value, you will get a reference to a different instance of that class, very much like working with strings. So you just wanna be aware of that. As you would expect, you often have to convert between the rapper classes and the primitives, and Java provides a number of ways to handle that. The good news is, is that the most common scenarios are handled automatically by Java. When we take a look at some code. So we go on here, we declare imager a equals 100 well in injure a means that A is a reference to an instance of the imager rapper class. But 100 is the primitive value. 100 Java will take care of getting a reference to an instance of the energy class that has a value 100 inside of it, have we say in two b equals any will be is a primitive type. A is a reference to a rapper class Job will take care of getting the value out of a And just to note that the idea of conversions happens with variables and liberals, right? Suggested we had an integer equals 100. We could have entered your C equals B. Well. B is a primitive variable. See is a reference to the energy class. Jabba will take care of getting a reference to the energy class that has the same value that B has inside of it. When it comes to making these conversions, Java also provides methods for doing explicit conversions. If you want to convert from a primitive type two. A rapper class, the rapper classes all have a value of methadone them. That process is known as boxing. The idea of boxing is that you take a primitive value and you wrap it up in a box, which is now the class. If you want to convert from a rapper class to the primitive type, each of the rapper classes has a what I call XXX value method. And basically the x X X is the name of the primitive type. So imager has energy dot int value double has double dot double value. As you would expect, this is what's called unboxing. To see this in practice, a little more code here. Well, say energy D equals imager dot value of 100 but it takes that primitive 100 give us back at reference to the energy class with that same value in e equals, d dot int value desire referenced one of rapper classes that in value methods gives us the value out of it. And again, imager AF vehicles entered your dot value of E again. It gives us a rapper class reference that corresponds to the value of E. You take a look at the code of the top there we say Energia a equals 100 then we'll get imager d equals energy value of 100 you know? So we're doing very much the same thing there, and turns out we're actually doing exactly the same thing in a situation like that. Compiler actually injects that image of the value of call for us. In fact, we don't really have to use these value of and in values that often anymore prior to Java five, you always had to use them. Starting a job of five, the compiler started inferring their usage. So a good deal of time. You can rely on the compiler to do the conversion for you, but know that those methods are there if you need them and just be clear, they're not limited to imagers, right? This were there for all of the rapper classes. So I look here like float G equals float down value of whatever turns back a reference to the float class with a value 18.125 inside of it. And I say float h equals G, that float value that could be the permanent value back out of that instance reference by G . Now there's one other type conversion need to think about. And that strength and job provides mechanisms for that as well. If we want to convert a string toe a permanent value, each of the rapper classes has a parse method on so, like, imager has parse int that will parse a string value and give you back the primitive value corresponding to it. We also have a overloaded value of accepts a string, and this gives you back a reference to a rapper class. So we just look at that and code. If I say I have a string here asked with a value of 87.44 if I say double s one equals doubled up parse double of s notice that even though I'm calling parse double on the rapper class double, it returns back A primitive type of actual returns back to primitive 87.44 Whereas if I see Double s two doubled up value of s value of returns back a reference to a rapper class that has that value 87.44 inside of it. Now that we have the primitive rapper classes, we can take advantage of the capabilities that all classes have When working with our primitive types, for example, we can now treat their primitive types as object. So we have a situation where we have maybe an object array or any other type that expects object references. In addition to putting in things like a reference to a flight class or a pastor class, we could even drop in the value like 100 right? What happens in this case is that Java will go ahead and get a reference to an instance of the image a rapper class with a value of 100 a sign that reference into stuff sub to. We also have the benefit of no references. We have a distinct idea of a value not being set. Let's take a look at our flight class. Here are flight classes you recall has an aunt for flight number and a car for Flake class . So inside of our to string method, we said, Well, it flight number is greater than zero. We go and return back a string contain the flight number. Of course, the idea there is that we're saying that well, if the flight numbers greater than zero, we know what's been set, but we make the assumption that if it's not grated zero, it must not have been set, even though it's potentially possible to have a flight with a flight number of zero. Then we also makes the assumption that, well, if flight numbers not greater than zero, well, you must have set flight class because we don't really have a distinct way of knowing that the values haven't been set. But if we now convert our aunt in our care to the rapid class equivalents, we take flight number. We make that an imager. Instead, we take our flight class and make that a character instead. Now we go inside of our to string method. We want to check and see. A flight number has been set rather than checking to see if it's greater than zero, we can check to see if it's not equal in all its NyQuil don't know. We know it's been set, no matter what values inside of there. When it comes to checking the flight class, rather just assuming that will flight number wasn't set, they might have set flake class. We can actually check and see if flight classes Nike within all. So that gives us instead of just two states, you've set one or the other. We have three states. You could have set one, you could have set the other. Or maybe you didn't set anything at all. So we're getting that benefit that we've had with our classes along now with our primitive values. Now, as we mentioned, the rapper classes provide members as well. Let's take a look at just a few of those, so I have your own screen, a list of just a few of the members in each of the classes. If you look at the energy classes, bite short in a journal long, you see that we have things like Men Value and Max value. Which airfield to tell us the bottom range. In the top range of that, each type a method like bit count that led to see the individual bid values. In an instance are things like to binary strings. Let's get a string back with the buying a representation of an instance on our floating points. We have men value and Max value again for the bottom and range, top and range. But those introduces concepts like infinite or not a number on character. Once again, we have a minimum value in a maximum value. But then we also have things like Is Digit and his letter to see what kind of character is inside of a given instance and then on bullion. We even have fields for representing a reference to a true instance or false instance. Now these members I have on screen here are just a tiny time sampling to see the complete list of members everything on the right hand column. I have a shortcut link to the documentation on each individual class. Check this out. When you have a chance, you'll see there's actually a lot going on with each of these individual rapper classes. Let's take a look at how the rapper classes affect the idea of comparing for equality. So we have some code. Here we have a variable I 1000 Who's Dave? His imager. We sign it 10 times, 10 times tense. We have the value 1000 stored into the energy. A rapper class, I say energy I 1000 b equals 100 times. 10 said it also has the value 1000 stored into it instance of the energy rapper class. If I compare them, using the equals equals operator now. These were too primitive. Variables equals. Equals would compare just fine. But because these are references to classes, this will actually test for false. Because remember, equals equals only returns. True, if both references point to the same exact object. So we're working with these rapper classes. We generally want to use the equals method to check for equality. So we say I 1008 dot equals I 1000 b we give back to value. True, because it actually checks the value stored inside each one. But let's look at another example. Have a variable I ate a which again is a reference of type Manager equals four times to. So has the value. Eight. In that energy rapper class, then have Manager I eight b equals two times two times two. So again it has a value eight stored inside of a manager rapper class. But now, when I do, I ate a equals equals I eight b. I get back true everything that can only return true if both there's references pointed the same exact object, and that turns out to be true, because in Java, certain boxing conversions are defined. Always return back at reference to the exact same instance, and there are five types. When that happens, you have an end, a short or a bite in the range of mines. 1 28 to positive 1 27 When that is converted into the corresponding rapper class, you will always get a reference to the same exact object for the same exact value. So what? Int a value five. When it's converted to an imager, it will always be a reference of the same exact imager. Instance. On the carrot type. It's any character value from the range of the character, zero all way up to the character 00 ff and for bullion. It's all its values because member boy only has two true or false. So any time you convert the bullion value true to the class Capital B 1,000,000,000 all the truth points the same object instance and all the false is will point to the same object. Instance. Oftentimes in our programs will have fields that we don't allow to be set once they've been initialized. That's where final fields come in Now there are two kinds of final fields. A simple final field must be set doing creation of an object. Instance that means must be set using either a field initialize er on initialization block were constructor. Let's look at some could that uses that. Remember, we have our pastor class, our pastor class. We had this idea that a pastor could be created with a number of free bags that they received. We set that, of course, inside of our constructor. Now we may define our business models. The fact that the number of free banks is considered an aspect of the passenger so it can only be set during the creation of that passenger. So we can do that by taking our free bags declaration and simply including the word final there. By including that word final. Any attempt to set free banks after it's been setting instructor will actually result in a compile air so compiler and forces that ruled that it can't be assigned once it's been set . Now there's also what's known as a static final field. Static final fields create basically named Constance Kostanic. Final field cannot be changed in any object. Instance, its value is actually tied to the class itself. So we look at that and code. Look at our flight class. Remember that our flight class has this concept of the number of seats on a flight. So an instance of our flight class can set the number of seats. So we simply have a center to do that. Well, let's say that the Federal Aviation Administration right, That's the organization United States that sets the rules for planes. Let's say that they set a rule that there is a maximum number of seats that a flight is allowed to have. Well said. That's 550 so we can declare a static final field called Max. Underscore. FAA underscore seats has a value of 5 50 Now the convention is that whenever you have a static final, use all caps for the name of the field, and what we can do here is down inside of our set seats. We can actually use that Max F a seat, just like it's a value. So inside of your So we make some room, we're gonna put a check in to say, Well, if seats is lessner equal to Max FAA seats we set it. Otherwise, we handle the error. The key here is that no Arctic instance can create this Max. FAA seats will have the value of 550 in all flight instances. We use this most commonly when we're trying to avoid what we often call magic numbers, where we don't like to put a literal numbers inside of our code. Because when we look at this code, we know that the reason we're checking the value of seats is that the FAA has a rule in the max. If we just dropped a 5 50 in there, that wouldn't necessarily make sense. Now we often have times where we want a limit a type two, a finite number of values. And that's where the enumeration types come in. The numerator in types allow us to define it. Typed A. Has a list of valid values. We declare there's using the in oum keyword. So it's going declaring in newme for the jobs that the flight crew is allowed to have. You know, as we use the word a new marriage, so the word class and then sign their weaken, simply provide a comma separated list of the valid values to say the flight crew jobs could be a pilot, a co pilot, a flight attendant or an air marshal. So now we can use flight crew job as a type. So it's so we introduce a new class here called Crew member. Crew members have a job of type flight crew job. So again set that as part of the constructor of Crew Member as well as we have a center to change the job of a crew member. So now we go off and create an instance of Crew member called Judy, one of our new crew members. We can give her a job, so we'll say she's a co pilot. So knows the way we do. This is we use the name of the enumeration 0.1 of values, so we've created you to be a copilot. Let's say some time goes by and Judy gets promotion. We can now make Judy the pilot swing. So we say, Judy, that set job again. We used the enumeration named Flight Crew job dot and the Value Pilot enumeration Zehr most commonly used in this way defying this finite list of values. But in new Marais, Shin types actually have a number of much more advanced capabilities beyond this that we'll talk about later in the course. This demo will enhance our count engine program to take advantage of the data type capabilities we've talked about throughout this module. What we'll do is add in some string processing capability so we can take a string like ad space 1.0 space 2.0 will calculate the answer and then write it back out in a more traditional format like 1.0 plus 2.0 equals 3.0. Here we are on account engine program, and it's basically just like it was when we left at the end of the last module. Just a few small changes. One thing I've done is all the code that was in our main method. I've moved into other methods, so that's kind of not in our way here. As we're writing our new coat. I actually have the code in place. They're called his methods, and I've just commented him out. We're going to focus on those right now. I don't think I've done is I've created a stringer Ray here that actually has four strings in it and the strings all have the operation. You want to perform in the syntax we want to use like his 1st 1 says, Divide 100.0 50.0 Where with each one of those separated by space then what we want The program to Dio is built up ransom in like 100.0 slash 50.0 equals 2.0 and do that for all four math operation. So they get started. The first anyone dio that's going added enumeration that contains values for each of the four operations we want to perform. Ah, good and creator enumeration just like I created class. Now the way most of the ideas let you do it is that when you want to create something is not a class, you could just say what you want to create. Someone didn't say a new I was gonna call my in oum math command. We'll create that and we want to put our four operations in here so operation is going to be add, subtract, multiply and divide. So we have our enumeration with each of the command values separated by a comma, and that's all we need to do with that for right now. That's good Now and was created class that will use to do the string processing for us. So we will do the work to process the string value and get us those results back. Is the other string format so going to create a new class again? We're going to call this one our calculate helper. So we have that create it. So inside of here, we're going to need are four fields basically will need one field toe hold. The command will declare it out of their math command. So our command fields of type math command now declare one for the left value and then we'll do the same thing for right value and results. So we have all the fields we need. Now let's go down to method will call process that will accept the input string and do the work to process the contents of that strength. So make it a public void method and only parameter is the string. That will be the statement that we receive. We have that they're now remember that we want to do is receive a string that looks something like this ad space 1.0 space 2.0. So we have two good and process each of those parts. Remember that we were looking at the methods that the string class offers. There was one called Split that handles this scenario of breaking a string up into its parts based on some separating character. So it's good and deal with that. We want to create a stringer, Rang called parts, and all we have to do here is set it equal to statement dot split And then we specify the separate in character, which is just that space split will return the values inside of statement based on the space separator, right? So the first value inside of there is going to be the command and command string is going to be set equal to the value of parts sub zero. And what we expect to find in there is the value, like at next one do is get the left value out of there. So it's going to put the left value right into our field cut left value and that values going to be in parts someone now. Parts of one, though, is the strings we want to get and convert that string into a double. So we'll use double dot parse double to convert that string into the primitive type double . So that would give us back to 1.0 as a double. Well, then, do the same thing for the right value from parts sub to. So what? That will have the value on the right hand side. Something like 2.0. All right, so now we have our command is a string and then the left eyes in the right value. Now we want to do is convert our command from being a string into our math command enumeration. Let's go ahead and create another method here. It will be a private method, and we'll call it Set command from string. And it's only primer will be the command string. So we have that there. I remember that Well, we want this guy to Dio is take that string value like add and convert that into our math command dot at. So we'll do now is we'll take our command String wanted a comparison with That's when, say, if it's a command string, I'm going to use equals ignore case. So now The question is, what do we compare that to? Because all we have is our enumeration. So let's take our enumeration value for ad. Remember that I mentioned that if you want to convert a type to a string, you can call this to string method. That's also true for enumeration. So I want to say dot to string. And what that will dio is it will actually take that's characters capital a D D. And convert them into the string a d. D. So we're actually taking our enumeration value and making it a strength. So if we get a match on that, what we can do is we can take our command member variable, which is of type math command and a sign at the value of math command out ad. Then we could do that same thing on an else if, but we'll do it for subtract this time. And if that matches wil