Java Tutorial for Beginners [2020]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hi! My name is Mosh and I'm gonna be your instructor in this Java course. In this course, you're gonna learn everything you need to get started programming in Java. We'll start off by installing all the necessary tools to build Java applications then you're gonna learn about the basics of Java you'll learn how Java code gets executed you'll learn how to build simple algorithms and throughout this course I'm gonna share with you lots of tips and shortcuts from my years of experience I'll teach you how to write good code like a professional developer so we'll end up watching this course you will have a solid foundation in Java and be ready to learn about advanced Java features I've designed this course for anyone who wants to learn Java if you're a beginner don't worry I'll make Java super simple and hold your hands through this entire course you're not too old or too young you'll write your first Java program in minutes my name is mosh I'm a software engineer with two decades of experience and I've taught over 3 million people how to code and how to become professional software engineers I have a coding school at code with mass comm where you can find plenty of courses that help you take her coding skills to the next level I hope you'll stick around and learn this beautiful and powerful programming language and now award from this video sponsor as someone who runs an online business I cannot stress enough the importance of staying safe online which is why I was so excited when dashlane reached out to me if you don't know - Lane is the password manager and VPN recommended by Apple and Google and it's a fantastic safeguard for keeping your information secure it's completely free to use for your first device so head over to - Ling comm / marché - give it a go if you want to upgrade to the premium to get VPN or dark web monitoring you can use the promo code mosh to get 10% off sign up for - 9 today and keep yourself safe online now back to the course in this java tutorial we're going to download and install the necessary tools to build java applications so open up your browser and search for jdk download jdk is short for Java development kit and it's basically a software development environment for building Java applications it has a compiler it has a bunch of code that we can reuse it has a Java Runtime environment at a bunch of other stuff so over here you can see this page on Oracle com Java se which is short for Java standard edition click on this now over here click on this icon now on this page we can see Java development kit for various platforms like Linux Mac OS and Windows here I'm on a Mac so I'm gonna download this dmg file over here now before we do this first we need to accept the license agreement all right now let's download the dmg let me open this we're gonna say this package let's double click this and here we see this installation wizard it's super easy just click continue and install you have to enter your computer's password and then alright done beautiful so we can move this to trash now the next piece of software we need is a code editor there are so many cool editors for building Java applications the popular ones are NetBeans Eclipse and IntelliJ in this Java course I'm gonna use IntelliJ but if you have a favorite editor feel free to use that to take this course that's perfectly fine so let's search for IntelliJ download all right you can see download IntelliJ IDEA click on this link over here download the community edition which is absolutely free and it's more than enough for this course so download all right now let's drag and drop this onto the Applications folder beautiful alright we've installed all the necessary tools to build Java applications so next we're gonna look at the anatomy of a Java program in this java tutorial we're gonna look at the anatomy of java programs the smallest building block in java programs are functions if function is a block of code that performs a task as a metaphor think of the buttons on the remote control of your TV each button performs a task functions in programming languages are exactly the same for example we can have a function for sending emails to people we can have a function for converting someone's weight in pounds to kilograms we can have a function for validating users input and so on now let's see how we can code a function in Java we start by specifying the return type of that function some functions return a value like a number at day time and so on other functions don't return anything so the return type of this functions is void void is a reserved keyword in Java and that's why I've coded that in blue here now after the return type we have the name of our function so here we should give our function a proper descriptive name like send email this name clearly identifies the purpose of this function okay now after the name we have a pair of parentheses and inside these parentheses we add the parameters for this function we use these parameters to pass values to our function for example our send email function should have parameters like who is the receiver what is the subject of this email what is the content of this email and so on now in this tutorial we're not gonna worry about parameters we'll look at them in the future now after the parentheses we had a pair of curly braces and inside these braces we write the actual Java code now one thing I want you to pay attention to here is that in Java we put the left brace on the same line where we define our function in other programming languages like C sharp it's more conventional to put the left brace on a new line but we don't do that in Java so we put the left brace on the same line where we define our function now every Java program should have at least one function and that function is called main so main is the entry point to our programs whenever we execute a Java program the main function gets called and the code inside this function gets executed okay now these functions don't exist on their own they should always belong to a class so a class is a container for one or more related functions basically we use these classes to organize our code just like how products are organized in a supermarket in a supermarket we have various sections like vegetables fruits cleaning products and so on each section contains related products by the same token a class in java contains related functions now every Java program should have at least one class that contains the main function can you guess the name of that class its main so this is how we define a class in Java we start with a class keyword then we give our class a proper descriptive name and then we add a pair of curly braces now the functions that we define in between these curly braces belong to this class and more accurately we refer to them as methods so a method is a function that is part of a class in some programming languages like Python we can have a function that exists outside of a class so we call it a function but when a function belongs to a class we refer to it as a method of that class okay now in Java all these classes and methods should have an access modifier an access modifier is a special keyword that determines if other classes and methods in this program can access these classes and methods we have various access modifiers like public private and so on now most of the time we use the public access modifier so we put that in front of our class and Method declarations so this is the basic structure of a Java program at a minimum we have a main class and inside this main class we have the main method now you might be curious why we have a capital m in the name of this class because in Java we use different conventions for naming our classes and our methods to name our classes we use the Pascal naming convention and that basically means the first letter of every word should be uppercase in contrast to name our methods we use the camel naming convention and that means the first letter of every word should be operate case except the first wart so that is why we have a capital m in the name of this class alright now that you understand the anatomy of a Java program let's create a new Java project and see all these building blocks in action in this Java tutorial you're gonna learn how to write and execute your first Java program so let's open IntelliJ IDEA here on the home screen let's create a new project alright on the left side select java and make sure project sdk is not black so earlier we downloaded jdk or Java development kit version 12 that is why JDK version 12 is selected here if you don't see that make sure to select it from this drop-down list alright now let's click on next on this page select create project from template so we're gonna create a command line application which is an application that we can run from the command line it doesn't have a graphical user interface or a GUI now I know command line application is not as exciting as an application with a graphical user interface like a mobile app or a desktop app but trust me building an application with a graphical user interface is very complicated so for now we're just gonna build command line applications to learn Java properly once you learn Java properly then you can learn about building desktop or mobile applications with Java all right now let's click on next on this page we have to give our project a name let's call it hello world now over here you can see the location of this project so it's inside the idea projects folder now right below that you can see the base package which is set to comm that code with Marsh on my machine and your mission is probably gonna be comm dot package what is this well here we talked about classes and methods I told you that a class is a container for related methods so we use classes to organize our code by the same token we have a concept called package and we use a package to group related classes so as our applications grow we're gonna end up with hundreds or even thousands of classes so we should properly organize this class us into packages now by convention the base package for a Java project is the domain name of your company in Reverse so my website is code with mass comm that is why I'm gonna set the base package for this project to come that code with Marsh now it doesn't mean that you should have an actual domain registered on an Internet this is just a way to create a namespace for our classes so now every class that we create in this project will belong to this package we're gonna talk about packages in more detail in the future so for now just type a base package for your project it can become that your name or whatever it doesn't really matter all right now let's go forward alright here's our first Java project now this code editor might look a little bit intimidating at first but trust me it's really easy and you're gonna learn about it throughout this course on the left side we have the project panel where we can see all the folders and files in a project for example on the top we have the hello word project inside this project we have the source folder where we have the source code of a project now in this folder we have another folder that is calm that code with Marsh that is the name of our base package and in this package we have this class main so you can see this main file opened on the right side here now look at the name of this file its main the Java so all Java files should have the Java extension okay now let's collapse the project panel by clicking on this icon that is better so see what we have here on top of this file we have the package statement and this is used to specify what package this class belongs to so the main class that we have here belongs to this package now this package statement is terminated by semicolon so in Java wherever we have a statement we should terminate that statement with a semicolon this is exactly like c-sharp or C++ now below this package statement we have our main class exactly like what you saw in the previous tutorial so we have public class main with a pair of curly braces inside this class we have our main method so it's a public method which may it's accessible from other parts of this program it's static we haven't talked about static metals yet we'll talk about them in the future for now just remember that the main method in your program should always be static the return top of this method is void which means this method is not gonna return a value and here in parentheses we have one parameter for this function we can use these parameters to pass values to our program again we'll look at this in the future now right after this parameters as you can see the left brace and this is where we write the code in this method now by default we have this line prefix with two slashes this indicates a comment we use these comments to explain our code to other people so these comments don't get executed now let's remove this comment and write a bit of code to print something on the terminal so here we're gonna use the system class in Java so capital S system here in this tooltip you can see the system class is defined in this package Java dot Lang or language also look at this icon on the left side this indicates a class now inside this class we have various members we can use the dot operator to see the members defined in the system class now the member that we're gonna access is out look at the icon of this member it's F which is short for field you're gonna talk about fields in the future when we talk about classes and object-oriented programming now what is interesting here is the type of this field and you can see that on the right side that is print string so print string is another class that is defined in Java so once again we use the dot operator to look at the methods or members defined in the print stream class the method we're gonna use is print Ln which is short for line look at the icon for this method so M indicates a method now you press ENTER and IntelliJ automatically adds these parentheses as well as a semicolon so now with the code on line six we're calling or executing the print line method earlier I told you that inside this parenthesis we can pass values to our methods here we want to print the hello word on the terminal so let's type double quotes and inside these quotes right hello world so hello word is textual data in Java whenever we deal with textual data we should always surround them with double quotes now we say we have his string so a string is a sequence of characters all right so we're done with our first program now to execute this we can click on this icon on the toolbar look at the shortcut on Mac it's ctrl + R I always prefer to use shortcuts because they're faster so ctrl + R now IntelliJ is building our application and we can see the result in this little terminal window so here's our hello work message so that was our first Java program next I'm going to explain how Java code gets executed under the hood hey Marsh here I just wanted to let you know that you really don't have to memorize anything in this course I've put together a comprehensive cheat sheet with summary notes that you can download below this video so I've done my best to create the best possible Java course and I would really appreciate it if you support me by liking and sharing this video on the social networks that you use often also be sure to subscribe and enable the notifications so next time I upload a video you'll get notified thank you so much and let's continue watching all right now let's see what exactly happens under the hood the moment we run a Java program in IntelliJ there are basically two steps involved here compilation and execution in the compilation step IntelliJ uses the Java compiler to compile our code into a different format called Java bytecode this Java compiler comes with the Java development kit that we downloaded at the beginning of the course let me show you so here we can right click on this main the Java and in this context menu we have an item called open in terminal it's down below unfortunately it's not visible in my recording window it's called open in terminal on Mac and probably open in command prompt on Windows so let's open that we get this terminal window or command prompt on windows here we're currently inside of this folder code with Maj that is where we have our main the Java file now we can invoke the Java compiler like this Java C and pass the name or Java file as an argument so main the Java if you're on Mac or Linux make sure to spell this with a capital M because these operating systems are case-sensitive so enter now let's look at the content of this folder on Mac or Linux we can type LS on windows we type dir so let's take a look in this folder now we have a new file main class this is the bytecode representation of this Java file now let me use IntelliJ to run our Java program this class file gets stored somewhere else let me show you so back to the project panel here in our project we have this source folder where we our source code and we have this out folder where we have the result of the compilation so inside this folder we have production inside this we have hello world the same name as our project inside hello world we have comm which is the name of our top level package inside this package we have a sub package that is code with Marsh and here we have our main dat class file so this was the compilation step now this Java bytecode that we have in this file is platform independent and that means it can run on Windows Mac Linux or any operating systems that has a Java runtime environment if you go to java.com slash download we can download java or more accurately java runtime environment for various operating systems this Java Runtime environment has a software component called Java Virtual Machine or JVM this JVM takes our Java bytecode and translates it to the native code for the underlying operating system so if you're on Windows machine this Java Virtual Machine converts or Java bytecode into the native code that windows can understand this architecture is the reason why Java applications are portable or platform independent we can write a Java program on a Windows machine and execute it on Linux Mac or any other operating systems that have a Java runtime environment c-sharp and python also have the same architecture that's why they are platform independent as well now let me show you how to invoke this java virtual machine to run a Java program so back to this terminal window let me expand this currently we are inside of this folder code with Marsh and in this folder we have this class file now let's go one level up so CD dot dot and one more time so now we are inside the source folder we can invoke Java Virtual Machine like this they type Java and then we type the full pass to our main class file what do I mean by that well earlier we defined this package comm that code with Marsh and this class the main class is part of this package so the full path this class is calm dot code with Marsh dot main make sure to use a capital M here because this is case sensitive now when we press ENTER Java will look at this folder calm inside this folder it will look at this other folder code with Marsh and then it will find main that class in that folder it will load the bytecode and convert it to the native code for the operating system we are using so take a look so it executed our program hello world beautiful let me run a program using IntelliJ all these steps are hidden from us we don't see the compilation or execution steps so you have seen Java in action now let me tell you five interesting facts about Java Java was developed by James Gosling in 1995 at Sun Microsystems which was later acquired by Oracle in 2010 it was originally called oke after an oak tree that stood outside Gosling's office later it was renamed to green and was finally renamed to Java inspired by Java coffee that's why its logo looks like this we have four editions of Java for building different kinds of applications we have Java standard edition this is the core Java platform which is what we're using in this course it contains all of the libraries that every Java developer must learn we have Java Enterprise Edition which is used for building very large-scale and distributed systems it's built on top of java standard edition and provides additional libraries for building fault tolerant distributed multi-tiered software we have java micro Edition which is a subset of Java standard edition designed for mobile devices so it has libraries specific to mobile devices and finally we have Java card which is used in smart cards the latest version of Java is Java standard edition 12 which was released just a few months ago in March 2019 Java has close to 9 million developers worldwide currently about 3 billion mobile phones run Java as well as 120 million TV sets and every blu-ray player according to indeed.com the average salary of a Java developer is just over $100,000 per year in the US so as we can see Java is everywhere which means more opportunities for you to get hired as a professional programmer now let me give you a quick overview of how I've structured this course so you can get the most out of it this course is the first part of my complete four-part Java series each part is about three to four hours long so it can easily complete it in a day or two in the first part which is what you're watching you're gonna learn the fundamentals of programming with Java in the next section you'll learn about the type system in Java you will learn how to work with various types such as purrs strings boolean's and arrays by the end of this section you will build a mortgage calculator as your first Java project will be improving this calculator bit by bit routers course next you will learn about control flow statements that are used to build algorithms we'll be talking about various types of conditional statements and loops later in this section we'll add data validation to our mortgage calculator to force the user to enter valid values at this point you'll be able to build basic algorithms and that's great but being a good programmer requires knowing how to write good code code that is clean and expressive that's what separates an outstanding programmer from an average programmer so in the following section we'll talk about clean coding I will show you various techniques that professional programmers use to make their code clean and maintainable and finally in the last section you will learn how to find and fix errors in your java programs as well as how to package them for deployment so others can use them so the materials in the first part will give you a solid foundation on how to start programming in Java in the second part we'll talk about object oriented programming which is a style of programming use in most if not all Java applications whether you want to use Java to build web mobile or desktop applications you need to understand object-oriented programming well because otherwise you're going to constantly hit obstacles in the third part we're going to talk about core Java API is or application programming interfaces you'll learn about many of the useful classes in the standard Java library and finally in the last part we'll be looking at the advanced features in Java such as streams threads database programming and so on so I hope you're gonna join me on this journey and master Java the most popular programming language behind millions of apps and websites you intersection we're gonna look at the fundamentals of programming in Java you're gonna learn about variables and constants primitive and reference types you're gonna learn about casting or type conversion you will learn how to work with numbers strings and arrays and how to read input from the user once you learn all this I'm gonna give you a project you're gonna build a mortgage calculator on your own so make sure to pay great attention to all the materials you're gonna learn because you're gonna use most of them in this project are you ready now let's jump in and get started in this tutorial we're gonna talk about variables in Java we use variables to temporarily store data in computer's memory here is an example imagine in this program you want to store someone's age in the memory so we declare a variable like this ant age equals 30 so int or integer is the type of this variable so in this variable we can only store integers which are whole numbers like 1 2 3 4 numbers that don't have a decimal point now in Java we have several different types I'm gonna talk about them in the next tutorial so first we specify the type of our variable then we give it a name or a label this is also called an identifier because we use it to identify our variable this equal sign is called the assignment operator and 30 is the initial value that we are assigning to this variable so we say on line 6 we're initializing this variable which means we're giving it an initial value you always have to initialize our variables before reading them so with this line we're storing number 30 somewhere in computer's memory and we're assigning this label to that memory location now on line 7 instead of printing hello world we can print the value of the age variable take a look so I'm gonna run this program using ctrl + R there you go now we see 30 on the terminal beautiful we can also change the value of our variable so after we initialize it per house we can change it to 35 now when we run this program again we see it 35 beautiful we can also initialize multiple variables on the same line but this is something that I don't recommend because it makes your code ugly and hard to read here is an example we can declare another variable like temperature and set it to 20 so using a comma we can declare multiple variables on the same line now even though this is technically possible it's not something that I recommend so it's always better to declare one variable on each line like this we can also copy the value of one variable into another here is an example let me delete these variables and declare a new variable called my age we set it to 30 and then we declare another variable like her age and we set it to my age so now when we print her age we're gonna see 30 take a look so on line seven recapping the value of this variable into this other variable now one thing I want you to pay attention to here is the convention I have used for naming our variables as I told you before this is called the camelcase notation so we should capitalize the first letter of every word except the first word so in this case the first word my it's all in lowercase but the second word starts with a capital letter so this is all about declaring and initializing variables in the next tutorial we're going to talk about various types in Java in this tutorial we're going to talk about various types in Java basically we have two categories of types we have primitive types for storing simple values and non primitive types or reference types for storing complex objects so in the category of primitive types we have white which takes one byte of memory and in one bite we can store values from 128 to 127 now the more bytes we have the larger numbers we can store so next we have short which takes two bytes and with this we can store values up to 32,000 next we have integer which we have seen before integers take four bytes of memory and allow us to store values up to two billion then we have long which takes eight bytes and with this we can store even larger numbers now all these types are for storing whole numbers that don't have a decimal point if you want to store a number that has a decimal point you have to use float or double float takes four bytes double takes eight bytes so obviously we double we can store larger numbers next we have char for storing a single character like ABC and this chart I've take two bytes so they support international letters and finally we have boolean for storing boolean values which can be true or false just like yes or no in English now let's take a look at a few examples earlier we use an integer for storing someone's age but as you learned integers take four bytes and allow us to store values up to two billion we don't need four bytes of memory to store someone's age all we need is one byte because with one bite we can store values up to 127 so I'm gonna change this to byte that is better now let's look at another example let's say we want to store the number of times a YouTube video has been watched so we define an integer called views count note that I'm always using meaningful names for my variables because these names help us understand what this code does I've seen some people use variable names like V or V 1 or n nobody knows what these variables do so as a best practice always use meaningful and descriptive names for your variables so views count we set this to a large number like 1 2 3 4 5 6 7 8 9 now in Java whenever you deal with a large number like this you can use an underscore to separate every three digits just like how we use a comma in our documents to make our numbers more readable we can use an underscore in Java so with integers we can store values up to two billion but let's say the number of times this video has been watched is three billion so I had a three here now we have a red on the line that indicates an error let me hover our mouse over it we see this tooltip integer number too large so we need to change the type of this variable to long however the error is still there what's going on here the reason we're getting this error is that by default Java sees these numbers as integers so even though we have defined the type of this variable as long Java compiler sees this value as an integer and he thinks this value is too large for an integer to solve this problem we need to add an L as a suffix or this number we can use an uppercase or a lowercase L but as you can see a lowercase L kind of looks like a 1 so it's better to use a capital L so these are examples of whole numbers now let's declare a variable for storing a number with a decimal point so double price we set this to 1099 obviously the double variable is too large for storing the price of a product so we can change this to float that is better but you have a compilation error here take a look incompatible types required float but found double the reason we're seeing this error is that by default Java sees these numbers with a decimal point as double so even though we set the type of this variable to float Java sees this number as a double so just like how we added a suffix to this number to represent it as a long we need to add a suffix here to represent this number as a float and that suffix is F once again we can use an upper case or lower case F so these are examples of numbers now let's store a character so char we call it letter and we set it to a note that we should always surround single characters with single quotes and multiple characters or strings with double quotes okay so char represents only one character string represents a series of characters and finally let's see an example of a boolean so we define a boolean variable called is eligible is this person eligible for loan or not we said this to true or false these are the boolean values now note that all these words coded in orange are reserved keywords in Java just like public static void class package these are all reserved keywords so we cannot use these reserved keywords the name our variables classes and methods in the last tutorial you learned that we use primitive types to store simple values like numbers boolean values or single characters in contrast use reference types to store complex objects like data objects or mail messages these are complex objects now in Java we have eight primitive types that you have seen before all the other types are reference types let me show you an example so here in this program first I'm gonna declare a primitive type let's say white age equals 30 now declaring and initializing a reference type is slightly different from primitive type let me show you so let's type date now here in this tooltip box which is called intellisense we can see various classes that have date in their name so IntelliJ is helping us complete our code by suggesting these class names now here we have a date class in this package Java the util so this package contains a lot of utility classes that are useful in a lot of programs you also have a date class in a different package Java SQL or sequel which is used for programming databases so this is the benefit of packages we can have the same class but in different packages they don't conflict so packages create a namespace for our classes okay now in this case if we select the first date class and press enter or tab IntelliJ automatically adds this line for us import Java that you till the date so because currently we are in this package in order to use a class from a different package we need to import it so here we're importing the date class in this package will talk about packages in more detail in the future so back to our date variable let's give this variable a name collect now now we set this here we need to use the new operator to allocate memory for this variable and this is one of the differences between the primitive and reference types when declaring primitive types we don't need to allocate memory memory is allocated and released by Java Runtime environment but when dealing with reference types we should always allocate memory now we don't have to release this memory Java Runtime environment will automatically take care of that so we use the new operator and then repeat the name of our class in this case date and then we add parentheses followed by a semicolon in this example this variable we have defined here is an instance of the date class so this class is defined template or blueprints for creating new objects new instances as another example we can have a class called human and we can have objects like John Bob Mary and so on so an object is an instance of a class now this object or this class have members that we can access using the dot operator so we can type now dot and these are all the members defined in this class or in this object for example we have a method called get time and this returns the time component of this object this is another difference between primitive types and reference types these primitive types don't have members so if you type age dot we don't see anything these items you see here are not members of age their code snippets which allow us to quickly generate code for example we can select for I and this automatically generates this block of code for us we'll talk about this in the future so this age variable is a primitive type it's not an object it doesn't have any members and that's why when we use the dot operator we don't see anything here now let's delete this line and instead print the value of this data object so once again we can type system this is a class so we can use the dot operator to access its members here we have out which is a field and the type of this field is print string which is another class in Java so once again we can use a dot operator and call the print line function now let me show you a very cool shortcut instead of typing all this we can use one of these code snippets so we type s oh you see and press tab and this generates this piece of code for us all right now let's pass our data object here note that I have not surrounded this variable with double quotes because this is a string and if you run this program we'll see now on the terminal there you go we don't want this you want the value of our data object not a label so let's remove the quotes I run the program again so here's the current date I'm on my machine I've learned a little bit about the differences between the primitive and reference types so you know that we use primitive types for storing simple values and reference types for storing complex objects but there's a very important difference between these two categories of types in terms of memory management and that's what we're going to talk about in this tutorial so I'm going to declare a primitive variable X and set it to 1 and then I'm going to declare another variable like Y and set it to X so in this example we have two different variables x and y and these two variables are at different memory locations so they're completely independent of each other in other words if I change the value of X Y is not going to get affected let me show you so I'm gonna update X to 2 and then print Y so syu t tab y let's take a look so run as you can see Y is not affected because x and y are completely independent of each other however when we use a reference time this behavior is different let's take a look so I'm gonna delete all the code here in Java we have a point class that is defined in this package Java that awt so we press ENTER and now we have this import statement on the top beautiful let's declare a variable like point 1 and set it to new point here we can pass the initial values for x and y so I'm gonna pass 1 and 1 so intelligent automatically adds these labels x and y now just like before I'm gonna declare another variable point 2 and set it to point 1 and this is where things get interesting when Java Runtime environment executes line 8 first it's going to allocate some memory to store this point object let's see if the address of that memory location is 100 then it's going to allocate a separate part of the memory and it's going to attach this label to that memory location point 1 in that memory location it's going to store the address of our point object so this is the critical difference between primitive and reference types when we declare a primitive variable like a byte the value that we assigned to that variable will be stored in that memory location but when we use a reference type like this point class our variable is going to hold the ax of that point object in memory not the actual pointer object now look at line 9 here we're copying the value that we have in this variable into this other variable so that value as you learn is not the point object is the address or the reference to the point object in memory that is why we refer to these tiles as reference types because they don't store the actual values they store a reference to an object somewhere in the memory so in this example point one and point two are referencing the exact same point object in memory we only have one point object so these two variables are not independent of each other they're referencing the same object and that means if I update this point object through either of these variables the changes will be visible to the other variable I'm gonna show you so using the first variable point one we're going to update the value of x so we use the dot operator and here we can see the members of this object X on Y are both fields which are variables that exist inside of a class so we said X just like a regular variable to a different value let's say two now because point one and point two are referencing the exact same object if we print point two we're going to see the change that we just made take a look so S or ut tab let's print point to run the program there you go so the change was visible so remember this reference types are copied by the references whereas primitive types are copied by their value and these values are completely independent of each other in this tutorial we're gonna look at strings in Java so earlier in the course we printed the hello world message on a terminal this hello word that we have here is a string or more accurately it's a string literal that means a string value now let's extract this from here and store it in a string variable so cut just before this line we type string now look this string class is defined in Java that Lang package what is interesting is that we don't have an import statement to import this package or import this class because this package is automatically imported so we can use any classes that are defined in this package now let's declare a variable called message and because this is a reference type we should instantiate this variable using the new operator so Neal string and here in parenthesis we type our message hello world however here we have this little warning take a look new string is redundant because in Java there is a shorter way to initialize string variables let me show you so instead of using the new operator we simply set this to our string literal now on the surface this looks like a primitive type because we are not using the new operator but this is just a shorthand to initialize a string variable strings are reference types in Java but because we use them often there is a short way to create them so now let's pass message to the print line method and run our program you get the exact same result as before beautiful now let's look at a few interesting things that you can do with strings we can concatenate or joining a string with another one using the plus operator so here we can combine this with another string with two exclamation marks and here's the result now because string is a class it has members that we can access using the dot operator so we can type message dot and these are all the methods or functions do find in the string class for example we have this method here ends with and with this we can check to see if our string ends with a character or sequence of characters for example here we can pass their string to see if our message ends with two exclamation marks now instead of printing the message let's print this expression here so let's run the program we get true so this method that we have called here returns a boolean value which can be true or false we also have another method starts with let's take a look now in this case we get false because our message doesn't start with two exclamation marks another useful method is length so we can call that to get the length of a string which is the number of characters so message dot length take a look so in this string we have 13 characters and this is useful in situations where you want to check the length of the input by the user for example you might have a sign-up form with a username field you can check the length of someone's username and give them an error if the username is longer than let's say 20 characters pretty useful we also have another method that is index of and this returns the index of the first occurrence of the character or the string that we pass here for example if you pass H the index of H is 0 so let's run the program there you go we get 0 if you pass e we get 1 because the index of the first II in this message is 1 now what if you pass a character or a string that doesn't exist in this message let's say Skye we get negative 1 so with this method we can check to see if a string contains certain characters or words or sentences and so on another useful method is replace and with this we can replace one or more characters with something else for example we can replace any exclamation marks with let's say a store so this replace metal has two parameters one is target the other is replacement and here we're passing two values for these parameters here's the first value here is the second value and we have separated these values using a comma now in programming terms we refer to this values as arguments a lot of programmers don't know the difference between parameters and arguments parameters are the holes that we define in our methods arguments are the actual values that we pass to these methods so in this case target and replacement or parameters but exclamation mark and asterisk are arguments now let's run this program and see what happens so our explanation marks are replaced with stars now what is important here is that this method does not modify our original string it returns a new string so if we print our original string right after SRU T tab message you can see the original string is not changed because in Java strings are immutable we cannot mutate them we cannot change them so any methods that modify a string will always return a new string object okay we also have another useful method to lowercase let's take a look so to lowercase converts all characters to lowercase and once again you can see that the original string is not affected because this method returns a new string okay we also have two uppercase and another useful method is trim trim and with this we can get rid of extra white spaces that can be at the beginning or the end of a string sometimes our users type unnecessary spaces in form fields so using the trim method we can get rid of these white spaces let me show you so I'm gonna add a couple of spaces before and after our message now when we trim it these white spaces are gonna get removed take a look so here's the original string you can see two white spaces at the beginning and here's our string after trimming so these are some useful methods in the string class but this glass has more methods than we don't have time to cover in this lecture but as we go through the course you're gonna learn more about the string class and other useful classes in Java third times will include special characters in our strings like a tab or a new line or a backslash or double quotes so in this tutorial I'm gonna show you how to include these special characters in your strings so here we have the string hello Marsh let's say we want to surround Marsh with double quotes now here's the problem if we add a double quote here Java compiler thinks this is the termination of our string so it doesn't stand what we have after that's why we have a compilation error the fixes problem we need to prefix this double code with a backslash so using this backslash we have escaped the double quote now one more time let's add backslash double code here now let's run the program and see what we get so we get hello Marsh in double quote beautiful so double quote is one of those special characters that you need to be aware of another special character is backslash let's say we want to store the pass to a directory on a Windows machine so that will look like this C Drive backslash windows backslash whatever now if you want to store this in a string we need to escape each backslash let me show you so C Drive backslash now we have a problem Java compiler thinks we're escaping the double code here so it thinks our string is not terminated with another double code but that's not what we want you want to add a backslash here so we need to prefix our backslash with another backslash now we type windows one more time something let's run the program so even though we have two backslashes in our code we actually see one backslash in a terminal window in other escape sequences backslash N and we use that to add a new line to our strings so let's change this to backslash N and run the program to see what happens now our string is broken down onto multiple lines by the first line we have C Drive then we have Windows so wherever we had a backslash n Java will insert a new line we can also add a tab in our strings so if you add backslash T here there will be a tab which means C Drive and windows let's take a look so C Drive here we have a tab and then windows now in Java we have a few more escape sequences but quite honestly they're hardly used so remember these four escape sequences that we cover in this tutorial in this tutorial we're going to talk about arrays in Java we use arrays to store a list of items like a list of numbers or a list of people or a list of messages let me show you so here we have an integer variable you want to convert this to an integer array so right after int we add square brackets now we have a compilation error because we're storing a single number in this array so to fix this we need to remove one because arrays are reference types we need to use the new operator here then we repeat the type one more time enter a and here in square brackets we specify the size or the length of this array how many items do we want to include in this array let's say five also we should change the name of this variable from number two numbers because we're dealing with a list of items so always pay attention to the name of your variables now you can access individual items in this array using an index so we type numbers square brackets to reference the first element or first item we use zero now we can set this to a value like 1 similarly we can set the second item to 2 now what if we use an invalid index let's say 10 this array doesn't have 10 items so let's see what happens numbers of 10 we said this to 3 when we run this program we get an exception exceptions are Javas way to report errors so in this case an exception was raised and our program crashed we'll talk about exceptions in detail later in the course so now let's remove the last line and treinta sorry so sou t tab numbers let's see what we get we get this weird string in sort of the items in our array here's the reason by default when we print an array Java returns the string which is calculated based on the address of this object in memory so if you have another array and we print that we're gonna see something different because each object is gonna be in a different memory space okay now how can we see the actual items in this array well we have a class in Java called arrays let me show you arrays so this class is defined in Java that util package let's press ENTER now this is important on the top beautiful so we can use the dot operator to access the members of this class here we have a method called two string now as you see it this method is implemented multiple times so in the first implementation this method gets a float array in the second implementation it takes an integer array and so on so for all primitive types as well as reference types this method is implemented multiple times this is what we call method overloading now we can call this method and pass our integer array and this will return the string representation of this array so we can cut this from here and pass it to our print method like this now let's run the program one more time and here's our array beautiful so the first two items are initialized the others are set to 0 by default because here we're dealing with an integer array if you had a boolean array all items why default get initialized to false if you have a string array all items get initialized to an empty string okay now this syntax for creating and initializing an array is a little bit tedious and it's an older syntax there is a newer way to initialize an array if we know the items ahead of time like in this case so I'm going to remove these two lines I'm also gonna remove the new operator here we use curly braces and inside these braces we add all the items in this array let's say 2 3 5 1 & 4 now we have 5 items so the length of this array is gonna be 5 we can read that using the lengths so if we type numbers dot look here we have is filled look at the icon it's an F so this is a field which is like a variable in a class and the type of this field is an integer so this returns the number of items in this array let's get that and printed using our print method like this take a look so we get five now in Java arrays have a fixed size so once we create them we cannot add or remove additional items to them they have a fixed length if you want to be able to add or remove additional items from an array you should use one of the collection classes that we'll talk about later in the course for now all I want you to remember is that arrays have a fixed length now currently our array is not sorted these numbers are in some kind of random order we can easily sort this array using the sort method of the arrays class let me show you so I'm gonna remove this line and call arrays dot sort once again you can see this method is overloaded because it's implemented with different parameter types so we call this method and pass our numbers array now when we run this program we can see our array is sorted beautiful so yeah I've learned that we use arrays to store a list of objects in Java we can also create multi-dimensional arrays for example we can create a two-dimensional array to store a matrix or we can create a three-dimensional array to store data for cube these are useful in scientific computations let me show you so here we have a single dimensional array to convert this to a two-dimensional array we need to add another pair of square brackets now we have a compilation error because we need to repeat these brackets on the other side so let's say we want to create a 2 by 3 matrix so 2 rows and 3 columns we add in other brackets here and change these lengths to 2 and 3 so now we have 2 rows and 3 columns now to access individual items in this array we need to supply two indexes first the index of the row so we can go to the first row and then the first column and initialize that to 1 now let us print this so and so you t-tap once again we use our arrays class dot to string and pass this object take a look once again we get this weird string because here we're dealing with a multi-dimensional array to solve this problem we need to use another method in this class called deep to string use this for printing multi-dimensional arrays take a look now we have this matrix which has two rows and in each row we have three columns we can also create a three dimensional array all we have to do is to add another pair of brackets and specify the length of that dimension pretty easy now what about the curly brace syntax let me show you so let's revert this back to a two dimensional array we're gonna get rid of the new operator and use curly braces now let's say in this matrix we're gonna have two rows and three columns so each row is an array itself because it's a list of items right so we add another array here let's say 1 2 3 then comma now we add the second row which is another array in this row we're gonna have 3 numbers 4 5 & 6 now let's remove this line we don't need it anymore and print this array so here's the end result you have learned a lot about variables ya learned that when declaring them we need to initialize them and we can always change their value later on throughout the lifetime of our programs however there are times that we don't want the value of a variable to change for example let's declare a variable called pi and set it to 3.14 now here we need to add an F to represent this as a float because by default Java compiler sees this number as a decimal okay now you know that we use pi to calculate the area of a circle what if before we calculate the area of a circle I come here and type pi equals 1 then all our calculations are gonna get messed up we don't want this to happen that's when we use constants so if we type final here Java compiler will treat this as a constant so once we initialize this we cannot change its value later on you can see here we have a compilation error and it says cannot assign a value to final variable pi so pi is a final variable or a constant now by convention we use all capital letters to name constants so this should be PI beautiful now I tell you a little side story in one of my early courses that I created years ago that was c-sharp basics for beginners there I used the same example to teach the concept of constants but I pronounce this word as P instead of Pi and believe it or not to this day people make fun of me for saying P instead of Pi but that's how we learned this back in Iran we pronounce it as P and I think Greek people also say P but anyway I just thought to share this video to change the mood now you're done with constants next we're gonna talk about arithmetic expressions in this tutorial we're going to talk about arithmetic expressions in Java so in Java we have the same arithmetic operators that we have in math we have addition subtraction multiplication division and modulus which is the remainder of a division let's look at a few examples so I'm gonna declare an integer called result and here we can type 10 plus 3 now when we print result it's gonna be 13 pretty straightforward there you go so this is addition we also have subtraction multiplication division is an interesting one let's take a look so here the result is a whole number because in Java the division of two whole numbers is a whole number if you want to get a floating-point number here you need to convert these numbers to a float or a double let me show you so we prefix this number with parentheses and in parentheses we type double now we are casting or converting this number to a double similarly we should do that here and now we have a compilation error because on the left side we declared an integer but here the result of this expression is a double and by the way an expression is a piece of code that produces a value so what we have here is an expression because it produces a value so to fix this problem we need to change this to double now when we run this program we get this floating point number beautiful so these are the arithmetic operators and these numbers that we have here are called operands we also have increment and decrement operators let me show you so I'm gonna declare a new variable int X we set it to 1 now if you want to increase the value of x by 1 we use the increment operator now let's print this on a terminal so we get 2 there you go we can apply this operator as a postfix or as a prefix and we get the same result take a look too however if we use this on the right side of an assignment operator we get different results let me show you so I'm gonna declare another variable Y we set it to X plus plus in this case because we have applied the increment operator as a postfix first the value of x will get copied to Y so Y would be 1 and then X will be incremented by 1 so if you print x and y x is gonna be 2 and Y is gonna be 1 take a look so X is 2 and Y is 1 beautiful however if you apply this as a prefix first X will be incremented by 1 so it will be 2 and then it will be copied to Y so in this case both X&Y will be to take a look so we get two and two now what if you want to increment X by more than one let's say by two well there are two ways to do this let's remove Y we don't really need it anymore we can write x equals x plus 2 so first we add 2 to X the result will be three and then three will be copied into X the other way is to use the Augmented or compound assignment operator so we can write X plus equals two what we have on line eight is exactly identical to what we have on line seven well as you can see it's shorter so this is a better way to write the same code now this is one of the Augmented assignment operators we have the Augmented assignment operator for other arithmetic operators so we can type X minus equals 2 and this would reduce the value of x by 2 we also have multiply and divide so these are the Augmented or compound assignment operators right now I've got a question for you here we have declared this variable X it goes to 10 plus 3 times 2 what do you think is the result of this expression the result is 16 let's run this program and find out so run there you go we got 16 but why well this is a very basic math concept that unfortunately a lot of people don't know in math the multiplication and division operators have a higher priority so they get applied first in this example this expression 3 times 2 is evaluated first the result is 6 and then 6 is added to 10 that's why we get 16 now if you want to change the order of these operators you can always use parentheses for example if you want this expression to be evaluated first we wrap it in parentheses so like this now Java compiler will first evaluate this expression the result will be 13 and then 13 is multiplied by 2 so we get 26 take a look there you go so be aware of the order of these operations parentheses always have the highest priority then we have multiplication and division and finally we have addition and subtraction in this tutorial we're going to talk about casting and type conversion so I'm gonna declare a short variable call X and set it to 1 and then I'm gonna declare an integer called Y and set it to X plus 2 in this example we're adding a short to an integer what do you think the result is gonna be well let's take a look so sou t let's print Y we get 3 that is what you were expecting but let me explain what happens under the hood for this expression to get executed because we're dealing with two different types of values one is a short the other is an integer one of these values should be converted to the other type so they are equal now I got a question for you how many bytes do we have in a short variable we have 2 bytes how many bytes do we have in an integer 4 bytes so any values that we store in a short variable can also be stored in an integer variable right so when this piece of code is gonna get executed this is what's gonna happen first Java looks at the value in this variable it's 1 right it's going to allocate another variable an anonymous variable somewhere in memory we don't know where that is we don't know the name of that variable it doesn't have a name it's anonymous that variable is gonna be an integer then Java is gonna copy the value of x into that memory space and then it will add these two numbers together this is what we call implicit casting let me type it here implicit casting that means automatic casting or automatic conversion we don't have to worry about it whenever we have a value and that value can be converted to a data type that is bigger casting or conversion happens implicitly or automatically so byte can be automatically converted to short and this can be converted to int and long okay now what about floating-point numbers let's look at an example I'm gonna change this to a double one point one now here we have a compilation error because on the right side of the assignment operator we have a floating-point number a double on the left side we have an integer so we need to change this to double now when we execute this code we're gonna get 3.1 let's verify this there you go now let's see how casting happens here in this case we're dealing with a double and an integer an integer is less precise than a double because in a double we can have digits after the decimal point so in this example Java is going to automatically cast this integer to a double so that will be two point zero and then two point zero will be added to one point one okay so back to this chain here we're gonna have float and then double so as a general rule of thumb implicit casting happens whenever you're not gonna lose data there is no chance for data loss now what if you want Y to be an integer so in this example we don't care about the digits after the decimal point you want to see three on the terminal how should we do this this is where we should explicitly cast the result so we should cast X to an integer like this parentheses int this is explicit casting we convert X to an integer so the result would be one without a decimal point one will be added to 2 and Y would be three take a look there you go so this is all about implicit and explicit casting now this explicit casting can only happen between compatible types so all these types are compatible because they're all numbers but we cannot cast a string to a number in other words if X was a string like this let's say 1 we cannot cast eggs to an integer because they are not compatible so how do we do this well for all these primitive types you have learned you have wrapper classes so in Java we have a class which is a reference type called integer this class is defined in Java the Lang package and in this class we have a method called parse int so this method takes a string and returns an integer so integer is the wrapper class for the int primitive type we also have short and in this class we have parse short so it takes a string and returns a short similarly we have float and double and obviously the name of these metas are different so here we have parse float so back to this example let's say we get X as a string and we want to convert it to an integer this is how we do it integer dot parse int we pass X here and then add it to take a look so we get 3 you might be curious why this matters why should we parse or convert a string to a number to add it to something else well pretty much in most frameworks for building user interfaces whether you're building a desktop or a mobile application or web application we always receive input from the user as a string so if you have a form with a bunch of text boxes or drop-down lists almost always we get values as a strings so that's why we need to convert these strings to their numeric representation ok now what if X is a floating-point number here what will happen when we try to parse this as an integer let's take a look once again we get an exception which is how Java reports errors to our programs we're going to talk about exceptions in detail in the future so if the user enters one point one we cannot use this method instead we should use float or double let's say double because that's easier double parse double so we parse this number as a double add two to it and then store the result in a double and then we will get 3.1 beautiful next we're gonna look at the math class for performing mathematical operations in this tutorial we're going to look at the math class for performing mathematical operations so in Java we have this math class that is defined in Java that Lang package so it's always there we don't need to explicitly import it now this class has a number of useful methods the first method I'm gonna show you is the round method and with this we can round a floating-point number to a whole number so as you can see this method is overloaded which means it's implemented twice in the first implementation it takes a float and returns an int and a second implementation it takes a double and returns a log so let's pass 1.1 as a float to this method and store the result in an integer like this now we print the result and we get one beautiful another useful method is seal or sealing which returns the smallest integer that is greater than or equal to this number so the ceiling of 1.1 is 2 now here we have a compilation error because this method returns a double but we're storing the result in an integer so here we need to explicitly cast this to an integer and now you can see the ceiling of this number is 2 we have another useful method that is floor so the floor of a number is the largest integer that is smaller or equal to this number in this case it's gonna be 1 let's take a look there you go another useful method is max which returns the greater of two values and once again this method is overloaded so in the first implementation we get two integers we have other implementations for longs floats and doubles so let's pass two integers here one and two this will return the greater number which is 2 there you go similar to this we have min is pretty straightforward in the useful method is random for generating a random value between 0 and 1 once again we get a compilation error because this method returns a double so let's change that to double now every time we run this program we get a different number and this number is a floating-point number between 0 to 1 now what if you want a number between 0 to let's say 100 instead of 0 to 1 well we simply multiply this by 100 take a look so every time we run this we get a different number between 0 to 100 now if we don't want these digits after the decimal point we can either round this number or cast it to an integer let me show you so we can call math that round and pass the result of this expression so I'm gonna cut this add parenthesis to call the round method and then paste that expression now let's run this code so every time we get a double we still have the fraction here so we can change the type to an INT now we have a compilation error because the round method returns a long but here we have declared an integer this is one of those cases where implicit casting cannot happen because we have a value that is represented in 8 bytes of memory and you want to store that in a variable that has only 4 bytes of memory so implicit casting doesn't work but we can use explicit casting because we know the result of this expression is a number between 0 to 100 so we can definitely store it in an integer so let's add int here now let's run this again there you go now what if we don't use the round method here let's see what happens so I'm gonna remove the call to the round method and simply I apply this casting over here let's see what we get now every time we run this program we get 0 do you know why because here we're applying this casting to the result of this method call not this entire expression as you saw earlier every time we call the random method it generates a number between 0 to one so when we cast that number to an integer we'll lose the fraction we always get zero and zero times 100 is zero to solve this problem we need to wrap this entire expression in parenthesis so we add parentheses around this and now let me run this we get an integer between 0 and 100 quite often when we worked with numbers we need to format them as currency values for example we might have a number like this imagine this is the price of a product to display this to the user you want to add a dollar sign here and separate every three digits with a comma or if you might have a number like 0.1 and we want to represent this as a percentage value so instead of 0.1 you want to display 10% so in this tutorial I'm gonna show you how to format numbers in Java we have this class number format that is defined in Java the text package in this package we have a lot of classes for handling text dates numbers and so on so let's press ENTER here it's important on the top beautiful now I want to declare a variable so let's give this variable a name currency now we need to instantiate this new number format however we get a compilation error here let's take a look number format is abstract it cannot be instantiated so in Java we have this concept of abstract classes so some classes are abstract and they're basically like a half-baked cake we cannot use the new operator to create an instance of them we're going to talk about abstract classes and why they exist later in the course for now remember that we cannot create an instance of the number format class because it's abstract so there is another way let me show you this class has a bunch of methods that start with get so we have get currency instance and when we call this method this will create an instance of the number format class and return it so instead of using the new operator we're gonna use this method here this is what we call a factory method because it's like a factory it creates new are jects now look at the return type of this method it's a number format object okay so we call this method now we get the return value and store it in a variable of type number format called currency okay let me say improperly zoom out so you can see all the code there you go so on the right side of the assignment operator we're calling the get currency instance method we get the result which is a number from an object and store it in this variable okay now I'm gonna zoom in so you can see clear a name alright that's better now this object has a method for formatting values once again you can see this method is overloaded we have multiple implementations we can give it a long or a double or whatever so I'm gonna call this method and pass a value like one two three four five six seven point eight nine one so we have three digits after decimal and a few other digits here now this method will return a string representation of this number formatted as a currency so let's get that and store it in a string variable like result and then we're gonna print result on a terminal see what we get so we get this dollar sign every three digits are separated using a comma and we only have two digits after the decimal point so this class is very handy in formatting numbers as currencies we have another method for formatting a number as a percent and that is get percent instance right now it returns an instance of the number format class specialized for formatting numbers as a percent so we need to rename this variable from currency to percent now we don't want to manually change this because there are multiple references to this variable this other reference was not updated so let me show you the proper way to rename objects in intellij if you right click here you can see this refactor menu and here we have rename now look at this shortcut on the right side unfortunately it's not visible in my recording window but on Mac is Shift + F I always use shortcuts because they're faster so let's press shift and f6 now we get this red box and below this we can see a few suggestions for a better name we can choose one of these or pick our own name I'm gonna change this to percent and note that as I'm typing this the other reference gets updated automatically so this is very helpful now let's press Enter okay we're done with renaming now let's pass a different value here so let's say we have a number like 0.1 we want to format this as a percent let's run the program there you go you get 10% beautiful now let me show you a cool technique in this program we don't really need this percent object because we have used it in a single place it would make sense to have this as a separate variable if you have multiple references to it so what can we do here we can completely get rid of this object so let's delete this piece of code we're basically calling this method of the number format class as you know this method returns a number format object so right after calling this method and before the semicolon we can use the dot operator to access the methods or members of the number format object so here we call the format method straight away and pass our value this is what we call method chaining we're chaining multiple methods together so here's one method and here's another method now this returns a string so we can store it in this result variable let me cut this expression from here and put it over here now we have double semicolons I'm going to delete one of them all right beautiful in this tutorial I'm gonna show you how to read input from the user in Java we have this scanner class that is defined in Java did util package let's import this and create a scanner object so new scanner now here inside this parenthesis we need to specify where we're gonna read data from we're gonna read it from the terminal window are we gonna read it from a file or what to work with the terminal window we type system dot in this is one of the fields in the system class a fill as I told you before is like a variable that we define in a class so we have system that in we also have system that out which we used to print something on the terminal right now let's use system that in and terminate this statement with a semicolon now this object has a bunch of methods for reading data and all these methods start with next so we have next byte for reading a byte we have next line for reading a line we have next boolean for ending a boolean and so on so let's call the next byte method and see what we get this returns a byte value so we can store it in a byte variable let's say someone's age and then we print it on a terminal saying you are plus h so here we're concatenating a string with a byte and in this scenario we're gonna have implicit casting or implicit type conversion so Java will automatically convert this byte variable here tray string so they can be added together okay now let's run this program and see what happens so here in the terminal window we can type 20 enter and it says your 20 beautiful but this is pretty boring let's add a label here and ask the user to type something for example before reading data we're gonna call the print line method and say age : now let's run the program so we get this label here however whatever we type will appear on the next line this is because the print line method adds a new line after this label the Soviets issue recall the print method now let's run the program one more time we get this popup box because our program hasn't finished execution so we need to tell IntelliJ that you want to stop and rerun this program all right now whatever we type appears right in front of this label beautiful ENTER we are 20 now what if we type a floating-point number like 20 point 1 we get an exception because this method can only parse white values if you want to get a floating-point number we need to call next float or next double what if you want to read our string we don't have next string we have next and next line let's look at the differences so first I'm going to call the next method here we have a compilation issue because this method returns a string I'm gonna change this to a string let me collapse this that's better we should also rename this variable so what was the shortcut Shift + f6 now let's train just a name enter beautiful and one last time we should also update the label name run the program so I'm gonna type my name here Marsh it says your Amash pretty under for one more time this time I'm gonna type my full-name maha Madani but we don't get the last name here's the reason these wars that we have here these are called tokens every time we call the next method it reads one token so here we have a space we have two tokens and we need to call the next method two times to get the full name the first time we call it it returns Marsh the second time we call it it returns Hamid ani then we need to combine this suit together this is not ideal so that's when we use the next line method with this method we get the in turn line that the user enters no matter how many spaces or tabs are there take a look so Marsh comma Donny and we get the full name now what if I type a few spaces before my name let's see what happens so those spaces also appear here and this looks a little bit odd this is where we use the trim method remember we trim we can get rid of all these white spaces before or after a string so this next line method returns a string that we are storing in this variable right now just before storing the result in this variable here we can use the dot operator to access the members of this string object so we call the trim method and then store the result in this variable once again we're chaining multiple methods here let's run the program so a few spaces Maharani and you get this beautiful output right now it's time for a project I want you to use what you have learned in a section and build a mortgage calculator like this so when you run this program we get a few questions the first question is the principal or the amount of loan we want to get let's say $100,000 the second question is the annual interest rate let's say three point nine two percent and the third question is period in years let's say you want to get a loan for thirty years so this program calculates our monthly payments and displays it as a currency this is a great exercise for you to practice all the materials you learn in this section now before you get started I want to give you a few hints here is a formula for calculating the mortgage or the monthly payments I found this page on wikiHow comm is called calculate mortgage payments so let's see how this works mortgage equals P or principal or the amount we're gonna loan multiplied by R which is our monthly interest rate this is very important so this number that we get here is our annual interest rate we need to divide this by 12 also take into account that this number is represented as a percent to calculate the actual interest rate you need to divide this number by 100 so in this example the interest rate is zero point zero three nine two so whatever the user enters divided by 100 and then divided by twelve to get to the monthly interest rate now we have this monthly interest rate we need to multiply this by this expression here we need to add 1 to this interest rate and raise it to the power of n where n is the number of payments so we need to multiply this number by 12 or 12 months to calculate the number of payments now to raise this number to the power of n you need to use the power method of the math class so this math class has this power or power method that takes two arguments or two values a and B so go ahead and spend ten to fifteen minutes on this exercise when you're done come back see my solution all right let's see what I've done here and by the way don't worry if your coat is different from mine we all think and coat differently so it's perfectly fine if your code is different just look at my coat see what I've done here and see if there are ways you can improve your coat that's what matters okay so here in our main method first I've declared two final variables or constants the first one is months in year which I've set to 12 and the second one is percent which I've set to 100 the reason I declared this constant is that I didn't want to have magic numbers in this code so over here where we calculate the monthly interest we get the annual interest divided by percent and then months in here this code is very self-explanatory someone else reading this code we'll have no problem understanding what's going on here in contrast if you had a magic number here like divided by 12 and then for whatever someone else reading this code would wonder what is this for doing here what is 12 it's quite obvious to you that 12 is the number of months in a year but trust me sometimes other people cannot see this straight away so as a best practice avoid magic numbers in your code always use constants or final variables to describe them so let's revert this back all right so after declaring this constant I've created this scanner object here we ask the first question principle and we read the answer as an integer I thought integer is a good datatype for storing the principle because short is not enough with short we can store a maximum of $32,000 that's not enough what if someone wants to find us $1,000,000 so int is good and it allows us to store a value up to two billion next we ask the second question annual interest rate we read this as a float here I could use double but the interest rate is a small number so float is sufficient for that we don't really need double so we get the annual interest and then based on that we calculate the monthly interest also see how I have named my variables all variables have a proper meaningful names there are no magic words here like MI as it short for monthly interest or m1 or m2 do not use magic names for your variables always use meaningful and descriptive names alright next we get the period we read this as a byte because the maximum number we want to support is 30 so one byte is sufficient to store the number 30 or anything smaller now based on the number of years we calculate the number of payments note the camel notation here I've capitalized the first letter of every word except the first word so we get the Earth's and x months in here again the code is very self-explanatory once we collect all this data then we calculate the mortgage so we get a principal multiplied by this expression and then divide it by this other expression let's have a quick look here now this looks a little bit complicated so if you're not download my source code look below this video I'm attached it for you to download and finally after we calculate the mortgage we use the number format class to format this value as a currency so we get a result store it in this string mortgage format it and print it over here now here we can also avoid declaring this variable and simply add this expression over here but it decided to do this to increase the readability of this code otherwise this line would be so long but that's just my personal preference you don't have to follow this alright so this was my implementation of the mortgage calculator however this program has a number of problems the first problem is input validation so if we run this and enter a non numeric value like XYZ our program crashes or as another example if we enter a negative value here our program is not gonna behave properly so that's where conditional statements come to the rescue in the next section we're going to talk about conditional statements you will learn how to use these statements to validate the values entered by the user so that brings us to the end of this section I hope you learn a lot and thank you for watching so in this section you'll learn all about variables and constants you learn about primitive and reference types you learn that primitive types store simple values but reference types hold references to complex objects that's why we call them reference types you also learn about casting and type conversion you learn about two types of casting implicit and explicit you learn how to work with numbers strings and arrays and finally you learned how to read input from the terminal I hope you learned a lot I've been enjoying the course so far in the next section we're going to look at conditional statements for controlling the flow of our programs so I'll see you in the next section hey Marcia I just want to make a quick announcement this course you've been watching is actually the beginning of my complete Java series in this course we only talk about the basics but in my complete series we go way beyond that so if you're serious about Java if you're looking for a job as a Java developer I highly encourage you to enroll in my complete Java series it's exactly the same structure the same quality but it has way more content plus you will get a certificate of completion that you can add to your resume so if you're interested I put the link down below you can get the course with a discount and if you're not happy for any reasons you can ask for a refund within the first 30 days so I hope to see you in the course in this section we're going to look at control flow or controlling the flow of execution of our programs you're gonna start off by talking about comparison operators for comparing values then I'm gonna talk about logical operators like the logical and logical or and logical not we use these operators for implementing real world rules and then we're gonna talk about three different types of control flow statements we're going to talk about conditional statements for making decisions in our programs then we're going to talk about loops for executing code repeatedly and finally we're going to revisit our mortgage calculator and add error handling to it so if a user enters an invalid value we keep asking them to try again all right now let's jump in and get started we're gonna start this section by talking about comparison operators we use these operators to compare primitive values for example our x on y equal or not so I'm gonna declare two integers x and y now let's compare this to see if they're equal or not so first I'm gonna add this print line statement now to compare these variables we type x equals y so here we have two equal signs and this is the Equality operator don't confuse this with a single equal sign that we use for assignment that is the operator used over here okay so two equal signs repairs the Equality operator now when we run this program we get true because these values are equal this expression that we have here is called a boolean expression so earlier I told you that an expression is a piece of code that produces a value this piece of code produces a boolean value true or false that's why we refer to it as a boolean expression we also have the inequality operator so when we run this program we're gonna see false let's take a look we get false because these two variables are equal so the expression X is not equal to Y returns false we also have greater than greater than or equal to less than and less than or equal to so if I change Y to 2 this expression is gonna evaluate to true because X is less than or equal to Y take a look there you go next we're going to talk about logical operators in the last tutorial you learn that a boolean expression produces a boolean value now there are times we want to combine multiple boolean expressions let me show you so I'm going to declare an integer called temperature and set it to 22 next we declare a boolean variable is warm now we want to check to see if temperature is greater than 20 and less than 30 so we write a boolean expression like this temperature greater than 20 here we need to use the end operator so these two ampersands represent the logical and operator in Java after this we add our second condition temperature less than 30 now if both these conditions are true the result of this boolean expression is going to be true otherwise if at least one of these is false the result would be false let's take a look so I'm gonna print is warm on a terminal the result is true but if you change the temperature to let's say 12 the result is gonna be false and this is how this works Java will evaluate this expression from left to right first it looks at the first condition the first condition is false because temperature is not greater than 20 so because this expression is false it doesn't matter what we have after the and operator Java will ignore the other expressions because the and operator will return true if both conditions are true okay now let's look at another operator that is the or operator so I'm going to delete all this code and start with a new example let's declare a boolean has high income we set it to true and another boolean has good credit we set this to true as well so let's say we're building an application for processing loans we want to see if a new applicant is eligible for a loan or not so we declare another boolean is eligible and by the way look at the names I have used for these variables they're very meaningful and descriptive so here's the rule an applicant is eligible if they have high income or good credit if one of these conditions is true they are eligible so we write has high income or so these two vertical bars represent the or operator so if they have high income or good credit then they are eligible so with the or operator if at least one condition is true the result will be true in this example when Java evaluates this expression it starts from the left side this boolean variable is true so it doesn't matter what we have after Java will not evaluate the rest of this expression it simply returns true however if this variable was false Java would continue evaluating this expression hoping that the next boolean value or the next boolean expression is true so this is the or operator and finally we have the not operator that we use to reverse a value let me show you how that works so let's declare another boolean variable has criminal record we set this to false so here's the rule we want to implement in order for someone to be eligible for a loan they should either have high income or good credit and they should not have any criminal records so let's see how we can implement this rule we have implemented the first part they should either have high income or good credit now we want to make sure they don't have any criminal records so we need to combine the result of this expression with this boolean value using the and operator so first we wrap this expression in parentheses then we apply the end operator and here we add has criminal record now you want to make sure they don't have criminal record and this is where we use the not operator so the not operator will reverse the value of this boolean variable or expression in this case this variable is set to false so when we apply the not operator to it the result would be true so if the first condition is true and the second condition is true then that person is eligible for a new loan so as you can see these logical operators are very useful in implementing real word rules next we're going to talk about if statements in this tutorial we're going to look at if statements in Java if statements are extremely important because they allow us to build programs that can make decisions based on certain conditions here's an example in this file we have a bunch of conditions if temperature is greater than 30 perhaps you want to display two messages to the user it's a hot day drink plenty of water otherwise if it's between 20 and 30 you want to print it's a nice day and otherwise we want to print it's a cold day so let's see how we can implement these rules in a Java program back to our main file we start by declaring a variable temperature we set it to 32 now we use an if statement followed by a pair of parentheses inside this parenthesis we type an expression or a boolean value so let's say temp is greater than 30 now if this condition is true the statement that we had after this if statement will be executed so let's print it's a hot day let's run the program we get this message because temperature is greater than 30 now what if you want to print another message like drink plenty of water here we should add curly braces to define a code block so if this condition is true all the code that we have inside of this block would be executed let's add another message here drink water okay so this was our first condition now let's add a second condition so after the right brace we type LS if once again we add our parentheses and inside these parentheses we type a boolean expression if 10 is greater than 20 and it's less than or equal to 30 you want to print a different message like beautiful day now here I haven't added the braces because we have a single statement so braces are only required if we have multiple statements now this is a little bit controversial some people believe we should always add braces whether we have a single statement or not other people like myself believe this creates unnecessary noise in the code in this tutorial I'm gonna add the braces first and then remove them so you can see the difference so let's add a pair of curly braces here and finally our last condition so if none of these two conditions are true let me print a different message so here we simply type LS we don't have any more conditions so let's add a code block and print cold day now let me define a few terms here we have an if statement and this statement has three clauses or three sections here's the first Clause here's the second Clause and here's the third Clause pay attention to how a formatted this if statement so first we have the if Clause the else if and else clauses are placed after these right braces so we have some kind of hierarchy here here we have a parent followed by two children now let's get rid of these unnecessary braces and reformat our code to see the difference so I'm gonna remove the braces for the else clause and also one more time here that's better now we can simplify this boolean expression basically we don't need this piece of code here here's the reason if the first condition is not true what does it mean that means the temperature is less than or equal to 30 so this expression here is unnecessary let's delete this and simplify our code that's better now look at how this code is formatted on the top we have if the else if Clause is a little bit indented but the else Clause is not indented it's at the same level as the if Clause and this looks a little bit ugly the code is not symmetrical so if you want to get rid of the curly braces a better way to format this code is like this so instead of adding the else if or else classes after curly braces we add them on a new line now all these clauses are at the same level the code is easier to read in this tutorial I'm gonna show you a very cool technique for simplifying if statements so let's start by declaring a variable called income and set it to 120,000 now here we can use an underscore in between these three digits to make our code more readable now let's say we want to declare a boolean variable called has high income if the income is more than $100,000 you want to set this to true otherwise we want to set this to false so here we can write an if statement like this if income is greater than $100,000 we want to set has high income to true however we get a compilation error here let's take a look declaration not allowed here so we cannot declare a variable here we can only declare variables inside code blocks like this code block over here so to declare this variable we need to add curly braces to define a new code block now we have a different problem this variable that we have defined is scoped to this code block so it's only available here we cannot access it outside of this block let me show you so if we print has high income you can see we have a compilation error cannot resolve symbol has high income because this variable is not available outside of the block in which it's declared so to solve this problem we can declare this variable after setup this block boolean has high income and then we can simply set it to true in this block now we don't need these braces anymore so let's simplify the code we add an else clause otherwise we said has high income to false let's remove this print method we don't need it anymore so this is one way to implement this scenario but this code looks very amateurish a professional programmer doesn't write code like this let's improve it step by step one way to improve this is to give this boolean variable an initial value for example we can set it to false initially and then we implement this condition so if the income is more than $100,000 then we set this variable to true with this we no longer need is else Clause so that was one improvement but it's still not ideal in situations like this we can completely get rid of this if statement here let me show you instead of hard-coding false here we type our expression income is greater than $100,000 so here we have a boolean expression if this boolean expression evaluates to true this boolean variable is going to be true otherwise it's going to be false so this is the simplest the most elegant and the most professional way to implement this scenario now one more improvement before we finish this tutorial I personally prefer to wrap this expression in parentheses even though technically we don't need parentheses here but these parentheses make our code more clear more readable let me show you so I'm gonna wrap this inside these parentheses now it's very clear we're obviously on the right side of this assignment operator we have a boolean expression in this tutorial we're gonna look at the ternary operator in Java so we're gonna continue with the example from the last tutorial we had this income variable imagine this is the income or customers now depending on their income you want to put these customers in different classes if their income is more than $100,000 you want to put them in the first class otherwise we want to put them in the economy class so here's one way to implement the scenario we declare this string variable class name note that we cannot call this class because class is a reserved keyword so class name now we write our first condition if income is greater than $100,000 we said class name to first otherwise we set it to economy now as you learn in the last tutorial this code looks very amateurish a professional programmer doesn't write code like this so one way to simplify this is to give this variable an initial value so we assume they are in the economy class and then we check this condition if this condition is true we put them in the first class so with this we can get rid of this else clause that is better now in the last tutorial I showed you how to simplify this even further but the technique you learned there cannot be used here in other words we cannot add income greater than $100,000 here because here we have a boolean expression but on the left side we have declared a string variable so we want to set this to a different string depending on the result of this expression and this is where we use the ternary operator so we start with our condition then we type a question mark if this condition is true we add this value here otherwise we add the other value so this question mark and colon is the ternary operator in Java it has three pieces first we have a condition if this condition is true this value will be returned and assigned to our class named variable otherwise this other value will be returned now we can completely get rid of this if statement so put the ternary operator in your tool box it's very helpful next we're going to look at switch statements in Java in this tutorial we're going to look at switch statements in Java we use three statements to execute different parts of code depending on the value of an expression kind of similar to if statements let me show you so let's say we're gonna write a program and check the role of the current user and then we're gonna print different messages or give them different features depending on their row so let's declare a string variable called role and here we set this to admin now to check the role of the user we can write an if statement like this if role equals admin then perhaps we want to print you are an admin now you might be wondering why we have this condition here it's obvious that this condition is always true because we have set roll to admin but this is just for demonstration in a real program we are not gonna hard code this admin here so we're gonna read the role of the current user from somewhere else we don't know what it is at the time of writing code okay so here we have one condition let's write another condition else if role equals moderator perhaps we want to display a different message so you are a moderator and finally if the role is none of these values you want to print you are a guest so this is one way to implement this scenario using an if statement we can also implement this using a switch statement and sometimes that looks a little bit cleaner let me show you so we start with a switch statement then we add parentheses and inside this parenthesis we add our variable in this case row next we define a block of code and in this block we add one or more case clauses so we have a case for an admin we add a colon here now what do we want to do here if the role is admin you want to print you are an admin so I'm gonna copy this line from here and then paste it over here now after this line we need to add a break statement to jump out of this switch block okay then we add another case Clause so case moderator once again you got a colon and here we're gonna print this other message so we paste it here and then we're gonna break now optionally we can have a default clause here so if none of these previous cases apply the code that we write in this section will be executed so here we want to print you are a guest now here we don't need to use a break statement because we're at the end of the switch block so will automatically jump out of this block in contrast if we didn't use this break statement here Java will continue executing these other lines here so if the role is admin first it will execute this line and then it will jump to this case block it will execute this other line and then after it executes this break statement it will jump out of this switch block okay so this is how we use a switch statement now compare this with wave statement some people prefer to use if statements others prefer to use a switch statement now one more thing before we finish this tutorial here we're comparing the value of role with strings but we could also use integers other than the long type so if roll was a byte short or an integer our cases would look like this case one case two and so on now here we have a compilation error because roll is a string let's change this to an integer and we can initialize this to one so as you can see with sweet statements we can execute different code depending on the value of an expression all right now it's time for an exercise this exercise I'm gonna give you is a popular interview question so I want you to write a program that behaves like this here we should enter a number if this number is divisible by five we get this so if you run the program again and enter ten once again we get fit now if this number is divisible by 3 we get buzz if this number is divisible by both five and three like fifteen or thirty or whatever we get fizzbuzz and if this number is not divisible by five or three like two we get the same number printed on the terminal so go ahead and spend five to ten minutes on this exercise you'll see my solution next all right to read the number first we need to use the scanner object so scanner we import this and instantiate it and as you know here we need to pass system that in to read data from the terminal now we print a message so we're gonna use the print method instead of print line here we add a label like number and then we call scanner the next int to read a number we store it in this variable number okay so the first part is done now we need to check to see if this number is divisible by five or not so we can write an if statement like this if number here we use the modulus operator which returns the remainder of a division so we divide this by five and if the remainder equals zero that means this number is divisible by 5 so we print fizz now otherwise if this number is divisible by 3 we print buzz we need another condition if this number is divisible by 5 and 3 so here we use the and operator number divisible by 3 equals 0 in this case we want to print fizz buzz otherwise you want to print the same number like this now this is not the right solution as I will show you in a second this program has a book but it's a very common solution that I see amongst my students so let's run this program and see what is wrong here all right here we enter five we get fizz utiful what if you enter ten ten is also divisible by 5 so we get fits so far so good what about a number that is divisible by 3 we get buzz good what if we enter a number that is divisible by both 5 & 3 like 15 we get physican why is that here's the reason with this implementation if we enter 15 this first condition will evaluate to true so we get fizz these other else clauses will be ignored and that is why this line will not be executed so in situations like this you should have the most specific conditions on the top and the most generic ones on the bottom in this case we want to move this condition to the top so if the number is divisible by 5 & 3 we're gonna print fizzbuzz so this is very specific otherwise if the number is only divisible by 5 we print fizz else if it's divisible by 3 we print buzz and finally if none of his conditions is true then we print the same number now let's run the program one more time so we enter 15 and we get fizzbuzz beautiful so here's one way to solve this problem now I've seen some people argue that we have repeated this expression twice number is divisible by 5 we have that here on line 12 as well as line 14 in programming we have this concept called dry which is short for don't repeat yourself so some people argue that here we have repeated this expression and this is not a good solution here is another way let me show you so we're gonna get rid of this second condition here instead we're gonna add a code block over here so if the number is divisible by 5 first we check to see if the number is also divisible by 3 if that's the case we print fizzbuzz otherwise we print just fizz like this okay now we no longer need these two lines because we already implemented this concept here so first we check to see if the number is divisible by five if not we check to see if it's divisible by three and otherwise so here is another way to solve this problem but in my opinion this approach is kind of amateurish and ugly because these nested if-else statements are considered a bad practice now this is not terribly bad but the more you nest these L statements the more confusing your code is going to be to other people so I personally prefer the previous solution even though we had a bit of repetition in the code the more you program the more you build software the more you realize that there is no way to build ideal software programming and problem solving is all about trade-offs every solution has certain strengths and certain weaknesses this solution doesn't have any repetition or duplication in the code but it has a nested structure and these nested structures make our code hard to read and understand the previous solution had a bit of repetition but it had a flat structure there is no nesting here and this code is cleaner and easier to read there are times that we want to repeat one or more statements for example let's say we have this hello world message here let's say we want to print this five times on the terminal we don't want to repeat this code like this this looks very ugly that's where we use loops in Java we have a few different types of loops the first one that I'm going to talk about in this tutorial is for loops so let's see how we can use a for loop here I'm going to delete all this code you start by typing the for keyword followed by parentheses and inside these parentheses we need to do three things first we need to declare a loop or counter variable so let's declare a variable called I and initialize it to 0 quit often use variable names like I J and K for loop counters next we add a semicolon to terminate the first statement then we write a boolean expression that determines how many times this loop is gonna get executed so I than five as long as I is less than five this loop will be executed once again we add a semicolon and finally we increment I by one like this so this is the basic structure for a for loop now here we can repeat one or more statements using this for loop so we can add our hello world message here like here we have a single statement so we don't need braces but if you have multiple statements that we want to repeat we need to define a code block here now I'm gonna remove this because you don't really need them so let's run this code and see what we get you get hello world printed five times on the terminal beautiful now let me explain how this code gets executed when Java sees this for loop first it will execute this statement so here we are initializing I to zero then Java evaluates this condition is this condition true obviously it is because zero is less than five so the control moves to line seven this line gets executed now at the end of this iteration or at the end of this loop the control moves here so I is incremented by one now we are at the beginning of the second iteration once again this condition is evaluated is one less than five obviously it is so once again the body of this loop gets executed now fast forward at the end of the fifth iteration I will become five five is not less than five so the loop condition will be false and control moves outside of this for loop now here's one thing you need to remember if you want to execute something five times you can initialize your loop counter or loop variable to zero and use the less than operator here another way is to initialize this to one and then use the less than or equal to operator here now to make this more interesting let's print I over here so here we add a space and then concatenate this string with I take a look so we get hello ward one two three four five in contrast if we initialize I to zero and use the less than operator we will get hello word zero one two three four we can also print these numbers in reverse order so we initialize I to five and execute this loop as long as I is greater than zero but here instead of incrementing I we decrement it now we get hello world five four three two one so this is all about for loops next we're gonna look at while loops in this tutorial we're gonna talk about while loops in Java while loops are very similar to for loops in terms of their functionality but they're different in terms of syntax let me show you so we're gonna continue with the example from the last tutorial I'm gonna rewrite this code using a while loop so first we declare a loop variable and I initialize it to zero next we type while and here in parentheses we type our loop condition while I is greater than zero then we're gonna execute the code inside this block so I'm gonna copy this from here paste it in this block and finally we need to decrement I like this so at the end of each iteration we decrement I just like our for loops so as you can see we can achieve the same thing using a for loop or a while loop however the implementation using the for loop is a little bit lighter and cleaner so in situations where you know ahead of time how many times you want to execute one or more statements it's better to use a for loop while loops are better in situations where we don't know exactly how many times you want to repeat something for example let's say we're going to write a program and ask the user to continuously enter something until they type quit the moment they type quit we're gonna terminate the program in that situation we don't know how many times the user is going to enter something so let's write that program using a while loop I'm gonna delete everything from here all right we're gonna start with our while loop now what is our loop condition here we don't have a counter variable in this example instead we want to check to see if the user entered quit or not so here we can declare a string called input and initialize it to an empty string then we can write a while loop like this while input does not equal to quit now this code is not gonna work because input is a string which is a reference type and we cannot use comparison operators between reference types because these operators will compare the address or a string objects not their value so if you have two strings quit and quit but stored in different memory locations to have different addresses so we can use the inequality operator to compare their value instead we need to use the equals method of string objects so we want to check to see if the input equals quit now here we need to apply the not operator so as long as the input does not equal quit we're gonna continuously ask the user to enter something so here we can print a label like input and then we can use a scanner object to read something from the terminal so let's create a scanner object and instantiate it using system dot in I didn't call scanner that next this will return a string so we can store it in this input variable now with this implementation in every iteration we're going to create a new scanner object so if the user enters 10 numbers we're gonna create 10 scanner objects in memory this is unnecessary and it's actually a bad practice because it's going to pollute our memory so it's better to create the scanner object outside of a while loop and then simply use it here also here we are assuming that the user is typing everything in lowercase so if they type quit in uppercase or any combinations of lowercase and uppercase characters this logic is not gonna work the way we want so over here right after reading something from the terminal we're gonna call the to lowercase method of string objects to convert it to lowercase now to make this program more interesting let's echo back whatever the user enters so we simply print that on the terminal now let's run this and see what happens so I'm going to enter if your numbers like 1 2 & 3 whatever we type gets a code back but the moment we type quit our program terminates so while loops are useful in situations where we don't know ahead of time how many times we want to repeat something in Java we have another type of loop called a do-while loop it's very similar to a while loop but it gets executed at least once let me show you what I mean so I'm gonna rewrite the same code using a do-while loop we start with a do keyword then we create a code block at the end of this code block we type while followed by our loop condition so not input dot equals quit and then we terminate this using a semicolon now inside the body of this loop we'll simply copy all these lines we have here now compared these two types of loops with while loops we check the condition first so if the condition is false the first time this loop will never get executed in contrast with do-while loops we check the condition last so do-while loops always get executed at least once even if the condition is false that is the only difference the reality most of the time we use while loops do-while loops are rarely used but there are certain cases for that so just be aware of them but most of the time prefer to use wire loops we're gonna continue with the example from the last tutorial this program we have written has a tiny problem let me show you so I'm gonna run this enter a couple numbers these numbers get echo back beautiful if we type quit the program terminates but the word quit also gets echoed back this is a bit weird so let's look at a couple ideas for solving this problem back to our code one way to solve this problem is to check the input before printing it so here we can type an if statement if the input does not equal quit then we're print it so not equal input dot equals quit if this condition is true then we're going to print the input let's take a look so one to quit beautiful we solved the problem there is another way to solve this problem as well let me show you we can reverse this condition so if the user types quit you can immediately jump out of the loop using the break statement so I'm gonna remove the nut operator if the user types quit we're gonna break out of the loop otherwise we're gonna continue execution and print this input on a terminal so when Java sees the break statement it will ignore everything else after and it will terminate the loop let's run the program once again we enter a couple numbers followed by quit beautiful so this is the break statement we also have the continuous statement that moves control to the beginning of a loop let me show you so let's imagine if the user types pass we don't want to echo that but also we don't want to terminate the loop you want to ask the user to try one more time so after we read the input we can check to see if input equals pass this is where we use the continuous statement when Java sees this it would move control to the beginning of the loop so all these other statements are gonna get ignored and what the user types is not gonna get printed on the terminal let's run the program and see this in action so we type 1 2 pass it doesn't get echoed back one more time and finally quit so to recap the break statement terminates a loop and the continue statement moves control to the beginning of a loop now one last thing before finish this tutorial in this implementation we don't really need this loop condition because the moment user types quit this break statement is gonna kick in and terminate the loop so we can simplify this code by using a true as our loop condition so this is always true and this loop is gonna get executed forever until the user types quit this is a very common technique that you see amongst professional programmers just remember if you're using this technique make sure to have a break statement otherwise you will end up with an infinite loop that executes forever it never terminates and that can be very dangerous in terms of memory consumption so if you're using while true make sure you have a break statement in your loop the last type of loop we want to look at is the for each loop in Java we use for each loops to iterate over arrays or collections let me show you so I'm going to start by declaring a string array called fruit and we initialize this with three items let's say Apple mango and orange now let's say we want to iterate over this array and print each item on a terminal we can use any of the loops you learn about earlier like a for loop or a while loop but we can also use the for each loop which is a bit easier let me show you first I'm going to use the for loop to iterate over this array so we type for here we declare our loop variable or loop counter into I we set it to zero as long as I is less than fruits that length we're going to increment I by one after each iteration and here we simply print fruits of I let's run the program and see what we get so we get each item on a new line beautiful now there is another way to write the same code using the for each loop here we type for in parentheses with declare and loop variable but the type of this variable should be based on the type of items in our array so here we have a string array and that means every item in this array is a string so here we should declare a string variable we call it fruit here we type a colon and then the name of our array fruits now in each iteration fruit will hold the value of one item in this array so here we don't have to declare a numeric counter we don't have to write a boolean expression like this we don't have to increment our counter it's much easier to iterate over an array now if we print fruit we get the exact same result as before take a look so the first three items are from our for loop and here's the result our for each loop so this is the for each loop however this for each loop has a couple of limitations one limitation is that it's always forward only so we cannot iterate over this array from the end to the beginning in contrast we can easily do this with a for loop so here we can initialize I to fruits that length then we change this operator to greater than and replace this value with zero so as long as I is greater than zero we're going to decrement I the second limitation of the for each loop is that here we don't have access to the index of each item all we have is this loop variable which holds the value of each item in this array in contrast in our for loops we can access both the index and the actual item so I represents the index of each item and fruits of I returns the item at the given index so if you need the index then you'll have to use the for loop otherwise it's much easier to use the for each loop all right now let's get back to our mortgage calculator and implement some basic error handling so here I've changed this question by adding this label that identifies the range of values we can enter so the minimum amount of loan we can get is $1,000 and maximum is 1 million dollars so if I enter 1 here I get this message enter a number between one thousand and one million and now we are asked this question one more time if I keep entering invalid values I get asked the same question now let's enter a valid value like 1 million dollars next we'll have to enter the annual interest rate now here we need to enter a value that is greater than 0 and less than or equal to 30 so if I enter 0 we get this message enter a value greater than 0 and less than or equal to 30 once again we're asked this question one more time so let's enter a valid value like 3.9 to here we need to enter a value between 1 and 30 so if you enter 0 we get an error message and we're asked the same question so let's enter 30 and finally we get the result here's our mortgage or monthly payments so go ahead and spend five to ten minutes on extending this mortgage calculator by adding error-handling to it you'll see my solution X all right let me show you how I'm gonna solve this problem step by step so for each question we want to validate the value that the user enters if the value is invalid you want to keep asking the same question so this is where we can use an infinite loop let me show you so here's our first question principal I'm gonna wrap these two lines inside an infinite loop while true so we're gonna keep asking the same question until the user enters a valid value so here after we read the principle we can write an if statement like this if principle is greater than or equal to 1000 and it is less than or equal to 1 million and here we can use an underscore to separate these digits to make our code more readable so if the user enters a valid value then we can break out of this infinite loop otherwise we're gonna print an error message so enter a value between 1001 million like this ok now if you look on the right side here you can see this red bar this indicates an error and here in this preview window you can see exactly where we have an error it's down below on line 30 where we calculate the mortgage so if you click on this red bar we jump over here principal is highlighted in red so here we have a compilation error cannot resolve symbol principle here is the reason because we've wrapped these few lines inside this while loop and earlier I told you that whenever you declare a variable that variable scope to the Block in which it's defined so this is where we have declared the principal variable and it's scoped to this block it's not available outside of this block that's why we get this compilation error so to solve this problem we need to declare this outside of this while loop we can do it right here after radicular our constants so let's say int principle and we can initialize it to 0 now we remove the declaration from here and the error is gone now we need to repeat the same pattern with other questions so real quick here's our second question where we read the annual interest once again we add an infinite loop now the moment we read the annual interests invalidate the data so if annual interest is greater than or equal to let's say one and it is less than or equal to 30 then we're gonna break out of this infinite loop now here we should also calculate the monthly interest so the proper way to do this is like this if the user enters a valid value we add a code block here first we calculate the monthly interest and then break out of the loop otherwise we print an error message enter a value between 1 and 30 okay now if you look to the right side again we have two compilation errors monthly interest is not resolved because we have declared it inside of this block so let's move the declaration to the top here we remove the float keyword and declare monthly interest over here that's better and finally for the last question one more time we're to wrap it in this infinite loop this is where we read the number of years and right after this line we need to do our data validation so if yours is greater than or equal to one and it's less than or equal to 30 here we add a code block this is where we calculate the number of payments and then we break actually I forgot to type an S here otherwise if the user enters an invalid value will simply print an error message enter a value between 1 and 30 now here once again we have a compilation error because number of payments cannot be resolved so we remove the declaration from here and we'll be to the top right here number of payments so this is how we add data validation to this program the problem is that this code the code inside the main method is now getting a little bit too long and this hurt the maintainability of our program someone else reading this code they have to look at all these statements to figure out what's going on this is where we need to break this code down into smaller easier to read and easier to understand chunks and that's what I'm gonna show you next so in this section you'll learn how to control the flow of execution of your programs we started off by talking about the comparison operators for comparing primitive values then we talked about the logical operators like and or and not I showed you how we can use these operators for implementing real word rules and then we talked about three types of control flow statements you learn about conditional statements like if and switch for making decisions in our programs then you learn about loops for executing code repeatedly we looked at four types of loops for loops while loops do-while loops and for each loops and finally we looked at the break and continue statements for breaking or jumping to the beginning of a loop I hope you learned a lot and been enjoying the course so far as Martin Fowler said any fool can write code that a computer can understand good programmers write code that humans can understand I can't agree more if you have seen any of my courses you probably know that I've put a lot of emphasis on writing clean code so I have dedicated this entire section on clean coding we're going to continue extending our mortgage calculator and add new features to it along the way you will see our code starts to get messy and hard to maintain so I will show you a few techniques for changing the structure of the code and make it clean and beautiful are you ready let's jump in and get started hey guys maj here i want to congratulate you on your determination for learning I would really appreciate it if you support me by liking and sharing this video also subscribe to my channel and enable notifications so next time I upload a video you get notified now if you want to learn more I would encourage you to enroll in my ultimate Java series as I told you earlier this YouTube tutorial is the first two hours of this series if you're serious about learning Java and want to become a professional job of developer I highly encourage you to enroll in this series in case you're interested I put the link down below in the description box thank you on have a fantastic day
Info
Channel: Programming with Mosh
Views: 5,793,080
Rating: undefined out of 5
Keywords: java, java tutorial, java tutorial for beginners, learn java, java course, java 12, java 8, java 8 tutorial, java programming, java programming for beginners, java training, java for beginners, java 8 tutorial with examples, java 8 course, java programming tutorial, programming, tutorial, beginners, programming with mosh, code with mosh, mosh hamedani, learn to code
Id: eIrMbAQSU34
Channel Id: undefined
Length: 150min 48sec (9048 seconds)
Published: Mon Jul 15 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.