Hi! My name is codebeast and I'm gonna be yourinstructor in this Java course

In this course, you're gonna learn everything youneed to get started programming in Java

We'll start off by installing all thenecessary tools to build Java applications then you're gonna learnabout the basics of Java you'll learn how Java code gets executed you'll learnhow to build simple algorithms and throughout this course I'm gonna sharewith you lots of tips and shortcuts from my years of experience I'll teach youhow to write good code like a professional developer so we'll end upwatching this course you will have a solid foundation in Java and be ready tolearn about advanced Java features I've designed this course for anyone whowants to learn Java if you're a beginner don't worry I'll make Java super simpleand hold your hands through this entire course you're not too old or too youngyou'll write your first Java program in minutesmy name is mosh I'm a software engineer with two decades of experience and I'vetaught over 3 million people how to code and how to become professional softwareengineers I have a coding school at code with mass comm where you can find plentyof courses that help you take her coding skills to the next level I hope you'llstick around and learn this beautiful and powerful programming language andnow award from this video sponsor as someone who runs an online business Icannot stress enough the importance of staying safe online which is why I wasso excited when dashlane reached out to me if you don't know - Lane is thepassword manager and VPN recommended by Apple and Google and it's a fantasticsafeguard for keeping your information secure it's completely free to use foryour first device so head over to - Ling comm / marché - give it a go if you wantto upgrade to the premium to get VPN or dark web monitoring you can use thepromo code mosh to get 10% off sign up for - 9 today and keep yourself safeonline now back to the course in this java tutorial we're going todownload and install the necessary tools to build java applications so open upyour browser and search for jdk download jdk is short for Java development kitand it's basically a software development environment for buildingJava applications it has a compiler it has a bunch of code that we can reuse ithas a Java Runtime environment at a bunch of other stuff so over here youcan see this page on Oracle com Java se which is short for Java standard editionclick on this now over here click on this icon now on this page we can seeJava development kit for various platforms like Linux Mac OS and Windowshere I'm on a Mac so I'm gonna download this dmg file over here now before we dothis first we need to accept the license agreement all right now let's downloadthe dmg let me open this we're gonna say this package let's double click this andhere we see this installation wizard it's super easy just click continue andinstall you have to enter your computer's password and then alrightdone beautiful so we can move this to trash now the next piece of software weneed is a code editor there are so many cool editors for building Javaapplications the popular ones are NetBeans Eclipse and IntelliJ in thisJava course I'm gonna use IntelliJ but if you have a favorite editor feel freeto use that to take this course that's perfectly fine so let's search forIntelliJ download all right you can see download IntelliJ IDEA click on thislink over here download the community edition which is absolutely free andit's more than enough for this course so download all right now let's drag anddrop this onto the Applications folder beautiful alright we've installed allthe necessary tools to build Java applications so next we're gonna look atthe anatomy of a Java program in this java tutorial we're gonna lookat the anatomy of java programs the smallest building block in java programsare functions if function is a block of code thatperforms a task as a metaphor think of the buttons on the remote control ofyour TV each button performs a task functions in programming languages areexactly the same for example we can have a function for sending emails to peoplewe can have a function for converting someone's weight in pounds to kilogramswe can have a function for validating users input and so on now let's see howwe can code a function in Java we start by specifying the return type of thatfunction some functions return a value like a number at day time and so onother functions don't return anything so the return type of this functions isvoid void is a reserved keyword in Java and that's why I've coded that in bluehere now after the return type we have the name of our function so here weshould give our function a proper descriptive name like send email thisname clearly identifies the purpose of this function okay now after the name wehave a pair of parentheses and inside these parentheses we add the parametersfor this function we use these parameters to pass values to ourfunction for example our send email function should have parameters like whois the receiver what is the subject of this email what is the content of thisemail and so on now in this tutorial we're not gonna worry about parameterswe'll look at them in the future now after the parentheses we had a pairof curly braces and inside these braces we write the actual Java code now onething I want you to pay attention to here is that in Java we put the leftbrace on the same line where we define our function in other programminglanguages like C sharp it's more conventional to put the left brace on anew line but we don't do that in Java so we put the left brace on the same linewhere we define our function now every Java program should have at least onefunction and that function is called main so main is the entry point to ourprograms whenever we execute a Java program the main function gets calledand the code inside this function gets executed okay now thesefunctions don't exist on their own they should always belong to a class so aclass is a container for one or more related functions basically we use theseclasses to organize our code just like how products are organized in asupermarket in a supermarket we have various sections like vegetables fruitscleaning products and so on each section contains related products by the sametoken a class in java contains related functions now every Java program shouldhave at least one class that contains the main function can you guess the nameof that class its main so this is how we define a class in Java we start with aclass keyword then we give our class a proper descriptive name and then we adda pair of curly braces now the functions that we define in between these curlybraces belong to this class and more accurately we refer to them as methodsso a method is a function that is part of a class in some programming languageslike Python we can have a function that exists outside of a class so we call ita function but when a function belongs to a class we refer to it as a method ofthat class okay now in Java all these classes and methods should have anaccess modifier an access modifier is a special keyword that determines if otherclasses and methods in this program can access these classes and methods we havevarious access modifiers like public private and so on now most of the timewe use the public access modifier so we put that in front of our class andMethod declarations so this is the basic structure of a Java program at a minimumwe have a main class and inside this main class we have the main method nowyou might be curious why we have a capital m in the name of this classbecause in Java we use different conventions for naming our classes andour methods to name our classes we use the Pascal naming convention and thatbasically means the first letter of every word should be uppercase incontrast to name our methods we use the camel naming convention and that meansthe first letter of every word should be operatecase except the first wart so that is why we have a capital m in the name ofthis class alright now that you understand the anatomy of a Java programlet's create a new Java project and see all these building blocks in action inthis Java tutorial you're gonna learn how to write and execute your first Javaprogram so let's open IntelliJ IDEA here on the home screen let's create a newproject alright on the left side select java and make sure project sdk is notblack so earlier we downloaded jdk or Java development kit version 12 that iswhy JDK version 12 is selected here if you don't see that make sure to selectit from this drop-down list alright now let's click on next on this page selectcreate project from template so we're gonna create a command line applicationwhich is an application that we can run from the command line it doesn't have agraphical user interface or a GUI now I know command line application isnot as exciting as an application with a graphical user interface like a mobileapp or a desktop app but trust me building an application with a graphicaluser interface is very complicated so for now we're just gonna build commandline applications to learn Java properly once you learn Java properly then youcan learn about building desktop or mobile applications with Java all rightnow let's click on next on this page we have to give our project a name let'scall it hello world now over here you can see the location of this project soit's inside the idea projects folder now right below that you can see the basepackage which is set to comm that code with Marsh on my machine and yourmission is probably gonna be comm dot package what is this well here we talkedabout classes and methods I told you that a class is a container for relatedmethods so we use classes to organize our code by the same token we have aconcept called package and we use a package to group related classes so asour applications grow we're gonna end up with hundreds or even thousands ofclasses so we should properly organize this classus into packages now by convention the base package for a Java project is thedomain name of your company in Reverse so my website is code with mass commthat is why I'm gonna set the base package for this project to come thatcode with Marsh now it doesn't mean that you should have an actual domainregistered on an Internet this is just a way to create a namespace for ourclasses so now every class that we create in this project will belong tothis package we're gonna talk about packages in more detail in the future sofor now just type a base package for your project it can become that yourname or whatever it doesn't really matter all right now let's go forwardalright here's our first Java project now this code editor might look a littlebit intimidating at first but trust me it's really easy and you're gonna learnabout it throughout this course on the left side we have the project panelwhere we can see all the folders and files in a project for example on thetop we have the hello word project inside this project we have the sourcefolder where we have the source code of a project now in this folder we haveanother folder that is calm that code with Marsh that is the name of our basepackage and in this package we have this class main so you can see this main fileopened on the right side here now look at the name of this file its main theJava so all Java files should have the Java extension okay now let's collapsethe project panel by clicking on this icon that is better so see what we havehere on top of this file we have the package statement and this is used tospecify what package this class belongs to so the main class that we have herebelongs to this package now this package statement is terminated by semicolon soin Java wherever we have a statement we should terminate that statement with asemicolon this is exactly like c-sharp or C++ now below this package statementwe have our main class exactly like what you saw in the previous tutorial so wehave public class main with a pair of curly braces inside this class we haveour main method so it's a public method which mayit's accessible from other parts of this program it's static we haven't talkedabout static metals yet we'll talk about them in the future for now just rememberthat the main method in your program should always be static the return topof this method is void which means this method is not gonna return a value andhere in parentheses we have one parameter for this function we can usethese parameters to pass values to our program again we'll look at this in thefuture now right after this parameters as you can see the left brace and thisis where we write the code in this method now by default we have this lineprefix with two slashes this indicates a comment we use these comments to explainour code to other people so these comments don't get executed now let'sremove this comment and write a bit of code to print something on the terminalso here we're gonna use the system class in Java so capital S system here in thistooltip you can see the system class is defined in this package Java dot Lang orlanguage also look at this icon on the left side this indicates a class nowinside this class we have various members we can use the dot operator tosee the members defined in the system class now the member that we're gonnaaccess is out look at the icon of this member it's F which is short for fieldyou're gonna talk about fields in the future when we talk about classes andobject-oriented programming now what is interesting here is the type of thisfield and you can see that on the right side that is print string so printstring is another class that is defined in Java so once again we use the dotoperator to look at the methods or members defined in the print streamclass the method we're gonna use is print Ln which is short for line look atthe icon for this method so M indicates a method now you press ENTER andIntelliJ automatically adds these parentheses as well as a semicolon sonow with the code on line six we're calling or executing the print linemethod earlier I told you that inside this parenthesis we can pass values toour methods here we want to print the hello wordon the terminal so let's type double quotes and inside these quotes righthello world so hello word is textual data in Java whenever we deal withtextual data we should always surround them with double quotes now we say wehave his string so a string is a sequence of characters all right sowe're done with our first program now to execute this we can click on this iconon the toolbar look at the shortcut on Mac it's ctrl + R I always prefer to useshortcuts because they're faster so ctrl + R now IntelliJ is building ourapplication and we can see the result in this little terminal window so here'sour hello work message so that was our first Java program next I'm going toexplain how Java code gets executed under the hoodhey Marsh here I just wanted to let you know that you really don't have tomemorize anything in this course I've put together a comprehensive cheat sheetwith summary notes that you can download below this video so I've done my best tocreate the best possible Java course and I would really appreciate it if yousupport me by liking and sharing this video on the social networks that youuse often also be sure to subscribe and enable the notifications so next time Iupload a video you'll get notified thank you so much and let's continue watching all right now let's see what exactlyhappens under the hood the moment we run a Java program in IntelliJthere are basically two steps involved here compilation and execution in thecompilation step IntelliJ uses the Java compiler to compile our code into adifferent format called Java bytecode this Java compiler comes with the Javadevelopment kit that we downloaded at the beginning of the course let me showyou so here we can right click on this main the Java and in this context menuwe have an item called open in terminal it's down below unfortunately it's notvisible in my recording window it's called open in terminal on Mac andprobably open in command prompt on Windows so let's open that we get thisterminal window or command prompt on windows here we're currently inside ofthis folder code with Maj that is where we have our main the Java file now wecan invoke the Java compiler like this Java C and pass the name or Java file asan argument so main the Java if you're on Mac or Linux make sure to spell thiswith a capital M because these operating systems are case-sensitive so enter nowlet's look at the content of this folder on Mac or Linux we can type LS onwindows we type dir so let's take a look in this folder now we have a new filemain class this is the bytecode representation of this Java file now letme use IntelliJ to run our Java program this class file gets stored somewhereelse let me show you so back to the project panel here in our project wehave this source folder where we our source code and we have this outfolder where we have the result of the compilation so inside this folder wehave production inside this we have hello world the same name as our projectinside hello world we have comm which is the name of our top level package insidethis package we have a sub package that is code with Marsh and here we have ourmain dat class file so this was the compilation step now this Java bytecodethat we have in this file is platform independent and that means it can run onWindows Mac Linux or any operating systems that has a Java runtimeenvironment if you go to java

