Course Hive
Search

Welcome

Sign in or create your account

Continue with Google
or
Java Full Course for Beginners
Play lesson

Java Tutorials - Java Full Course for Beginners

4.0 (0)
2 learners

What you'll learn

This course includes

  • 4 hours of video
  • Certificate of completion
  • Access on mobile and TV

Summary

Keywords

Full Transcript

Hi, my name is Marsh and I'm going to be your instructor in this Java course. In this course, you're going to learn everything you need to get started programming in Java. We'll start off by installing all the necessary tools to build Java applications. Then you're going to 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 going to 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 by the end of 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 Marsh. I'm a software engineer with two decades of experience and I've taught over 3 million people how to code and how to become professional software engineers.

I have a coding school at codeglidmosh.com where you can find plenty of courses that help you take your coding skills to the next level. I hope you stick around and learn this beautiful and powerful programming language. And now I'm award from this video's sponsor. As someone who runs an online business, I cannot stress enough the importance of staying safe online.

Which is why I was so excited when Dashlane reached out to me. If you don't know, Dashlane 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 Dashlane.com slash mosh to give it a go. If you want to upgrade to the premium to get VPN or dark web monitoring, you can use the promo code mosh to get 10% off.

Sign up for Dashlane today and keep yourself safe online. Now back to the course. In this Java tutorial, we're going to download and install the necessary tools to build Java applications. So open up your browser and search for JDK download.

JDK is short for Java development kit and it's basically a software development environment for building Java applications. It has a compiler. It has a bunch of code that we can reuse. It has a Java runtime environment and a bunch of other stuff.

So over here, you can see this page on Oracle.com. Now, here's the Java SEO which is short for Java standard edition. Click on this. Now over here, click on this icon.

Now on this page, you can see Java development kit for various platforms like Linux, Mac OS and Windows. Here I'm on a Mac so I'm going to 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 going to see 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, all right, 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 code editors for building Java applications.

The popular ones are netbeams, eclips and IntelliJ. In this Java course, I'm going to 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 application folder. Beautiful. All right. We have installed all the necessary tools to build Java applications.

So next, we're going to look at the anatomy of a Java program. In this Java tutorial, we're going to look at the anatomy of Java programs. This smallest building block in Java programs are functions. A 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, a date time and so on. Other functions don't return anything. So the return type of this function 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. Now after the name, we have a pair of parentheses and inside these parentheses, we add the parameters for this function.

We use these parameters to pass values to our function. For example, our send email function should have parameters like who's 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 going to worry about parameters, but look at them in the future. Now after the parentheses, we add a pair of curly braces and inside these braces, we write the actual Java code.

Now one thing I want you to pay attention to here is that in Java, we put the left brace on the same line where we define our function. In other programming languages like C sharp, it's more conventional to put the left brace on a new line. What 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. But 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? It's 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 the minimum, we have a main class and inside this main class, we have the main method. Now you may 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 uppercase except the first word.

So that is why we have a capital M in the name of this class. 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 going to 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. All right, on the left side, select Java and make sure project SDK is not blank. 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. All right, now let's click on next. On this page, select create project from template. So we're going to 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 a 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 going to 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 come. That code with mosh on my machine on your machine is probably going to be calm dot package. What is this?

Well, are you ever talked about classes and methods? I told you that a class is a container for related methods. So we use classes to organize our code. By the same token, we have a concept called package and we use a package to group related classes.

So as our applications grow, we're going to end up with hundreds or even thousands of classes. So we should properly organize this classes 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 mosh.com.

That is why I'm going to set the base package for this project to come. Code with mosh. Now, it doesn't mean that you should have an actual domain registered on the 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 going to 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. All right.

Here is 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 going to 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 our 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 our project. Now in this folder, we have another folder that is com.code with mosh. 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. It's 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 the 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 means it's accessible from other parts of this program. It's static. We haven't talked about static methods 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 going to 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 parentheses, you can see the left raise. 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 this comment to explain our code to other people. So these comments don't get executed.

Now let's remove this comment and write a bit of code to print something on the terminal. So here we're going to use the system class in Java. So capital S system here in this tooltip, you can see the system classes defined in this package, Java.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 dots operator to see the members defined in the system class. Now the member that we're going to access is out.

Look at the icon of this member. It's f which is short for field. We're going to 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 stream. So print stream 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 going to 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 intelligent automatically adds these parentheses as well as a semicolon. So now with the code online six, we're calling or executing the print line method.

Earlier, I told you that inside this parentheses, we can pass values to our methods. Here we want to print the hello word message on the terminal. So let's type double quotes and inside this quotes, right? Hello world.

So hello world is textual data in Java, whenever we deal with textual data, we should always surround them with double quotes. Now we say we have a 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 is control and R. I always prefer to use shortcuts because they're faster. So control and R.

Now intelligent is building our application and we can see the result in this little terminal window. So here is our hello work message. So that was our first Java program. Next, I'm going to explain how Java code gets executed under the hood.

Hey, marsher, I just wanted to let you know that you really don't have to memorize anything in this course. I put together a comprehensive cheat sheet with summary notes that you can download below this video. So I've done my best to create the best possible Java course and I would really appreciate it if you support me by liking and sharing this video on the social networks that you use often. Also, be sure to subscribe and enable the notifications.

So next time I upload a video, you'll get notified. Thank you so much and let's continue watching. All right, now let's see what exactly happens under the hood. The moment we run a Java program in IntelliJ.

There are basically two steps involved here. Compilation and execution. In the compilation step, IntelliJ uses the Java compiler to compile our code into a different format called Java bytecode. This Java compiler comes with the Java development kit that we downloaded at the beginning of the course.

Let me show you. So here we can right-click on this main the Java and in this context menu, we have an item called Open in Terminal. It's down below, I'm fortunately 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 mush. That is where we have our main the Java file.

Now we can invoke the Java compiler like this, Java C, and past the name of our Java file as an argument. So main the Java. If you're on Mac or Linux, make sure to spell this with a capital M because these operating systems are case sensitive. So enter.

Now let's look at the content of this folder. On Mac or Linux, we can type Ls, on Windows we type DIR. So let's take a look. In this folder now we have a new file main.class.

This is the bytecode representation of this Java file. Now let me use Intelligate 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 have 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 calm, which is the name of our top level package. Inside this package, we have a sub package that is code with mush.

And here we have our main.class file. So this was the compilation step. Now this Java bytecode that we have in this file is platform independent. And that means it can run on Windows, Mac, Linux, or any operating systems that has a Java runtime environment.

If we go to Java.com slash download, we can download Java or more accurately Java runtime environment for various operating systems. This Java runtime environment has a software component called Java virtual machine or JVM. This JVM takes our Java bytecode and translates it to the native code for the underlying operating system. So if you're on a Windows machine, this Java virtual machine converts our 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're 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 mush 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. You 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 com.co.wdmosh and this class, the main class, is part of this package. So the full path to this class is com dot code with mosh 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 com. Inside this folder, it will look at this other folder code with mosh and then it will find main.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. When we run a program using IntelliJ, all these steps are hidden from us.

We don't see the compilation or execution steps. So you have seen Java in action. Now let me tell you five interesting facts about Java. Java was developed by James Gosling in 1995 at Sun Microsystems, which was later acquired by Oracle in 2010.

It was originally called 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 it's 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 multitour 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 closed the 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 Indy.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 you can easily complete it in a day or two.

In the first part, which is what you're watching, you're going to 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 numbers, strings, booleans, and arrays. By the end of this section, you will build a mortgage calculator as your first Java project.

We'll be improving this calculator bit by bit throughout this 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. 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. 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 used 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 APIs 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 going to join me on this journey and master Java, the most popular programming language behind millions of apps and websites. In this section, we're going to look at the fundamentals of programming in Java.

You're going to learn about variables and constants, primitive and reference types. You're going to learn about casting or type conversion. You will learn how to work with numbers, strings, and arrays, and how to read input from the user. Once you learn all this, I'm going to give you a project.

You're going to build a mortgage calculator on your own. So make sure to pay great attention to all the materials you're going to learn, because you're going to use most of them in this project. Are you ready? Now let's jump in and get started.

And this tutorial, we're going to talk about variables in Java. We use variables to temporarily store data in computers 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, nth, age equals 30. So nth or integer is the type of this variable. So in this variable, we can only store integers, which are whole numbers, like one, two, three, four numbers that don't have a decimal point. Now in Java, we have several different types.

I'm going to talk about them in the next tutorial. So first, we specify the type of our variable. Then we give it a name or 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 six, we're initializing this variable, which means we're giving it an initial value. You always have to initialize our variables before reading them.

