Hello and Welcome Guys, To learn JavaScript first you must know about what is Coding. In simple words your computer cannot recognize your common or native language because computers are not designed to read these language, so the word coding arrives which means writing a computer language which can be easily read by your computer. Okay Let's get start.
Hi! My name is Ankit
and I'm gonna be your instructor in this Java course. In this course, you're gonna learn everything you need to get started programming in Java.
First of all What is JAVA?
JavaScript is a programming language for the web development. Under JavaScript you can change and update both HTML and CSS. It can calculate, manipulate and validate data.
Tools
We'll start off by installing all the necessary tools to build Java applications then you're gonna learn about the basics of Java you'll learn how Java code gets executed you'll learn how to build simple algorithms and throughout this course I'm gonna share with you lots of tips and shortcuts from my years of experience I'll teach you how to write good code like a professional developer, so we'll end up watching this course you will have a solid foundation in Java and be ready to learn about advanced Java features I've designed this course for anyone who wants to learn Java if you're a beginner don't worry I'll make Java super simple and hold your hands through this entire course you're not too old or too young you'll write your first Java program in minutes my name is Ankit.
Hi! My name is Ankit
and I'm gonna be your instructor in this Java course. In this course, you're gonna learn everything you need to get started programming in Java.
First of all What is JAVA?
JavaScript is a programming language for the web development. Under JavaScript you can change and update both HTML and CSS. It can calculate, manipulate and validate data.
We'll start off by installing all the necessary tools to build Java applications then you're gonna learn about the basics of Java you'll learn how Java code gets executed you'll learn how to build simple algorithms and throughout this course I'm gonna share with you lots of tips and shortcuts from my years of experience I'll teach you how to write good code like a professional developer, so we'll end up watching this course you will have a solid foundation in Java and be ready to learn about advanced Java features I've designed this course for anyone who wants to learn Java if you're a beginner don't worry I'll make Java super simple and hold your hands through this entire course you're not too old or too young you'll write your first Java program in minutes my name is Ankit.
I'm a software Programmer with two years of experience and I've taught over 3 thousand people how to code and how to become professional software Programmer I have a coding blog at code with Raj where you can find plenty of courses that help you take her coding skills to the next level.
I hope you'll stick around and learn this beautiful and powerful programming language and now award from this Blog sponsor as someone who runs an online business I cannot stress enough the importance of staying safe online which is why I was so excited when dash lane reached out to me if you don't know - Lane is the password manager and VPN recommended by Apple and Google and it's a fantastic safeguard for keeping your information secure it's completely free to use for your first device so head over to -Ling comm / marche
Now today and keep yourself safe online now back to the course in this java tutorial we're going to download and install the necessary tools to build java applications so open up your browser and search for jdk download.
kit
I hope you'll stick around and learn this beautiful and powerful programming language and now award from this Blog sponsor as someone who runs an online business I cannot stress enough the importance of staying safe online which is why I was so excited when dash lane reached out to me if you don't know - Lane is the password manager and VPN recommended by Apple and Google and it's a fantastic safeguard for keeping your information secure it's completely free to use for your first device so head over to -Ling comm / marche
Now today and keep yourself safe online now back to the course in this java tutorial we're going to download and install the necessary tools to build java applications so open up your browser and search for jdk download.
kit
jdk is short form of Java development kit and it's basically a software development environment for building Java applications it has a compiler it has a bunch of code that we can reuse it has a Java Runtime environment at a bunch of other stuff so over here you can see this page on Oracle com Java which is short for Java standard edition click on this now over. here click on this icon now on this page we can see Java development kit for various platforms like Linux Mac OS and Windows here I'm on a Mac so I'm gonna download this dmg file over here now before we do this first we need to accept the license agreement all right now let's download the dmg let me open this we're gonna say this package let's double click this and here we see this installation wizard it's super easy just click continue and install you have to enter your computer's password and then alright done beautiful,
So we can move this to trash now the next piece of software we need is a code editor there are so many cool editors for building Java applications the popular ones are Net Beans Eclipse and IntelliJ in this Java course I'm gonna use IntelliJ but if you have a favorite editor feel free to use that to take this course that's perfectly fine so let's search for IntelliJ download all right you can see download IntelliJ IDEA click on this link over here download the community edition which is absolutely free and it's more than enough for this course so download all right now let's drag and drop this onto the Applications folder beautiful alright we've installed all the necessary tools to build Java applications so next we're gonna look at the anatomy of a Java program in this java tutorial we're gonna look at the anatomy of java programs the smallest building block in java programs are functions if function is a block of code that performs a task as a metaphor think of the buttons on the remote control of your TV each button performs a task functions in programming languages are exactly the same for example we can have a function for sending emails to people we can have a function for converting someone's weight in pounds to kilograms we can have a function for validating users input and so on now let's see how we can code a function in Java we start by specifying the return type of that function some functions return a value like a number at day time and so on other functions don't return anything so the return type of this functions is void void is a reserved keyword in Java and that's why I've coded that in blue here now after the return type we have the name of our function so here we should give our function a proper descriptive name like send email this name clearly identifies the purpose of this function okay now after the name we have a pair of parentheses and inside these parentheses we add the para meters for this function we use these parameters to pass values to our function for example our send email function should have parameters like who is the receiver what is the subject of this email what is the content of this email and so on now in this tutorial we're not gonna worry about parameters we'll look at them in the future now after the parentheses we had a pair of curly braces and inside these braces we write the actual Java code now one thing I want you to pay attention to here is that in Java we put the left brace on the same line,
where we define our function in other programming languages like C sharp it's more conventional to put the left brace on anew line but we don't do that in Java so we put the left brace on the same line where we define our function now every Java program should have at least one function and that function is called main so main is the entry point to our programs whenever we execute a Java program the main function gets called and the code inside this function gets executed okay now these functions don't exist on their own they should always belong to a class so a class is a container for one or more related functions.
Basically we use these classes to organize our code just like how products are organized in a supermarket in a supermarket we have various sections like vegetables fruits cleaning products and so on each section contains related products by the same token a class in java contains related functions now every Java program should have at least one class that contains the main function can you guess the name of that class its main so this is how we define a class in Java we start with a class keyword then we give our class a proper descriptive name and then we add a pair of curly braces now the functions that we define in between these curly braces belong to this class and more accurately we refer to them as methods so a method is a function that is part of a class in some programming languages like Python we can have a function that exists outside of a class so we call it a function but when a function belongs to a class we refer to it as a method of that class okay now in Java all these classes and methods should have an access modifier an access modifier is a special keyword that determines if other classes and methods in this program can access these classes and methods we have various access modifiers like public private and so on now most of the time we use the public access modifier so we put that in front of our class and Method declarations so this is the basic structure of a Java program at a minimum we have a main class and inside this main class we have the main method now you might be curious why we have a capital m in the name of this class because in Java we use different conventions for naming our classes and our methods to name our classes we use the Pascal naming convention and that basically means the first letter of every word should be uppercase in contrast to name our methods we use the camel naming convention and that means the first letter of every word should be operate case except the first wart so that is why we have a capital m in the name of this class alright now that you understand the anatomy of a Java program let's create a new Java project and see all these building blocks in action in this Java tutorial you're gonna learn how to write and execute your first Java program so let's open IntelliJ IDEA here on the home screen let's create a new project alright on the left side select java and make sure project sdk is not black so earlier we downloaded jdk or Java development kit version 12 that is why JDK version 12 is selected here if you don't see that make sure to select it from this drop-down list alright now let's click on next on this page select create project from template so we're gonna create a command line application which is an application that we can run from the command line it doesn't have a graphical user interface or a GUI now I know command line application is not as exciting as an application with a graphical user interface like a mobile app or a desktop app but trust me building an application with a graphical user interface is very complicated so for now we're just gonna build command line applications to learn Java properly once you learn Java properly then you can learn about building desktop or mobile applications with Java all right now let's click on next on this page we have to give our project a name let's call it hello world.
Now over here you can see the location of this project so it's inside the idea projects folder now right below that you can see the base package which is set to comm that code with Marsh on my machine and your mission is probably gonna be comm dot package what is this well here we talked about classes and methods I told you that a class is a container for related methods so we use classes to organize our code by the same token we have a concept called package and we use a package to group related classes so a sour applications grow we're gonna end up with hundreds or even thousands of classes so we should properly organize this class us into packages now by convention the base package for a Java project is the domain name of your company in Reverse so my website is code with mass comm that is why I'm gonna set the base package for this project to come that code with Marsh now it doesn't mean that you should have an actual domain registered on an Internet this is just a way to create a namespace for our classes so now every class that we create in this project will belong to this package we're gonna talk about packages in more detail in the future so for now just type a base package for your project it can become that your name or whatever it doesn't really matter all right now let's go forward alright here's our first Java project now this code editor might look a little bit intimidating at first but trust me it's really easy and you're gonna learn about it throughout this course on the left side we have the project panel where we can see all the folders and files in a project for example on the top we have the hello word project inside this project we have the source folder where we have the source code of a project now in this folder we have another folder that is calm that code with Marsh that is the name of our base package and in this package we have this class main so you can see this main file opened on the right side here now look at the name of this file its main the Java so all Java files should have the Java extension.
Okay now let's collapse the project panel by clicking on this icon that is better so see what we have here on top of this file we have the package statement and this is used to specify what package this class belongs to so the main class that we have here belongs to this package now this package statement is terminated by semicolon so in Java wherever we have a statement we should terminate that statement with a semicolon this is exactly like c-sharp or C++ now below this package statement we have our main class exactly like what you saw in the previous tutorial so we have public class main with a pair of curly braces inside this class we have our main method so it's a public method which may it's accessible from other parts of this program it's static we haven't talked about static metals yet we'll talk about them in the future for now just remember that the main method in your program should always be static the return top of this method is void which means this method is not gonna return a value and here in parentheses we have one parameter for this function we can use these parameters to pass values to our program again we'll look at this in the future now right after this parameters as you can see the left brace and this is where we write the code in this method now by default we have this line prefix with two slashes this indicates a comment we use these comments to explain our code to other people so these comments don't get executed now let's remove this comment and write a bit of code to print something on the term in also here we're gonna use the system class in Java so capital S system.
Here in this tool tip you can see the system class is defined in this package Java dot Lang or language also look at this icon on the left side this indicates a class now inside this class we have various members we can use the dot operator to see the members defined in the system class now the member that we're gonna access is out look at the icon of this member it's F which is short for field you're gonna talk about fields in the future when we talk about classes and object-oriented programming now what is interesting here is the type of this field and you can see that on the right side that is print string so print string is another class that is defined in Java so once again we use the dot operator to look at the methods or members defined in the print stream class the method we're gonna use is print Ln which is short for line look at the icon for this method so M indicates a method now you press ENTER and IntelliJ automatically adds these parentheses as well as a semicolon so now with the code on line six we're calling or executing the print line method earlier I told you that inside this parenthesis we can pass values to our methods here we want to print the hello word on the terminal so let's type double quotes and inside these quotes right hello world so hello word is textual data in Java whenever we deal with textual data we should always surround them with double quotes now we say we have his string so a string is a sequence of characters all right so we're done with our first program now to execute this we can click on this icon on the toolbar look at the shortcut on Mac it's ctrl + R I always prefer to use shortcuts because they're faster so ctrl + R now IntelliJ is building our application and we can see the result in this little terminal window so here'sour hello work message so that was our first Java program next I'm going to explain how Java code gets executed under the hood hey Marsh here I just wanted to let you know that you really don't have to memorize anything in this course. I've done my best to create the best possible Java course and I would really appreciate it if you support me by liking and sharing this post on the social networks that you use often also be sure to subscribe and enable the notifications so next time I upload a post you'll get notified thank you so much and let's continue watching all right.
Now let's see what exactly happens under the hood the moment we run a Java program in IntelliJ there are basically two steps involved here compilation and execution in the compilation step IntelliJ uses the Java compiler to compile our code into a different format called Java byte code this Java compiler comes with the Java development kit that we downloaded at the beginning of the course let me show you so here we can right click on this main the Java and in this context menu we have an item called open in terminal it's down below unfortunately it's not visible in my recording window it's called open in terminal on Mac and probably open in command prompt on Windows so let's open that we get this terminal window or command prompt on windows here we're currently inside of this folder code with Maj that is where we have our main the Java file now we can invoke the Java compiler like this Java C and pass the name or Java file as an argument so main the Java if you're on Mac or Linux make sure to spell this with a capital M because these operating systems are case-sensitive so enter now let's look at the content of this folder on Mac or Linux we can type LS on windows we type dir.
So let's take a look in this folder now we have a new file main class this is the byte code representation of this Java file now let me use IntelliJ to run our Java program this class file gets stored somewhere else let me show you so back to the project panel here in our project we have this source folder where we our source code and we have this out folder where we have the result of the compilation so inside this folder we have production inside this we have hello world the same name as our project inside hello world we have comm which is the name of our top level package inside this package we have a sub package that is code with Marsh and here we have our main date class file so this was the compilation step now this Java byte code that we have in this file is platform independent and that means it can run on Windows Mac Linux or any operating systems that has a Java runtime environment if you go to java.com slash download we can download java or more accurately java runtime environment for various operating systems this Java Runtime environment has a software component called Java Virtual Machine or JVM this JVM takes our Java byte code and translates it to the native code for the underlying operating system so if you're on Windows machine this Java Virtual Machine converts or Java bytecode into the native code that windows can understand this architecture is the reason why Java applications are portable or platform independent we can write a Java program on a Windows machine and execute it on Linux Mac or any other operating systems that have a Java runtime environment c-sharp and python also have the same architecture that's why they are platform independent as well now let me show you how to invoke this java virtual machine to run a Java program so back to this terminal window let me expand this currently we are inside of this folder code with Marsh and in this folder we have this class file now let's go one level up so CD dot dot and one more time so now we are inside the source folder we can invoke Java Virtual Machine like this they type Java and then we type the full pass to our main class file what do I mean by that well earlier we defined this package comm that code with Marsh and this class the main class is part of this package so the full path this class is calm dot code with Marsh dot main make sure to use a capital M here because this is case sensitive now when we press ENTER Java will look at this folder calm inside this folder it will look at this other folder code with Marsh and then it will find main that class in that folder it will load the byte code and convert it to the native code for the operating system we are using so take a look so it executed our program hello world beautiful let me run a program using IntelliJ all these steps are hidden from us we don't see the compilation or execution steps so you have seen Java in action now let me tell you five interesting facts about Java Java was developed by James Gosling in 1995 at Sun Micro systems which was later acquired by Oracle in 2010 it was originally called oak after an oak tree that stood outside Gosling's office later it was renamed to green and was finally renamed to Java inspired by Java coffee that's why its logo looks like this we have four editions of Java for building different kinds of applications we have Java standard edition this is the core Java platform which is what we're using in this course it contains all of the libraries that every Java developer must learn we have Java Enterprise Edition which is used for building very large-scale and distributed systems it's built on top of java standard edition and provides additional libraries for building fault tolerant distributed multi-tiered software we have java micro Edition which is a subset of Java standard edition designed for mobile devices so it has libraries specific to mobile devices and finally we have Java card which is used in smart cards the latest version of Java is Java standard edition 12 which was released just a few months ago in March 2019 Java has close to 9 million developers worldwide currently about 3 billion mobile phones run Java as well as 120 million TV sets and every blu-ray player according to indeed.com the average salary of a Java developer is just over $100,000 per year in the US so as we can see Java is everywhere which means more opportunities for you to get hired as a professional programmer now let me give you a quick overview of how I've structured this course so you can get the most out of it this course is the first part of my complete four-part Java series each part is about three to four hours long so it can easily complete it in a day or two in the first part which is what you're watching you're gonna learn the fundamentals of programming with Java in the next section you'll learn about the type system in Java you will learn how to work with various types such as purrs strings boolean's and arrays by the end of this section you will build a mortgage calculator as your first Java project will be improving this calculator bit by bit routers course next you will learn about control flow statements that are used to build algorithms we'll be talking about various types of conditional statements and loops later in this section we'll add data validation to our mortgage calculator to force the user to enter valid values at this point you'll be able to build basic algorithms and that's great but being a good programmer requires knowing how to write good code code that is clean and expressive that's what separates an outstanding programmer from an average programmer so in the following section we'll talk about clean coding I will show you various techniques that professional programmers use to make their code clean and maintainable and finally in the last section you will learn how to find and fix errors in your java programs as well as how to package them for deployment so others can use them.
So the materials in the first part will give you a solid foundation on how to start programming in Java in the second part we'll talk about object oriented programming which is a style of programming use in most if not all Java applications whether you want to use Java to build web mobile or desktop applications you need to understand object-oriented programming well because otherwise you're going to constantly hit obstacles in the third part we're going to talk about core Java API is or application programming interfaces you'll learn about many of the useful classes in the standard Java library and finally in the last part we'll be looking at the advanced features in Java such as streams threads database programming and so on so I hope you're gonna join me on this journey and master Java the most popular programming language behind millions of apps and websites you intersection we're gonna look at the fundamentals of programming in Java you're gonna learn about variables and constants primitive and reference types you're gonna learn about casting or type conversion you will learn how to work with numbers strings and arrays and howto read input from the user once you learn all this I'm gonna give you a project you're gonna build a mortgage calculator on your own so make sure to pay great attention to all the materials you're gonna learn because you're gonna use most of them in this project are you ready now let's jump in and get started in this tutorial we're gonna talk about variables in Java we use variables to temporarily store data in computer's memory here is an example imagine in this program you want to store someone's age in the memory so we declare a variable like this ant age equals 30 so int or integer is the type of this variable so in this variable we can only store integers which are whole numbers like 1 2 3 4 numbers that don't have a decimal point now in Java we have several different types I'm gonna talk about them in the next tutorial so first we specify the type of our variable then we give it a name or a label this is also called an identifier because we use it to identify our variable this equal sign is called the assignment operator and 30 is the initial value that we are assigning to this variable so we say on line 6 we're initializing this variable which means we're giving it an initial value you always have to initialize our variables before reading them so with this line we're storing number 30 some where in computer's memory and we're assigning this label to that memory location now on line 7 instead of printing hello world we can print the value of the age variable take a look so I'm gonna run this program using ctrl +R there you go now we see 30 on the terminal beautiful we can also change the value of our variable so after we initialize it per house we can change it to 35 now when we run this program again we see it 35 beautiful we can also initialize multiple variables on the same line but this is something that I don't recommend because it makes your code ugly and hard to read here is an example we can declare another variable like temperature and set it to 20 sousing a comma we can declare multiple variables on the same line now even though this is technically possible it's not something that I recommend so it's always better to declare one variable on each line like this we can also copy the value of one variable into another here is an example let me delete these variables and declare a new variable called my age we set it to 30 and then we declare another variable like her age and we set it to my age so now when we print her age we're gonna see 30 take a look so on line seven recapping the value of this variable into this other variable now one thing I want you to pay attention to here is the convention I have used for naming our variables as I told you before this is called the camel case notation so we should capitalize the first letter of every word except the first word so in this case the first word my it's all in lower case but the second word starts with a capital letter so this is all about declaring and initializing variables in the next tutorial we're going to talk about various types in Java in this tutorial we're going to talk about various types in Java basically we have two categories of types we have primitive types for storing simple values and non primitive types or reference types for storing complex objects so in the category of primitive types we have white which takes one byte of memory and in one bite we can store values from 128 to 127 now the more bytes we have the larger numbers we can store so next we have short which takes two bytes and with this we can store values up to 32,000 next we have integer which we have seen before integers take four bytes of memory and allow us to store values up to two billion then we have long which takes eight bytes and with this we can store even larger numbers now all these types are for storing whole numbers that don't have a decimal point if you want to store a number that has a decimal point you have to use float or double float takes four bytes double takes eight bytes so obviously we double we can store larger numbers next we have char for storing a single character like ABC and this chart I've take two bytes so they support international letters and finally we have boolean for storing boolean values which can be true or false just like yes or no in English now let's take a look at a few examples earlier we use an integer for storing someone's age but as you learned integers take four bytes and allow us to store values up to two billion we don't need four bytes of memory to store someone's age all we need is one byte because with one bite we can store values up to 127.
So I'm gonna change this to byte that is better now let's look at another example let's say we want to store the number of times a Post has been watched/or viewed so we define an integer called views count note that I'm always using meaningful names for my variables because these names help us understand what this code does I've seen some people use variable names like V or V 1 or n nobody knows what these variables do so as a best practice always use meaningful and descriptive names for your variables so views count we set this to a large number like 1 2 3 4 5 6 7 8 9 now in Java whenever you deal with a large number like this you can use an underscore to separate every three digits just like how we use a comma in our documents to make our numbers more readable we can use an underscore in Java so with integers we can store values up to two billion but let's say the number of times this Post has been watched is three billion so I had a three here now we have a red on the line that indicates an error let me hover our mouse over it we see this tool tip integer number too large so we need to change the type of this variable to long however the error is still there what's going on here the reason we're getting this error is that by default Java sees these numbers as integers so even though we have defined the type of this variable as long Java compiler sees this value as an integer and he thinks this value is too large for an integer to solve this problem we need to add an L as a suffix or this number we can use an uppercase or a lower case L but as you can see a lowercase L kind of looks like a 1 so it's better to use a capital L so these are examples of whole numbers now let's declare a variable for storing a number with a decimal point so double price we set this to 1099 obviously the double variable is too large for storing the price of a product so we can change this to float that is better but you have a compilation error here take a look incompatible types required float but found double the reason we're seeing this error is that by default Java sees these numbers with a decimal point as double so even though we set the type of this variable to float Java sees this number as a double so just like how we added a suffix to this number to represent it as a long we need to add a suffix here to represent this number as a float and that suffix is F once again we can use an upper case or lower case F so these are examples of numbers now let's store a character so char we call it letter and we set it to a note that we should always surround single characters with single quotes and multiple characters or strings with double quotes.
Okay so char represents only one character string represents a series of characters and finally let's see an example of a boolean so we define a boolean variable called is eligible is this person eligible for loan or not we said this to true or false these are the boolean values now note that all these words coded in orange are reserved keywords in Java just like public static void class package these are all reserved keywords so we cannot use these reserved keywords the name our variables classes and methods in the last tutorial you learned that we use primitive types to store simple values like numbers boolean values or single characters in contrast use reference types to store complex objects like data objects or mail messages these are complex objects now in Java we have eight primitive types that you have seen before all the other types are reference types let me show you an example so here in this program first I'm gonna declare a primitive type let's say white age equals 30 now declaring and initializing a reference type is slightly different from primitive type let me show you so let's type date now here in this tool tip box which is called intelliJ sense we can see various classes that have date in their name so IntelliJ is helping us complete our code by suggesting these class names now here we have a date class in this package Java the util so this package contains a lot of utility classes that are useful in a lot of programs you also have a date class in a different package Java SQL or sequel which is used for programming databases so this is the benefit of packages we can have the same class but in different packages they don't conflict so packages create a namespace for our classes okay now in this case if we select the first date class and press enter or tab IntelliJ automatically adds this line for us import Java that you till the date so because currently we are in this package in order to use a class from a different package we need to import it so here we're importing the date class in this package will talk about packages in more detail in the future so back to our date variable let's give this variable a name collect now now we set this here we need to use the new operator to allocate memory for this variable and this is one of the differences between the primitive and reference types when declaring primitive types we don't need to allocate memory memory is allocated and released by Java Runtime environment but when dealing with reference types we should always allocate memory now we don't have to release this memory Java Runtime environment will automatically take care of that so we use the new operator and then repeat the name of our class in this case date and then we add parentheses followed by a semicolon in this example this variable we have defined here is an instance of the date class so this class is defined template or blueprints for creating new objects new instances as another example we can have a class called human and we can have objects like John Bob Mary and so on so an object is an instance of a class now this object or this class have members that we can access using the dot operator so we can type now dot and these are all the members defined in this class or in this object for example we have a method called get time 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 is print string which is another class in Java so once again we can use a dot operator and call the print line function now let me show you a very cool shortcut instead of typing all this we can use one of these code snippets so we type s oh you see and press tab and this generates this piece of code for us allright now let's pass our data object here note that I have not surrounded this variable with double quotes because this is a string and if you run this program.
We'll see now on the terminal there you 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 different let's take a look so I'm gonna delete all the code here in Java we have a point class that is defined in this package Java that awt so we press ENTER and now we have this import statement on the top beautiful let's declare a variable like point 1 and set it to new point here we can pass the initial values for x and y so I'm gonna pass 1 and 1 so intelligent automatically adds these labels x and y now just like before I'm gonna declare 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 if ,we print point two we're going to see the change that we just made take a look so S or ut tab let's print point to run the program there you go so the change was visible so remember this reference types are copied by the references,
whereas primitive types are copied by their value and these values are completely independent of each other in this tutorial we're gonna look at strings in Java so earlier in the course we printed the hello world message on a terminal this hello word that we have here is a string or more accurately it'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 look so in this string we have 13 characters and this is useful in situations where you want to check the length of the input by the user.
For example you might have a sign-up form with a username field you can check the length of someone's username and give them an error if the username is longer than let's say 20 characters pretty useful we also have another method that is index of and this returns the index of the first occurrence of the character or the string that we pass here for example if you pass H the index of H is 0 so let's run the program there you go we get 0 if you pass e we get 1 because the index of the first II in this message is 1 now what if you pass a character or a string that doesn't exist in this message let's say Skye we get negative 1 so with this method we can check to see if a string contains certain characters or words or sentences and so on another useful method is replace and with this we can replace one or more characters with something else for example we can replace any exclamation marks with let's say a store so this replace metal has two parameters one is target the other is replacement and here we're passing two values for these parameters here's the first value here is the second value and we have separated these values using a comma now in programming terms we refer to this values as arguments a lot of programmers don't know the difference between parameters and arguments parameters are the holes that we define in our methods arguments are the actual values that we pass to these methods so in this case target and replacement or parameters but exclamation mark and asterisk are arguments now let's run this program and see what happens so our explanation marks are replaced with stars now what is important here is that this method does not modify our original string it returns a new string so if we print our original string right after SRU T tab message you can see the original string is not changed because in Java strings are immutable.
we cannot mutate them we cannot change them so any methods that modify a string will always return a new string object okay we also have another useful method to lower case let's take a look so to lowercase converts all characters to lowercase and once again you can see that the original string is not affected because this method returns a new string okay we also have two uppercase and another useful method is trim trim and with this we can get rid of extra white spaces that can be at the beginning or the end of a string sometimes our users type unnecessary spaces in form fields so using the trim method we can get rid of these white spaces let me show you so I'm gonna add a couple of spaces before and after our message now when we trim it these white spaces are gonna get removed take a look so here's the original string you can see two white spaces at the beginning and here's our string after trimming so these are some useful methods in the string class but this glass has more methods than we don't have time to cover in this lecture but as we go through the course you're gonna learn more about the string class and other useful classes in Java third times will include special characters in our strings like a tab or a new line or a backslash or double quotes so in this tutorial I'm gonna show you how to include these special characters in your strings so here we have the string hello Marsh let's say we want to surround Marsh with double quotes now here's the problem if we add a double quote here Java compiler thinks this is the termination of our string so it doesn't stand what we have after that's why we have a compilation error the fixes problem we need to prefix this double code with a backslash so using this backslash we have escaped the double quote now one more time let's add backslash double code here now let's run the program and see what we get so we get hello Marsh in double quote beautiful so double quote is one of those special characters that you need to be aware of another special character is backslash let's say we want to store the pass to a directory on a Windows machine so that will look like this C Drive backslash windows backslash whatever now if you want to store this in a string we need to escape each backslash let me show you so C Drive backslash now we have a problem Java compiler thinks we're escaping the double code here so it thinks our string is not terminated with another double code but that's not what we want you want to add a backslash here so we need to prefix our backslash with another back slash now we type windows one more time something let's run the program so even though we have two backslashes in our code we actually see one back slash in a terminal window in other escape sequences backslash N and we use that to add a new line to our strings so let's change this to backslash N and run the program to see what happens now our string is broken down onto multiple lines by the first line we have C Drive then we have Windows so wherever we had a backslash n Java will insert a new line,
we can also add a tab in our strings so if you add backslash T here there will be a tab which means C Drive and windows let's take a look so C Drive here we have a tab and then windows now in Java we have a few more escape sequences but quite honestly they're hardly used so remember these four escape sequences that we cover in this tutorial in this tutorial we're going to talk about arrays in Java we use arrays to store a list of items like a list of numbers or a list of people or a list of messages let me show you so here we have an integer variable you want to convert this to an integer array so right after int we add square brackets now we have a compilation error because we're storing a single number in this array so to fix this we need to remove one because arrays are reference types we need to use the new operator here then we repeat the type one more time enter a and here in square brackets we specify the size or the length of this array how many items do we want to include in this array let's say five also we should change the name of this variable from number two numbers because we're dealing with a list of items so always pay attention to the name of your variables now you can access individual items in this array using an index so we type numbers square brackets to reference the first element or first item we use zero now we can set this to a value like 1 similarly we can set the second item to 2 now what if we use an invalid index let's say 10 this array doesn't have 10 items so let's see what happens numbers of 10 we said this to 3 when we run this program we get an exception exceptions are Javas way to report errors so in this case an exception was raised and our program crashed we'll talk about exceptions in detail later in the course.
so now let's remove the last line let's see what we get we get this weird string in sort of the items in our array here's the reason by default when we print an array Java returns the string which is calculated based on the address of this object in memory so if you have another array and we print that we're gonna see something different because each object is gonna be in a different memory space okay now how can we see the actual items in this array well we have a class in Java called arrays let me show you arrays so this class is defined in Java that util package let's press ENTER now this is important on the top beautiful so we can use the dot operator to access the members of this class here we have a method called two string.
Now as you see it this method is implemented multiple times so in the first implementation this method gets a float array in the second implementation it takes an integer array and so on so for all primitive types as well as reference types this method is implemented multiple times this is what we call method overloading,
now we can call this method and pass our integer array and this will return the string representation of this array so we can cut this from here and pass it to our print method like this now let's run the program one more time and here's our array beautiful so the first two items are initialized the others are set to 0 by default because here we're dealing with an integer array if you had a boolean array all items why default get initialized to false if you have a string array all items get initialized to an empty string okay now this syntax for creating and initializing an array is a little bit tedious and it's an older syntax there is a newer way to initialize an array if we know the items ahead of time like in this case so I'm going to remove these two lines I'm also gonna remove the new operator here we use curly braces and inside these braces we add all the items in this array let's say 2 3 5 1 & 4 now we have 5 items so the length of this array is gonna be 5 we can read that using the lengths so if we type numbers dot look here we have is filled look at the icon it's an F so this is a field which is like a variable in a class and the type of this field is an integer so this returns the number of items in this array let's get that and printed using our print method like this take a look so we get five now in Java arrays have a fixed size so once we create them we cannot add or remove additional items to them they have a fixed length if you want to be able to add or remove additional items from an array you should use one of the collection classes that we'll talk about later in the course for now all I want you to remember is that arrays have a fixed length now currently our array is not sorted these numbers are in some kind of random order we can easily sort this array using the sort method of the arrays class let me show you so I'm gonna remove this line and call arrays dot sort once again you can see this method is overloaded because it's implemented with different parameter types so we call this method and pass our numbers array now when we run this program we can see our array is sorted beautiful so yeah I've learned that we use arrays to store a list of objects in Java.
We can also create multi-dimensional arrays for example we can create a two-dimensional array to store a matrix or we can create a three-dimensional array to store data for cube these are useful in scientific computations let me show you so here we have a single dimensional array to convert this to a two-dimensional array we need to add another pair of square brackets now we have a compilation error because we need to repeat these brackets on the other side so let's say we want to create a 2 by 3 matrix so 2 rows and 3 columns we add in other brackets here and change these lengths to 2 and 3 so now we have 2 rows and 3 columns now to access individual items in this array we need to supply two indexes first the index of the row so we can go to the first row and then the first column and initialize that to 1 now let us print this so and so you t-tap once again we use our arrays class dot to string and pass this object take a look once again we get this weird string because here we're dealing with a multi-dimensional array to solve this problem we need to use another method in this class called deep to string use this for printing multi-dimensional arrays take a look now we have this matrix which has two rows and in each row we have three columns we can also create a three dimensional array all we have to do is to add another pair of brackets and specify the length of that dimension pretty easy now what about the curly brace syntax let me show you.
So let's revert this back to a two dimensional array we're gonna get rid of the new operator and use curly braces now let's say in this matrix we're gonna have two rows and three columns so each row is an array itself because it's a list of items right so we add another array here let's say 12 3 then comma now we add the second row which is another array in this row we're gonna have 3 numbers 4 5 & 6 now let's remove this line we don't need it anymore and print this array so here's the end result you have learned a lot about variables ya learned that when declaring them we need to initialize them and we can always change their value later on throughout the life time of our programs however there are times that we don't want the value of a variable to change for example let's declare a variable called pi and set it to 3.14 now here we need to add an F to represent this as a float because by default Java compiler sees this number as a decimal okay now you know that we use pi to calculate the area of a circle what if before we calculate the area of a circle I come here and type pi equals 1 then all our calculations are gonna get messed up we don't want this to happen that's when we use constants so if we type final here Java compiler will treat this as a constant so once we initialize this we cannot change its value later on you can see here we have a compilation error and it says cannot assign a value to final variable pi so pi is a final variable or a constant now by convention we use all capital letters to name constants so this should be PI beautiful.
Now I tell you a little side story in one of my early courses in another blog, that I created years ago that was c-sharp basics for beginners there I used the same example to teach the concept of constants but I pronounce this word as P instead of Pi and believe it or not to this day people make fun of me for saying P instead of Pi but that's how we learned this back in Iran we pronounce it as P and I think Greek people also say P but anyway I just thought to share this Post to change the mood now you're done with constants next we're gonna talk about arithmetic expressions in this tutorial we're going to talk about arithmetic expressions in Java so in Java we have the same arithmetic operators that we have in math we have addition subtraction multiplication division and modulus which is the remainder of a division let's look at a few examples so I'm gonna declare an integer called result and here we can type 10 plus 3 now when we print result it's gonna be 13 pretty straightforward there you go so this is addition we also have subtraction multiplication division is an interesting one let's take a look so here the result is a whole number because in Java the division of two whole numbers is a whole number if you want to get a floating-point number here you need to convert these numbers to afloat or a double let me show you so we prefix this number with parentheses and in parentheses we type double now we are casting or converting this number to a double similarly we should do that here and now we have a compilation error because on the left side we declared an integer but here the result of this expression is a double and by the way an expression is a piece of code that produces a value so what we have here is an expression because it produces a value so to fix this problem we need to change this to double now when we run this program we get this floating point number beautiful so these are the arithmetic operators and these numbers that we have here are called operands we also have increment and decrement operators let me show you.
So I'm gonna declare a new variable int X we set it to 1 now if you want to increase the value of x by 1 we use the increment operator now let's print this on a terminal so we get 2 there you go we can apply this operator as a post fix or as a prefix and we get the same result take a look too however if we use this on the right side of an assignment operator we get different results let me show you so I'm gonna declare another variable Y we set it to X plus plus in this case because we have applied the increment operator as a post fix first the value of x will get copied to Y so Y would be 1 and then X will be incremented by 1 so if you print x and y x is gonna be 2 and Y is gonna be 1 take a look so X is 2 and Y is 1 beautiful however if you apply this as a prefix first X will be incremented by 1 so it will be 2 and then it will be copied to Y so in this case both X & amp;Y will be to take a look so we get two and two now what if you want to increment X by more than one let's say by two well there are two ways to do this let's remove Y we don't really need it anymore we can write x equals x plus 2 so first we add 2 to X the result will be three and then three will be copied into X the other way is to use the Augmented or compound assignment operator so we can write X plus equals two what we have on line eight is exactly identical to what we have on line seven well as you can see it's shorter so this is a better way to write the same code now this is one of the Augmented assignment operators we have the Augmented assignment operator for other arithmetic operators so we can type X minus equals 2 and this would reduce the value of x by 2 we also have multiply and divide so these are the Augmented or compound assignment operators right now.
I've got a question for you here we have declared this variable X it goes to 10 plus 3 times 2 what do you think is the result of this expression the result is 16 let's run this program and find out so run there you go we got 16 but why well this is a very basic math concept that unfortunately a lot of people don't know in math the multiplication and division operators have a higher priority so 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 of these 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 conversion happens 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 we calculate the mortgage so we get a principal multiplied by this expressionand then divide it by this other expression, so we get a result store it in this string mortgage format it and print it over here now here we can also avoid declaring this variable and simply add this expression over here but it decided to do this to increase the readabilityof this code otherwise this line would be so long but that's just my personal preference you don't have to follow this alright so this was my implementation 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 because zero is less than five so the control moves to line seven this line gets executed now at the end of this iteration or at the end of this loop the control moves here so I is incremented by one now we are at the beginning of the second iteration once again this condition is evaluated is one less than five obviously it is so once again the body of this loop gets executed now fast forward at the end of the fifth iteration I will become five five is not less than five so the loop condition will be false and control moves outside of this for loop now here's one thing you need to remember if you want to execute something five times you can initialize your loop counter or loop variable to zero and use the less than operator here another way is to initialize this to one and then use the less than or equal to operator here now to make this more interesting let's print I over here so here we add a space and then concatenate this string with I take a look so we get hello ward one two three four five in contrast if we initialize I to zero and use the less than operator we will get hello word zero one two three four we can also print these numbers in reverse order so we initialize I to five and execute this loop as long as I is greater than zero but here instead of incrementing I we decrement it now we get hello world five four three two one so this is all about for loops next we're gonna look at while loops in this tutorial we're gonna talk about while loops in Java while loops are very similar to for loops in terms of their functionality but they're different in terms of syntax let me show you so we're gonna continue with the example from the last tutorial I'm gonna rewrite this code using a while loop so first we declare a loop variable and I initialize it to zero next we type while and here in parentheses we type our loop condition while I is greater than zero then we're gonna execute the code inside this block so I'm gonna copy this from here paste it in this block and finally we need to decrement I like this so at the end of each iteration we decrement I just like our for loops so as you can see we can achieve the same thing using a for loop or a while loop however the implementation using the for loop is a little bit lighter and cleaner so in situations where you know ahead of time how many times you want to execute one or more statements it's better to use a for loop while loops are better in situations where we don't know exactly how many times you want to repeat something for example let's say we're going to write a program and ask the user to continuously enter something until they type quit the moment they type quit we're gonna terminate the program in that situation we don't know how many times the user is going to enter something so let's write that program using a while loop I'm gonna delete everything from here all right we're gonna start with our while loop now what is our loop condition here we don't have a counter variable in this example instead we want to check to see if the user entered quit or not so here we can declare a string called input and initialize it to an empty string then we can write a while loop like this while input does not equal to quit now this code is not gonna work,
because input is a string which is a reference type and we cannot use comparison operators between reference types because these operators will compare the address or a string objects not their value so if you have two strings quit and quit but stored indifferent memory locations to have different addresses so we can use the inequality operator to compare their value instead we need to use the equals method of string objects so we want to check to see if the input equals quit now here we need to apply the not operator so as long as the input does not equal quit we're gonna continuously ask the user to enter something so here we can print a label like input and then we can use a scanner object to read something from the terminal so let's create a scanner object and instantiate it using system dot in I didn't call scanner that next this will return a string so we can store it in this input variable now with this implementation in every iteration, we're going to create a new scanner object so if the user enters 10 numbers we're gonna create 10 scanner objects in memory this is unnecessary and it's actually a bad practice because it's going to pollute our memory so it's better to create the scanner object outside of a while loop and then simply use it here also here we are assuming that the user is typing everything in lowercase so if they type quit in uppercase or any combinations of lowercase and uppercase characters this logic is not gonna work the way we want so over here right after reading something from the terminal we're gonna call the to lowercase method of string objects to convert it to lowercase now to make this program more interesting let's echo back whatever the user enters so we simply print that on the terminal now let's run this and see what happens so I'm going to enter if your numbers like 1 2 & 3 whatever we type gets a code back but the moment we type quit our program terminates so while loops are useful in situations where we don't know ahead of time how many times we want to repeat something in Java we have another type of loop called a do-while loop it's very similar to a while loop but it gets executed at least once let me show you what I mean so I'm gonna rewrite the same code using a do-while loop we start with a do keyword then we create a code block at the end of this code block we type while followed by our loop condition so not input dot equals quit and then we terminate this using a semicolon now inside the body of this loop we'll simply copy all these lines we have here now compared these two types of loops with while loops we check the condition first so if the condition is false the first time this loop will never get executed in contrast with do-while loops we check the condition last so do-while loops always get executed at least once even if the condition is false that is the only difference the reality most of the time we use while loops do-while loops are rarely used but there are certain cases for that so just be aware of them but most of the time prefer to use wire loops we're gonna continue with the example from the last tutorial this program we have written has a tiny problem let me show you so I'm gonna run this enter a couple numbers these numbers get echo back beautiful if we type quit the program terminates but the word quit also gets echoed back this is a bit weird so let's look at a couple ideas for solving this problem back to our code one way to solve this problem is to check the input before printing it so here we can type an if statement if the input does not equal quit then we're print it so not equal input dot equals quit if this condition is true then we're going to print the input.
let's take a look so one to quit beautiful we solved the problem there is another way to solve this problem as well let me show you we can reverse this condition so if the user types quit you can immediately jump out of the loop using the break statement so I'm gonna remove the nut operator if the user types quit we're gonna break out of the loop otherwise we're gonna continue execution and print this input on a terminal so when Java sees the break statement it will ignore everything else after and it will terminate the loop let's run the program once again we enter a couple numbers followed by quit beautiful so this is the break statement we also have the continuous statement that moves control to the beginning of a loop let me show you so let's imagine if the user types pass we don't want to echo that but also we don't want to terminate the loop you want to ask the user to try one more time so after we read the input we can check to see if input equals pass this is where we use the continuous statement when Java sees this it would move control to the beginning of the loop so all these other statements are gonna get ignored and what the user types is not gonna get printed on the terminal let's run the program and see this in action so we type 1 2 pass it doesn't get echoed back one more time and finally quit so to recap the break statement terminates a loop and the continue statement moves control to the beginning of a loop now one last thing before finish this tutorial in this implementation we don't really need this loop condition because the moment user types quit this break statement is gonna kick in and terminate the loop so we can simplify this code by using a true as our loop condition so this is always true and this loop is gonna get executed forever until the user types quit this is a very common technique that you see among professional programmers just remember if you're using this technique make sure to have a break statement otherwise you will end up with an infinite loop that executes forever it never terminates and that can be very dangerous in terms of memory consumption,
so if you're using while true make sure you have a break statement in your loop the last type of loop we want to look at is the for each loop in Java we use for each loops to iterate over arrays or collections let me show you so I'm going to start by declaring a string array called fruit and we initialize this with three items let's say Apple mango and orange now let's say we want to iterate over this array and print each item on a terminal we can use any of the loops you learn about earlier like a for loop or awhile loop but we can also use the for each loop which is a bit easier let me show you first I'm going to use the for loop to iterate over this array so we type for here we declare our loop variable or loop counter into I we set it to zero as long as I is less than fruits that length we're going to increment I by one after each iteration and here we simply print fruits of I let's run the program and see what we get so we get each item on a new line beautiful now there is another way to write the same code using the for each loop here we type for in parentheses with declare and loop variable but the type of this variable should be based on the type of items in our array so here we have a string array and that means every item in this array is a string so here we should declare a string variable we call it fruit here we type a colon and then the name of our array fruits now in each iteration fruit will hold the value of one item in this array so here we don't have to declare a numeric counter we don't have to write a boolean expression like this we don't have to increment our counter it's much easier to iterate over an array now if we print fruit we get the exact same result as before take a look so the first three items are from our for loop and here's the result our for each loop so this is the for each loop however this for each loop has a couple of limitations, one limitation is that it's always forward only so we cannot iterate over this array from the end to the beginning in contrast we can easily do this with a for loop so here we can initialize I to fruits that length then we change this operator to greater than and replace this value with zero so as long as I is greater than zero we're going to decrement I the second limitation of the for each loop is that here we don't have access to the index of each item all we have is this loop variable which holds the value of each item in this array in contrast in our for loops we can access both the index and the actual item so I represents the index of each item and fruits of I returns the item at the given index so if you need the index then you'll have to use the for loop otherwise it's much easier to use the for each loop all right now let's get back to our mortgage calculator and implement some basic error handling so here I've changed this question by adding this label that identifies the range of values we can enter so the minimum amount of loan we can get is $1,000 and maximum is 1 million dollars so if I enter 1 here I get this message enter a number between one thousand and one million and now we are asked this question one more time if I keep entering invalid values I get asked the same question now let's enter a valid value like 1 million dollars next we'll have to enter the annual interest rate now here we need to enter a value that is greater than 0 and less than or equal to 30 so if I enter 0 we get this message enter a value greater than 0 and less than or equal to 30 once again we're asked this question one more time so let's enter a valid value like 3.9 to here we need to enter a value between 1 and 30,
so if you enter 0 we get an error message and we're asked the same question so let's enter 30 and finally we get the result here's our mortgage or monthly payments so go ahead and spend five to ten minutes on extending this mortgage calculator by adding error-handling to it you'll see my solution X all right let me show you how I'm gonna solve this problem step by step so for each question we want to validate the value that the user enters if the value is invalid you want to keep asking the same question so this is where we can use an infinite loop let me show you so here's our first question principal I'm gonna wrap these two lines inside an infinite loop while true so we're gonna keep asking the same question until the user enters a valid value so here after we read the principle we can write an if statement like this if principle is greater than or equal to 1000 and it is less than or equal to 1 million and here we can use an underscore to separate these digits to make our code more readable so if the user enters a valid value then we can break out of this infinite loop otherwise we're gonna print an error message so enter a value between 1001 million like this ok now if you look on the right side here you can see this red bar this indicates an error and here in this preview window you can see exactly where we have an error it's down below on line 30 where we calculate the mortgage so if you click on this red bar we jump over here principal is highlighted in red so here we have a compilation error cannot resolve symbol principle here is the reason because we've wrapped these few lines inside this while loop and earlier I told you that whenever you declare a variable that variable scope to the Block in which it's defined so this is where we have declared the principal variable and it's scoped to this block it's outside of this block that's why we get this compilation error so to solve this problem we need to declare this outside of this while loop we can do it right here after radicular our constants.
So let's say int principle and we can initialize it to 0 now we remove the declaration from here and the error is gone now we need to repeat the same pattern with other questions so here's our second question where we read the annual interest once again we add an infinite loop now the moment we read the annual interests invalidate the data so if annual interest is greater than or equal to let's say one and it is less than or equal to 30 then we're gonna break out of this infinite loop now here we should also calculate the monthly interest so the proper way to do this is like this if the user enters a valid value we add a code block here first we calculate the monthly interest and then break out of the loop otherwise we print an error message enter a value between 1 and 30 okay now if you look to the right side again we have two compilation errors monthly interest is not resolved because we have declared it inside of this block so let's move the declaration to the top here we remove the float keyword and declare monthly interest over here that's better and finally for the last question one more time we're to wrap it in this infinite loop this is where we read the number of years and right after this line we need to do our data validation so if yours is greater than or equal to one and it's less than or equal to 30 here we add a code block this is where we calculate the number of payments and then we break actually I forgot to type an S here otherwise if the user enters an invalid value will simply print an error message enter a value between 1 and 30 now here once again we have a compilation error because number of payments cannot be resolved so we remove the declaration from here and we'll be to the top right here number of payments so this is how we add data validation to this program the problem is that this code the code inside the main method is now getting a little bit too long and this hurt the maintainability of our program someone else reading this code they have to look at all these statements to figure out what's going on this is where we need to break this code down into smaller easier to read and easier to understand chunks and that's what I'm gonna show you next so in this section you'll learn how to control the flow of execution of your programs we started off by talking about the comparison operators for comparing primitive values then we talked about the logical operators like and or and not I showed you how we can use these operators for implementing real word rules and then we talked about three types of control flow statements you learn about conditional statements like if and switch for making decisions in our programs then you learn about loops for executing code repeatedly we looked at four types of loops for loops while loops do-while loops and for each loops and finally we looked at the break and continue statements for breaking or jumping to the beginning of a loop I hope you learned a lot and been enjoying the course so far as Martin Fowler said any fool can write code that a computer can understand good programmers write code that humans can understand I can't agree more if you have seen any of my courses you probably know that I've put a lot of emphasis on writing clean code so I have dedicated this entire section on clean coding we're going to continue extending our mortgage calculator and add new features to it along the way you will see our code starts to get messy and hard to maintain so I will show you a few techniques for changing the structure of the code and make it clean and beautiful are you ready let's jump in and get started hey guys maj here i want to congratulate you on your determination for learning I would really appreciate it if you support me by liking and sharing this Post also subscribe to my Blog and enable notifications so next time I upload a Post you get notified now if you want to learn more I would encourage you to enroll in my ultimate Java series as.
If you're serious about learning Java and want to become a professional job of developer I highly encourage you to enroll in this series in case you're interested I put the link down below in the description box thank you on have a fantastic day.
So we can move this to trash now the next piece of software we need is a code editor there are so many cool editors for building Java applications the popular ones are Net Beans Eclipse and IntelliJ in this Java course I'm gonna use IntelliJ but if you have a favorite editor feel free to use that to take this course that's perfectly fine so let's search for IntelliJ download all right you can see download IntelliJ IDEA click on this link over here download the community edition which is absolutely free and it's more than enough for this course so download all right now let's drag and drop this onto the Applications folder beautiful alright we've installed all the necessary tools to build Java applications so next we're gonna look at the anatomy of a Java program in this java tutorial we're gonna look at the anatomy of java programs the smallest building block in java programs are functions if function is a block of code that performs a task as a metaphor think of the buttons on the remote control of your TV each button performs a task functions in programming languages are exactly the same for example we can have a function for sending emails to people we can have a function for converting someone's weight in pounds to kilograms we can have a function for validating users input and so on now let's see how we can code a function in Java we start by specifying the return type of that function some functions return a value like a number at day time and so on other functions don't return anything so the return type of this functions is void void is a reserved keyword in Java and that's why I've coded that in blue here now after the return type we have the name of our function so here we should give our function a proper descriptive name like send email this name clearly identifies the purpose of this function okay now after the name we have a pair of parentheses and inside these parentheses we add the para meters for this function we use these parameters to pass values to our function for example our send email function should have parameters like who is the receiver what is the subject of this email what is the content of this email and so on now in this tutorial we're not gonna worry about parameters we'll look at them in the future now after the parentheses we had a pair of curly braces and inside these braces we write the actual Java code now one thing I want you to pay attention to here is that in Java we put the left brace on the same line,
where we define our function in other programming languages like C sharp it's more conventional to put the left brace on anew line but we don't do that in Java so we put the left brace on the same line where we define our function now every Java program should have at least one function and that function is called main so main is the entry point to our programs whenever we execute a Java program the main function gets called and the code inside this function gets executed okay now these functions don't exist on their own they should always belong to a class so a class is a container for one or more related functions.
Basically we use these classes to organize our code just like how products are organized in a supermarket in a supermarket we have various sections like vegetables fruits cleaning products and so on each section contains related products by the same token a class in java contains related functions now every Java program should have at least one class that contains the main function can you guess the name of that class its main so this is how we define a class in Java we start with a class keyword then we give our class a proper descriptive name and then we add a pair of curly braces now the functions that we define in between these curly braces belong to this class and more accurately we refer to them as methods so a method is a function that is part of a class in some programming languages like Python we can have a function that exists outside of a class so we call it a function but when a function belongs to a class we refer to it as a method of that class okay now in Java all these classes and methods should have an access modifier an access modifier is a special keyword that determines if other classes and methods in this program can access these classes and methods we have various access modifiers like public private and so on now most of the time we use the public access modifier so we put that in front of our class and Method declarations so this is the basic structure of a Java program at a minimum we have a main class and inside this main class we have the main method now you might be curious why we have a capital m in the name of this class because in Java we use different conventions for naming our classes and our methods to name our classes we use the Pascal naming convention and that basically means the first letter of every word should be uppercase in contrast to name our methods we use the camel naming convention and that means the first letter of every word should be operate case except the first wart so that is why we have a capital m in the name of this class alright now that you understand the anatomy of a Java program let's create a new Java project and see all these building blocks in action in this Java tutorial you're gonna learn how to write and execute your first Java program so let's open IntelliJ IDEA here on the home screen let's create a new project alright on the left side select java and make sure project sdk is not black so earlier we downloaded jdk or Java development kit version 12 that is why JDK version 12 is selected here if you don't see that make sure to select it from this drop-down list alright now let's click on next on this page select create project from template so we're gonna create a command line application which is an application that we can run from the command line it doesn't have a graphical user interface or a GUI now I know command line application is not as exciting as an application with a graphical user interface like a mobile app or a desktop app but trust me building an application with a graphical user interface is very complicated so for now we're just gonna build command line applications to learn Java properly once you learn Java properly then you can learn about building desktop or mobile applications with Java all right now let's click on next on this page we have to give our project a name let's call it hello world.
Now over here you can see the location of this project so it's inside the idea projects folder now right below that you can see the base package which is set to comm that code with Marsh on my machine and your mission is probably gonna be comm dot package what is this well here we talked about classes and methods I told you that a class is a container for related methods so we use classes to organize our code by the same token we have a concept called package and we use a package to group related classes so a sour applications grow we're gonna end up with hundreds or even thousands of classes so we should properly organize this class us into packages now by convention the base package for a Java project is the domain name of your company in Reverse so my website is code with mass comm that is why I'm gonna set the base package for this project to come that code with Marsh now it doesn't mean that you should have an actual domain registered on an Internet this is just a way to create a namespace for our classes so now every class that we create in this project will belong to this package we're gonna talk about packages in more detail in the future so for now just type a base package for your project it can become that your name or whatever it doesn't really matter all right now let's go forward alright here's our first Java project now this code editor might look a little bit intimidating at first but trust me it's really easy and you're gonna learn about it throughout this course on the left side we have the project panel where we can see all the folders and files in a project for example on the top we have the hello word project inside this project we have the source folder where we have the source code of a project now in this folder we have another folder that is calm that code with Marsh that is the name of our base package and in this package we have this class main so you can see this main file opened on the right side here now look at the name of this file its main the Java so all Java files should have the Java extension.
Okay now let's collapse the project panel by clicking on this icon that is better so see what we have here on top of this file we have the package statement and this is used to specify what package this class belongs to so the main class that we have here belongs to this package now this package statement is terminated by semicolon so in Java wherever we have a statement we should terminate that statement with a semicolon this is exactly like c-sharp or C++ now below this package statement we have our main class exactly like what you saw in the previous tutorial so we have public class main with a pair of curly braces inside this class we have our main method so it's a public method which may it's accessible from other parts of this program it's static we haven't talked about static metals yet we'll talk about them in the future for now just remember that the main method in your program should always be static the return top of this method is void which means this method is not gonna return a value and here in parentheses we have one parameter for this function we can use these parameters to pass values to our program again we'll look at this in the future now right after this parameters as you can see the left brace and this is where we write the code in this method now by default we have this line prefix with two slashes this indicates a comment we use these comments to explain our code to other people so these comments don't get executed now let's remove this comment and write a bit of code to print something on the term in also here we're gonna use the system class in Java so capital S system.
Here in this tool tip you can see the system class is defined in this package Java dot Lang or language also look at this icon on the left side this indicates a class now inside this class we have various members we can use the dot operator to see the members defined in the system class now the member that we're gonna access is out look at the icon of this member it's F which is short for field you're gonna talk about fields in the future when we talk about classes and object-oriented programming now what is interesting here is the type of this field and you can see that on the right side that is print string so print string is another class that is defined in Java so once again we use the dot operator to look at the methods or members defined in the print stream class the method we're gonna use is print Ln which is short for line look at the icon for this method so M indicates a method now you press ENTER and IntelliJ automatically adds these parentheses as well as a semicolon so now with the code on line six we're calling or executing the print line method earlier I told you that inside this parenthesis we can pass values to our methods here we want to print the hello word on the terminal so let's type double quotes and inside these quotes right hello world so hello word is textual data in Java whenever we deal with textual data we should always surround them with double quotes now we say we have his string so a string is a sequence of characters all right so we're done with our first program now to execute this we can click on this icon on the toolbar look at the shortcut on Mac it's ctrl + R I always prefer to use shortcuts because they're faster so ctrl + R now IntelliJ is building our application and we can see the result in this little terminal window so here'sour hello work message so that was our first Java program next I'm going to explain how Java code gets executed under the hood hey Marsh here I just wanted to let you know that you really don't have to memorize anything in this course. I've done my best to create the best possible Java course and I would really appreciate it if you support me by liking and sharing this post on the social networks that you use often also be sure to subscribe and enable the notifications so next time I upload a post you'll get notified thank you so much and let's continue watching all right.
Now let's see what exactly happens under the hood the moment we run a Java program in IntelliJ there are basically two steps involved here compilation and execution in the compilation step IntelliJ uses the Java compiler to compile our code into a different format called Java byte code this Java compiler comes with the Java development kit that we downloaded at the beginning of the course let me show you so here we can right click on this main the Java and in this context menu we have an item called open in terminal it's down below unfortunately it's not visible in my recording window it's called open in terminal on Mac and probably open in command prompt on Windows so let's open that we get this terminal window or command prompt on windows here we're currently inside of this folder code with Maj that is where we have our main the Java file now we can invoke the Java compiler like this Java C and pass the name or Java file as an argument so main the Java if you're on Mac or Linux make sure to spell this with a capital M because these operating systems are case-sensitive so enter now let's look at the content of this folder on Mac or Linux we can type LS on windows we type dir.
So let's take a look in this folder now we have a new file main class this is the byte code representation of this Java file now let me use IntelliJ to run our Java program this class file gets stored somewhere else let me show you so back to the project panel here in our project we have this source folder where we our source code and we have this out folder where we have the result of the compilation so inside this folder we have production inside this we have hello world the same name as our project inside hello world we have comm which is the name of our top level package inside this package we have a sub package that is code with Marsh and here we have our main date class file so this was the compilation step now this Java byte code that we have in this file is platform independent and that means it can run on Windows Mac Linux or any operating systems that has a Java runtime environment if you go to java.com slash download we can download java or more accurately java runtime environment for various operating systems this Java Runtime environment has a software component called Java Virtual Machine or JVM this JVM takes our Java byte code and translates it to the native code for the underlying operating system so if you're on Windows machine this Java Virtual Machine converts or Java bytecode into the native code that windows can understand this architecture is the reason why Java applications are portable or platform independent we can write a Java program on a Windows machine and execute it on Linux Mac or any other operating systems that have a Java runtime environment c-sharp and python also have the same architecture that's why they are platform independent as well now let me show you how to invoke this java virtual machine to run a Java program so back to this terminal window let me expand this currently we are inside of this folder code with Marsh and in this folder we have this class file now let's go one level up so CD dot dot and one more time so now we are inside the source folder we can invoke Java Virtual Machine like this they type Java and then we type the full pass to our main class file what do I mean by that well earlier we defined this package comm that code with Marsh and this class the main class is part of this package so the full path this class is calm dot code with Marsh dot main make sure to use a capital M here because this is case sensitive now when we press ENTER Java will look at this folder calm inside this folder it will look at this other folder code with Marsh and then it will find main that class in that folder it will load the byte code and convert it to the native code for the operating system we are using so take a look so it executed our program hello world beautiful let me run a program using IntelliJ all these steps are hidden from us we don't see the compilation or execution steps so you have seen Java in action now let me tell you five interesting facts about Java Java was developed by James Gosling in 1995 at Sun Micro systems which was later acquired by Oracle in 2010 it was originally called oak after an oak tree that stood outside Gosling's office later it was renamed to green and was finally renamed to Java inspired by Java coffee that's why its logo looks like this we have four editions of Java for building different kinds of applications we have Java standard edition this is the core Java platform which is what we're using in this course it contains all of the libraries that every Java developer must learn we have Java Enterprise Edition which is used for building very large-scale and distributed systems it's built on top of java standard edition and provides additional libraries for building fault tolerant distributed multi-tiered software we have java micro Edition which is a subset of Java standard edition designed for mobile devices so it has libraries specific to mobile devices and finally we have Java card which is used in smart cards the latest version of Java is Java standard edition 12 which was released just a few months ago in March 2019 Java has close to 9 million developers worldwide currently about 3 billion mobile phones run Java as well as 120 million TV sets and every blu-ray player according to indeed.com the average salary of a Java developer is just over $100,000 per year in the US so as we can see Java is everywhere which means more opportunities for you to get hired as a professional programmer now let me give you a quick overview of how I've structured this course so you can get the most out of it this course is the first part of my complete four-part Java series each part is about three to four hours long so it can easily complete it in a day or two in the first part which is what you're watching you're gonna learn the fundamentals of programming with Java in the next section you'll learn about the type system in Java you will learn how to work with various types such as purrs strings boolean's and arrays by the end of this section you will build a mortgage calculator as your first Java project will be improving this calculator bit by bit routers course next you will learn about control flow statements that are used to build algorithms we'll be talking about various types of conditional statements and loops later in this section we'll add data validation to our mortgage calculator to force the user to enter valid values at this point you'll be able to build basic algorithms and that's great but being a good programmer requires knowing how to write good code code that is clean and expressive that's what separates an outstanding programmer from an average programmer so in the following section we'll talk about clean coding I will show you various techniques that professional programmers use to make their code clean and maintainable and finally in the last section you will learn how to find and fix errors in your java programs as well as how to package them for deployment so others can use them.
So the materials in the first part will give you a solid foundation on how to start programming in Java in the second part we'll talk about object oriented programming which is a style of programming use in most if not all Java applications whether you want to use Java to build web mobile or desktop applications you need to understand object-oriented programming well because otherwise you're going to constantly hit obstacles in the third part we're going to talk about core Java API is or application programming interfaces you'll learn about many of the useful classes in the standard Java library and finally in the last part we'll be looking at the advanced features in Java such as streams threads database programming and so on so I hope you're gonna join me on this journey and master Java the most popular programming language behind millions of apps and websites you intersection we're gonna look at the fundamentals of programming in Java you're gonna learn about variables and constants primitive and reference types you're gonna learn about casting or type conversion you will learn how to work with numbers strings and arrays and howto read input from the user once you learn all this I'm gonna give you a project you're gonna build a mortgage calculator on your own so make sure to pay great attention to all the materials you're gonna learn because you're gonna use most of them in this project are you ready now let's jump in and get started in this tutorial we're gonna talk about variables in Java we use variables to temporarily store data in computer's memory here is an example imagine in this program you want to store someone's age in the memory so we declare a variable like this ant age equals 30 so int or integer is the type of this variable so in this variable we can only store integers which are whole numbers like 1 2 3 4 numbers that don't have a decimal point now in Java we have several different types I'm gonna talk about them in the next tutorial so first we specify the type of our variable then we give it a name or a label this is also called an identifier because we use it to identify our variable this equal sign is called the assignment operator and 30 is the initial value that we are assigning to this variable so we say on line 6 we're initializing this variable which means we're giving it an initial value you always have to initialize our variables before reading them so with this line we're storing number 30 some where in computer's memory and we're assigning this label to that memory location now on line 7 instead of printing hello world we can print the value of the age variable take a look so I'm gonna run this program using ctrl +R there you go now we see 30 on the terminal beautiful we can also change the value of our variable so after we initialize it per house we can change it to 35 now when we run this program again we see it 35 beautiful we can also initialize multiple variables on the same line but this is something that I don't recommend because it makes your code ugly and hard to read here is an example we can declare another variable like temperature and set it to 20 sousing a comma we can declare multiple variables on the same line now even though this is technically possible it's not something that I recommend so it's always better to declare one variable on each line like this we can also copy the value of one variable into another here is an example let me delete these variables and declare a new variable called my age we set it to 30 and then we declare another variable like her age and we set it to my age so now when we print her age we're gonna see 30 take a look so on line seven recapping the value of this variable into this other variable now one thing I want you to pay attention to here is the convention I have used for naming our variables as I told you before this is called the camel case notation so we should capitalize the first letter of every word except the first word so in this case the first word my it's all in lower case but the second word starts with a capital letter so this is all about declaring and initializing variables in the next tutorial we're going to talk about various types in Java in this tutorial we're going to talk about various types in Java basically we have two categories of types we have primitive types for storing simple values and non primitive types or reference types for storing complex objects so in the category of primitive types we have white which takes one byte of memory and in one bite we can store values from 128 to 127 now the more bytes we have the larger numbers we can store so next we have short which takes two bytes and with this we can store values up to 32,000 next we have integer which we have seen before integers take four bytes of memory and allow us to store values up to two billion then we have long which takes eight bytes and with this we can store even larger numbers now all these types are for storing whole numbers that don't have a decimal point if you want to store a number that has a decimal point you have to use float or double float takes four bytes double takes eight bytes so obviously we double we can store larger numbers next we have char for storing a single character like ABC and this chart I've take two bytes so they support international letters and finally we have boolean for storing boolean values which can be true or false just like yes or no in English now let's take a look at a few examples earlier we use an integer for storing someone's age but as you learned integers take four bytes and allow us to store values up to two billion we don't need four bytes of memory to store someone's age all we need is one byte because with one bite we can store values up to 127.
So I'm gonna change this to byte that is better now let's look at another example let's say we want to store the number of times a Post has been watched/or viewed so we define an integer called views count note that I'm always using meaningful names for my variables because these names help us understand what this code does I've seen some people use variable names like V or V 1 or n nobody knows what these variables do so as a best practice always use meaningful and descriptive names for your variables so views count we set this to a large number like 1 2 3 4 5 6 7 8 9 now in Java whenever you deal with a large number like this you can use an underscore to separate every three digits just like how we use a comma in our documents to make our numbers more readable we can use an underscore in Java so with integers we can store values up to two billion but let's say the number of times this Post has been watched is three billion so I had a three here now we have a red on the line that indicates an error let me hover our mouse over it we see this tool tip integer number too large so we need to change the type of this variable to long however the error is still there what's going on here the reason we're getting this error is that by default Java sees these numbers as integers so even though we have defined the type of this variable as long Java compiler sees this value as an integer and he thinks this value is too large for an integer to solve this problem we need to add an L as a suffix or this number we can use an uppercase or a lower case L but as you can see a lowercase L kind of looks like a 1 so it's better to use a capital L so these are examples of whole numbers now let's declare a variable for storing a number with a decimal point so double price we set this to 1099 obviously the double variable is too large for storing the price of a product so we can change this to float that is better but you have a compilation error here take a look incompatible types required float but found double the reason we're seeing this error is that by default Java sees these numbers with a decimal point as double so even though we set the type of this variable to float Java sees this number as a double so just like how we added a suffix to this number to represent it as a long we need to add a suffix here to represent this number as a float and that suffix is F once again we can use an upper case or lower case F so these are examples of numbers now let's store a character so char we call it letter and we set it to a note that we should always surround single characters with single quotes and multiple characters or strings with double quotes.
Okay so char represents only one character string represents a series of characters and finally let's see an example of a boolean so we define a boolean variable called is eligible is this person eligible for loan or not we said this to true or false these are the boolean values now note that all these words coded in orange are reserved keywords in Java just like public static void class package these are all reserved keywords so we cannot use these reserved keywords the name our variables classes and methods in the last tutorial you learned that we use primitive types to store simple values like numbers boolean values or single characters in contrast use reference types to store complex objects like data objects or mail messages these are complex objects now in Java we have eight primitive types that you have seen before all the other types are reference types let me show you an example so here in this program first I'm gonna declare a primitive type let's say white age equals 30 now declaring and initializing a reference type is slightly different from primitive type let me show you so let's type date now here in this tool tip box which is called intelliJ sense we can see various classes that have date in their name so IntelliJ is helping us complete our code by suggesting these class names now here we have a date class in this package Java the util so this package contains a lot of utility classes that are useful in a lot of programs you also have a date class in a different package Java SQL or sequel which is used for programming databases so this is the benefit of packages we can have the same class but in different packages they don't conflict so packages create a namespace for our classes okay now in this case if we select the first date class and press enter or tab IntelliJ automatically adds this line for us import Java that you till the date so because currently we are in this package in order to use a class from a different package we need to import it so here we're importing the date class in this package will talk about packages in more detail in the future so back to our date variable let's give this variable a name collect now now we set this here we need to use the new operator to allocate memory for this variable and this is one of the differences between the primitive and reference types when declaring primitive types we don't need to allocate memory memory is allocated and released by Java Runtime environment but when dealing with reference types we should always allocate memory now we don't have to release this memory Java Runtime environment will automatically take care of that so we use the new operator and then repeat the name of our class in this case date and then we add parentheses followed by a semicolon in this example this variable we have defined here is an instance of the date class so this class is defined template or blueprints for creating new objects new instances as another example we can have a class called human and we can have objects like John Bob Mary and so on so an object is an instance of a class now this object or this class have members that we can access using the dot operator so we can type now dot and these are all the members defined in this class or in this object for example we have a method called get time 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 is print string which is another class in Java so once again we can use a dot operator and call the print line function now let me show you a very cool shortcut instead of typing all this we can use one of these code snippets so we type s oh you see and press tab and this generates this piece of code for us allright now let's pass our data object here note that I have not surrounded this variable with double quotes because this is a string and if you run this program.
We'll see now on the terminal there you 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 different let's take a look so I'm gonna delete all the code here in Java we have a point class that is defined in this package Java that awt so we press ENTER and now we have this import statement on the top beautiful let's declare a variable like point 1 and set it to new point here we can pass the initial values for x and y so I'm gonna pass 1 and 1 so intelligent automatically adds these labels x and y now just like before I'm gonna declare 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 if ,we print point two we're going to see the change that we just made take a look so S or ut tab let's print point to run the program there you go so the change was visible so remember this reference types are copied by the references,
whereas primitive types are copied by their value and these values are completely independent of each other in this tutorial we're gonna look at strings in Java so earlier in the course we printed the hello world message on a terminal this hello word that we have here is a string or more accurately it'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 look so in this string we have 13 characters and this is useful in situations where you want to check the length of the input by the user.
For example you might have a sign-up form with a username field you can check the length of someone's username and give them an error if the username is longer than let's say 20 characters pretty useful we also have another method that is index of and this returns the index of the first occurrence of the character or the string that we pass here for example if you pass H the index of H is 0 so let's run the program there you go we get 0 if you pass e we get 1 because the index of the first II in this message is 1 now what if you pass a character or a string that doesn't exist in this message let's say Skye we get negative 1 so with this method we can check to see if a string contains certain characters or words or sentences and so on another useful method is replace and with this we can replace one or more characters with something else for example we can replace any exclamation marks with let's say a store so this replace metal has two parameters one is target the other is replacement and here we're passing two values for these parameters here's the first value here is the second value and we have separated these values using a comma now in programming terms we refer to this values as arguments a lot of programmers don't know the difference between parameters and arguments parameters are the holes that we define in our methods arguments are the actual values that we pass to these methods so in this case target and replacement or parameters but exclamation mark and asterisk are arguments now let's run this program and see what happens so our explanation marks are replaced with stars now what is important here is that this method does not modify our original string it returns a new string so if we print our original string right after SRU T tab message you can see the original string is not changed because in Java strings are immutable.
we cannot mutate them we cannot change them so any methods that modify a string will always return a new string object okay we also have another useful method to lower case let's take a look so to lowercase converts all characters to lowercase and once again you can see that the original string is not affected because this method returns a new string okay we also have two uppercase and another useful method is trim trim and with this we can get rid of extra white spaces that can be at the beginning or the end of a string sometimes our users type unnecessary spaces in form fields so using the trim method we can get rid of these white spaces let me show you so I'm gonna add a couple of spaces before and after our message now when we trim it these white spaces are gonna get removed take a look so here's the original string you can see two white spaces at the beginning and here's our string after trimming so these are some useful methods in the string class but this glass has more methods than we don't have time to cover in this lecture but as we go through the course you're gonna learn more about the string class and other useful classes in Java third times will include special characters in our strings like a tab or a new line or a backslash or double quotes so in this tutorial I'm gonna show you how to include these special characters in your strings so here we have the string hello Marsh let's say we want to surround Marsh with double quotes now here's the problem if we add a double quote here Java compiler thinks this is the termination of our string so it doesn't stand what we have after that's why we have a compilation error the fixes problem we need to prefix this double code with a backslash so using this backslash we have escaped the double quote now one more time let's add backslash double code here now let's run the program and see what we get so we get hello Marsh in double quote beautiful so double quote is one of those special characters that you need to be aware of another special character is backslash let's say we want to store the pass to a directory on a Windows machine so that will look like this C Drive backslash windows backslash whatever now if you want to store this in a string we need to escape each backslash let me show you so C Drive backslash now we have a problem Java compiler thinks we're escaping the double code here so it thinks our string is not terminated with another double code but that's not what we want you want to add a backslash here so we need to prefix our backslash with another back slash now we type windows one more time something let's run the program so even though we have two backslashes in our code we actually see one back slash in a terminal window in other escape sequences backslash N and we use that to add a new line to our strings so let's change this to backslash N and run the program to see what happens now our string is broken down onto multiple lines by the first line we have C Drive then we have Windows so wherever we had a backslash n Java will insert a new line,
we can also add a tab in our strings so if you add backslash T here there will be a tab which means C Drive and windows let's take a look so C Drive here we have a tab and then windows now in Java we have a few more escape sequences but quite honestly they're hardly used so remember these four escape sequences that we cover in this tutorial in this tutorial we're going to talk about arrays in Java we use arrays to store a list of items like a list of numbers or a list of people or a list of messages let me show you so here we have an integer variable you want to convert this to an integer array so right after int we add square brackets now we have a compilation error because we're storing a single number in this array so to fix this we need to remove one because arrays are reference types we need to use the new operator here then we repeat the type one more time enter a and here in square brackets we specify the size or the length of this array how many items do we want to include in this array let's say five also we should change the name of this variable from number two numbers because we're dealing with a list of items so always pay attention to the name of your variables now you can access individual items in this array using an index so we type numbers square brackets to reference the first element or first item we use zero now we can set this to a value like 1 similarly we can set the second item to 2 now what if we use an invalid index let's say 10 this array doesn't have 10 items so let's see what happens numbers of 10 we said this to 3 when we run this program we get an exception exceptions are Javas way to report errors so in this case an exception was raised and our program crashed we'll talk about exceptions in detail later in the course.
so now let's remove the last line let's see what we get we get this weird string in sort of the items in our array here's the reason by default when we print an array Java returns the string which is calculated based on the address of this object in memory so if you have another array and we print that we're gonna see something different because each object is gonna be in a different memory space okay now how can we see the actual items in this array well we have a class in Java called arrays let me show you arrays so this class is defined in Java that util package let's press ENTER now this is important on the top beautiful so we can use the dot operator to access the members of this class here we have a method called two string.
Now as you see it this method is implemented multiple times so in the first implementation this method gets a float array in the second implementation it takes an integer array and so on so for all primitive types as well as reference types this method is implemented multiple times this is what we call method overloading,
now we can call this method and pass our integer array and this will return the string representation of this array so we can cut this from here and pass it to our print method like this now let's run the program one more time and here's our array beautiful so the first two items are initialized the others are set to 0 by default because here we're dealing with an integer array if you had a boolean array all items why default get initialized to false if you have a string array all items get initialized to an empty string okay now this syntax for creating and initializing an array is a little bit tedious and it's an older syntax there is a newer way to initialize an array if we know the items ahead of time like in this case so I'm going to remove these two lines I'm also gonna remove the new operator here we use curly braces and inside these braces we add all the items in this array let's say 2 3 5 1 & 4 now we have 5 items so the length of this array is gonna be 5 we can read that using the lengths so if we type numbers dot look here we have is filled look at the icon it's an F so this is a field which is like a variable in a class and the type of this field is an integer so this returns the number of items in this array let's get that and printed using our print method like this take a look so we get five now in Java arrays have a fixed size so once we create them we cannot add or remove additional items to them they have a fixed length if you want to be able to add or remove additional items from an array you should use one of the collection classes that we'll talk about later in the course for now all I want you to remember is that arrays have a fixed length now currently our array is not sorted these numbers are in some kind of random order we can easily sort this array using the sort method of the arrays class let me show you so I'm gonna remove this line and call arrays dot sort once again you can see this method is overloaded because it's implemented with different parameter types so we call this method and pass our numbers array now when we run this program we can see our array is sorted beautiful so yeah I've learned that we use arrays to store a list of objects in Java.
We can also create multi-dimensional arrays for example we can create a two-dimensional array to store a matrix or we can create a three-dimensional array to store data for cube these are useful in scientific computations let me show you so here we have a single dimensional array to convert this to a two-dimensional array we need to add another pair of square brackets now we have a compilation error because we need to repeat these brackets on the other side so let's say we want to create a 2 by 3 matrix so 2 rows and 3 columns we add in other brackets here and change these lengths to 2 and 3 so now we have 2 rows and 3 columns now to access individual items in this array we need to supply two indexes first the index of the row so we can go to the first row and then the first column and initialize that to 1 now let us print this so and so you t-tap once again we use our arrays class dot to string and pass this object take a look once again we get this weird string because here we're dealing with a multi-dimensional array to solve this problem we need to use another method in this class called deep to string use this for printing multi-dimensional arrays take a look now we have this matrix which has two rows and in each row we have three columns we can also create a three dimensional array all we have to do is to add another pair of brackets and specify the length of that dimension pretty easy now what about the curly brace syntax let me show you.
So let's revert this back to a two dimensional array we're gonna get rid of the new operator and use curly braces now let's say in this matrix we're gonna have two rows and three columns so each row is an array itself because it's a list of items right so we add another array here let's say 12 3 then comma now we add the second row which is another array in this row we're gonna have 3 numbers 4 5 & 6 now let's remove this line we don't need it anymore and print this array so here's the end result you have learned a lot about variables ya learned that when declaring them we need to initialize them and we can always change their value later on throughout the life time of our programs however there are times that we don't want the value of a variable to change for example let's declare a variable called pi and set it to 3.14 now here we need to add an F to represent this as a float because by default Java compiler sees this number as a decimal okay now you know that we use pi to calculate the area of a circle what if before we calculate the area of a circle I come here and type pi equals 1 then all our calculations are gonna get messed up we don't want this to happen that's when we use constants so if we type final here Java compiler will treat this as a constant so once we initialize this we cannot change its value later on you can see here we have a compilation error and it says cannot assign a value to final variable pi so pi is a final variable or a constant now by convention we use all capital letters to name constants so this should be PI beautiful.
Now I tell you a little side story in one of my early courses in another blog, that I created years ago that was c-sharp basics for beginners there I used the same example to teach the concept of constants but I pronounce this word as P instead of Pi and believe it or not to this day people make fun of me for saying P instead of Pi but that's how we learned this back in Iran we pronounce it as P and I think Greek people also say P but anyway I just thought to share this Post to change the mood now you're done with constants next we're gonna talk about arithmetic expressions in this tutorial we're going to talk about arithmetic expressions in Java so in Java we have the same arithmetic operators that we have in math we have addition subtraction multiplication division and modulus which is the remainder of a division let's look at a few examples so I'm gonna declare an integer called result and here we can type 10 plus 3 now when we print result it's gonna be 13 pretty straightforward there you go so this is addition we also have subtraction multiplication division is an interesting one let's take a look so here the result is a whole number because in Java the division of two whole numbers is a whole number if you want to get a floating-point number here you need to convert these numbers to afloat or a double let me show you so we prefix this number with parentheses and in parentheses we type double now we are casting or converting this number to a double similarly we should do that here and now we have a compilation error because on the left side we declared an integer but here the result of this expression is a double and by the way an expression is a piece of code that produces a value so what we have here is an expression because it produces a value so to fix this problem we need to change this to double now when we run this program we get this floating point number beautiful so these are the arithmetic operators and these numbers that we have here are called operands we also have increment and decrement operators let me show you.
So I'm gonna declare a new variable int X we set it to 1 now if you want to increase the value of x by 1 we use the increment operator now let's print this on a terminal so we get 2 there you go we can apply this operator as a post fix or as a prefix and we get the same result take a look too however if we use this on the right side of an assignment operator we get different results let me show you so I'm gonna declare another variable Y we set it to X plus plus in this case because we have applied the increment operator as a post fix first the value of x will get copied to Y so Y would be 1 and then X will be incremented by 1 so if you print x and y x is gonna be 2 and Y is gonna be 1 take a look so X is 2 and Y is 1 beautiful however if you apply this as a prefix first X will be incremented by 1 so it will be 2 and then it will be copied to Y so in this case both X & amp;Y will be to take a look so we get two and two now what if you want to increment X by more than one let's say by two well there are two ways to do this let's remove Y we don't really need it anymore we can write x equals x plus 2 so first we add 2 to X the result will be three and then three will be copied into X the other way is to use the Augmented or compound assignment operator so we can write X plus equals two what we have on line eight is exactly identical to what we have on line seven well as you can see it's shorter so this is a better way to write the same code now this is one of the Augmented assignment operators we have the Augmented assignment operator for other arithmetic operators so we can type X minus equals 2 and this would reduce the value of x by 2 we also have multiply and divide so these are the Augmented or compound assignment operators right now.
I've got a question for you here we have declared this variable X it goes to 10 plus 3 times 2 what do you think is the result of this expression the result is 16 let's run this program and find out so run there you go we got 16 but why well this is a very basic math concept that unfortunately a lot of people don't know in math the multiplication and division operators have a higher priority so 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 of these 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 conversion happens 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 we calculate the mortgage so we get a principal multiplied by this expressionand then divide it by this other expression, so we get a result store it in this string mortgage format it and print it over here now here we can also avoid declaring this variable and simply add this expression over here but it decided to do this to increase the readabilityof this code otherwise this line would be so long but that's just my personal preference you don't have to follow this alright so this was my implementation 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 because zero is less than five so the control moves to line seven this line gets executed now at the end of this iteration or at the end of this loop the control moves here so I is incremented by one now we are at the beginning of the second iteration once again this condition is evaluated is one less than five obviously it is so once again the body of this loop gets executed now fast forward at the end of the fifth iteration I will become five five is not less than five so the loop condition will be false and control moves outside of this for loop now here's one thing you need to remember if you want to execute something five times you can initialize your loop counter or loop variable to zero and use the less than operator here another way is to initialize this to one and then use the less than or equal to operator here now to make this more interesting let's print I over here so here we add a space and then concatenate this string with I take a look so we get hello ward one two three four five in contrast if we initialize I to zero and use the less than operator we will get hello word zero one two three four we can also print these numbers in reverse order so we initialize I to five and execute this loop as long as I is greater than zero but here instead of incrementing I we decrement it now we get hello world five four three two one so this is all about for loops next we're gonna look at while loops in this tutorial we're gonna talk about while loops in Java while loops are very similar to for loops in terms of their functionality but they're different in terms of syntax let me show you so we're gonna continue with the example from the last tutorial I'm gonna rewrite this code using a while loop so first we declare a loop variable and I initialize it to zero next we type while and here in parentheses we type our loop condition while I is greater than zero then we're gonna execute the code inside this block so I'm gonna copy this from here paste it in this block and finally we need to decrement I like this so at the end of each iteration we decrement I just like our for loops so as you can see we can achieve the same thing using a for loop or a while loop however the implementation using the for loop is a little bit lighter and cleaner so in situations where you know ahead of time how many times you want to execute one or more statements it's better to use a for loop while loops are better in situations where we don't know exactly how many times you want to repeat something for example let's say we're going to write a program and ask the user to continuously enter something until they type quit the moment they type quit we're gonna terminate the program in that situation we don't know how many times the user is going to enter something so let's write that program using a while loop I'm gonna delete everything from here all right we're gonna start with our while loop now what is our loop condition here we don't have a counter variable in this example instead we want to check to see if the user entered quit or not so here we can declare a string called input and initialize it to an empty string then we can write a while loop like this while input does not equal to quit now this code is not gonna work,
because input is a string which is a reference type and we cannot use comparison operators between reference types because these operators will compare the address or a string objects not their value so if you have two strings quit and quit but stored indifferent memory locations to have different addresses so we can use the inequality operator to compare their value instead we need to use the equals method of string objects so we want to check to see if the input equals quit now here we need to apply the not operator so as long as the input does not equal quit we're gonna continuously ask the user to enter something so here we can print a label like input and then we can use a scanner object to read something from the terminal so let's create a scanner object and instantiate it using system dot in I didn't call scanner that next this will return a string so we can store it in this input variable now with this implementation in every iteration, we're going to create a new scanner object so if the user enters 10 numbers we're gonna create 10 scanner objects in memory this is unnecessary and it's actually a bad practice because it's going to pollute our memory so it's better to create the scanner object outside of a while loop and then simply use it here also here we are assuming that the user is typing everything in lowercase so if they type quit in uppercase or any combinations of lowercase and uppercase characters this logic is not gonna work the way we want so over here right after reading something from the terminal we're gonna call the to lowercase method of string objects to convert it to lowercase now to make this program more interesting let's echo back whatever the user enters so we simply print that on the terminal now let's run this and see what happens so I'm going to enter if your numbers like 1 2 & 3 whatever we type gets a code back but the moment we type quit our program terminates so while loops are useful in situations where we don't know ahead of time how many times we want to repeat something in Java we have another type of loop called a do-while loop it's very similar to a while loop but it gets executed at least once let me show you what I mean so I'm gonna rewrite the same code using a do-while loop we start with a do keyword then we create a code block at the end of this code block we type while followed by our loop condition so not input dot equals quit and then we terminate this using a semicolon now inside the body of this loop we'll simply copy all these lines we have here now compared these two types of loops with while loops we check the condition first so if the condition is false the first time this loop will never get executed in contrast with do-while loops we check the condition last so do-while loops always get executed at least once even if the condition is false that is the only difference the reality most of the time we use while loops do-while loops are rarely used but there are certain cases for that so just be aware of them but most of the time prefer to use wire loops we're gonna continue with the example from the last tutorial this program we have written has a tiny problem let me show you so I'm gonna run this enter a couple numbers these numbers get echo back beautiful if we type quit the program terminates but the word quit also gets echoed back this is a bit weird so let's look at a couple ideas for solving this problem back to our code one way to solve this problem is to check the input before printing it so here we can type an if statement if the input does not equal quit then we're print it so not equal input dot equals quit if this condition is true then we're going to print the input.
let's take a look so one to quit beautiful we solved the problem there is another way to solve this problem as well let me show you we can reverse this condition so if the user types quit you can immediately jump out of the loop using the break statement so I'm gonna remove the nut operator if the user types quit we're gonna break out of the loop otherwise we're gonna continue execution and print this input on a terminal so when Java sees the break statement it will ignore everything else after and it will terminate the loop let's run the program once again we enter a couple numbers followed by quit beautiful so this is the break statement we also have the continuous statement that moves control to the beginning of a loop let me show you so let's imagine if the user types pass we don't want to echo that but also we don't want to terminate the loop you want to ask the user to try one more time so after we read the input we can check to see if input equals pass this is where we use the continuous statement when Java sees this it would move control to the beginning of the loop so all these other statements are gonna get ignored and what the user types is not gonna get printed on the terminal let's run the program and see this in action so we type 1 2 pass it doesn't get echoed back one more time and finally quit so to recap the break statement terminates a loop and the continue statement moves control to the beginning of a loop now one last thing before finish this tutorial in this implementation we don't really need this loop condition because the moment user types quit this break statement is gonna kick in and terminate the loop so we can simplify this code by using a true as our loop condition so this is always true and this loop is gonna get executed forever until the user types quit this is a very common technique that you see among professional programmers just remember if you're using this technique make sure to have a break statement otherwise you will end up with an infinite loop that executes forever it never terminates and that can be very dangerous in terms of memory consumption,
so if you're using while true make sure you have a break statement in your loop the last type of loop we want to look at is the for each loop in Java we use for each loops to iterate over arrays or collections let me show you so I'm going to start by declaring a string array called fruit and we initialize this with three items let's say Apple mango and orange now let's say we want to iterate over this array and print each item on a terminal we can use any of the loops you learn about earlier like a for loop or awhile loop but we can also use the for each loop which is a bit easier let me show you first I'm going to use the for loop to iterate over this array so we type for here we declare our loop variable or loop counter into I we set it to zero as long as I is less than fruits that length we're going to increment I by one after each iteration and here we simply print fruits of I let's run the program and see what we get so we get each item on a new line beautiful now there is another way to write the same code using the for each loop here we type for in parentheses with declare and loop variable but the type of this variable should be based on the type of items in our array so here we have a string array and that means every item in this array is a string so here we should declare a string variable we call it fruit here we type a colon and then the name of our array fruits now in each iteration fruit will hold the value of one item in this array so here we don't have to declare a numeric counter we don't have to write a boolean expression like this we don't have to increment our counter it's much easier to iterate over an array now if we print fruit we get the exact same result as before take a look so the first three items are from our for loop and here's the result our for each loop so this is the for each loop however this for each loop has a couple of limitations, one limitation is that it's always forward only so we cannot iterate over this array from the end to the beginning in contrast we can easily do this with a for loop so here we can initialize I to fruits that length then we change this operator to greater than and replace this value with zero so as long as I is greater than zero we're going to decrement I the second limitation of the for each loop is that here we don't have access to the index of each item all we have is this loop variable which holds the value of each item in this array in contrast in our for loops we can access both the index and the actual item so I represents the index of each item and fruits of I returns the item at the given index so if you need the index then you'll have to use the for loop otherwise it's much easier to use the for each loop all right now let's get back to our mortgage calculator and implement some basic error handling so here I've changed this question by adding this label that identifies the range of values we can enter so the minimum amount of loan we can get is $1,000 and maximum is 1 million dollars so if I enter 1 here I get this message enter a number between one thousand and one million and now we are asked this question one more time if I keep entering invalid values I get asked the same question now let's enter a valid value like 1 million dollars next we'll have to enter the annual interest rate now here we need to enter a value that is greater than 0 and less than or equal to 30 so if I enter 0 we get this message enter a value greater than 0 and less than or equal to 30 once again we're asked this question one more time so let's enter a valid value like 3.9 to here we need to enter a value between 1 and 30,
so if you enter 0 we get an error message and we're asked the same question so let's enter 30 and finally we get the result here's our mortgage or monthly payments so go ahead and spend five to ten minutes on extending this mortgage calculator by adding error-handling to it you'll see my solution X all right let me show you how I'm gonna solve this problem step by step so for each question we want to validate the value that the user enters if the value is invalid you want to keep asking the same question so this is where we can use an infinite loop let me show you so here's our first question principal I'm gonna wrap these two lines inside an infinite loop while true so we're gonna keep asking the same question until the user enters a valid value so here after we read the principle we can write an if statement like this if principle is greater than or equal to 1000 and it is less than or equal to 1 million and here we can use an underscore to separate these digits to make our code more readable so if the user enters a valid value then we can break out of this infinite loop otherwise we're gonna print an error message so enter a value between 1001 million like this ok now if you look on the right side here you can see this red bar this indicates an error and here in this preview window you can see exactly where we have an error it's down below on line 30 where we calculate the mortgage so if you click on this red bar we jump over here principal is highlighted in red so here we have a compilation error cannot resolve symbol principle here is the reason because we've wrapped these few lines inside this while loop and earlier I told you that whenever you declare a variable that variable scope to the Block in which it's defined so this is where we have declared the principal variable and it's scoped to this block it's outside of this block that's why we get this compilation error so to solve this problem we need to declare this outside of this while loop we can do it right here after radicular our constants.
So let's say int principle and we can initialize it to 0 now we remove the declaration from here and the error is gone now we need to repeat the same pattern with other questions so here's our second question where we read the annual interest once again we add an infinite loop now the moment we read the annual interests invalidate the data so if annual interest is greater than or equal to let's say one and it is less than or equal to 30 then we're gonna break out of this infinite loop now here we should also calculate the monthly interest so the proper way to do this is like this if the user enters a valid value we add a code block here first we calculate the monthly interest and then break out of the loop otherwise we print an error message enter a value between 1 and 30 okay now if you look to the right side again we have two compilation errors monthly interest is not resolved because we have declared it inside of this block so let's move the declaration to the top here we remove the float keyword and declare monthly interest over here that's better and finally for the last question one more time we're to wrap it in this infinite loop this is where we read the number of years and right after this line we need to do our data validation so if yours is greater than or equal to one and it's less than or equal to 30 here we add a code block this is where we calculate the number of payments and then we break actually I forgot to type an S here otherwise if the user enters an invalid value will simply print an error message enter a value between 1 and 30 now here once again we have a compilation error because number of payments cannot be resolved so we remove the declaration from here and we'll be to the top right here number of payments so this is how we add data validation to this program the problem is that this code the code inside the main method is now getting a little bit too long and this hurt the maintainability of our program someone else reading this code they have to look at all these statements to figure out what's going on this is where we need to break this code down into smaller easier to read and easier to understand chunks and that's what I'm gonna show you next so in this section you'll learn how to control the flow of execution of your programs we started off by talking about the comparison operators for comparing primitive values then we talked about the logical operators like and or and not I showed you how we can use these operators for implementing real word rules and then we talked about three types of control flow statements you learn about conditional statements like if and switch for making decisions in our programs then you learn about loops for executing code repeatedly we looked at four types of loops for loops while loops do-while loops and for each loops and finally we looked at the break and continue statements for breaking or jumping to the beginning of a loop I hope you learned a lot and been enjoying the course so far as Martin Fowler said any fool can write code that a computer can understand good programmers write code that humans can understand I can't agree more if you have seen any of my courses you probably know that I've put a lot of emphasis on writing clean code so I have dedicated this entire section on clean coding we're going to continue extending our mortgage calculator and add new features to it along the way you will see our code starts to get messy and hard to maintain so I will show you a few techniques for changing the structure of the code and make it clean and beautiful are you ready let's jump in and get started hey guys maj here i want to congratulate you on your determination for learning I would really appreciate it if you support me by liking and sharing this Post also subscribe to my Blog and enable notifications so next time I upload a Post you get notified now if you want to learn more I would encourage you to enroll in my ultimate Java series as.
If you're serious about learning Java and want to become a professional job of developer I highly encourage you to enroll in this series in case you're interested I put the link down below in the description box thank you on have a fantastic day.
0 Comments:
Hi , How can i help you.
If you have any DOUBT let me know.
🙏🙏🙏