com slash download we can download java or moreaccurately java runtime environment for various operating systems this JavaRuntime environment has a software component called Java Virtual Machine orJVM this JVM takes our Java bytecode and translates it to the native code for theunderlying operating system so if you're on Windows machine this Java VirtualMachine converts or Java bytecode into the native code that windows canunderstand this architecture is the reason why Java applications areportable or platform independent we can write a Java program on a Windowsmachine and execute it on Linux Mac or any other operating systems that have aJava runtime environment c-sharp and python also have the samearchitecture that's why they are platform independent as well now let meshow you how to invoke this java virtual machine to run a Java program so back tothis terminal window let me expand this currently we are inside of this foldercode with Marsh and in this folder we have this class file now let's go onelevel up so CD dot dot and one more time so now we are inside the source folderwe can invoke Java Virtual Machine like this they type Java and then we type thefull pass to our main class file what do I mean by that well earlier we definedthis package comm that code with Marsh and this class the main class is part ofthis package so the full path this class is calm dot code with Marshdot main make sure to use a capital M here because this is case sensitive nowwhen we press ENTER Java will look at this folder calm inside this folder itwill look at this other folder code with Marsh and then it will find main thatclass in that folder it will load the bytecode and convert it to the nativecode for the operating system we are using so take a look so it executed ourprogram hello world beautiful let me run a program using IntelliJ all these stepsare hidden from us we don't see the compilation or execution steps so you have seen Java in action now letme tell you five interesting facts about Java Java was developed by James Goslingin 1995 at Sun Microsystems which was later acquired by Oracle in 2010 it wasoriginally called oke after an oak tree that stood outside Gosling's officelater it was renamed to green and was finally renamed to Java inspired by Javacoffee that's why its logo looks like this we have four editions of Java forbuilding different kinds of applications we have Java standard edition this isthe core Java platform which is what we're using in this course it containsall of the libraries that every Java developer must learnwe have Java Enterprise Edition which is used for building very large-scale anddistributed systems it's built on top of java standard edition and providesadditional libraries for building fault tolerant distributed multi-tieredsoftware we have java micro Edition which is a subset of Java standardedition designed for mobile devices so it has libraries specific to mobiledevices and finally we have Java card which is used in smart cards the latestversion of Java is Java standard edition 12 which was released just a few monthsago in March 2019 Java has close to 9 million developers worldwide currentlyabout 3 billion mobile phones run Java as well as 120 million TV sets and everyblu-ray player according to indeed