So with this line, we're storing number 30 somewhere in computers memory, and we're assigning this label to that memory location. Now on line seven, instead of printing a little world, we can print the value of the age variable. Take a look. So I'm going to run this program using control and 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 35. Beautiful. We can also initialize multiple variables on the same line.

But this is something that I don't recommend because it makes your code ugly and hard to read. Here is an example. We can declare another variable like temperature and set it to 20. So using a comma, we can declare multiple variables on the same line.

Now, even though this is technically possible, it's not something that I recommend. So it's always better to declare one variable on each line like this. We can also copy the value of one variable into another. Here is an example.

Let me delete these variables and declare a new variable called my age. We set it to 30. And then we declare another variable like her age and we set it to my age. So now when we print her age, we're going to see 30.

Take a look. So on line seven, we're copying 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 the 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-perimative types or reference types for storing complex objects. So in the category of primitive types, we have byte, which takes one byte of memory.

And in one byte, 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, with double, we can store larger numbers. Next, we have char for storing a single character like a, b, c.

And these char types 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 used 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 byte, we can store values up to 127.

So I'm going to change this to byte. That is better. Now, let's look at another example. Let's say we want to store the number of times a YouTube video has been watched.

So we define an integer called views count. Note that I'm always using meaningful names for my variables because these names help us understand what this code does. I've seen some people use variable names like v or v1 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 one, two, three, four, five, six, seven, eight, nine. Now, in Java, whenever you deal with a large number like this, you can use an underscore to separate every three digits, just like how we use a comma in our documents to make our numbers more readable. We can use an underscore in Java.

So with integers, we can store values up to two billion. But let's say the number of times this video has been watched is three billion. So I had a three here. Now we have a red on the line that indicates an error.

Let me hover our mouse over it. We see this tool tip, integer number, two 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 to this number.

We can use an uppercase or a lowercase L. But as you can see, a lowercase L kind of looks like a one. 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 said 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 we have a compilation error here. Take a look.

In compatible 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 uppercase or lowercase F. So these are examples of numbers. Now let's store a character.

So char, we call it letter and we set it to 8. 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 the 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 are variables, classes and methods. In the last tutorial, you learn that we use primitive types to store simple values like numbers, Boolean values, or single characters. In contrast, we use reference types to store complex objects like data objects or mail messages.

These are complex objects. Now in Java, we have 8 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 going to declare a primitive type. Let's say bite H 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 to box, which is called IntelliSense, we can see various classes that have date and their name. So IntelliSense is helping us complete our code by suggesting these class names. Now here we have a date class in this package Java.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 SQL, 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 name space 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.util.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 are importing the date class and this package. We'll talk about packages in more detail in the future.

So back to our date variable. Let's give this variable a name like now. Now we said 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 over 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 these objects or these classes have members that we can access using the dot operator. So we can type now dot. And these are all the members defined in this class or in this object.

For example, we have a method called get time. And this returns the time component of this object. This is another difference between primitive types and reference types. These primitive types don't have members.

So if you type age dot, we don't see anything. These items you see here are not members of age. They're code snippets, which allow us to quickly generate code. For example, we can select four I and this automatically generates this block of code for us.

We'll talk about this in the future. So this age variable is a primitive type. It's not an object. It doesn't have any members.

And that's why when we use the dot operator, we don't see anything here. Now let's delete this line and instead print the value of this data object. So once again, we can type system. This is a class.

So we can use the dot operator to access its members. Here we have out, which is a field. And the type of this field is print stream, 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, o, u, t and press tap. And this generates this piece of code for us.

All right. Now let's pass our data object here. Note that I have not surrounded this variable with double quotes because this is a string. And if you run this program, we'll see now on the terminal.

There you go. We don't want this. You want the value of our data object, not a label. So let's remove the quotes.

I run the program again. So here's the current day time on my machine. You'll learn a little bit about the differences between the primitive and reference types. So you know that we use primitive types for storing simple values and reference types for storing complex objects.

But there is a very important difference between these two categories of types in terms of memory management. And that's what we're going to talk about in this tutorial. So I'm going to declare a primitive variable X and set it to one. And then I'm going to declare another variable like Y and set it to X.

So in this example, we have two different variables X and Y. And these two variables are at different memory locations. So they're completely independent of each other. In other words, if I change the value of X, Y is not going to get affected.

Let me show you. So I'm going to update X to two. I didn't print Y. So S or UT tab Y.

Let's take a look. So run. As you can see, Y is not affected because X and Y are completely independent of each other. However, when we use a reference time, this behavior is different.

Let's take a look. So I'm going to delete all the code here. In Java, we have a point class that is defined in this package Java that AWT. So you press enter.

And now we have this import statement on the top. Beautiful. This declare a variable like point one and set it to new point. Here, we can pass the initial values for X and Y.

So I'm going to pass one and one. So intelligent automatically adds these labels X and Y. Now, just like before, I'm going to declare another variable point two and set it to point one. And this is where things get interesting.

When Java runtime environment executes line eight, first is going to allocate some memory to store this point object. Let's see, the address of that memory location is 100. Then it's going to allocate a separate part of the memory and it's going to attach this label to that memory location point one. In that memory location, it's going to store the address of our point object.

So this is the critical difference between primitive and reference types. When we declare a primitive variable like a white, the value that we assign to that variable will be stored in that memory location. But when we use a reference type, like this point class, our variable is going to hold the address of that point object in memory, not the actual point object. Now, look at line nine.

Here, we're copying the value that we have in this variable into this other variable. So that value, as you learn, is not the point object is the address or the reference to the point object in memory. That is why we refer to these types as reference types because they don't store the actual values. They store a reference to an object somewhere in the memory.

So in this example, point one and point two are referencing the exact same point object in memory. We only have one point object. So these two variables are not independent of each other, the referencing the same object. And that means if I update this point object through either of these variables, the changes will be visible to the other variable.

Let me show you. So using the first variable point one, we're going to update the value of X. So we use the dot operator and here we can see the members of this object X and Y are both fields, which are variables that exist inside of a class. So we said X, just like a regular variable to a different value.

Let's say two. Now, because point one and point two are referencing the exact same object, if we print point two, we're going to see the change that we just made. Take a look. So S or U T, tab, let's print point two.

And 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. And this tutorial, we're going to look at strings in Java. So earlier in the course, we printed the hello word message on the terminal.

This hello word that we have here is a string or more accurately, it's a string literal. That means a string value. Now, let's extract this from here and store it in a string variable. So cut just before this line, we type string.

Now look, this string class is defined in Java dot lang package. What is interesting is that we don't have an import statement to import this package or import this class because this package is automatically imported. So we can use any classes that are defined in this package. Now, let's declare a variable called message.

And because this is a reference type, we should instantiate this variable using the new operator. So new, string, and here in parenthesis, we type our message. Hello world. However, here we have this little warning.

Take a look. New string is redundant. Because in Java, there is a shorter way to initialize string variables. Let me show you.

So instead of using the new operator, we simply set this to our string literal. Now on the surface, this looks like a primitive type because we are not using the new operator. But this is just a short hand to initialize a string variable. Strings are reference types in Java.

But because we use them often, there is a short way to create them. So now let's pass message to the print line method and run our program. We get the exact same result as before. Beautiful.

Now let's look at a few interesting things that you can do with strings. We can concatenate or join a string with another one using the plus operator. So here we can combine this with another string with two exclamation marks. And here's the result.

Now because string is a class, it has members that we can access using the dot operator. So we can type message dot. And these are all the methods or functions defined in the string class. For example, we have this method here ends with and with this we can check to see if our string ends with a character or sequence of characters.

For example, here we can pass your string to see if our message ends with two exclamation marks. Now instead of printing the message, let's print this expression here. So let's run the program. We get true.

So this method that we have called here returns a Boolean value, which can be true or false. We also have another method starts with let's take a look. Now in this case, we get false because our message doesn't start with two exclamation marks. Another useful method is length.

So we can call that to get the length of a string, which is the number of characters. So message dot length. Take a look. So in this string, we have 13 characters.

And this is useful in situations where you want to check the length of the input by the user. For example, you might have a sign up form with a username field. You can check the length of someone's username and give them an error if the username is longer than let's say 20 characters. Pretty useful.

We also have another method that is index of and this returns the index of the first occurrence of the character or the string that we pass here. For example, if you pass H, the index of H is zero. So let's run the program. There you go.

We can zero. If you pass E, we get one because the index of the first E in this message is one. Now, what if we pass a character or a string that doesn't exist in this message? Let's say sky.

We get negative one. 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 replacement 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's the second value and we have separated these values using a comma. Now in programming terms, we refer to these 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 this method. So in this case, target and replacement are parameters, but exclamation mark and asterisk are arguments.

Now, let's run this program and see what happens. So our exclamation 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 a so you t tab message, we 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 lower case, convert all characters to lower case.

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 upper case 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 going to add a couple of spaces before and after our message. Now when we trim it, these white spaces are going to 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 class has more methods that we don't have time to cover in this lecture.

But as we go through the course, you're going to learn more about the string class and other useful classes in Java. There are times we want to include special characters in our strings, like a tab or a new light or a backslash or double quotes. So in this tutorial, I'm going to show you how to include these special characters in your strings. So here we have the string.

Hello, Mosh. Let's say we want to surround Mosh 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 understand what we have after. That's why we have a compilation error. To fix this problem, we need to prefix this double quote with a backslash. So using this backslash, we have escaped the double quote.

Now, one more time, let's add backslash double quote here. Now let's run the program and see what we get. So we get hello Mosh in double quotes. 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 past with directory on a Windows machine. So that will look like this.

See 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 see drive backslash.

Now we have a problem. Java compiler thinks we're escaping the double quote here. So it thinks our string is not terminated with another double code, but that's not what we want. You want to add a backslash here.

So we need to prefix our backslash with another backslash. Now we type Windows one more time, something. Let's run the program. So even though we have two backslash as in our code, we actually see one backslash in a terminal window.

Another escape sequence is backslash and and we use that to add a new line to our strings. So let's change this to backslash in and run the program to see what happens. Now our string is broken down onto multiple lines. On the first line, we have C drive, then we have Windows.

So wherever we add a backslash in, Java will insert a new line. We can also add the tab in our strings. So if we add backslash T here, there will be a tab between 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 good honestly, they're hardly used. So remember these four escape sequences that we covered 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. We 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 in array. 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 to numbers because we're dealing with the list of items. So always pay attention to the name of your variables. Now, we 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 one. Similarly, we can set the second item to two. 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 set this to three. Let me run this program. We get an exception. Exceptions are Java's way to report errors.

So in this case, an exception was raised and our program crashed. We'll talk about exceptions in detail later in the course. So now let's remove the last line and print this array. So S o ut tab numbers.

Let's see what we get. We get this weird string instead 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 going to see something different because each object is going to 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 you till 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 to string. Now, as you see, 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 zero by default because here we're dealing with an integer array.

If you had a boolean array, all items by default get initialized to false. If you have a string array, all items get initialized to an empty string. Now, this syntax for creating an initializing 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 going to remove the new operator. Here we use curly braces and inside this braces, we add all the items in this array.

Let's say two, three, five, one, and four. Now we have five items. So the length of this array is going to be five. We can read that using the length field.

So if we type numbers dot look here we have this field, 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 print it 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 you want you to remember is that arrays have a fixed length. The 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 array's class.

Let me show you. So I'm going to 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 let me run this program. We can see our array is sorted. Beautiful. So you have 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 a 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 two by three matrix.

So two rows and three columns. We add another brackets here and change these lengths to two and three. So now we have two rows and three columns. Now to access individual items and 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 one. Now let's print this. So and so you t tab.

Once again, we use our arrays class dot two 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 two 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 lengths of that dimension. Pretty easy. Now what about the curly braces syntax? Let me show you.

So let's revert this back to a two-dimensional array. We're going to get rid of the new operator and use curly braces. Now let's say in this matrix we're going to have two rows and three columns. So each row is an array itself because it's a list of items.

So we add another array here. Let's say one, two, three. Then comma, now we add the second row which is another array. In this row we're going to have three numbers.

Four, five, and six. 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. You have learned that when declaring them we need to initialize them and we can always change their value later on throughout the lifetime of our programs. However, there are times that we don't want the value of a variable to change.

For example, let's declare a variable called pi and set it to 3.14. Now here we need to add an f to represent this as a float because by default Java compiler sees this number as a decimal. 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 one.

Then all our calculations are going to get messed up. We don't want this to happen. That's when we use constants. So if we type final here, Java compiler will treat this as a constant.

So once we initialize this, we cannot change its value later on. You can see here we have a compilation error and it says cannot assign a value to final variable pi. So pi is a final variable or a constant. Now by convention we use all capital letters to name constants.

So this should be pi. Beautiful. Now I tell you a little side story. In one of my early courses that I created years ago, that was C-Sharp Basics for beginners.

There I use the same example to teach the concept of constants. But it pronounced this word as P instead of pi. And believe it or not, to this date people make fun of me for saying P instead of pi. But that's how we learned this back in Iran.

We pronounce it as P and I think Greek people also say P. But anyway, I just thought to share this video to change the mood. Now we're done with constants. Next we're going to 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 going to declare an integer called result. And here we can type 10 plus 3. Now when we print result, it's going to be 13. Pretty straightforward.

There you go. So this is addition. We also have subtraction, multiplication. Division is an interesting one.

Let's take a look. So here the result is a whole number. Because in Java, the division of two whole numbers is a whole number. If you want to get a floating point number here, you need to convert these numbers to a float or a double.

Let me show you. So we prefix this number with parentheses and in parentheses, we type double. Now we are casting or converting this number to a double. Similarly, we should do that here.

And now we have a compilation error because on the left side, we declared an integer, but here the result of this expression is a double. And by the way, an expression is a piece of code that produces a value. So what we have here is an expression because it produces a value. So to fix this problem, we need to change this to double.

Now when we run this program, we get this floating point number. Beautiful. So these are the arithmetic operators. And these numbers that we have here are called operands.

We also have increment and decrement operators. Let me show you. So I'm going to declare a new variable and x we said it to one. Now if you want to increase the value of x by one, we use the increment operator.

Now let's print this on a terminal. So we get to 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 going to declare another variable.

Why we said 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 will be one. And then x will be incremented by one.

So if we print x and y, x is going to be two and y is going to be one. Take a look. So x is two and y is one. Beautiful.

However, if we apply this as a prefix, first x will be incremented by one. So it will be two. And then it will be copied to y. So in this case, both x and y will be two.

Take a look. So we get two and two. Now what if you want to increment x by more than one? Let's say it 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 two.

So first, we add two to x. The result would be three. And then three would 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. But 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 augment assignment operator for other arithmetic operators. So we can type x minus equals two. And this would reduce the value of x by two.

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 equals to 10 plus three times two. What do you think is the result of this expression? The result is 16. Let's run this program and find out.

So run, there you go. We got 16. But why? Well, this is a very basic math concept that unfortunately, a lot of people don't know.

In math, the multiplication and division operators have a higher priority. So they get applied first. In this example, this expression three times two is evaluated first. The result is six.

And then six is added to 10. That's why we get 16. Now, if you want to change the order of these operators, you can always use parentheses. For example, if you want this expression to be evaluated first, we wrap it in parentheses.

So like this. Now Java compiler will first evaluate this expression. The result will be 13. And then 13 is multiplied by two.

So we get 26. Take a look. There you go. So be aware of the order of these operations.

Parentheses always have the highest priority. Then we have multiplication and division. And finally, we have addition and subtraction. In this tutorial, we're going to talk about casting and type conversion.

So I'm going to declare a short variable called x and set it to one. And then I'm going to declare an integer called y and set it to x plus two. In this example, we're adding a short to an integer. What do you think the result is going to be?

Well, let's take a look. So as a UT, let's print y. We get three. That is what you were expecting.

But let me explain what happens under the hood for this expression to get executed. Because we're dealing with two different types of values. One is a short. The other is an integer.

One of these values should be converted to the other type. So they are equal. Now, I got a question for you. How many bytes do we have in a short variable?

We have two bytes. How many bytes do we have in an integer? Four bytes. So any values that we store in a short variable can also be stored in an integer variable.

Right? So when this piece of code is going to get executed, this is what's going to happen. First, Java looks at the value in this variable. It's one.

Right? It's going to allocate another variable. An anonymous variable, somewhere in memory, we don't know where that is. We don't know the name of that variable.

It doesn't have a name. It's anonymous. That variable is going to be an integer. Then Java is going to copy the value of x into that memory space.

And then it will add these two numbers together. This is what we call implicit casting. Let me type it here. Implicit casting.

That means automatic casting or automatic conversion. We don't have to worry about it. Whenever we have a value and that value can be converted to a data type that is bigger casting or conversion happens implicitly or automatically. So byte can be automatically converted to short.