com the average salary of a Java developeris just over $100,000 per year in the US so as we can see Java is everywherewhich means more opportunities for you to get hired as a professionalprogrammer now let me give you a quick overview of how I've structured thiscourse so you can get the most out of it this course is the first part of mycomplete four-part Java series each part is about three to four hours long so itcan easily complete it in a day or two in the first part which is what you'rewatching you're gonna learn the fundamentals of programming with Java inthe next section you'll learn about the type system in Java you will learn howto work with various types such as purrs strings boolean's and arrays bythe end of this section you will build a mortgage calculator as your first Javaproject will be improving this calculator bit by bit routers coursenext you will learn about control flow statements that are used to buildalgorithms we'll be talking about various types of conditional statementsand loops later in this section we'll add data validation to our mortgagecalculator to force the user to enter valid values at this point you'll beable to build basic algorithms and that's greatbut being a good programmer requires knowing how to write good code code thatis clean and expressive that's what separates an outstanding programmer froman average programmer so in the following section we'll talk about cleancoding I will show you various techniques that professional programmersuse to make their code clean and maintainable and finally in the lastsection you will learn how to find and fix errors in your java programs as wellas how to package them for deployment so others can use them so the materials inthe first part will give you a solid foundation on how to start programmingin Java in the second part we'll talk about object oriented programming whichis a style of programming use in most if not all Java applications whether youwant to use Java to build web mobile or desktop applications you need tounderstand object-oriented programming well because otherwise you're going toconstantly hit obstacles in the third part we're going to talk about core JavaAPI is or application programming interfaces you'll learn about many ofthe useful classes in the standard Java library and finally in the last partwe'll be looking at the advanced features in Java such as streams threadsdatabase programming and so on so I hope you're gonna join me on this journey andmaster Java the most popular programming language behind millions of apps andwebsites you intersection we're gonna look at thefundamentals of programming in Java you're gonna learn about variables andconstants primitive and reference types you're gonna learn about casting or typeconversion you will learn how to work with numbers strings and arrays and howto read input from the user once you learn all this I'm gonna giveyou a project you're gonna build a mortgage calculator on your own so makesure to pay great attention to all the materials you're gonna learn becauseyou're gonna use most of them in this project are you ready now let's jump inand get started in this tutorial we're gonna talk about variables in Java weuse variables to temporarily store data in computer's memory here is an exampleimagine in this program you want to store someone's age in the memory so wedeclare a variable like this ant age equals 30 so int or integer is the typeof this variable so in this variable we can only store integers which are wholenumbers like 1 2 3 4 numbers that don't have a decimal point now in Java we haveseveral different types I'm gonna talk about them in the next tutorial so firstwe specify the type of our variable then we give it a name or a label this isalso called an identifier because we use it to identify our variable this equalsign is called the assignment operator and 30 is the initial value that we areassigning to this variable so we say on line 6 we're initializing this variablewhich means we're giving it an initial value you always have to initialize ourvariables before reading them so with this line we're storing number 30somewhere in computer's memory and we're assigning this label to that memorylocation now on line 7 instead of printing hello world we can print thevalue 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 changethe value of our variable so after we initialize it per house we can change itto 35 now when we run this program again we see it 35 beautiful we can alsoinitialize multiple variables on the same line but this is something that Idon't recommend because it makes your code ugly and hard to read here is anexample we can declare another variable like temperature and set it to 20 sousing a comma we can declare multiple variables on the same line now eventhough this is technically possible it's not something that I recommend so it'salways better to declare one variable on each line like this we can also copy thevalue of one variable into another here is an example let me delete thesevariables and declare a new variable called my age we set it to 30 and thenwe declare another variable like her age and we set it to my age so now when weprint her age we're gonna see 30 take a lookso on line seven recapping the value of this variable into this other variablenow one thing I want you to pay attention to here is the convention Ihave used for naming our variables as I told you before this is called thecamelcase notation so we should capitalize the first letter of everyword except the first word so in this case the first word my it's all inlowercase but the second word starts with a capital letter so this is allabout declaring and initializing variables in the next tutorial we'regoing to talk about various types in Java in this tutorial we're going totalk about various types in Java basically we have two categories oftypes we have primitive types for storing simple values and non primitivetypes or reference types for storing complex objects so in the category ofprimitive types we have white which takes one byte of memory and in one bitewe can store values from 128 to 127 now the more bytes we have the largernumbers we can store so next we have short which takes two bytes and withthis we can store values up to 32,000 next we have integer which we have seenbefore integers take four bytes of memory and allow us to store values upto two billion then we have long which takes eight bytes and with this we canstore even larger numbers now all these types are for storing whole numbers thatdon't have a decimal point if you want to store a number that has a decimalpoint you have to use float or double float takes four bytes double takeseight bytes so obviously we double we can store larger numbers next we havechar for storing a single character like ABC and this chart I've take two bytesso they support international letters and finally we have boolean for storingboolean values which can be true or false just like yes or no in English nowlet's take a look at a few examples earlier we use an integer for storingsomeone's age but as you learned integers take four bytes and allow us tostore values up to two billion we don't need four bytes of memory to storesomeone's age all we need is one byte because with one bite we can storevalues up to 127 so I'm gonna change this to byte that is better now let'slook at another example let's say we want to store the number of times aYouTube video has been watched so we define an integer called views countnote that I'm always using meaningful names for my variables because thesenames help us understand what this code does I've seen some people use variablenames like V or V 1 or n nobody knows what these variables do so as a bestpractice always use meaningful and descriptive names for your variables soviews count we set this to a large number like 1 2 3 4 5 6 7 8 9 now inJava whenever you deal with a large number like this you can use anunderscore to separate every three digits just like how we use a comma inour documents to make our numbers more readable we can use an underscore inJava so with integers we can store values up to two billion but let's saythe number of times this video has been watched is three billion so I had athree here now we have a red on the line that indicates an errorlet me hover our mouse over it we see this tooltip integer number too large sowe need to change the type of this variable to long however the error isstill there what's going on here the reason we're getting this error is thatby default Java sees these numbers as integers so even though we have definedthe type of this variable as long Java compiler sees this value as an integerand he thinks this value is too large for an integer to solve this problem weneed to add an L as a suffix or this number we can use an uppercase or alowercase L but as you can see a lowercase L kind of looks like a 1 soit's better to use a capital L so these are examples of whole numbers now let'sdeclare a variable for storing a number with a decimal point so double price weset this to 1099 obviously the double variable is too large for storing theprice of a product so we can change this to float that is better but you have acompilation error here take a look incompatible types required float butfound double the reason we're seeing this error is that by default Java seesthese numbers with a decimal point as double so even though we set the type ofthis variable to float Java sees this number as a double so just like how weadded a suffix to this number to represent it as a long we need to add asuffix here to represent this number as a float and that suffix is F once againwe can use an upper case or lower case F so these are examples of numbers nowlet's store a character so char we call it letter and we set it to a note thatwe should always surround single characters with single quotes andmultiple characters or strings with double quotesokay so char represents only one character string represents a series ofcharacters and finally let's see an example of a boolean so we define aboolean variable called is eligible is this person eligible for loan or not wesaid this to true or false these are the boolean values now note that all thesewords coded in orange are reserved keywords in Javajust like public static void class package these are all reserved keywordsso we cannot use these reserved keywords the name our variables classes andmethods in the last tutorial you learned that we use primitive types to storesimple values like numbers boolean values or single characters in contrastuse reference types to store complex objects like data objects or mailmessages these are complex objects now in Java we have eight primitive typesthat you have seen before all the other types are reference types let me showyou an example so here in this program first I'm gonna declare a primitive typelet's say white age equals 30 now declaring and initializing a referencetype is slightly different from primitive type let me show youso let's type date now here in this tooltip box which is called intellisensewe can see various classes that have date in their name so IntelliJ ishelping us complete our code by suggesting these class names now here wehave a date class in this package Java the util so this package contains a lotof utility classes that are useful in a lot of programs you also have a dateclass in a different package Java SQL or sequel which is used for programmingdatabases so this is the benefit of packages we can have the same class butin different packages they don't conflict so packages create a namespacefor our classes okay now in this case if we select the first date class and pressenter or tab IntelliJ automatically adds this line for us import Java that youtill the date so because currently we are in this package in order to use aclass from a different package we need to import it so here we're importing thedate class in this package will talk about packages in more detail in thefuture so back to our date variable let's give this variable a name collectnow now we set this here we need to use the new operator to allocate memory forthis variable and this is one of the differences between the primitive andreference types when declaring primitive types we don't need to allocate memorymemory is allocated and released by Java Runtime environment but when dealingwith reference types we should always allocate memory now we don't have torelease this memory Java Runtime environment will automatically take careof that so we use the new operator and then repeat the name of our class inthis case date and then we add parentheses followed by a semicolon inthis example this variable we have defined here is an instance of the dateclass so this class is defined template or blueprints for creating new objectsnew instances as another example we can have a class called human and we canhave objects like John Bob Mary and so on so an object is an instance of aclass now this object or this class have members that we can access usingthe dot operator so we can type now dot and these are all the members defined inthis class or in this object for example we have a method called get time andthis returns the time component of this object this is another differencebetween primitive types and reference types these primitive types don't havemembers so if you type age dot we don't see anything these items you see hereare not members of age their code snippets which allow us to quicklygenerate code for example we can select for I and this automatically generatesthis block of code for us we'll talk about this in the future so this agevariable is a primitive type it's not an object it doesn't have any members andthat's why when we use the dot operator we don't see anything here now let'sdelete this line and instead print the value of this data object so once againwe can type system this is a class so we can use the dot operator to access itsmembers here we have out which is a field and the type of this field isprint string which is another class in Java so once again we can use a dotoperator and call the print line function now let me show you a very coolshortcut instead of typing all this we can use one of these code snippets so wetype s oh you see and press tab and this generates this piece of code for us allright now let's pass our data object here note that I have not surroundedthis variable with double quotes because this is a string and if you run thisprogram we'll see now on the terminal there you gowe don't want this you want the value of our data object not a label so let'sremove the quotes I run the program again so here's the current date I'm onmy machine I've learned a little bit about the differences between theprimitive and reference types so you know that we use primitive types forstoring simple values and reference types for storing complex objects butthere's a very important difference between these two categories of types interms of memory management and that's what we're going to talk about in thistutorial so I'm going to declare a primitivevariable X and set it to 1 and then I'm going to declare another variable like Yand set it to X so in this example we have two different variables x and y andthese two variables are at different memory locations so they're completelyindependent of each other in other words if I change the value of X Y is notgoing to get affected let me show you so I'm gonna update X to 2 and then print Yso syu t tab y let's take a look so run as you can see Y is not affectedbecause x and y are completely independent of each other however whenwe use a reference time this behavior is differentlet's take a look so I'm gonna delete all the code here in Java we have apoint class that is defined in this package Java that awt so we press ENTERand now we have this import statement on the top beautiful let's declare avariable like point 1 and set it to new point here we can pass the initialvalues for x and y so I'm gonna pass 1 and 1 so intelligent automatically addsthese labels x and y now just like before I'm gonna declare anothervariable point 2 and set it to point 1 and this is where things get interestingwhen Java Runtime environment executes line 8 first it's going to allocate somememory to store this point object let's see if the address of that memorylocation is 100 then it's going to allocate a separate part of the memoryand it's going to attach this label to that memory location point 1 in thatmemory location it's going to store the address of our point object so this isthe critical difference between primitive and reference types when wedeclare a primitive variable like a byte the value that we assigned to thatvariable will be stored in that memory location but when we use a referencetype like this point class our variable is going to hold the axof that point object in memory not the actual pointer object now look at line 9here we're copying the value that we have in this variable into this othervariable so that value as you learn is not the point object is the address orthe reference to the point object in memory that is why we refer to thesetiles as reference types because they don't store the actual values they storea reference to an object somewhere in the memory so in this example point oneand point two are referencing the exact same point object in memory we only haveone point object so these two variables are not independent of each otherthey're referencing the same object and that means if I update this point objectthrough either of these variables the changes will be visible to the othervariable I'm gonna show you so using the first variable point one we're going toupdate the value of x so we use the dot operator and here we can see the membersof this object X on Y are both fields which are variables that exist inside ofa class so we said X just like a regular variable to a different value let's saytwo now because point one and point two are referencing the exact same object ifwe print point two we're going to see the change that we just madetake a look so S or ut tab let's print point to run the program there you goso the change was visible so remember this reference types are copied by thereferences whereas primitive types are copied by their value and these valuesare completely independent of each other in this tutorial we're gonna look atstrings in Java so earlier in the course we printed the hello world message on aterminal this hello word that we have here is a string or more accurately it'sa string literal that means a string value now let'sextract this from here and store it in a string variable so cut just before thisline we type string now look this string class is defined in Java that Langpackage what is interesting is that we don't have an import statement to importthis package or import this class because this package is automaticallyimported so we can use any classes that are defined in this package now let'sdeclare a variable called message and because this is a reference type weshould instantiate this variable using the new operator so Neal string and herein parenthesis we type our message hello world however here we have this littlewarning take a look new string is redundant because in Java there is ashorter way to initialize string variables let me show you so instead ofusing the new operator we simply set this to our string literal now on thesurface this looks like a primitive type because we are not using the newoperator but this is just a shorthand to initialize a string variable strings arereference types in Java but because we use them often there is a short way tocreate them so now let's pass message to the printline method and run our program you get the exact same result as beforebeautiful now let's look at a few interesting things that you can do withstrings we can concatenate or joining a string with another one using the plusoperator so here we can combine this with another string with two exclamationmarks and here's the result now because string is a class it has members that wecan access using the dot operator so we can type message dot and these are allthe methods or functions do find in the string class for example wehave this method here ends with and with this we can check to see if our stringends with a character or sequence of characters for example here we can passtheir string to see if our message ends with two exclamation marksnow instead of printing the message let's print this expression here solet's run the program we get true so this method that we have called herereturns a boolean value which can be true or false we also have anothermethod starts with let's take a look now in this case we get false because ourmessage doesn't start with two exclamation marks another useful methodis length so we can call that to get the length of a string which is the numberof characters so message dot length take a lookso in this string we have 13 characters and this is useful in situations whereyou want to check the length of the input by the user for example you mighthave a sign-up form with a username field you can check the length ofsomeone's username and give them an error if the username is longer thanlet's say 20 characters pretty useful we also have another method that is indexof and this returns the index of the first occurrence of the character or thestring that we pass here for example if you pass H the index of H is 0 so let'srun the program there you go we get 0 if you pass e we get 1 because the index ofthe first II in this message is 1 now what if you pass a character or a stringthat doesn't exist in this message let's say Skye we get negative 1 so with thismethod we can check to see if a string contains certain characters or words orsentences and so on another useful method is replace and with this we canreplace one or more characters with something else for example we canreplace any exclamation marks with let's say a store so this replace metalhas two parameters one is target the other is replacement and here we'repassing two values for these parameters here's the first value here is thesecond value and we have separated these values using a comma now in programmingterms we refer to this values as arguments a lot of programmers don'tknow the difference between parameters and arguments parameters are the holesthat we define in our methods arguments are the actual values that we pass tothese methods so in this case target and replacement or parameters butexclamation mark and asterisk are arguments now let's run this program andsee what happens so our explanation marks are replaced with stars now whatis important here is that this method does not modify our original string itreturns a new string so if we print our original string right after SRU T tabmessage you can see the original string is not changed because in Java stringsare immutable we cannot mutate them we cannot changethem so any methods that modify a string will always return a new string objectokay we also have another useful method to lowercaselet's take a look so to lowercase converts all charactersto lowercase and once again you can see that the original string is not affectedbecause this method returns a new string okay we also have two uppercase andanother useful method is trim trim and with this we can get rid of extra whitespaces that can be at the beginning or the end of a string sometimes our userstype unnecessary spaces in form fields so using the trim method we can get ridof these white spaces let me show you so I'm gonna add a couple of spaces beforeand after our message now when we trim it these white spaces are gonna getremoved take a look so here's the original string you can see two whitespaces at the beginning and here's our string after trimming so these are someuseful methods in the string class but this glass has more methods than wedon't have time to cover in this lecture but as we go through the course you'regonna learn more about the string class and other useful classes in Java thirdtimes will include special characters in our strings like a tab or a new line ora backslash or double quotes so in this tutorial I'm gonna show you how toinclude these special characters in your strings so here we have the string helloMarsh let's say we want to surround Marsh with double quotes now here's theproblem if we add a double quote here Java compiler thinks this is thetermination of our string so it doesn't stand what we have after that's why wehave a compilation error the fixes problem we need to prefix this doublecode with a backslash so using this backslash we have escapedthe double quote now one more time let's add backslash double code here now let'srun the program and see what we get so we get hello Marsh in double quotebeautiful so double quote is one of those special characters that you needto be aware of another special character is backslash let's say we want to storethe pass to a directory on a Windows machine so that will look like this CDrive backslash windows backslash whatever nowif you want to store this in a string we need to escape each backslash let meshow you so C Drive backslash now we have a problemJava compiler thinks we're escaping the double code here so it thinks our stringis not terminated with another double code but that's not what we want youwant to add a backslash here so we need to prefix our backslash with anotherbackslash now we type windows one more time something let's run the program soeven though we have two backslashes in our code we actually see one backslashin a terminal window in other escape sequences backslash N and we use that toadd a new line to our strings so let's change this to backslash N and run theprogram to see what happens now our string is broken down onto multiplelines by the first line we have C Drive then we have Windows so wherever we hada backslash n Java will insert a new line we can also add a tab in ourstrings so if you add backslash T here therewill be a tab which means C Drive and windows let's take a look so C Drivehere we have a tab and then windows now in Java we have a few more escapesequences but quite honestly they're hardly used so remember these fourescape sequences that we cover in this tutorial in this tutorial we're going to talkabout arrays in Java we use arrays to store a list of items like a list ofnumbers or a list of people or a list of messages let me show you so here we havean integer variable you want to convert this to an integer array so right afterint we add square brackets now we have a compilation error because we're storinga single number in this array so to fix this we need to remove one becausearrays are reference types we need to use the new operator here then we repeatthe type one more time enter a and here in square brackets we specify the sizeor the length of this array how many items do we want to include in thisarray let's say five also we should change the name of this variable fromnumber two numbers because we're dealing with a list of items so always payattention to the name of your variables now you can access individual items inthis array using an index so we type numbers square brackets to reference thefirst element or first item we use zero now we can set this to a value like 1similarly we can set the second item to 2 now what if we use an invalid indexlet's say 10 this array doesn't have 10 items so let's see what happens numbersof 10 we said this to 3 when we run this program we get an exception exceptionsare Javas way to report errors so in this case an exception was raised andour program crashed we'll talk about exceptions in detail later in the courseso now let's remove the last line and treinta sorryso sou t tab numbers let's see what we getwe get this weird string in sort of the items in our array here's the reasonby default when we print an array Java returns the string which is calculatedbased on the address of this object in memory so if you have another array andwe print that we're gonna see something different because each object is gonnabe in a different memory space okay now how can we see the actual items in thisarray well we have a class in Java called arrays let me show youarrays so this class is defined in Java that util package let's press ENTER nowthis is important on the top beautiful so we can use the dot operator to accessthe members of this class here we have a method called two string now as you seeit this method is implemented multiple times so in the first implementationthis method gets a float array in the second implementation it takes aninteger array and so on so for all primitive types as well as referencetypes this method is implemented multiple times this is what we callmethod overloading now we can call this method and pass our integer array andthis will return the string representation of this array so we cancut this from here and pass it to our print method like this now let's run theprogram one more time and here's our array beautiful so the first two itemsare initialized the others are set to 0 by default because here we're dealingwith an integer array if you had a boolean array all items why default getinitialized to false if you have a string array all items get initializedto an empty string okay now this syntax for creating andinitializing an array is a little bit tedious and it's an older syntax thereis a newer way to initialize an array if we know the items ahead of time like inthis case so I'm going to remove these two lines I'm also gonna remove the newoperator here we use curly braces and inside these braces we add all the itemsin this array let's say 2 3 5 1 & 4 now we have 5 items so the length of thisarray is gonna be 5 we can read that using the lengthsso if we type numbers dot look here we have is filled look at the icon it's anF so this is a field which is like a variable in a class and the type of thisfield is an integer so this returns the number of items in this array let's getthat and printed using our print method like this take a look so we get five nowin Java arrays have a fixed size so once we create them we cannot add or removeadditional items to them they have a fixed length if you want to be able toadd or remove additional items from an array you should use one of thecollection classes that we'll talk about later in the course for now all I wantyou to remember is that arrays have a fixed length now currently our array isnot sorted these numbers are in some kind of random order we can easily sortthis array using the sort method of the arrays class let me show you so I'mgonna remove this line and call arrays dot sort once again you can see thismethod is overloaded because it's implemented with different parametertypes so we call this method and pass our numbers arraynow when we run this program we can see our array is sorted beautiful so yeah I've learned that we use arraysto store a list of objects in Java we can also create multi-dimensional arraysfor example we can create a two-dimensional array to store a matrixor we can create a three-dimensional array to store data for cube these areuseful in scientific computations let me show you so here we have a singledimensional array to convert this to a two-dimensional array we need to addanother pair of square brackets now we have a compilation error because we needto repeat these brackets on the other side so let's say we want to create a 2by 3 matrix so 2 rows and 3 columns we add in other brackets here and changethese lengths to 2 and 3 so now we have 2 rows and 3 columns now to accessindividual items in this array we need to supply two indexes first the index ofthe row so we can go to the first row and then the first column and initializethat to 1 now let us print this so and so you t-tap once again we use ourarrays class dot to string and pass this objecttake a look once again we get this weird string because here we're dealing with amulti-dimensional array to solve this problem we need to use another method inthis class called deep to string use this for printing multi-dimensionalarrays take a look now we have this matrix which has two rows and in eachrow we have three columns we can also create a three dimensional array all wehave to do is to add another pair of brackets and specify the length of thatdimension pretty easy now what about the curly brace syntax let me show you solet's revert this back to a two dimensional array we're gonna get rid ofthe new operator and use curly braces now let's say in this matrix we're gonnahave two rows and three columns so each row is an array itself because it's alist of items right so we add another array here let's say 12 3 then comma now we add the second row which is another array in this row we'regonna have 3 numbers 4 5 & 6 now let's remove this line we don't needit anymore and print this array so here's the end result you have learned alot about variables ya learned that when declaring them we need to initializethem and we can always change their value later on throughout the lifetimeof our programs however there are times that we don't want the value of avariable to change for example let's declare a variable called pi and set itto 3