And this can be converted to an int and long. Now, what about floating point numbers? Let's look at an example. I'm going to change this to a double 1.1.

Now, here we have a compilation error because on the right side of the assignment operator, we have a floating point number at double on the left side. We have an integer. So we need to change this to double. Now, when we execute this code, we're going to get 3.1.

Let's verify this. There you go. Now, let's see how casting happens here. In this case, we're dealing with a double and an integer.

An integer is less precise than a double because in a double, we can have digits after the decimal point. So in this example, Java is going to automatically cast this integer to a double. So that will be 2.0. And then 2.0 will be added to 1.1.

Okay. So back to this chain, here we're going to have float and then double. So as a general rule of thumb, implicit casting happens whenever we're not going to lose data. There is no chance for data loss.

Now, what if we want Y to be an integer? So in this example, we don't care about the digits after the decimal point. We want to see 3 on the terminal. How should we do this?

This is where we should explicitly cast the result. So we should cast X to an integer like this parenthesis int. This is explicit casting. We convert X to an integer.

So the result would be 1 without a decimal point. 1 will be added to 2 and Y will be 3. Take a look. There you go.

So this is all about implicit and explicit casting. Now, this explicit casting can only happen between compatible types. So all these types are compatible because they're all numbers. But we cannot cast a string to a number.

In other words, if X was a string like this, let's say 1. We cannot cast X to an integer because they are not compatible. So how do we do this? Well, for all these primitive types you have learned, you have wrapper classes.

So in Java, we have a class, which is a reference type called integer. This class is defined in Java.lang package. And in this class, we have a method called parse int. So this method takes a string and returns an integer.

So integer is the wrapper class for the int primitive type. We also have short. And in this class, we have parse short. So it takes a string and returns a short.

Similarly, we have float and double. And obviously the name of these methods are different. So here we have parse float. So back to this example, let's say we get X as a string and we want to convert it to an integer.

This is how we do it. integer dot parse int. We pass X here and then add it to take a look. So we get three.

Now you might be curious why this matters. Why should be parse or convert a string to a number to add it to something else? Well, pretty much in most frameworks for building user interfaces, whether you're building a desktop or a mobile application or web application, we always receive input from the user as a string. So if you have a form with a bunch of text boxes or drop-down list, almost always we get values as a string.

So that's why we need to convert these strings to their numeric representation. Okay. Now what if X is a floating point number here? What will happen when we try to parse this as an integer?

Let's take a look. Once again, we get an exception, which is how Java reports errors to our programs. We're going to talk about exceptions in detail in the future. So if the user enters 1.1, we cannot use this method.

Instead, we should use float or double. Let's say double because that's easier. Double parse double. So we parse this number as a double at two to it and then store the result in a double.

And then we will get 3.1. Beautiful. Next, we're going to look at the math class for performing mathematical operations. In this tutorial, we're going to look at the math class for performing mathematical operations.

So in Java, we have this math class that is defined in Java.lang package. So it's always there. We don't need to explicitly import it. Now this class has a number of useful methods.

The first method I'm going to show you is the round method. And with this, we can round a floating point number to a whole number. So as we can see, this method is overloaded, which means it's implemented twice. In the first implementation, it takes a float and returns an int.

In the second implementation, it takes a double and returns a long. So let's pass 1.1 as a float to this method and store the result in an integer like this. Now we print the result and we get 1. Beautiful.

Another useful method is seal or ceiling, which returns the smallest integer that is greater than or equal to this number. So the ceiling of 1.1 is 2. Now here we have a compilation error because this method returns a double, but we're storing the result in an integer. So here we need to explicitly cast this to an integer.

And now you can see the ceiling of this number is 2. We have another useful method that is floor. So the floor of a number is the largest integer that is smaller or equal to this number. In this case, it's going to be 1.

Let's take a look. There you go. Another useful method is max, which returns the greater of two values. And once again, this method is overloaded.

So in the first implementation, we get two integers. We have other implementations for longs, floats, and doubles. So let's pass two integers here. 1 and 2.

This will return the greater number, which is 2. There you go. Similar to this, we have min. Let's pretty straightforward.

Another useful method is random for generating a random value between 0 and 1. Once again, we get a compilation error because this method returns a double. So let's change that to double. Now every time we run this program, we get a different number.

And this number is a floating point number between 0 to 1. Now, what if we want a number between 0 to, let's say 100 instead of 0 to 1? Well, we simply multiply this by 100. Take a look.

So every time we run this, we get a different number between 0 to 100. Now, if we don't want these digits after the decimal point, we can either round this number or cast it to an integer. Let me show you. So we can call math.

That round and pass the result of this expression. So I'm going to cut this at parentheses to call the round method and then paste that expression. Now let's run this code. So every time we get a double, we still have the fraction here.

So we can change the type to an int. Now we have a compilation error because the round method returns along, but here we have declared an integer. This is one of those cases where implicit casting cannot happen because we have a value that is represented in 8 bytes of memory. And we want to store that in a variable that has only four bytes of memory.

So implicit casting doesn't work, but we can use explicit casting because we know the result of this expression is a number between 0 to 100. So we can definitely store it in an integer. So let's add int here. Now let's run this again.

There you go. Now what if we don't use the round method here? Let's see what happens. So I'm going to remove the call to the round method and simply apply this casting over here.

Let's see what we get. Now every time we run this program, we get zero. Do you know why? Because here we're applying this casting to the result of this method called not this entire expression.

As you saw earlier, every time we call the random method, it generates a number between 0 to 1. So when we cast that number, so an integer will lose the fraction. We always get 0 and 0 times 100 is 0. To solve this problem, we need to wrap this entire expression in parentheses.

So we add parentheses around this. And now when we run this, we get an integer between 0 and 100. Great. Often when we work with numbers, we need to format them as currency values.

For example, we might have a number like this. Imagine this is the price of a product. To display this to the user, you want to add a dollar sign here and separate every three digits with a comma. Or if we might have a number like 0.1, and we want to represent this as a percentage value.

So instead of 0.1, we want to display 10%. So in this tutorial, I'm going to show you how to format numbers in Java. We have this class number format that is defined in Java. The text package in this package, we have a lot of classes for handling text, dates, numbers and so on.

So let's present her here. It's important on the top. Beautiful. Now we want to declare a variable.

So let's give this variable a name, currency. Now we need to instantiate this. So new number format. However, we get a compilation over here.

Let's take a look. Number format is abstract. It cannot be instantiated. So in Java, we have this concept of abstract classes.

So some classes are abstract and they're basically like a half-baked cake. We cannot use the new operator to create an instance of them. We're going to talk about abstract classes and why they exist later in the course. For now, remember that we cannot create an instance of the number format class because it's abstract.

So there is another way. Let me show you. This class has a bunch of methods that start with get. So we have get currency instance.

And when we call this method, this will create an instance of the number format class and return it. So instead of using the new operator, we're going to use this method here. This is what we call a factory method because it's like a factory. It creates new objects.

Now look at the return type of this method. It's a number format object. So we call this method. Now we get the return value and store it in a variable of type number format called currency.

Let me see. I'm probably zoom out. So you can see all the code. There you go.

So on the right side of the assignment operator, we're calling the get currency instance method. We get the result, which is a number format object and store it in this variable. Now I'm going to zoom in. So you can see clearly.

All right, that's better. Now this object has a method for formatting values. Once again, you can see this method is overloaded. We have multiple implementations.

We can give it a long or a double or whatever. So I'm going to call this method and pass a value like 1, 2, 3, 4, 5, 6, 7, 0.891. So we have three digits after decimal and a few other digits here. Now this method will return a string representation of this number for method as a currency.

So let's get that and store it in a string variable like result. And then we're going to print result on a terminal. See what we get. So we get this dollar sign.

Every three digits are separated using a comma. And we only have two digits after decimal point. So this class is very handy in formatting numbers as currencies. We have another method for formatting a number as a percent.

And that is get percent instance. Right. Now it returns an instance of the number format class specialized for formatting numbers as a percent. So we need to rename this variable from currency to percent.

Now we don't want to manually change this because there are multiple references to this variable. This other reference was not updated. So let me show you the proper way to rename objects in IntelliJ. If you right click here, you can see this ReFactor menu.

And here we have rename. Now look at the shortcut on the right side. Unfortunately, it's not visible in my recording window. But on Mac is shift and F6.

I always use shortcuts because they're faster. So let's press shift and F6. Now we get this red box and below this we can see a few suggestions for a better name. We can choose one of these or pick our own name.

I'm going to change this to percent. And note that as I'm typing this, the other reference gets updated automatically. So this is very helpful. Now let's press enter.

Okay, you're done with renaming. Now let's pass a different value here. So let's say we have a number like 0.1. I want to format this as a percent.

Let's run the program. There you go. We get 10 percent. Beautiful.

Now let me show you a cool technique. In this program, we don't really need this percent object because we have used it in a single place. It would make sense to have this as a separate variable if we have multiple references to it. So what can we do here?

We can completely get rid of this object. So let's delete this piece of code. We're basically calling this method of the number format class. As you know, this method returns a number format object.

So right after calling this method and before the semicolon, we can use the dots operator to access the methods or members of the number format object. So here we call the format method straight away and pass our value. This is what we call method chaining. We're chaining multiple methods together.

So here's one method and here's another method. Now this returns a string so we can store it in this result variable. Let me cut this expression from here and put it over here. Now we have double semicolon, so I'm going to delete one of them.

All right, beautiful. In this tutorial, I'm going to show you how to read input from the user. In Java, we have this scanner class that is defined in Java, the utile package. Let's import this and create a scanner object.

So new scanner. Now here inside this parenthesis, we need to specify where we're going to read data from. Are we going to read it from the terminal window? Are we going to read it from a five or what?

To work with the terminal window, we type system dot in. This is one of the fields in the system class. A field, as I told you before, is like a variable that we're defining the class. So we have system that in.

We also have system that out, which we used to print something on the terminal, right? Now let's use system that in and terminate this statement with a semicolon. Now this object has a bunch of methods for reading data and all these methods start with next. So we have next byte for reading a byte.

We have next line for reading a line. We have next Boolean for reading a Boolean and so on. So let's call the next byte method and see what we get. This returns a byte value so we can store it in a byte variable.

Let's say someone's age. And then we print it on a terminal saying you are plus H. So here we're concatenating a string with a byte. And in this scenario, we're going to have implicit casting or implicit type conversion.

So Java will automatically convert this byte variable here to a string so they can be added together. Okay. Now let's run this program and see what happens. So here in the terminal window, we can type 20 enter and it says you're 20 beautiful.

But this is pretty boring. Let's add a label here and ask the user to type something. For example, before reading data, we're going to call the print line method and say age column. Now let's run the program.

So we get this label here. However, whatever we type will appear on the next line. This is because the print line method adds a new line after this label to solve this issue. We call the print method.

Now let's run the program one more time. We get this pop up box because our program hasn't finished execution. So we need to tell IntelliJ that we want to stop and rerun this program. All right.

Now whatever we type appears right in front of this label. Beautiful. Enter your 20. Now what if we type a floating point number like 20.1.

We get an exception because this method can only parse byte values. If you want to get a floating point number, we need to call next float or next double. What if you want to read a string? We don't have next string.

We have next and next line. Let's look at the differences. So first, I'm going to call the next method. Here we have a compilation issue because this method returns a string.

I'm going to change this to a string. Let me collapse this. That's better. We should also rename this variable.

So what was the shortcut shift NF6? Now this rename is to name, enter, beautiful. And one last time we should also update the label name. Run the program.

So I'm going to type my name here, Marsh. It says you're a Marsh. Beautiful. One more time.

This time I'm going to type my full name, Marsh, Hammondani. But we don't get the last name. Here's the reason. These words that we have here, these are called tokens.

Every time we call the next method, it reads one token. So here we have a space. We have two tokens and we need to call the next method two times to get the full name. The first time we call it it returns Marsh.

The second time we call it it returns Hammondani. Then we need to combine these two together. This is not ideal. So that's when we use the next line method.

With this method, we get the entire line that the user enters. No matter how many spaces or tabs are there. Take a look. So Marsh, Hammondani, and we get the full name.

Now what if I type a few spaces before my name? That's what happens. So those spaces also appear here. And this looks a little bit odd.

This is where we use the trim method. Remember, with trim, we can get rid of all these white spaces before or after a string. So this next line method returns a string that we are storing in this variable. Right.

Now just before storing the result in this variable, here we can use the dot operator to access the members of this string object. So we call the trim method and then store the result in this variable. Once again, we're chaining multiple methods here. Let's run the program.

So a few spaces, Marsh, Hammondani, and we get this beautiful output. All right. Now it's time for a project. I want you to use what you have learned in this section and build a mortgage calculator like this.

So when we run this program, we get a few questions. The first question is the principle or the amount of loan we want to get. Let's say 100,000 dollars. The second question is the annual interest rate.

Let's say 3.92%. And the third question is period in years. Let's say we want to get a loan for 30 years. So this program calculates our monthly payments and displays it as a currency.

This is a great exercise for you to practice all the materials you learn in this section. Now, before you get started, I want to give you a few hints. Here is a formula for calculating the mortgage or the monthly payments. I found this page on wikihau.com.

It's called calculate mortgage payments. So let's see how this works. Mortgage equals P or principle or the amount we're going to loan multiplied by R, which is our monthly interest rate. This is very important.

So this number that we get here is our annual interest rate. We need to divide this by 12. Also, taking to account that this number is represented as a percent to calculate the actual interest rate. You need to divide this number by 100.

So in this example, the interest rate is 0.0392. So whatever the user enters, divide it by 100 and then divide it by 12 to get to the monthly interest rate. Now, we have this monthly interest rate. We need to multiply this by this expression.

Here, we need to add 1 to this interest rate and raise it to the power of n where n is the number of payments. So we need to multiply this number by 12 or 12 months to calculate the number of payments. Now, to raise this number to the power of n, you need to use the power method of the math class. So this math class has this power or power method that takes two arguments or two values, a and b.

So go ahead and spend 10 to 15 minutes on this exercise. When you're done, come back and see my solution. All right, let's see what I've done here. And by the way, don't worry if your code is different from mine.

We all think and code differently. So it's perfectly fine if your code is different. Just look at my code, see what I've done here and see if there are ways you can improve your code. That's what matters.

Okay. So here in our main method, first, I've declared two final variables or constants. The first one is months in year, which I've set to 12. And the second one is percent, which I've set to 100.

The reason I declared this constant is that I didn't want to have magic numbers in this code. So over here, where we calculate the monthly interest, we get the annual interest divided by percent and then months in year. This code is very self-explanatory. Someone else reading this code will have no problem understanding what's going on here.

In contrast, if you had a magic number here, like divide by 12 and then four, whatever. Someone else reading this code would wonder, what is this for doing here? What is 12? Now, it's quite obvious to you that 12 is the number of months in a year, but trust me, sometimes other people cannot see this straight away.

So as a best practice, avoid magic numbers in your code. Always use constants or final variables to describe them. So let's revert this back. All right.

So after declaring this constants, I have created this scanner object. Here we ask the first question principle. And we read the answer as an integer. I thought integer is a good data type for storing the principle because short is not enough with short, we can store a maximum of $32,000.

That's not enough. What if someone wants to find us $1 million? So int is good. And it allows us to store a value up to $2 billion.

Next, we ask the second question, annual interest rate. We read this as a float. Here, I could use double, but the interest rate is a small number. So float is sufficient for that.

We don't really need double. So we get the annual interest and then based on that, we calculate the monthly interest. Also, see how I have named my variables. All variables have a proper meaningful names.

There are no magic words here like MI as in short for monthly interest or M1 or M2. Do not use magic names for your variables. Always use meaningful and descriptive names. All right.

Next, we get the period. We read this as a byte because the maximum number we want to support is 30. So one byte is sufficient to store the number 30 or anything smaller. Now based on the number of years, we calculate the number of payments.

Note the camel notation here. I've capitalized the first letter of every word except the first word. So we get years I multiplied by months in year. Again, the code is very self explanatory.

Once we collect all this data, then we calculate the mortgage. So we get the principle multiplied by this expression and then divided by this other expression. Let's have a quick look here. Now this looks a little bit complicated.

So if you want to download my source code, look below this video. I'm attached it for you to download. And finally, after we calculate the mortgage, we use the number format class to format this value as a currency. So we get the result stored in the string mortgage formatted and print it over here.

Now here we could also avoid declaring this variable and simply add this expression over here. But I decided to do this to increase the readability of this code. Otherwise, this line would be so long, but that's just my personal preference. You don't have to follow this.

All right, so this was my implementation of the mortgage calculator. However, this program has a number of problems. The first problem is input validation. So if you run this and enter a non numeric value like x, y, z or program crashes, or as another example, if we enter a negative value here, our program is not going to behave properly.