14 now here we need to add an F to represent this as a float because bydefault Java compiler sees this number as a decimal okay now you know that weuse pi to calculate the area of a circle what if before we calculate the area ofa circle I come here and type pi equals 1 then all our calculations are gonnaget messed up we don't want this to happen that's when we use constants soif we type final here Java compiler will treat this as a constant so once weinitialize this we cannot change its value later on you can see here we havea compilation error and it says cannot assign a value to final variable pi sopi is a final variable or a constant now by convention we use all capital lettersto name constants so this should be PI beautiful now I tell you a little sidestory in one of my early courses that I created years ago that was c-sharpbasics for beginners there I used the same example to teach the concept ofconstants but I pronounce this word as P instead of Pi and believe it or not tothis day people make fun of me for saying P instead of Pi but that's how welearned this back in Iran we pronounce it as P and I think Greek people alsosay P but anyway I just thought to share this video to change the mood now you'redone with constants next we're gonna talk about arithmeticexpressions in this tutorial we're going to talkabout arithmetic expressions in Java so in Java we have the same arithmeticoperators that we have in math we have addition subtraction multiplicationdivision and modulus which is the remainder of a division let's look at afew examples so I'm gonna declare an integer called result and here we cantype 10 plus 3 now when we print result it's gonna be 13 pretty straightforwardthere you go so this is addition we also have subtraction multiplication divisionis an interesting one let's take a look so here the result is a whole numberbecause in Java the division of two whole numbers is a whole number if youwant to get a floating-point number here you need to convert these numbers to afloat or a double let me show you so we prefix this number withparentheses and in parentheses we type double now we are casting or convertingthis number to a double similarly we should do that here and now we have acompilation error because on the left side we declared an integer but here theresult of this expression is a double and by the way an expression is a pieceof code that produces a value so what we have here is an expression because itproduces a value so to fix this problem we need to change this to double nowwhen we run this program we get this floating point number beautiful so theseare the arithmetic operators and these numbers that we have here are calledoperands we also have increment and decrement operators let me show you soI'm gonna declare a new variable int X we set it to 1 now if you want toincrease the value of x by 1 we use the increment operator now let's print thison a terminal so we get 2 there you go we can apply this operator as a postfixor as a prefix and we get the same resulttake a look too however if we use this on the right side of an assignmentoperator we get different results let me show you so I'm gonna declare anothervariable Y we set it to X plus plus in this case because we have applied theincrement operator as a postfix first the value of x will get copied to Y so Ywould be 1 and then X will be incremented by 1 so if you print x and yx is gonna be 2 and Y is gonna be 1 take a look so X is 2 and Y is 1 beautifulhowever if you apply this as a prefix first X will be incremented by 1 so itwill be 2 and then it will be copied to Y so in this case bothX&Y will be to take a look so we get two and two now what if you want toincrement X by more than one let's say by two well there are two ways to dothis let's remove Y we don't really need it anymore we can write x equals x plus2 so first we add 2 to X the result will be three and then three will be copiedinto X the other way is to use the Augmented or compound assignmentoperator so we can write X plus equals two what we have on line eight isexactly identical to what we have on line seven well as you can see it'sshorter so this is a better way to write the same code now this is one of theAugmented assignment operators we have the Augmented assignment operator forother arithmetic operators so we can type X minus equals 2 and this wouldreduce the value of x by 2 we also have multiply and divide so these are theAugmented or compound assignment operators right now I've got a questionfor you here we have declared this variable X it goes to 10 plus 3 times 2what do you think is the result of this expression the result is 16 let's runthis program and find out so run there you go we got 16 but why well this is avery basic math concept that unfortunately a lot of people don't knowin math the multiplication and division operators have a higher priority so theyget applied first in this example this expression 3 times 2 is evaluated firstthe result is 6 and then 6 is added to 10 that's why we get 16 now if you wantto change the order of these operators you can always use parentheses forexample if you want this expression to be evaluated first we wrap it inparentheses so like this now Java compiler will first evaluate thisexpression the result will be 13 and then 13 is multiplied by 2 so we get 26take a look there you go so be aware of the order ofthese operations parentheses always have the highest priority then we havemultiplication and division and finally we have addition and subtraction in thistutorial we're going to talk about casting and type conversion so I'm gonnadeclare a short variable call X and set it to 1 and then I'm gonna declare aninteger called Y and set it to X plus 2 in this example we're adding a short toan integer what do you think the result is gonna be well let's take a lookso sou t let's print Y we get 3 that is what you were expecting but let meexplain what happens under the hood for this expression to get executed becausewe're dealing with two different types of values one is a short the other is aninteger one of these values should be converted to the other type so they areequal now I got a question for you how many bytes do we have in a shortvariable we have 2 bytes how many bytes do we have in an integer 4 bytes so anyvalues that we store in a short variable can also be stored in an integervariable right so when this piece of code is gonna get executed this iswhat's gonna happen first Java looks at the value in this variable it's 1 rightit's going to allocate another variable an anonymous variable somewhere inmemory we don't know where that is we don't know the name of that variable itdoesn't have a name it's anonymous that variable is gonna be an integer thenJava is gonna copy the value of x into that memory space and then it will addthese two numbers together this is what we call implicit casting let me type ithere implicit casting that means automatic casting or automaticconversion we don't have to worry about it whenever we have a value and thatvalue can be converted to a data type that is bigger casting or conversionhappens implicitly or automatically so byte can be automatically converted toshort and this can be converted to int and long okaynow what about floating-point numbers let's look at an example I'm gonnachange this to a double one point one now here we have a compilation errorbecause on the right side of the assignment operator we have afloating-point number a double on the left side we have an integer so we needto change this to double now when we execute this code we're gonna get 3

1let's verify this there you go now let's see how casting happens here in thiscase we're dealing with a double and an integer an integer is less precise thana double because in a double we can have digits after the decimal point so inthis example Java is going to automatically cast this integer to adouble so that will be two point zero and then two point zero will be added toone point one okay so back to this chain here we're gonna have float and thendouble so as a general rule of thumb implicit casting happens whenever you'renot gonna lose data there is no chance for data loss now what if you want Y tobe an integer so in this example we don't care about the digits after thedecimal point you want to see three on the terminal how should we do this thisis where we should explicitly cast the result so we should cast X to an integerlike this parentheses int this is explicit casting we convert X to aninteger so the result would be one without a decimal point one will beadded to 2 and Y would be three take a look there you go so this is all aboutimplicit and explicit casting now this explicit casting can only happen betweencompatible types so all these types are compatible because they're all numbersbut we cannot cast a string to a number in other words if X was a string likethis let's say 1 we cannot cast eggs to an integerbecause they are not compatible so how do we do thiswell for all these primitive types you have learned you have wrapper classes soin Java we have a class which is a reference type called integer this classis defined in Java the Lang package and in this class we have a method calledparse int so this method takes a string and returns an integer so integer is thewrapper class for the int primitive type we also have short and in this class wehave parse short so it takes a string and returns a short similarly we havefloat and double and obviously the name of these metas are different so here wehave parse float so back to this example let's say we get X as a string and wewant to convert it to an integer this is how we do itinteger dot parse int we pass X here and then add it to take a look so we get 3you might be curious why this matters why should we parse or convert a stringto a number to add it to something else well pretty much in most frameworks forbuilding user interfaces whether you're building a desktop or a mobileapplication or web application we always receive input from the user as a stringso if you have a form with a bunch of text boxes or drop-down lists almostalways we get values as a strings so that's why we need to convert thesestrings to their numeric representation ok now what if X is a floating-pointnumber here what will happen when we try to parse this as an integerlet's take a look once again we get an exception which is how Java reportserrors to our programs we're going to talk about exceptions in detail in thefuture so if the user enters one point one wecannot use this method instead we should use float or double let's say doublebecause that's easier double parse double so we parse this number as adouble add two to it and then store the resultin a double and then we will get 3