So that's where conditional statements come to the rescue. In the next section, we're going to talk about conditional statements. You will learn how to use these statements to validate the values entered by the user. So that brings us to the end of this section.

I hope you learned a lot and thank you for watching. So in this section, you learn all about variables and constants. You learn about primitive and reference types. You learn that primitive types store simple values, but reference types hold references to complex objects.

That's why we call them reference types. You also learn about casting and type conversion. You learn about two types of casting implicit and explicit. You learn how to work with numbers, strings and arrays.

And finally, you learn how to read input from the terminal. I hope you learned a lot and been enjoying the course so far. In the next section, we're going to look at conditional statements for controlling the flow of our programs. So I will see you in the next section.

Hey, Marsh here. I just want to make a quick announcement. This course you've been watching is actually the beginning of my complete Java series. In this course, we only talk about the basics, but in my complete series, we go way beyond that.

So if you're serious about Java, if you're looking for a job as a Java developer, I highly encourage you to enroll in my complete Java series. It's exactly the same structure, the same quality, but it has way more content. Plus, you will get a certificate of completion that you can add to your resume. So if you're interested, I put the link down below.

You can get the course with a discount. And if you're not happy for any reasons, you can ask for a refund within the first 30 days. So I hope to see you in the course. In this section, we're going to look at control flow or controlling the flow of execution of our programs.

We're going to start off by talking about comparison operators for comparing values. Then we're going to talk about logical operators, like the logical and logical or and logical not. We use these operators for implementing real world rules. And then we're going to talk about three different types of control flow statements.

We're going to talk about conditional statements for making decisions in our programs. Then we're going to talk about loops for executing code repeatedly. And finally, we're going to revisit our mortgage calculator and add error handling to it. So if the user enters an invalid value, we keep asking them to try again.

All right, now let's jump in and get started. We're going to start this section by talking about comparison operators. We use these operators to compare primitive values. For example, our x and y equal or not.

So I'm going to declare two integers x and y. Now let's compare this to see if they're equal or not. So first, I'm going to add this print line statement. Now to compare these variables, we type x equals y.

So here we have two equal signs. And this is the equality operator. Don't confuse this with the single equal sign that we use for assignment. That is the operator used over here.

Okay. So two equal signs represents the equality operator. Now when we run this program, we get true because these values are equal. This expression that we have here is called a Boolean expression.

So earlier, I told you that an expression is a piece of code that produces a value. This piece of code produces a Boolean value true or false. That's why we refer to it as a Boolean expression. We also have the inequality operator.

So when we run this program, we're going to see false. Let's take a look. We get false because these two variables are equal. So the expression x is not equal to y returns false.

We also have greater than greater than or equal to less than and less than or equal to. So if I change y to two, this expression is going to evaluate true because x is less than or equal to y. Take a look. There you go.

Next, we're going to talk about logical operators. In the last tutorial, you learn that a Boolean expression produces a Boolean value. Now, there are times we want to combine multiple Boolean expressions. Let me show you.

So I want to declare an integer called temperature and set it to 22. Next, we declare a Boolean variable is warm. Now we want to check to see if temperature is greater than 20 and less than 30. So we write a Boolean expression like this.

Temperature greater than 20. Here, we need to use the end operator. So these two ampersand represent the logical and operator in Java. After this, we add our second condition.

Temperature less than 30. Now, if both these conditions are true, the result of this Boolean expression is going to be true. Otherwise, if at least one of these is false, the result would be false. Let's take a look.

So I'm going to print is warm on a terminal. The result is true. But if we change the temperature to let's say 12, the result is going to be false. And this is how this works.

Java will evaluate this expression from left to right. First, it looks at the first condition. The first condition is false because temperature is not greater than 20. So because this expression is false, it doesn't matter what we have after the end operator.

Java will ignore the other expressions because the end operator will return true if both conditions are true. Now, let's look at another operator. That is the or operator. So I'm going to delete all this code and start with a new example.

Let's declare a Boolean has high income. We set it to true. And another Boolean has good credit. We set this to true as well.

So let's say we're building an application for processing loans. We want to see if a new applicant is eligible for loan or not. So we declare another Boolean is eligible. And by the way, look at the names I have used for these variables.

They're very meaningful and descriptive. So here's the rule. An applicant is eligible if they have high income or good credit. If one of these conditions is true, they are eligible.

So we write has high income or so these two vertical bars represent the or operator. So if they have high income or good credit, then they are eligible. So with the or operator, if at least one condition is true, the result would be true. In this example, when Java evaluates this expression, it starts from the left side.

This Boolean variable is true. So it doesn't matter what we have after. Java will not evaluate the rest of this expression. It simply returns true.

However, if this variable was false, Java would continue evaluating this expression, hoping that the next Boolean value or the next Boolean expression is true. So this is the or operator. And finally, we have the not operator that we use to reverse a value. Let me show you how that works.

So let's declare another Boolean variable has criminal record. We said this to false. So here's the rule we want to implement. In order for someone to be eligible for a loan, they should either have high income or good credit and they should not have any criminal records.

So let's see how we can implement this rule. We have implemented the first part. They should either have high income or good credit. Now we want to make sure that they don't have any criminal records.

So we need to combine the result of this expression with this Boolean value using the and operator. So first we wrap this expression in parentheses. Then we apply the and operator. And here we add has criminal record.

Now we want to make sure they don't have criminal record. And this is where we use the not operator. So the not operator will reverse the value of this Boolean variable or expression. In this case, this variable is set to false.

So when we apply the not operator to it, the result would be true. So if the first condition is true and the second condition is true, then that person is eligible for a new loan. So as we can see, these logical operators are very useful in implementing real world rules. Next we're going to talk about if statements.

In this tutorial, we're going to look at if statements in Java. If statements are extremely important because they allow us to build programs that can make decisions based on certain conditions. Here's an example. In this file, we have a bunch of conditions.

If temperature is greater than 30, perhaps you want to display two messages to the user. It's a hot day, drink, plain water. Otherwise, if it's between 20 and 30, you want to print, it's a nice day. And otherwise, we want to print.

It's a quality. So let's see how we can implement these rules in a Java program. Back to our main file, we start by declaring a variable, temperature, we set it to 32. Now we use an if statement followed by a pair of parentheses.

Inside this parentheses, we type a Boolean expression or a Boolean value. So let's say temp is greater than 30. Now, if this condition is true, the statement that we add after this if statement will be executed. So let's print.

It's a hot day. Let's run the program. We get this message because temperature is greater than 30. Now, what if we want to print another message like drink, plain water.

Here we should add curly braces to define a code block. So if this condition is true, all the code that we have inside of this block would be executed. Let's add another message here, drink water. Okay.

So this was our first condition. Now, let's add the second condition. So after the right brace, we type else. If once again, we add our parentheses and inside this parentheses, we type a Boolean expression.

If temp is greater than 20 and it's less than or equal to 30, you want to print a different message like beautiful day. Now here, I haven't added the braces because we have a single statement. So braces are only required if we have multiple statements. Now, this is a little bit controversial.

Some people believe we should always add braces, whether we have a single statement or not, other people like myself believe this creates unnecessary noise in the code. In this tutorial, I'm going to add the braces first and then remove them so you can see the difference. So let's add a pair of curly braces here and finally our last condition. So if none of these two conditions are true, then we want to print a different message.

So here we simply type else. We don't have any more conditions. So let's add a code block and print called day. Now, let me define a few terms.

Here we have an if statement and this statement has three clauses or three sections. Here's the first clause. Here's the second clause and here's the third clause. Pay attention to how I've formatted this if statement.

So first we have the if clause. The else if and else clauses are placed after these right braces. So we have some kind of hierarchy here. Here we have a parent followed by two children.

Now let's get rid of these unnecessary braces and reformat our code to see the difference. So I'm going to remove the braces for the else clause and also one more time here. That's better. Now we can simplify this Boolean expression.

Basically we don't need this piece of code here. Here's the reason. If the first condition is not true, what does it mean? That means the temperature is less than or equal to 30.

So this expression here is unnecessary. Let's delete this and simplify our code. That's better. Now look at how this code is formatted.

On the top we have if the else if clause is a little bit indented, but the else clause is not indented. It's at the same level as the if clause. And this looks a little bit ugly. The code is not symmetrical.

So if you want to get rid of the curly braces, a better way to format this code is like this. So instead of adding the else if or else clauses after curly braces, we add them on a new line. Now all these clauses are at the same level. The code is easier to read.

In this tutorial, I'm going to show you a very cool technique for simplifying if statements. So let's start by declaring a variable called income and set it to 120,000. Now here we can use an underscore in between these three digits to make our code more readable. Now let's say we want to declare a Boolean variable called has high income.

If the income is more than 100,000 dollars, you want to set this to true. Otherwise we want to set this to false. So here we can write an if statement like this. If income is greater than 100,000 dollars, we want to set has high income to true.

However, we get a compilation error here. Let's take a look. Declareation not allowed here. So we cannot declare a variable here.

We can only declare variables inside code blocks like this code block over here. So to declare this variable, we need to add curly braces to define a new code block. Now we have a different problem. This variable that we have defined is scoped to this code block.

So it's only available here. We cannot access it outside of this block. Let me show you. So if we print has high income, we can see we have a compilation error.

Cannot resolve symbol has high income because this variable is not available outside of the block in which it's declared. So to solve this problem, we can declare this variable outside of this block. Boolean has high income. And then we can simply set it to true in this block.

Now we don't need these braces anymore. So let's simplify the code. We add an else clause. Otherwise, we set has high income to false.

Let's remove this print method. We don't need it anymore. So this is one way to implement the scenario, but this code looks very amateurish. A professional programmer doesn't write code like this.

Let's improve it step by step. One way to improve this is to give this Boolean variable an initial value. For example, we can set it to false initially. And then we implement this condition.

So if the income is more than $100,000, then we set this variable to true. With this, we no longer need is else clause. So that was one improvement, but it's still not ideal. In situations like this, we can completely get rid of this if statement here.

Let me show you. Instead of hard coding false here, we type our expression. Income is greater than $100,000. So here we have a Boolean expression.

If this Boolean expression evaluates to true, this Boolean variable is going to be true. Otherwise, it's going to be false. So this is the simplest, the most elegant, and the most professional way to implement this scenario. Now, one more improvement before we finish this tutorial.

I personally prefer to wrap this expression in parentheses, even though technically we don't need parentheses here, but these parentheses make our code more clear, more readable. Let me show you. So I'm going to wrap this inside this parenthesis. Now it's very clear, very obvious that on the right side of this assignment operator, we have a Boolean expression.

In this tutorial, we're going to look at the ternary operator in Java. So we're going to continue with the example from the last tutorial. We have this income variable. Imagine this is the income of our customers.

Now, depending on their income, you want to put these customers in different classes. If their income is more than $100,000, you want to put them in the first class. Otherwise, we want to put them in the economy class. So here's one way to implement the scenario.

We declared this string variable, class name, note that we cannot call this class because class is a reserved keyword. So class name. Now, we write our first condition. If income is greater than $100,000, we set class name to first.

Otherwise, we set it to economy. Now, as you learn in the last tutorial, this code looks very amateurish. A professional programmer doesn't write code like this. So one way to simplify this is to give this variable an initial value.

So we assume they are in the economy class. And then we check this condition. If this condition is true, we put them in the first class. So with this, we can get rid of this else class.

That is better. Now, in the last tutorial, I showed you how to simplify this even further, but the technique you learned there cannot be used here. In other words, we cannot add income greater than $100,000 here. Because here we have a Boolean expression, but on the left side, we have declared a string variable.

So we want to set this to a different string, depending on the result of this expression. And this is where we use the turner operator. So we start with our condition. Then we type a question mark.

If this condition is true, we add this value here. Otherwise, we add the other value. So this question mark and colon is the turner operator in Java. It has three pieces.

First, we have a condition. If this condition is true, this value will be returned and assigned to our class name variable. Otherwise, this other value will be returned. Now, we can completely get rid of this if statement.

So put the turner operator in your toolbox. It's very helpful. Next, we're going to look at switch statements in Java. In this tutorial, we're going to look at switch statements in Java.

We use switch statements to execute different parts of code, depending on the value of an expression, kind of similar to if statements. Let me show you. So let's say we're going to write a program and check the role of the current user. And then we're going to print different messages or give them different features depending on the role.

So let's declare a string variable called role. And here we set this to admin. Now, to check the role of the user, we can write an if statement like this. If role equals admin, then perhaps you want to print.

You are an admin. Now, you might be wondering why we have this condition here. It's obvious that this condition is always true because we have set role to admin. But this is just for demonstration.

In a real program, we are not going to hard code this admin here. So we're going to read the role of the current user from somewhere else. We don't know what it is at the time of writing code. Okay.

So here we have one condition. Let's write another condition else if role equals moderator. Perhaps we want to display a different message. So you are a moderator.

And finally, if the role is none of these values, you want to print, you are a guest. So this is one way to implement this scenario using an if statement. We can also implement this using a switch statement. And sometimes that looks a little bit cleaner.

Let me show you. So we start with a switch statement. Then we add parentheses. And inside this parenthesis, we add our variable.

In this case, role. Next, we define a block of code. And in this block, we add one or more case clauses. So we have a case for an admin.

We add a colon here. Now, what do we want to do here? If the role is admin, you want to print, you are an admin. So I'm going to copy this line from here and then paste it over here.

Now, after this line, we need to add a break statement to jump out of this switch block. Okay. Then we add another case clause. So case moderator.

Once again, we add a colon. And here we're going to print this other message. So we paste it here. And then we're going to break.

Now, absolutely, we can have a default clause here. So if none of these previous cases apply, the code that we write in this section will be executed. So here, we want to print. You are a guest.

Now, here we don't need to use a break statement because we're at the end of the switch block. So we'll automatically jump out of this block. In contrast, if we didn't use this break statement here, Java will continue executing these other lines here. So if the role is admin, first, it will execute this line.

And then it will jump to this case block. It will execute this other line. And then after it executes this break statement, it will jump out of the switch block. Okay.

So this is how we use a switch statement. Now, compare this with the state man. Some people prefer to use if statements, others prefer to use a switch statement. Now, one more thing before I finished this tutorial, here we're comparing the value of role with strings, but we could also use integers other than the long type.

So if role was a byte, a short or an integer, our cases would look like this. Case one, case two, and so on. Now, here we have a compilation error because role is a string. Let's change this to an integer and we can initialize this to one.

So as you can see, with switch statements, we can execute different code depending on the value of an expression. All right. Now it's time for an exercise. This exercise I'm going to give you is a popular interview question.

So I want you to write a program that behaves like this. Here we should enter a number. If this number is divisible by five, we get this. So if you run the program again and enter 10, once again, we get fits.

Now, if this number is divisible by three, we get buzz. If this number is divisible by both five and three, like 15 or 30 or whatever, we get fits buzz. And if this number is not divisible by five or three, like two, we get the same number printed on the terminal. So go ahead and spend five to 10 minutes on this exercise.

You'll see my solution next. All right, to read the number, first we need to use the scanner object. So scanner, we import this and instantiate it. And as you know, here we need to pass system that in to read data from the terminal.

Now we print a message. So we're going to use the print method instead of print line. Here we add a label like number. And then we call scanner that next int to read a number.

We store it in this variable number. Okay, so the first part is done. Now we need to check to see if this number is divisible by five or not. So we can write an if statement like this.

If number, here we use the modulus operator, which returns the remainder of a division. So we divide this by five, and if the remainder equals zero, that means this number is divisible by five. So we print Fizz. Now, otherwise, if this number is divisible by three, we print buzz.

We need another condition. If this number is divisible by five and three. So here we use the and operator number divisible by three equals zero. In this case, we want to print Fizz buzz.

Otherwise, we want to print the same number like this. Now, this is not the right solution. As I will show you in a second, this program has a bug, but it's a very common solution that I see amongst my students. So let's run this program and see what is wrong here.

All right, here we enter five. We get Fizz, beautiful. What if we enter 10? 10 is also divisible by five.

So we get Fizz. So far, so good. What about a number that is divisible by three? We get buzz.

Good. What if we enter a number that is divisible by both five and three, like 15? We get Fizz again. Why is that?

Here's the reason. With this implementation, if we enter 15, this first condition will evaluate to true. So we get Fizz. These other else clauses will be ignored.

And that is why this line will not be executed. So in situations like this, you should have the most specific conditions on the top and the most generic ones on the bottom. In this case, we want to move this condition to the top. So if the number is divisible by five and three, we're going to print Fizz buzz.

So this is very specific. Otherwise, if the number is only divisible by five, we print Fizz else. If it's divisible by three, we print buzz. And finally, if none of his conditions is true, then we print the same number.

Now let's run the program one more time. So we enter 15 and we get Fizz buzz. Beautiful. So here's one way to solve this problem.

Now, I have seen some people argue that we have repeated this expression twice. Number is divisible by five. We have that here on line 12, as well as line 14. In programming, we have this concept called dry, which is short for don't repeat yourself.