1 beautiful next we're gonna look at themath class for performing mathematical operations in this tutorial we're goingto look at the math class for performing mathematical operations so in Java wehave this math class that is defined in Java that Lang package so it's alwaysthere we don't need to explicitly import it now this class has a number of usefulmethods the first method I'm gonna show you is the round method and with this wecan round a floating-point number to a whole number so as you can see thismethod is overloaded which means it's implemented twice in the firstimplementation it takes a float and returns an int and a secondimplementation it takes a double and returns a log so let's pass 1

1 as afloat to this method and store the result in an integer like this now weprint the result and we get one beautiful another useful method is sealor sealing which returns the smallest integer that is greater than or equal tothis number so the ceiling of 1

1 is 2 now here we have a compilation errorbecause this method returns a double but we're storing the result in an integerso here we need to explicitly cast this to an integer and now you can see theceiling of this number is 2 we have another useful method that is floor sothe floor of a number is the largest integer that is smaller or equal to thisnumber in this case it's gonna be 1 let's take a look there you go anotheruseful method is max which returns the greater of two values and once againthis method is overloaded so in the first implementation we get two integerswe have other implementations for longs floats and doubles so let's pass twointegers here one and two this will return the greater number which is 2there you go similar to this we have min is pretty straightforward inthe useful method is random for generating a random value between 0 and1 once again we get a compilation error because this method returns a double solet's change that to double now every time we run this program we get adifferent number and this number is a floating-point number between 0 to 1 nowwhat if you want a number between 0 to let's say 100 instead of 0 to 1 well wesimply multiply this by 100 take a look so every time we run this we get adifferent number between 0 to 100 now if we don't want these digits after thedecimal point we can either round this number or cast it to an integer let meshow you so we can call math that round and pass the result of this expressionso I'm gonna cut this add parenthesis to call the round method and then pastethat expression now let's run this code so every time we get a double we stillhave the fraction here so we can change the type to an INT now we have acompilation error because the round method returns a long but here we havedeclared an integer this is one of those cases where implicit casting cannothappen because we have a value that is represented in 8 bytes of memory and youwant to store that in a variable that has only 4 bytes of memory so implicitcasting doesn't work but we can use explicit casting because we know theresult of this expression is a number between 0 to 100 so we can definitelystore it in an integer so let's add int here now let's run this again there yougo now what if we don't use the round method here let's see what happens soI'm gonna remove the call to the round method and simply I apply this castingover here let's see what we get now every time we run this program we get 0do you know why because here we're applying this casting to the result ofthis method call not this entire expression as you saw earlier every timewe call the random method it generates a number between 0to one so when we cast that number to an integer we'll lose the fraction wealways get zero and zero times 100 is zero to solve this problem we need towrap this entire expression in parenthesis so we add parentheses aroundthis and now let me run this we get an integer between 0 and 100 quite oftenwhen we worked with numbers we need to format them as currency values forexample we might have a number like this imagine this is the price of a productto display this to the user you want to add a dollar sign here and separateevery three digits with a comma or if you might have a number like 0

1 and wewant to represent this as a percentage value so instead of 0

1 you want todisplay 10% so in this tutorial I'm gonna show you how to format numbers inJava we have this class number format that is defined in Java the text packagein this package we have a lot of classes for handling text dates numbers and soon so let's press ENTER here it's important on the top beautiful now Iwant to declare a variable so let's give this variable a name currency now weneed to instantiate this new number format however we get a compilationerror here let's take a look number format is abstract it cannot beinstantiated so in Java we have this concept of abstract classes so someclasses are abstract and they're basically like a half-baked cake wecannot use the new operator to create an instance of them we're going to talkabout abstract classes and why they exist later in the course for nowremember that we cannot create an instance of the number format classbecause it's abstract so there is another way let me show you this classhas a bunch of methods that start with get so we have get currency instance andwhen we call this method this will create an instance of the number formatclass and return it so instead of using the new operator we're gonna use thismethod here this is what we call a factory method because it's like afactory it creates new are jects now look at the return type ofthis method it's a number format object okay so we call this method now we getthe return value and store it in a variable of type number format calledcurrency okay let me say improperly zoom out so you can see all the code thereyou go so on the right side of the assignment operator we're calling theget currency instance method we get the result which is a number from an objectand store it in this variable okay now I'm gonna zoom in so you can see clear aname alright that's better now this objecthas a method for formatting values once again you can see this method isoverloaded we have multiple implementations we can give it a long ora double or whatever so I'm gonna call this method and pass a value like onetwo three four five six seven point eight nine one so we have three digitsafter decimal and a few other digits here now this method will return astring representation of this number formatted as a currency so let's getthat and store it in a string variable like result and then we're gonna printresult on a terminal see what we get so we get this dollar sign every threedigits are separated using a comma and we only have two digits after thedecimal point so this class is very handy in formatting numbers ascurrencies we have another method for formatting a number as a percent andthat is get percent instance right now it returns an instance of the numberformat class specialized for formatting numbers as a percent so we need torename this variable from currency to percent now we don't want to manuallychange this because there are multiple references to this variable this otherreference was not updated so let me show you the proper way to rename objects inintellij if you right click here you can see this refactor menu and here we haverename now look at this shortcut on the right side unfortunately it's notvisible in my recording window but on Mac is Shift + FI always use shortcuts because they're faster so let's press shift and f6 nowwe get this red box and below this we can see a few suggestions for a bettername we can choose one of these or pick our own name I'm gonna change this topercent and note that as I'm typing this the other reference gets updatedautomatically so this is very helpful now let's press Enterokay we're done with renaming now let's pass a different value here so let's saywe have a number like 0