So some people argue that here we have repeated this expression. And this is not a good solution. Here is another way. Let me show you.

So we're going to get rid of this second condition here. Instead, we're going to add a code block over here. So if the number is divisible by five, first, we check to see if the number is also divisible by three. If that's the case, we print Fizz buzz.

Otherwise, we print just Fizz. Like this. Okay. Now we no longer need these two lines because we already implemented this concept here.

So first, we check to see if the number is divisible by five. If not, we check to see if it's divisible by three. And otherwise, so here is another way to solve this problem. But in my opinion, this approach is kind of a matured and ugly because these nested if else statements are considered a bad practice.

Now, this is not terribly bad. But the more you nest these if else statements, the more confusing your code is going to be to other people. So I personally preferred the previous solution, even though we had a bit of repetition in the code, the more you program, the more you build software, the more you realize that there is no way to build ideal software. Programming and problem solving is all about trade-offs.

Every solution has certain strengths and certain weaknesses. This solution doesn't have any repetition or duplication in the code, but it has a nested structure and these nested structures make our code hard to read and understand. The previous solution had a bit of repetition, but it had a flat structure. There is no nesting here.

And this code is cleaner and easier to read. There are times that we want to repeat one or more statements. For example, let's say we have Hello World message here. Let's say we want to print this five times on the terminal.

We don't want to repeat this code like this. This looks very ugly. That's where we use loops. In Java, we have a few different types of loops.

The first one that I'm going to talk about in this tutorial is four loops. So let's see how we can use a four loop here. I'm going to delete on this code. You start by typing the four keyword followed by parentheses and inside these parentheses, we need to do three things.

First, we need to declare a loop or a counter variable. So let's declare a variable called i and initialize it to zero. Quit often use variable names like i, j and k for loop counters. Next, we add a semicolon to terminate the first statement.

Then we write a Boolean expression that determines how many times this loop is going to get executed. So i less than five. As long as i is less than five, this loop will be executed. Once again, we add a semicolon.

And finally, we increment i by one like this. So this is the basic structure for a four loop. Now, here we can repeat one or more statements using this for loop. So we can add our Hello World message here.

Here we have a single statement. So we don't need braces. But if you have multiple statements that we want to repeat, we need to define a code block here. Now, I'm going to remove these because we don't really need them.

So let's run this code and see what we get. You get Hello World printed five times on the terminal. Beautiful. Now let me explain how this code gets executed.

When Java sees this for loop, first it will execute this statement. So here we are initializing i to zero. Then Java evaluates this condition. Is this condition true?

Obviously it is because zero is less than five. So the control moves to line seven. This line gets executed. Now at the end of this iteration or at the end of this loop, the control moves here.

So i is incremented by one. Now we are at the beginning of the second iteration. Once again, this condition is evaluated. Is one less than five?

Obviously it is. So once again, the body of this loop gets executed. Now fast forward. At the end of the fifth iteration, I will become five.

Five is not less than five. So the loop condition will be false and control moves outside of this for loop. Now here's one thing you need to remember. If you want to execute something five times, you can initialize your loop counter or loop variable to zero and use the less than operator here.

Another way is to initialize this to one and then use the less than or equal to operator here. Now to make this more interesting, let's print i over here. So here we add a space and then concatenate this string with i. Take a look.

So we get hello word one two three four five. In contrast, if we initialize i to zero and use the less than operator, you would 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 decremented. Now we get hello word five four three two one. So this is all about four loops. Next we're going to look at while loops.

In this tutorial, we're going to talk about while loops in Java. While loops are very similar to four loops in terms of their functionality, but they're different in terms of syntax. Let me show you. So we're going to continue with the example from the last tutorial.

I'm going to rewrite this code using a while loop. So first we declare a loop variable and i we initialize it to zero. Next we type while and here in parenthesis we type our loop condition. While i is greater than zero, then we're going to execute the code inside this block.

So I'm going to copy this from here, paste it in this block and find that we need to decrement i like this. So at the end of each iteration, we decrement i just like our four 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 going to 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 going to delete everything from here. All right, we're going to 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 a string.

Then we can write a while loop like this. While input does not equal to quit. Now this code is not going to 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 of our string objects, not their value.

So if you have two strings, quit and quit, but stored in different memory locations, they have different addresses. So we cannot 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 going to 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. And then call scanner dot 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 going to 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 our while loop. And then simply use it here.

Also, here we're 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 going to work the way we want. So over here, right after reading something from the terminal, we're going to call the two 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 a few numbers like one, two, and three. Whatever we type gets echoed 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 going to 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 the slew, we'll simply copy all these lines we have here.

Now compare 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. Now in reality, most of the time we use while loops. Do while loops are rarely used, but there are certain cases for them.

So just be aware of them, but most of the time prefer to use while loops. We're going to continue with the example from the last tutorial. This program we have written has a tiny problem. Let me show you.

So I'm going to 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 of 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 printed. 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, two, quit, beautiful. We solve 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, we can immediately jump out of the loop using the break statement. So I'm going to remove the not operator. If the user types quit, we're going to break out of the loop.

Otherwise, we're going to continue execution and print this input on the 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 will move control to the beginning of the loop. So all these other statements are going to get ignored and what the user types is not going to get printed on the terminal. Let's run the program and see this in action. So we type one, two, pass, it doesn't get echoed back one more time and finally quit.

So to recap, the break statement terminates the loop and the continuous statement moves control to the beginning of a loop. Now, one last thing before we finish this tutorial, in this implementation, we don't really need this loop condition because the moment user types quit, this break statement is going to 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 going to get executed forever until the user types quit.

This is a very common technique that you see amongst professional programmers. Just remember, if you're using this technique, make sure to have a break statement. Otherwise, you will end up with an infinite loop that executes forever. It never terminates and that can be very dangerous in terms of memory consumption.

So if you're using while true, make sure you have a break statement in your loop. The last type of loop you want to look at is the 4-H loop in Java. We use 4-H loops to iterate over arrays or collections. Let me show you.

So I'm going to start by declaring a string array called fruits 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 learned about earlier, like a for loop or a while loop, but we can also use the 4-H 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 4, here we declare a loop variable or loop counter, int i we set it to 0. As long as i is less than fruits.length, we're going to increment i by 1 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 4, in parenthesis we declare a 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 of 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 fruit the 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 will have to use the for loop. Otherwise, it's much easier to use the for each loop. 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. So if i enter one here, i get this message enter a number between $1,000 and $1 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. Next we need to enter the annual interest rate. Now here we need to enter a value that is greater than zero and less than or equal to 30. So if i enter zero, we get this message enter a value greater than zero 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.92. Here we need to enter a value between 1 and 30. So if we enter zero, 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 5 to 10 minutes on extending this mortgage calculator by adding error handling to it. You'll see my solution next.

All right, let me show you how i'm going to 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, we 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 principle. I'm going to wrap these two lines inside an infinite loop while true. So we're going to 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 going to print an error message.

So enter a value between 1000 and 1 million like this. Okay. 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. Principle is highlighted in red.

So here we have a compilation error. Cannot resolve symbol principle. Here's 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 is scope to the block in which it's defined.

So this is where we have declared the principle variable and it's scoped to this block. It's not available outside of this block. That's why we get this compilation error. So to solve this problem, we need to declare this outside of this while loop.

We can do it right here after we declare our constants. So let's say int principle and we can initialize it to zero. Now we remove the declaration from here and the error is gone. Now we need to repeat the same pattern with other questions.

So real quick, here's our second question where we read the annual interest. Once again, we add an infinite loop. Now the moment we read the annual interest, you validate 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 going to 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 the 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, more more time, we need 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 years is greater than or equal to one and it's less than or equal to 30, here we add the code block.

This is where we calculate the number of payments and then we break. Actually, I forgot to type on s here. Otherwise, if the user enters an invalid value, we 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 move it 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 hurts 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 going to show you next. So in this section, you 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 world 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, four 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 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, Marsh here. I want to congratulate you on your determination for learning. I would really appreciate it if you support me by liking and sharing this video. Also subscribe to my channel and enable notifications.

So next time I upload a video, you get notified. Now, if you want to learn more, I would encourage you to enroll in my ultimate Java series. As I told you earlier, this YouTube tutorial is the first two hours of this series. If you're serious about learning Java and want to become a professional Java 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 and have a fantastic day.

Course Hive

Continue this lesson in the app

Install CourseHive on Android or iOS to keep learning while you move.

Related Courses

FAQs

Course Hive
Download CourseHive
Keep learning anywhere