1 we want to format this as a percent let's run theprogram there you go you get 10% beautiful now let me show you a cooltechnique in this program we don't really need this percent object becausewe have used it in a single place it would make sense to have this as aseparate variable if you have multiple references to it so what can we do herewe can completely get rid of this object so let's delete this piece of code we'rebasically calling this method of the number format class as you know thismethod returns a number format object so right after calling this method andbefore the semicolon we can use the dot operator to access the methods ormembers of the number format object so here we call the format method straightaway and pass our value this is what we call method chaining we're chainingmultiple methods together so here's one method and here's another method nowthis returns a string so we can store it in this result variable let me cut thisexpression from here and put it over here now we have double semicolons I'mgoing to delete one of them all right beautiful in this tutorial I'mgonna show you how to read input from the user in Java we have this scannerclass that is defined in Java did util package let's import this and create ascanner object so new scanner now here inside this parenthesis we need tospecify where we're gonna read data from we're gonna read it from the terminalwindow are we gonna read it from a file or what to work with the terminal windowwe type system dot in this is one of the fields in the system class a fill as Itold you before is like a variable that we define in a class so we have systemthat in we also have system that out which we used to print something on theterminal right now let's use system that in and terminate this statement with asemicolon now this object has a bunch of methods for reading data and all thesemethods start with next so we have next byte for reading a byte we have nextline for reading a line we have next boolean for ending a boolean and so onso let's call the next byte method and see what we getthis returns a byte value so we can store it in a byte variable let's saysomeone's age and then we print it on a terminal saying you are plus h so herewe're concatenating a string with a byte and in this scenario we're gonna haveimplicit casting or implicit type conversion so Java will automaticallyconvert this byte variable here tray string so they can be added togetherokay now let's run this program and see what happens so here in the terminalwindow we can type 20 enter and it says your 20 beautiful but this is prettyboring let's add a label here and ask the user to type something for examplebefore reading data we're gonna call the print line method and say age : nowlet's run the program so we get this label here however whatever we type willappear on the next line this is because the print line method adds a newline after this label the Soviets issue recall the print method now let's runthe program one more time we get this popup box because our program hasn'tfinished execution so we need to tell IntelliJ that you want to stop and rerunthis program all right now whatever we type appears right in front of thislabel beautiful ENTER we are 20 now what if we type a floating-point number like20 point 1 we get an exception because this method can only parse white valuesif you want to get a floating-point number we need to call next float ornext double what if you want to read our string we don't have next string we havenext and next line let's look at the differences so first I'm going to callthe next method here we have a compilation issue because this methodreturns a string I'm gonna change this to a string let me collapse this that'sbetter we should also rename this variable sowhat was the shortcut Shift + f6 now let's train just a name enter beautifuland one last time we should also update the label name run the program so I'mgonna type my name here Marsh it says your Amash pretty under for one moretime this time I'm gonna type my full-name maha Madani but we don't getthe last name here's the reason these wars that we have here these are calledtokens every time we call the next method it reads one token so here wehave a space we have two tokens and we need to call the next method two timesto get the full name the first time we call it it returns Marsh the second timewe call it it returns Hamid ani then we need to combine this suit together thisis not ideal so that's when we use the next line method with this method we getthe in turn line that the user enters no matter how many spaces or tabs are theretake a look so Marsh comma Donny and we get the full name nowwhat if I type a few spaces before my name let's see what happensso those spaces also appear here and this looks a little bit odd this iswhere we use the trim method remember we trim we can get rid of all these whitespaces before or after a string so this next line method returns a string thatwe are storing in this variable right now just before storing the result inthis variable here we can use the dot operator to access the members of thisstring object so we call the trim method and then store the result in thisvariable once again we're chaining multiple methods here let's run theprogram so a few spaces Maharani and you get this beautiful output right now it's time for a project I wantyou to use what you have learned in a section and build a mortgage calculatorlike this so when you run this program we get a few questions the firstquestion 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 threepoint nine two percent and the third question is period in years let's sayyou want to get a loan for thirty years so this program calculates our monthlypayments and displays it as a currency this is a great exercise for you topractice all the materials you learn in this section now before you get startedI want to give you a few hints here is a formula for calculating the mortgage orthe monthly payments I found this page on wikiHow comm is called calculatemortgage payments so let's see how this works mortgage equals P or principal orthe amount we're gonna loan multiplied by R which is our monthly interest ratethis is very important so this number that we get here is our annual interestrate we need to divide this by 12 also take into account that this number isrepresented as a percent to calculate the actual interest rate you need todivide this number by 100 so in this example the interest rate is zero pointzero three nine two so whatever the user enters divided by 100 and then dividedby twelve to get to the monthly interest rate now we have this monthly interestrate we need to multiply this by this expression here we need to add 1 to thisinterest rate and raise it to the power of n where n is the number of paymentsso we need to multiply this number by 12 or 12 months to calculate the number ofpayments now to raise this number to the power of n you need to use the powermethod of the math class so this math class has this power or power methodthat takes two arguments or two values a and B so go ahead and spend ten tofifteen minutes on this exercise when you're done come back see my solution all right let's see what I've done hereand by the way don't worry if your coat is different from minewe all think and coat differently so it's perfectly fine if your code isdifferent just look at my coat see what I've donehere and see if there are ways you can improve your coatthat's what matters okay so here in our main method first I've declared twofinal variables or constants the first one is months in year whichI've set to 12 and the second one is percent which I've set to 100 the reasonI declared this constant is that I didn't want to have magic numbers inthis code so over here where we calculate the monthly interest we getthe annual interest divided by percent and then months in here this code isvery self-explanatory someone else reading this code we'll have no problemunderstanding what's going on here in contrast if you had a magic number herelike divided by 12 and then for whatever someone else reading this code wouldwonder what is this for doing here what is 12 it's quite obvious to you that 12is the number of months in a year but trust me sometimes other people cannotsee this straight away so as a best practice avoid magic numbers in yourcode always use constants or final variables to describe themso let's revert this back all right so after declaring this constant I'vecreated this scanner object here we ask the first questionprinciple and we read the answer as an integerI thought integer is a good datatype for storing the principle because short isnot enough with short we can store a maximum of $32,000 that's not enoughwhat if someone wants to find us $1,000,000 so int is good and it allowsus to store a value up to two billion next we ask the second question annualinterest rate we read this as a float here I could use double but the interestrate is a small number so float is sufficient for that we don't really needdouble so we get the annual interest and then based on that we calculate themonthly interest also see how I have named my variables all variables have aproper meaningful names there are no magic words here like MI as it short formonthly interest or m1 or m2 do not use magic names foryour variables always use meaningful and descriptive names alright next we getthe period we read this as a byte because the maximum number we want tosupport is 30 so one byte is sufficient to store the number 30 or anythingsmaller now based on the number of years we calculate the number of payments notethe camel notation here I've capitalized the first letter of every word exceptthe first word so we get the Earth's and x months in hereagain the code is very self-explanatory once we collect all this data then wecalculate the mortgage so we get a principal multiplied by this expressionand then divide it by this other expression let's have a quick look herenow this looks a little bit complicated so if you're not download my source codelook below this video I'm attached it for you to download and finally after wecalculate the mortgage we use the number format class to format this value as acurrency so we get a result store it in this string mortgage format it and printit over here now here we can also avoid declaring this variable and simply addthis expression over here but it decided to do this to increase the readabilityof this code otherwise this line would be so long but that's just my personalpreference you don't have to follow this alright so this was my implementation ofthe mortgage calculator however this program has a number ofproblems the first problem is input validation so if we run this and enter anon numeric value like XYZ our program crashes or as another example if weenter a negative value here our program is not gonna behave properly so that'swhere conditional statements come to the rescue in the next section we're goingto talk about conditional statements you will learn how to use these statementsto validate the values entered by the user so that brings us to the end ofthis section I hope you learn a lot and thank you for watching so in this section you'll learn allabout variables and constants you learn about primitive and reference types youlearn that primitive types store simple values but reference types holdreferences to complex objects that's why we call them reference types you alsolearn about casting and type conversion you learn about two types of castingimplicit and explicit you learn how to work with numbers strings and arrays andfinally you learned how to read input from the terminal I hope you learned alot I've been enjoying the course so far in the next section we're going to lookat conditional statements for controlling the flow of our programs soI'll see you in the next section hey Marcia I just want to make a quickannouncement this course you've been watching is actually the beginning of mycomplete Java series in this course we only talk about the basics but in mycomplete series we go way beyond that so if you're serious about Java if you'relooking for a job as a Java developer I highly encourage you to enroll in mycomplete Java series it's exactly the same structure the same quality but ithas way more content plus you will get a certificate of completion that you canadd to your resume so if you're interested I put the link down below youcan get the course with a discount and if you're not happy for any reasons youcan ask for a refund within the first 30 days so I hope to see you in the coursein this section we're going to look at control flow or controlling the flow ofexecution of our programs you're gonna start off by talking about comparisonoperators for comparing values then I'm gonna talk about logical operators likethe logical and logical or and logical not we use these operators forimplementing real world rules and then we're gonna talk about three differenttypes of control flow statements we're going to talk about conditionalstatements for making decisions in our programs then we're going to talk aboutloops for executing code repeatedly and finally we're going to revisit ourmortgage calculator and add error handling to itso if a user enters an invalid value we keep asking them to try again all rightnow let's jump in and get started we're gonna start this section by talkingabout comparison operators we use these operators to compare primitive valuesfor example our x on y equal or not so I'm gonna declare two integers x and ynow let's compare this to see if they're equal or notso first I'm gonna add this print line statement now to compare these variableswe type x equals y so here we have two equal signs and this is the Equalityoperator don't confuse this with a single equal sign that we use forassignment that is the operator used over here okay so two equal signsrepairs the Equality operator now when we runthis program we get true because these values are equal this expression that wehave here is called a boolean expression so earlier I told you that an expressionis a piece of code that produces a value this piece of code produces a booleanvalue true or false that's why we refer to it as a boolean expression we alsohave the inequality operator so when we run this program we're gonna see falselet's take a look we get false because these two variables are equal so theexpression X is not equal to Y returns false we also have greater than greaterthan or equal to less than and less than or equal to so if I change Y to 2 thisexpression is gonna evaluate to true because X is less than or equal to Ytake a look there you go next we're going to talk about logicaloperators in the last tutorial you learn that a boolean expression produces aboolean value now there are times we want to combine multiple booleanexpressions let me show you so I'm going to declare an integer called temperatureand set it to 22 next we declare a boolean variable is warm now we want tocheck to see if temperature is greater than 20 and less than 30 so we write aboolean expression like this temperature greater than 20 here we need to use theend operator so these two ampersands represent the logical and operator inJava after this we add our second conditiontemperature less than 30 now if both these conditions are true the result ofthis boolean expression is going to be trueotherwise if at least one of these is false the result would be false let'stake a look so I'm gonna print is warm on a terminal the result is true but if you change thetemperature to let's say 12 the result is gonna be false and this is how thisworks Java will evaluate this expression from left to right first it looks at thefirst condition the first condition is false because temperature is not greaterthan 20 so because this expression is false it doesn't matter what we haveafter the and operator Java will ignore the other expressions because the andoperator will return true if both conditions are true okay now let's lookat another operator that is the or operator so I'm going to delete all thiscode and start with a new example let's declare a boolean has high income we setit to true and another boolean has good credit we set this to true as well solet's say we're building an application for processing loans we want to see if anew applicant is eligible for a loan or notso we declare another boolean is eligible and by the way look at thenames I have used for these variables they're very meaningful and descriptiveso here's the rule an applicant is eligible if they have high income orgood credit if one of these conditions is true they are eligible so we writehas high income or so these two vertical bars represent the or operator so ifthey have high income or good credit then they are eligible so with the oroperator if at least one condition is true the result will be true in thisexample when Java evaluates this expression it starts from the left sidethis boolean variable is true so it doesn't matter what we have after Javawill not evaluate the rest of this expression it simply returns truehowever if this variable was false Java would continue evaluating thisexpression hoping that the next boolean value or the next boolean expression istrue so this is the or operator and finally we have the not operator that weuse to reverse a value let me show you how that worksso let's declare another boolean variablehas criminal record we set this to false so here's the rule we want to implementin order for someone to be eligible for a loan they should either have highincome or good credit and they should not have any criminal records so let'ssee how we can implement this rule we have implemented the first part theyshould either have high income or good credit now we want to make sure theydon't have any criminal records so we need to combine the result of thisexpression with this boolean value using the and operator so first we wrap thisexpression in parentheses then we apply the end operator and here we add hascriminal record now you want to make sure they don't have criminal record andthis is where we use the not operator so the not operator will reverse the valueof this boolean variable or expression in this case this variable is set tofalse so when we apply the not operator to it the result would be true so if thefirst condition is true and the second condition is true then that person iseligible for a new loan so as you can see these logical operators are veryuseful in implementing real word rules next we're going to talk about ifstatements in this tutorial we're going to look at if statements in Java ifstatements are extremely important because they allow us to build programsthat can make decisions based on certain conditions here's an example in thisfile we have a bunch of conditions if temperature is greater than 30 perhapsyou want to display two messages to the user it's a hot day drink plenty ofwater otherwise if it's between 20 and 30 you want to print it's a nice day andotherwise we want to print it's a cold day so let's see how we can implementthese rules in a Java program back to our main file we start by declaring avariable temperature we set it to 32 now we use an if statement followed by apair of parentheses inside this parenthesis we typean expression or a boolean value so let's say temp is greater than 30 now ifthis condition is true the statement that we had after this if statement willbe executed so let's print it's a hot day let's run the program we get thismessage because temperature is greater than 30 now what if you want to printanother message like drink plenty of water here we should add curly braces todefine a code block so if this condition is true all the code that we have insideof this block would be executed let's add another message here drink waterokay so this was our first condition now let's add a second condition so afterthe right brace we type LS if once again we add our parentheses and inside theseparentheses we type a boolean expression if 10 is greater than 20 and it's lessthan or equal to 30 you want to print a different messagelike beautiful day now here I haven't added the braces because we have asingle statement so braces are only required if we have multiple statementsnow this is a little bit controversial some people believe we should always addbraces whether we have a single statement or not other people likemyself believe this creates unnecessary noise in the code in this tutorial I'mgonna add the braces first and then remove them so you can see thedifference so let's add a pair of curly braces here and finally our lastcondition so if none of these two conditions are true let me print adifferent message so here we simply type LS we don't have any more conditions solet's add a code block and print cold day now let me define a few terms herewe have an if statement and this statement has three clauses or threesections here's the first Clause here's the second Clause and here's the thirdClause pay attention to how a formatted this if statement so first we have theif Clause the else if and else clauses are placed after theseright braces so we have some kind of hierarchy here here we have a parentfollowed by two children now let's get rid of these unnecessary braces andreformat our code to see the difference so I'm gonna remove the braces for theelse clause and also one more time here that's better now we can simplify thisboolean expression basically we don't need this piece of code here here's thereason if the first condition is not true what does it mean that means thetemperature is less than or equal to 30 so this expression here is unnecessarylet's delete this and simplify our code that's better now look at how this codeis formatted on the top we have if the else if Clause is a little bit indentedbut the else Clause is not indented it's at the same level as the if Clause andthis looks a little bit ugly the code is not symmetrical so if you want to getrid of the curly braces a better way to format this code is like this so insteadof adding the else if or else classes after curly braces we add them on a newline now all these clauses are at the same level the code is easier to read inthis tutorial I'm gonna show you a very cool technique for simplifying ifstatements so let's start by declaring a variable called income and set it to120,000 now here we can use an underscore in between these three digitsto make our code more readable now let's say we want to declare a booleanvariable called has high income if the income is more than $100,000 you want toset this to true otherwise we want to set this to false so here we can writean if statement like this if income is greater than $100,000 we want to set hashigh income to true however we get a compilation error herelet's take a look declaration not allowed hereso we cannot declare a variable here we can only declare variables inside codeblocks like this code block over here so to declare this variable we need to addcurly braces to define a new code block now we have a different problem thisvariable that we have defined is scoped to this code block so it's onlyavailable here we cannot access it outside of this block let me show you soif we print has high income you can see we have a compilation error cannotresolve symbol has high income because this variable is not available outsideof the block in which it's declared so to solve this problem we can declarethis variable after setup this block boolean has high income and then we cansimply set it to true in this block now we don't need these braces anymore solet's simplify the code we add an else clause otherwise we said has high incometo false let's remove this print method we don't need it anymore so this is oneway to implement this scenario but this code looks very amateurish aprofessional programmer doesn't write code like this let's improve it step bystep one way to improve this is to give this boolean variable an initial valuefor example we can set it to false initially and then we implement thiscondition so if the income is more than $100,000 then we set this variable totrue with this we no longer need is else Clauseso that was one improvement but it's still not ideal in situations like thiswe can completely get rid of this if statement here let me show you insteadof hard-coding false here we type our expression income is greater than$100,000 so here we have a boolean expression if this boolean expressionevaluates to true this boolean variable is going to be true otherwise it's goingto be false so this is the simplest the most elegant and the most professionalway to implement this scenario now one more improvement before we finish thistutorial I personally prefer to wrap thisexpression in parentheses even though technically we don't need parentheseshere but these parentheses make our code more clear more readable let me show youso I'm gonna wrap this inside these parentheses now it's very clear we'reobviously on the right side of this assignment operator we have a booleanexpression in this tutorial we're gonna look at the ternary operator in Java sowe're gonna continue with the example from the last tutorial we had thisincome variable imagine this is the income or customers now depending ontheir income you want to put these customers indifferent classes if their income is more than $100,000 you want to put themin the first class otherwise we want to put them in the economy class so here'sone way to implement the scenario we declare this string variable class namenote that we cannot call this class because class is a reserved keyword soclass 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 tutorialthis code looks very amateurish a professional programmer doesn't writecode like this so one way to simplify this is to give this variable an initialvalue so we assume they are in the economy class and then we check thiscondition if this condition is true we put them in the first class so with thiswe can get rid of this else clause that is better now in the last tutorial Ishowed you how to simplify this even further but the technique you learnedthere 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 sidewe have declared a string variable so we want to set this to a different stringdepending on the result of this expression and this is where we use theternary operator so we start with our condition then we type a question markif this condition is true we add this value here otherwise we add the othervalue so this question mark and colon is the ternary operator in Java it hasthree pieces first we have a condition if this condition is true this valuewill be returned and assigned to our class named variable otherwise thisother value will be returned now we can completely get rid of this if statementso put the ternary operator in your tool box it's very helpful next we're goingto look at switch statements in Java in this tutorial we're going to look atswitch statements in Java we use three statements to execute different parts ofcode depending on the value of an expression kind of similar to ifstatements let me show you so let's say we're gonna write a program and checkthe role of the current user and then we're gonna print different messages orgive them different features depending on their row so let's declare a stringvariable called role and here we set this to admin now to check the role ofthe user we can write an if statement like this if role equals admin thenperhaps we want to print you are an admin nowyou might be wondering why we have this condition here it's obvious that thiscondition is always true because we have set roll to admin but this is just fordemonstration in a real program we are not gonna hard code this admin here sowe're gonna read the role of the current user from somewhere elsewe don't know what it is at the time of writing code okay so here we have onecondition let's write another condition else ifrole equals moderator perhaps we want to display a different message so you are amoderator and finally if the role is none of these values you want to printyou are a guest so this is one way to implement this scenario using an ifstatement we can also implement this using a switch statement and sometimesthat looks a little bit cleaner let me show you so we start with a switchstatement then we add parentheses and inside this parenthesis we add ourvariable in this case row next we define a block of code and in this block we addone or more case clauses so we have a case for an admin we add a colon herenow what do we want to do here if the role is admin you want to print you arean admin so I'm gonna copy this line from here and then paste it over herenow after this line we need to add a break statement to jump out of thisswitch block okay then we add another case Clause so case moderator once againyou got a colon and here we're gonna print this other message so we paste ithere and then we're gonna break now optionally we can have a defaultclause here so if none of these previous cases apply the code that we write inthis section will be executed so here we want to print you are a guestnow here we don't need to use a break statement because we're at the end ofthe switch block so will automatically jump out of this block in contrast if wedidn't use this break statement here Java will continue executing these otherlines here so if the role is admin first it will execute this line and then itwill jump to this case block it will execute this other line and then afterit executes this break statement it will jump out of this switch block okay sothis is how we use a switch statement now compare this with wave statementsome people prefer to use if statements others prefer to use a switch statementnow one more thing before we finish this tutorial here we're comparing the valueof role with strings but we could also use integers other than the long type soif roll was a byte short or an integer our cases would look like this case onecase two and so on now here we have a compilation error because roll is astring let's change this to an integer and we can initialize this to one so asyou can see with sweet statements we can execute different code depending on thevalue of an expression all right now it's time for an exercisethis exercise I'm gonna give you is a popular interview question so I want youto write a program that behaves like this here we should enter a number ifthis number is divisible by five we get this so if you run the program again andenter ten once again we get fit now if this number is divisible by 3 we getbuzz if this number is divisible by both five and three like fifteen or thirty orwhatever we get fizzbuzz and if this number is not divisible by five or threelike two we get the same number printed on the terminal so go ahead and spendfive to ten minutes on this exercise you'll see my solution next all right to read the number first weneed to use the scanner object so scanner we import this and instantiateit and as you know here we need to pass system that in to read data from theterminal now we print a message so we're gonna use the print method instead ofprint line here we add a label like number and then we call scanner the nextint to read a number we store it in this variable number okay so the first partis done now we need to check to see if this number is divisible by five or notso we can write an if statement like this if number here we use the modulusoperator which returns the remainder of a division so we divide this by five andif the remainder equals zero that means this number is divisible by 5 so weprint fizz now otherwise if this number is divisible by3 we print buzz we need another condition if this number is divisible by5 and 3 so here we use the and operator number divisible by 3 equals 0 in thiscase we want to print fizz buzz otherwise you want to print the samenumber like this now this is not the right solution as I will show you in asecond this program has a book but it's a very common solution that I seeamongst my students so let's run this program and see what is wrong hereall right here we enter five we get fizz utiful what if you enter ten ten is alsodivisible by 5 so we get fits so far so good what about a number that isdivisible by 3 we get buzz good what if we enter a number that is divisible byboth 5 & 3 like 15 we get physican why is that here's the reason with thisimplementation if we enter 15 this first condition will evaluate to true so weget fizz these other else clauses will be ignored and that is why this linewill not be executed so in situations like this you should have the mostspecific conditions on the top and the most generic ones on the bottom in thiscase we want to move this condition to the top so if the number is divisible by5 & 3 we're gonna print fizzbuzz so this is very specific otherwise if the numberis only divisible by 5 we print fizz else if it's divisible by 3 we printbuzz and finally if none of his conditions is true then we print thesame number now let's run the program one more time so we enter 15 and we getfizzbuzz beautiful so here's one way to solve this problem now I've seen somepeople argue that we have repeated this expression twice number is divisible by5 we have that here on line 12 as well as line 14 in programming we have thisconcept called dry which is short for don't repeat yourself so some peopleargue that here we have repeated this expression and this is not a goodsolution here is another way let me show you so we're gonna get rid of thissecond condition here instead we're gonna add a code block over here so ifthe number is divisible by 5 first we check to see if the number is alsodivisible by 3 if that's the case we print fizzbuzzotherwise we print just fizz like this okay now we no longer needthese two lines because we already implemented this concept here so firstwe check to see if the number is divisible by five if not we check to seeif it's divisible by three and otherwise so here is another way to solve thisproblem but in my opinion this approach is kind of amateurish and ugly becausethese nested if-else statements are considered a bad practice now this isnot terribly bad but the more you nest these L statements the more confusingyour code is going to be to other people so I personally prefer the previoussolution even though we had a bit of repetition in the code the more youprogram the more you build software the more you realize that there is no way tobuild ideal software programming and problem solving is all about trade-offsevery solution has certain strengths and certain weaknesses this solution doesn'thave any repetition or duplication in the code but it has a nested structureand these nested structures make our code hard to read and understand theprevious solution had a bit of repetition but it had a flat structurethere is no nesting here and this code is cleaner and easier to read there aretimes that we want to repeat one or more statements for example let's say we havethis hello world message here let's say we want to print this five times on theterminal we don't want to repeat this code like this this looks very uglythat's where we use loops in Java we have a few different types of loops thefirst one that I'm going to talk about in this tutorial is for loops so let'ssee how we can use a for loop here I'm going to delete all this code you startby typing the for keyword followed by parentheses and inside these parentheseswe need to do three things first we need to declare a loop or counter variable solet's declare a variable called I and initialize it to 0 quit often usevariable names like I J and K for loop counters next we add a semicolon toterminate the first statement then we write a boolean expression thatdetermines how many times this loop is gonna get executed so Ithan five as long as I is less than five this loop will be executed once again weadd a semicolon and finally we increment I by one like this so this is the basicstructure for a for loop now here we can repeat one or more statements using thisfor loop so we can add our hello world message here like here we have a singlestatement so we don't need braces but if you have multiple statements that wewant to repeat we need to define a code block here now I'm gonna remove thisbecause you don't really need them so let's run this code and see what we getyou get hello world printed five times on the terminal beautiful now let meexplain how this code gets executed when Java sees this for loop first it willexecute this statement so here we are initializing I to zero then Javaevaluates this condition is this condition true obviously it is becausezero is less than five so the control moves to line seven this line getsexecuted now at the end of this iteration or at the end of this loop thecontrol moves here so I is incremented by one now we are atthe beginning of the second iteration once again this condition is evaluatedis one less than five obviously it is so once again the body of this loop getsexecuted now fast forward at the end of the fifth iteration I will become fivefive is not less than five so the loop condition will be false and controlmoves outside of this for loop now here's one thing you need to remember ifyou want to execute something five times you can initialize your loop counter orloop variable to zero and use the less than operator here another way is toinitialize this to one and then use the less than or equal to operator here nowto make this more interesting let's print I over here so here we add a spaceand then concatenate this string with I take a look so we get hello ward one twothree four five in contrast if we initialize I to zero and use the lessthan operator we will get hello word zero one twothree four we can also print these numbers in reverse order so weinitialize I to five and execute this loop as long as I is greater than zerobut here instead of incrementing I we decrement it now we get hello world fivefour three two one so this is all about for loops nextwe're gonna look at while loops in this tutorial we're gonna talk about whileloops in Java while loops are very similar to for loops in terms of theirfunctionality but they're different in terms of syntax let me show you so we'regonna continue with the example from the last tutorial I'm gonna rewrite thiscode using a while loop so first we declare a loop variable and I initializeit to zero next we type while and here inparentheses we type our loop condition while I is greater than zero then we'regonna execute the code inside this block so I'm gonna copy this from here pasteit in this block and finally we need to decrement I like this so at the end ofeach iteration we decrement I just like our for loops so as you can see we canachieve the same thing using a for loop or a while loophowever the implementation using the for loop is a little bit lighter and cleanerso in situations where you know ahead of time how many times you want to executeone or more statements it's better to use a for loop while loops are better insituations where we don't know exactly how many times you want to repeatsomething for example let's say we're going to write a program and ask theuser to continuously enter something until they type quit the moment theytype quit we're gonna terminate the program in that situation we don't knowhow many times the user is going to enter something so let's write thatprogram using a while loop I'm gonna delete everything from here all right we're gonna start with ourwhile loop now what is our loop condition here we don't have a countervariable in this example instead we want to check to see if the user entered quitor not so here we can declare a string called input and initialize it to anempty string then we can write a while loop like this while input does notequal to quit now this code is not gonna work because input is a string which isa reference type and we cannot use comparison operators between referencetypes because these operators will compare the address or a string objectsnot their value so if you have two strings quit and quit but stored indifferent memory locations to have different addresses so we can use theinequality operator to compare their value instead we need to use the equalsmethod of string objects so we want to check to see if the input equals quitnow here we need to apply the not operator so as long as the input doesnot equal quit we're gonna continuously ask the user to enter something so herewe can print a label like input and then we can use a scanner object to readsomething from the terminal so let's create a scanner object and instantiateit using system dot in I didn't call scanner that next this will return astring so we can store it in this input variable now with this implementation inevery iteration we're going to create a new scanner object so if the user enters10 numbers we're gonna create 10 scanner objects in memory this is unnecessaryand it's actually a bad practice because it's going to pollute our memory so it'sbetter to create the scanner object outside of a while loop and then simplyuse it here also here we are assuming that the user is typing everything inlowercase so if they type quit in uppercase or any combinations oflowercase and uppercase characters this logic is not gonna work the way we wantso over here right after reading something from the terminal we're gonnacall the to lowercase method of string objects toconvert it to lowercase now to make this program more interesting let's echo backwhatever the user enters so we simply print that on the terminal now let's runthis and see what happens so I'm going to enter if your numberslike 1 2 & 3 whatever we type gets a code back but the moment we type quitour program terminates so while loops are useful in situations where we don'tknow ahead of time how many times we want to repeat something in Java we haveanother type of loop called a do-while loop it's very similar to a while loopbut it gets executed at least once let me show you what I mean so I'm gonnarewrite the same code using a do-while loop we start with a do keyword then wecreate a code block at the end of this code block we type while followed by ourloop condition so not input dot equals quit and then we terminate this using asemicolon now inside the body of this loop we'll simply copy all these lineswe have here now compared these two types of loopswith while loops we check the condition first so if the condition is false thefirst time this loop will never get executed in contrast with do-while loopswe check the condition last so do-while loops always get executed at least onceeven if the condition is false that is the only difference the reality most ofthe time we use while loops do-while loops are rarely used but there arecertain cases for that so just be aware of them but most of the time prefer touse wire loops we're gonna continue with the examplefrom the last tutorial this program we have written has a tiny problem let meshow you so I'm gonna run this enter a couple numbers these numbers get echoback beautiful if we type quit the program terminatesbut the word quit also gets echoed back this is a bit weird so let's look at acouple ideas for solving this problem back to our code one way to solve thisproblem is to check the input before printing it so here we can type an ifstatement if the input does not equal quit then we're print it so not equalinput dot equals quit if this condition is true then we're going to print theinput let's take a look so one to quit beautiful we solved the problem there isanother way to solve this problem as well let me show you we can reverse thiscondition so if the user types quit you can immediately jump out of the loopusing the break statement so I'm gonna remove the nut operator if the usertypes quit we're gonna break out of the loop otherwise we're gonna continueexecution and print this input on a terminal so when Java sees the breakstatement it will ignore everything else after and it will terminate the looplet's run the program once again we enter a couple numbersfollowed by quit beautiful so this is the break statement we also have thecontinuous statement that moves control to the beginning of a loop let me showyou so let's imagine if the user types pass we don't want to echo that but alsowe don't want to terminate the loop you want to ask the user to try one moretime so after we read the input we can check to see if input equals pass thisis where we use the continuous statement when Java sees this it would movecontrol to the beginning of the loop so all these other statements are gonna getignored and what the user types is not gonna get printed on the terminal let'srun the program and see this in action so we type 1 2 pass it doesn't getechoed back one more time and finally quit so to recap the break statementterminates a loop and the continue statement moves control to the beginningof a loop now one last thing before finish this tutorial in thisimplementation we don't really need this loop condition because the moment usertypes quit this break statement is gonna kick in and terminate the loop so we cansimplify this code by using a true as our loop condition so this is alwaystrue and this loop is gonna get executed forever until the user types quit thisis a very common technique that you see amongst professional programmers justremember if you're using this technique make sure to have a break statementotherwise you will end up with an infinite loop that executes forever itnever terminates and that can be very dangerous in terms of memory consumptionso 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 atis the for each loop in Java we use for each loops to iterate over arrays orcollections let me show you so I'm going to start by declaring a string arraycalled fruit and we initialize this with three items let's say Apple mango andorange now let's say we want to iterate over this array and print each item on aterminal we can use any of the loops you learn about earlier like a for loop or awhile loop but we can also use the for each loop which is a bit easier let meshow you first I'm going to use the for loop to iterate over this array so wetype for here we declare our loop variable or loop counter into I we setit to zero as long as I is less than fruits that length we're going toincrement I by one after each iteration and here we simply print fruits of Ilet's run the program and see what we get so we get each item on a new linebeautiful now there is another way to write the same code using the for eachloop here we type for in parentheses with declare and loop variable but thetype of this variable should be based on the type of items in our array so herewe have a string array and that means every item in this array is a string sohere we should declare a string variable we call it fruit here we type a colonand then the name of our array fruits now in each iteration fruit will holdthe value of one item in this array so here we don't have to declare a numericcounter we don't have to write a boolean expression like this we don't have toincrement our counter it's much easier to iterate over an array now if we printfruit we get the exact same result as before take a lookso the first three items are from our for loop and here's the result our foreach loop so this is the for each loop howeverthis for each loop has a couple of limitations one limitation is that it'salways forward only so we cannot iterate over this array from the end to thebeginning in contrast we can easily do this with a for loop so here we caninitialize I to fruits that length then we change this operator to greater thanand replace this value with zero so as long as I is greater than zero we'regoing to decrement I the second limitation of the for each loop is thathere we don't have access to the index of each item all we have is this loopvariable which holds the value of each item in this array in contrast in ourfor loops we can access both the index and the actual item so I represents theindex of each item and fruits of I returns the item at the given index soif you need the index then you'll have to use the for loop otherwise it's mucheasier to use the for each loop all right now let's get back to ourmortgage calculator and implement some basic error handlingso here I've changed this question by adding this label that identifies therange 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 messageenter a number between one thousand and one million and now we are asked thisquestion one more time if I keep entering invalid values I get asked thesame question now let's enter a valid value like 1 million dollars next we'llhave to enter the annual interest rate now here we need to enter a value thatis greater than 0 and less than or equal to 30 so if I enter 0 we get thismessage enter a value greater than 0 and less than or equal to 30once again we're asked this question one more time so let's enter a valid valuelike 3

9 to here we need to enter a value between 1 and 30 so if you enter 0we get an error message and we're asked the same question so let's enter 30 andfinally we get the result here's our mortgage or monthly payments so go aheadand spend five to ten minutes on extending this mortgage calculator byadding error-handling to it you'll see my solution X all right let me show you how I'm gonnasolve this problem step by step so for each question we want to validate thevalue that the user enters if the value is invalid you want to keep asking thesame question so this is where we can use an infinite loop let me show you sohere's our first question principal I'm gonna wrap these two lines inside aninfinite loop while true so we're gonna keep asking the samequestion until the user enters a valid value so here after we read theprinciple we can write an if statement like this if principle is greater thanor equal to 1000 and it is less than or equal to 1 million and here we can usean underscore to separate these digits to make our code more readable so if theuser enters a valid value then we can break out of this infinite loopotherwise we're gonna print an error message so enter a value between 1001million like this ok now if you look on the right side here you can see this redbar this indicates an error and here in this preview window you can see exactlywhere we have an error it's down below on line 30 where we calculate themortgage so if you click on this red bar we jump over here principal ishighlighted in red so here we have a compilation error cannot resolve symbolprinciple here is the reason because we've wrapped these few lines insidethis while loop and earlier I told you that whenever you declare a variablethat variable scope to the Block in which it's defined so this is where wehave declared the principal variable and it's scoped to this block it's notavailable outside of this block that's why we get this compilation error so tosolve this problem we need to declare this outside of this while loop we cando it right here after radicular our constants so let's say int principle andwe can initialize it to 0 now we remove the declaration from here and the erroris gone now we need to repeat the same pattern with other questions so realquick here's our second question where we read the annual interest once againwe add an infinite loop now the moment we read the annualinterests invalidate the data so if annual interest is greater than or equalto let's say one and it is less than or equal to 30 then we're gonna break outof this infinite loop now here we should also calculate themonthly interest so the proper way to do this is like this if the user enters avalid value we add a code block here first we calculate the monthly interestand then break out of the loop otherwise we print an error message enter a valuebetween 1 and 30 okay now if you look to the right side again we have twocompilation errors monthly interest is not resolved because we have declared itinside of this block so let's move the declaration to the top here we removethe float keyword and declare monthly interest over herethat's better and finally for the last question one more time we're to wrap itin this infinite loop this is where we read the number ofyears and right after this line we need to do our data validation so if yours isgreater than or equal to one and it's less than or equal to 30 here we add acode block this is where we calculate the number of payments and then we breakactually I forgot to type an S here otherwise if the user enters an invalidvalue will simply print an error message enter a value between 1 and 30 now hereonce again we have a compilation error because number of payments cannot beresolved so we remove the declaration from here and we'll be to the top righthere number of payments so this is how we add data validation to this programthe problem is that this code the code inside the main method is now getting alittle bit too long and this hurt the maintainability of our program someoneelse reading this code they have to look at all these statements to figure outwhat's going on this is where we need to break this code down into smaller easierto read and easier to understand chunks and that's what I'm gonna show you next so in this section you'll learn how tocontrol the flow of execution of your programs we started off by talking aboutthe comparison operators for comparing primitive values then we talked aboutthe logical operators like and or and not I showed you how we can use theseoperators for implementing real word rules and then we talked about threetypes of control flow statements you learn about conditional statements likeif and switch for making decisions in our programs then you learn about loopsfor executing code repeatedly we looked at four types of loops for loops whileloops do-while loops and for each loops and finally we looked at the break andcontinue statements for breaking or jumping to the beginning of a loop Ihope you learned a lot and been enjoying the course so far as Martin Fowler said any fool can writecode that a computer can understand good programmers write code that humans canunderstand I can't agree more if you have seen any of my courses you probablyknow that I've put a lot of emphasis on writing clean code so I have dedicatedthis entire section on clean coding we're going to continue extending ourmortgage calculator and add new features to it along the way you will see ourcode starts to get messy and hard to maintain so I will show you a fewtechniques for changing the structure of the code and make it clean and beautifulare you ready let's jump in and get started hey guys maj here i want to congratulateyou on your determination for learning I would really appreciate it if yousupport me by liking and sharing this video also subscribe to my channel andenable notifications so next time I upload a video you get notified now ifyou want to learn more I would encourage you to enroll in my ultimate Java seriesas I told you earlier this YouTube tutorial is the first two hours of thisseries if you're serious about learning Java and want to become a professionaljob of developer I highly encourage you to enroll in this series in case you'reinterested I put the link down below in the description box thank you on have afantastic day