Java Programming for Beginners – Full Course Java Programming for Beginners – Full Course
Java Programming for Beginners – Full Course Transcript and Lesson Notes
You're about to learn how to program in Java from Farhan Hasein Chaudhary. Farhan is an experienced software developer here at Freeco Camp. He is great at breaking down concepts for beginners. This is a great course if you want to learn Java. You can follow along with the whole course from within your web
Quick Summary
You're about to learn how to program in Java from Farhan Hasein Chaudhary. Farhan is an experienced software developer here at Freeco Camp. He is great at breaking down concepts for beginners. This is a great course if you want to learn Java. You can follow along with the whole course from within your web
Key Takeaways
- Review the core idea: You're about to learn how to program in Java from Farhan Hasein Chaudhary. Farhan is an experienced software developer here at Freeco Camp. He is great at breaking down concepts for beginners.
- Understand how java fits into Java Programming for Beginners – Full Course.
- Understand how programming fits into Java Programming for Beginners – Full Course.
- Understand how beginners fits into Java Programming for Beginners – Full Course.
- Understand how full fits into Java Programming for Beginners – Full Course.
Key Concepts
Full Transcript
You're about to learn how to program in Java from Farhan Hasein Chaudhary. Farhan is an experienced software developer here at Freeco Camp. He is great at breaking down concepts for beginners. This is a great course if you want to learn Java.
You can follow along with the whole course from within your web browser. Farhan will teach you the basics of Java using Replit. Replit is an online IDE that allows people to write all sorts of programming languages right within their web browser and Replit provided a grant that made this course possible. So it's time to learn Java.
Hello everyone, welcome to the Java for Beginners course. I am Farhan Hasein Chaudhary and in this course I will teach you all the fundamental concepts around Java. Now, ideally a programming course usually starts by downloading and installing a lot of SDKs or IDEs or whatnot. But since we will be using Replit throughout the entire course, we don't need to do any of those.
Replit is an online collaborative IDE that you can use right from your browser. To start go to www.replit.com and you should land on the page. You can create an account on Replit or if you already have an account, just go ahead and log into that. I will just use my Google account to log in.
Once you have logged in, you will land on your homepage. From here you can create a new Repl by using this create button. Now from the list of language, we will pick Java but just so that you know Replit supports a long list of languages. Make sure you are giving your new Repls some descriptive names such as Hello World.
Finally hit the create Repl button and wait until the process finishes. If you have worked with some other code editors such as Visual Studio Code, the look of Replit should not be very different to you. You can change its default layout by going to settings and default layout. By default it should be side by side but you can also pick stack if you like that layout.
Now the default Java Repl usually comes with a bunch of code and you may have already guessed that this is the famous Hello World program retaining Java. To run this code, click on this run button here and you will see the code's output on the console. There you go. Congratulations on creating and running your first Repl on the next lesson I will explain what's going on just before we leave.
Remember you can always turn Replit dark by clicking on this Moonaikon and if you prefer dark themes over the lighter ones please go ahead. The Hello World program is probably the simplest executable Java program that you can write yet it's very important that you understand each part of this program. As you may have already guessed source files in Java end with the dark Java extension and compiled bytecodes usually end with the dark class extension. To see the compiled bytecodes on Replit click on these three dots on the files menu and click on show hidden files.
The program starts with a class declaration. A class is a collection of related code in Java. In every Java source file that is the file with the dark Java extension you can have one top level public class and that class has to match the name of the source file. This is because if you have multiple classes in your program like this you will see that the Java compiler produces individual bytecodes for each class.
To avoid any confusion about which of these classes is the entry point to the program. The JVM is designed to treat the bytecode that matches the name of the source file as the entry point. Inside the class there is a main method. Those of you familiar with C, C++ or Go may already know that the main method or function serves as the entry point to your program.
The JVM is programmed in a way that it will specifically look for a static method that is named main has public access, takes an array of string as a parameter and doesn't return any value. So you will have to write your main method as public static void main string args and nothing else. One thing that you can change however is the name of the args array. To something like arguments, the array holds the command line arguments passed to the program upon execution.
The system.out.println method prints out whatever string you pass to it as an argument. Unlike Python or Java script, semicolons are mandatory in Java. So if you leave it out the program will fail to compile. That's pretty much it about the hello world program.
Don't worry if you didn't understand all the terms used in this lesson, you will have a much better idea about topics like public and private access modifiers, statics, classes, methods in later lessons. Now if you try to run the program using the run button, everything works out just as expected. Another thing that you can change is the entry point. This will make sure that Replete opens the correct Java source file whenever you decide to return to this project.
Now there are a lot of other options in this dot Replete file but those are not important right now. The hello world program you have been seeing so far is pretty simple. If you want to write more complex programs, you will at least need some understanding of the different types of data and variables. Variable is any entity that can take on different values.
For example, if you want to store your age inside a variable, you can do so like this. First, you will have to write the type of the variable. Age is an integer or int. Then you will have to write the name of the variable which is age in this case.
Then you can finish off by putting a semicolon. You just declared a variable. Declaring means the compiler will know that this variable exists. However, you will also need to define it.
You can do so by assigning a value to this variable like this. Write the name of the variable. Then an equal sign followed by your desired value. In this case, the equal sign is known as an assignment operator.
We'll learn about operator in lot more detail in later lessons. Now you can print out the variable to the console like this. And just in case you are wondering, using a plus sign is one of the many ways to print out a dynamic value in between sentences. Keep in mind, you cannot use an uninitialized variable in Java.
So if you remove this line and try to run the code, the code will fail with the error message variable age might not have been initialized. Instead of declaring and initializing the variable in different lines, you can do it in one go like this. On the line of declaration, after the name of the variable, put an assignment operator followed by your desired value. Now if you try to run the code again, you can change the value of a variable as many times as you want.
So if you set the value of the age variable to 28 instead of 27, just before printing it out, you will see that the value has changed in the output. Although you can assign new values to the variable multiple times, you cannot declare the same variable twice. So if you do something like this and try to run the code, the code will fail with the error message variable age is already defined in method main. If you look closely, you will see two different sets of curly braces in this code.
The first set marks the start and end of the hello world class. The second set is inside the class and marks the start and end of the main method. Code inside a set of curly braces is known as a code block. Since the main method is inside the hello world class, any variable you declare inside the method will be only available inside the method.
These are local variables. However, you can also declare variables outside the method like here in the hello world class code block. If you do that, the variable will be available within the entire class. To use this variable inside the main method, you will have to declare it as a static.
We will discuss the reason behind this in a letter lesson. For now, just remember that a static method can only work with static variables. Moving out the declaration of the age variable and marking it as a static has not made any difference whatsoever. But if you remove the value of the variable and attempt to rerun the program, you will see the program runs without any issues this time and prints out 0 as the value of age.
This is because whenever you declare a variable in the class level, the Java compiler will assign a default value to it. For numbers, it's always 0. Another thing that I'd like to show you is if you redeclarate the age variable inside the main method now, there will be no problem whatsoever because the initial declaration of the age variable is not local to the main method. So, as long as you do not redeclarate a variable within the same code block, it will be good to go.
When it comes to naming your variables, you can name them anything as long as the names don't start with a number and don't have any spaces in them. There are also around 50 words reserved by Java itself as keywords and you cannot use any of them either. You can start a variable name with a dollar sign or an underscore, but excessive usage of these signs can make your code unreadable. In case of multi-word names, always follow camel casing when naming your variables.
If you want to learn about different programming naming conventions, I'll leave the link to this article in the description. Finally, avoid naming your variables using single letters. Now that you know about variables, we will discuss the different types of data. Keep in mind, I have reorganized the source file to better reflect what I will be talking about.
At a high level, there are two types of data in Java. There are the primitive types and the non-primitive or reference types. Primitive types store values. For example, int is a primitive type and stores and integer value.
A reference type on the other hand, stores the reference to a memory location where a dynamic object is being stored. We will discuss reference types later. There are eight primitive data types in Java. Six out of those eight types deals with different types of numbers.
First, there are the bytes. These are small numbers within the range of minus 128 to 127. Then, there are the shorts with a much larger range than bytes. The integers with an even larger range.
If you ever need to store a value so large that it doesn't fit in an int, you can use the long type. By default, any number with no decimal point is treated as an integer by the compiler. To let the compiler know that a number is actually a long, you have to append the letter L at the end of the number. You can also use a small L instead of the capital L if you want.
For numbers with decimal points in them, there are double and float types. Doubles are double precision 64-bit floating point numbers with a very long range. Floats on the other hand are single precision 32-bit floating point numbers with a smaller range. By default, any number with a decimal point is treated as a double by the compiler.
To let the compiler know that a number is actually a float, you have to append the letter if at the end of the number. Like the longs, you can use a small if instead of the capital one here. Boolean data type can have only two values through or false. At the moment, usage of a data type that can only hold true or false as values may not seem that useful to you.
But once you learn about conditional statements, you will see their usefulness. Finally, the character type can hold any valid Unicode character. The Unicode escape sequence for the copyright symbol is backslash U00A9. So if you store this value in a car variable and print it out on the console like this we have, you will see that the copyright symbol has been printed on the console instead of the value we have saved.
Of course, you can also save any standard character from your keyboard instead of these kinds of Unicode escape sequences. For example, if we remove the name copyright symbol and change it to something like percent symbol and replace this Unicode escape character with the percent sign and update or code accordingly. You will see the percentage symbol printed out on console instead of the copyright symbol. There you go.
Now for the most part when working with integers, the in type should suffice and for numbers with decimal points, the double type should suffice. But you should also know about the other types. Although you cannot store one type of data inside another type of variable, conversion between the different types is absolutely possible. Type conversion in Java can be either implicit or explicit.
When the compiler converts a smaller type of data, for example, an integer to a larger one like a double automatically, it's known as an implicit or narrowing type conversion. Let's see an example. First, get rid of all the old code in our project. Then begin by declaring a new integer.
You can call it anything. Then declare a double. And for the value of the double type, assign number one like this. So what you are essentially doing is first taking an integer with a value of five and then taking a double and assigning number one as its value.
Let's try to print it out using the standard system.out.println function, number two, and run. So as you can see, the compiler has successfully converted the integer to a double. This is because a double is larger than an integer. But what will happen if you try to do the reverse?
Let's try out. This time start with a double, 5.8 maybe, then an int. Okay, I'm Mr. Two here.
Now system.out.println, number two, and run. So as you can see, the program immediately fails. Same incompatible types possible lossy conversion from double to in. What the compiler is saying that an integer to double conversion is not possible automatically.
Although conversion from an int to a double is not possible automatically, you can still do it explicitly by letting the compiler know that you want this to happen. The cast operator can be of help here. First, inside a set of parentheses, write int. This will tell the compiler that you want to convert this double to an int.
Let's try to run the program once again. And this time the program works without any issues. But you have lost the point eight part after five. If you are doing explicit type conversion in Java, be extremely careful, whether the type you are converting to will be able to hold the entire value or not.
In this case, I knew that an integer will never be able to hold the entire 5.8 value. And I will lose the second part. But I went with it anyway. So as long as you know what you are doing, you should be all right.
But at any given moment, if you perform an explicit conversion and lose a bit of data, accidentally, the results can be catastrophic. Now that you know about variables and the different types of data you can work with in Java, you will have to learn about operators. Keep in mind, I have made some changes to our code to better explain our topic in hand. And since our code has become much longer than before, I suggest that you go to settings and change the default layout from stacked to side by side and then hit the reset layout button to apply the new layout.
This will give you a lot of vertical space and make the code easier to read. Operators in Java or programming in general are certain symbols that tell the compiler to perform certain operations, such as arithmetic relational or logical operations. Although there are six types of operators in Java, I will only discuss four. Bitwise, operators are a little bit more complex than the other ones.
And I don't think they fit well in a beginner's course like this. We will begin our discussion with arithmetic operators. 8-metic operators are the ones that you can use to perform arithmetic operations such as addition, subtraction, multiplication or division or so on. There are five arithmetic operators in Java and these are the addition operator, the subtraction operator, the multiplication operator, the division operator and the remainder operator.
The remainder operator is also known as modulo or modulo operator. Additions, subtraction, multiplication and division, these four are pretty self-explanatory. You can have a look at our code example here and you should be able to understand what they do and how they do it. If you have used a calculator in real life, the arithmetic operators in programming work similarly.
In our code, we have two integer numbers, number one and number two with the values 12 and 6 respectively. So if you add number one and number two together, the result will be 18. If you subtract number two from number one, the result will be six. If you multiply number one with number two, the result will be 72 and finally, if you divide number one by number two, the result will be two.
We will talk about the remainder or modulo operator later. The addition and multiplication operations in this code are pretty simple, but the subtraction and division operation need some more discussion. So we'll get rid of our addition and multiplication code here. We'll comment out the division code and the remainder code and focus solely on the subtraction part.
As you can see, the value of number one is 12 and number two is six, which means the number one is greater than number two. As a result, the result of the subtraction operator comes out as positive, but if we change the order of the operation here, so if we make number two, the first operand and number one, the second operand, you will see that the result of the operation changes from six to minus six. Again, if you have used calculator CNGL live before, you should already be aware of this situation. Now, the division operation.
Since dividing 12 by six yields the result two, this operation is perfectly fine, but if we change six with something live, maybe five, then the result will not be a whole number. As you can see, according to this program, the result will be two, but if we perform the same operation in a calculator or by hand, we know that the result of this operation should have been 2.4. Now, this happens because if you divide an integer with another integer, the result will always be an integer. So, let's try by changing this integer type to a double for both operands and run the program once again.
As you can see, this time the result is 2.4, but what happens if we divide a double by an integer? Again, the result is 2.4 and if we change the first operand to an end and the second to a double, the result will still be 2.4, which means if you divide an integer by another integer, the result will always be an integer. But if you divide a double or float by an integer, or divide an integer by a double or float, the result will always be another double. Now, let's get rid of our division code as well and focus solely on the remainder or the modulus operation.
Now, for this example, I would like to go back to our original values, which are 12 and 6 in the beginning and I'd like to go back to integer. Let's run the program and see what is the output. Compiling a program may take some time, but we just need to be patient here. So, as you can see, the result of this operation is 0.
First, we need to understand what is a remainder. Now, you may or may not already know that a remainder is the value that remains after you have divided a number with another one. So, if you divide 12 by 6, the result will be 2 and there will be nothing left. You can always divide a 12 into 2 6s.
But if I change 6 to something like maybe 8 and run the program once again, as you can see, the value has changed from 0 to 4. This is because if you try to divide 12 by 8, there will always be 4 left. I hope you got the idea. You have already seen examples of the assignment operators in previous lessons.
It's pretty simple. You can use the equal sign to assign a value to any variable in your code. But you can also combine the assignment operator with the five arithmetic operators you just learned about. For example, here we have an integer with a value of 12.
Now, if I tell you that you will have to add five with this value and save in the same variable, you can do that like this. Now, the output of number should be 17 instead of 12. Very simple. But instead of doing this in such a far-bosed manner, you can do it far more easily.
Let's just remove the second part here. And instead of using the assignment operator, use a plus sign than the assignment operator and then five. This small line of code is actually equivalent to number equals number plus five. Let's comment this out and see if this gives the same result as before or not.
Yeah, 17. So you can use all the five arithmetic operators similarly. Say, for example, if you want to take out six from 12, you can do so by saying number minus equals six. And this will turn the value of number from 12 to six.
There. You can also do modular operation like this. Like if you say modular equals and then two. The result of this operation is zero because when you divide 12 by two, there will be two success as a result and nothing left.
I hope you got the idea of using assignment operator with all the five arithmetic operators. And I would suggest that you try out usage of the other ones like the multiplication sign and the division sign with the assignment operator by yourself and see how the result varies from time to time. So far in this course, you have learned about the arithmetic operators and the assignment operators. The arithmetic operators usually lets you perform different types of arithmetic operations on your numbers.
And the assignment operator usually lets you assign different kinds of value to variables. Relational operators on the other hands usually check the relation among multiple operations. By relation, what I mean is for example, in this code, we have two integer numbers, number one and number two with the values 12 and 15 respectively. Now you may want to know whether number one or number two is equal to each other or maybe number one is greater than number two or maybe number one is less than number two or not.
These are the relation between these two numbers. So in Java, there are six types of relational operators. The first one is the equality operator. Now keep in mind each relational operator in Java or in other programming languages as well, usually returns true or false as a result of an operation.
For example, on line seven, I have written system dot out of print, and number one equals equals number two. The usage of this double equal sign here is the equality operator. Now if I run the code, since the value of number one and number two is not equal, the output will be false, which is correct in this case. Now you may also want to check whether number one is different from number two or not.
For that, you can use the not equal to operator. Instead of putting two equal sign side by side, you will have to put an exclamation sign followed by an equal sign. Now if I run the code again, you will see that the second operation gives us a truth because indeed number one is not equal to number two. Then you can also use the greater than operator to check whether number one is greater than number two or not.
Since 12 is smaller than 15, the output of this line will be false. There you go. There is also the opposite of the greater than operator, which is the less than operator. This operation in this case will give us true because number one is actually smaller than number two.
Finally, there are the greater than or equal operators and the less than or equal operator. Now the greater than or equal operator will give us true only if number one is greater than number two or equal to number two. The less than or equal to operator on the other hand will give us true only and only if number one is less than number two or equals to number two. Since number one is actually less than number two, the greater than or equal operation will give us false and the less than or equal operation will give us the result true.
Now the usage of these relational operators may not seem that much fun to you at the moment, but once you start working with things like relational statements, you will start to understand how important these operators are. The logical operators in Java or in programming in general, let's you make logical decision based on multiple conditions. For example, imagine you are writing a program that can only be used by people within the age limit of 18 years old to 40 years old. Here we have an integer number with the value of 25.
Now we will have to make two checks. First, we will have to check whether age is greater than or equal to 18 or not and then we will have to check whether age is less than or equal to 40 or not. So you have already learned about the greater than or equal and less than or equal operators in the previous lesson. Here I will teach you how you can combine these two operators using a logical and operator to make a connected decision.
So let's write system.out.println because we want to print up the result of our operation here and start with the greater than or equal operation. Age is greater than or equal 18. Then you will have to put double-n person sign and this is the logical and operator in Java and then age is less than or equal to 40. Let's run the code and see what the output is.
As you can see the output is true here. Let me explain. The logical and operator in Java or another programming languages as well works in this way. If the left side of the logical and operator and the right side of the logical and operator yields true as a result then the whole operation will give the result true.
Here the value of age is 25 which is larger than 18 which means the left side is true and it's also less than 40 which means the right side is also true. That's why the result of this and operation will be true. But if you change this value to maybe something like 45 which is clearly over 40 years old and run the program once again. You will see that the output becomes false because although the left side is true the right side is not.
So in case of a logical and operator both side of the operator has to be true. Now apart from the logical and operator there is also a logical or operator. Let's imagine another scenario. Maybe you are writing a program for your school's library and to be able to borrow books from the library a person either has to be a student of your school or a member of the library.
So we can have two Boolean cells here is student which is false maybe this person is not a student of your school and is library member. This is false true maybe he is a member of your library. Now to check whether this person is a student or is a library member you can use the logical or operator like this system dot out dot print Ellen. And first we will we will check if this is a student or not student or unlike the logical and operator you have to use two pipe characters to express the logical or operator.
And then we will check is library member. I hope you remember that in order for the operation to be true in case of a logical and a person both sides of the operator had to be true. But in case of the or a person if either side of the operator is true the entire operation will be true. So as you can see although easy student is false given his library member is true the operation gives us the result true.
So if you turn both of these Booleans to true the result will still be true. And the only case when you will get a false result is if both of these Booleans are false. Yes false. Finally there is another type of logical operator in Java which is the not operator.
The not operator in programming usually reverses a Boolean value. For example here the value of the easy student Boolean is clearly false right if we run the program it will surely print out false. But if we put a not operator in front of this this exclamation sign is actually the not operator and run the program you will see that it turns out as true. So instead of using the not operator over a single Boolean value you can actually reverse the value of an entire and or or a person in Java like this.
Let's go back a few steps and I hope you remember that in this case we got the result false because both of these Booleans are false. Now if you put a not operator in front of the easy student Boolean this will be turned to true. So now if I run the program the result of the entire operation will be true. Yes there you go.
The different types of operators that you have learned about so far usually work with multiple operands at a time except the not operator. It usually works on a single value or variable at a time. Now these kind of operators that usually work with a single operand is usually called unary operators. Apart from the not operator there are also two more operators that are unary in nature and very commonly used in programming.
These are the increment operator and decrement operators. As you know that you are trying to make a game where you have to store the score of the player and the number of turns left. Now you can store these values in two different integer numbers maybe named score and turns. Now whenever you have to increase the value of score by one you can do so by saying score plus equals one.
You have already learned about the usage of the arithmetic operators along with the assignment operator in previous lessons. Well this is one way to do this using this method you can actually add any number to score. But since here in this code you will only increase the score by one. Well you may think that what kind of game that is that gives you one in every time.
Well that's just for the example just very good. You can do it like plus plus. So putting two double plus signs after an integer or maybe float or double or any number kind out there will increase its value by one. Similarly you can put two minus signs to decrease or decrement the value of a number time.
Now if we print out the values of these two variables with system.out.print.score and we will just make a copy of this line and change it to trance. You will see that the value of score is now one and the value of trance is now nine. So this is pretty simple. Incrementing and decrementing values there is nothing fancy until I make it a big complex.
Let me show you something. Let's get rid of all this code and declare a new integer is called number and maybe its value is 55. Now if I say system.out.println a number plus plus. You may think that this will print out 56 because you know the you increment 55 by one and it becomes 56.
Well let's see if that's true or not. Since like that the value has not incremented at all. Okay let's make a copy of this line and get rid of the plus plus and run the programming in. This time the value has changed but at line five where you have used the plus plus or the increment operator the value remained unchanged but online six where you have haven't used any operator at all the value seems to be incremented.
But you see when the compiler reads your code it usually goes from left to right. So when it comes to system.out.println and sees the number variable here it immediately prints out its value. So at that point the value of number will be 55. Then it sees that there is an increment operator here and it goes like oh that means I have to increase the value by one as well.
Then the compiler increases the value of number to 56 and keeps that in memory. So if you ever print out the value of number later on it will actually print out 56. Now this is same for the minus minus sign or the decrement operator. Initially the value will be 55 even though the value has changed in the memory and on the second pre-dustatement it prints out 54.
So far I have showed you only one way of writing the increment or decrement operator. Instead of writing it at the end you can also put it in front like this. And let's see what output we get in this case. As you can see this time we are getting 56 because when the compiler reads your code from left to right it goes like system.out.println and it immediately encounters the increment operator and then it sees the number and goes like okay.
So I have to increase the value of number and then print it out. So it prints out 56 online 5 and online 6 as well. Saying goes for the decrement operator. 54 and 54.
So this is something that you should be aware of when using the increment or decrement operator inside other statements like in this case the println method call. If you are just incrementing or decrementing the number outside of anything like this method call like this number plus plus then you shouldn't have any problem at all. See so if you ever get like unexpected values after using the increment or decrement operator in your program just make sure that you are using it correctly or you are using it in the right place. I hope that you remember in a previous lesson I have taught you about the character type.
It is one of the primitive types in Java and you can store any unique code character in it. Like in this example I have stored the percentage sign in a character variable called the percent sign and I have printed out the character on my console using the standard system.out.println method. Now the character type is good and everything but if you want to store multiple characters together for example your name or a sentence you cannot use a character for that. For this type of scenarios we have string.
In Java there are multiple ways of declaring a new string. Let's see the literal way first. So instead of car you will need to type a string with a capital S and then name of the string in this case name and then the value. This is my name.
You can put any string right here and then you can print it out like any other variable in Java. Let's run the code. Now the other way to declare a string in Java is by using the new keyword. The new keyword in Java can be used to create new objects from classes.
Now we have not discussed classes at all in this course yet but we will get into classes and objects and object rendered programming later. For now just remember that the new keyword can be used to create a new object from a class. Now to create a string using the new keyword you will have to write string and the name of the string equals new string and the value. If you run the program there should be no change whatsoever because essentially declaring the string this way or that way doesn't make any visible changes to the program but there is a slight difference in these two techniques.
Now the JVM or the Java virtual machine usually uses a portion of your computer's memory to store strings. Now this little portion of memory is usually called the string pull. Now whenever you create a new string in the literal way, Java will first check whether this string Farhan has in jub3 already exists in the string pull or not. If it does then the JVM will simply reuse that previous string with a new name but in case of the new keyword the JVM will create a new object regardless of whether this value already exists in the pull or not.
I think this can be demonstrated with an example very well. Before this I will create four strings. First one is string literal is string one equals to A, B, C and I will create another literal string with the same value but different name. There you go.
Now I will create two object strings and don't get me wrong this strings are actually same but I am just naming them as literally string and object string to make clear that which is what. Now object string equals to new string maybe E, F, G or XYZ. So I will make a copy of this string change its name to object string two with the same value. Now if I convert these four strings with each other like this, print Ln, literal string one equals equals literal string two and I will make a copy of this line and use object string instead of literal ones.
Sorry. Let's make this wider so that the code becomes easier to read. Now if we run the code, as you can see when declaring a new string using the literal format since the value A, B, C was already present in the string pool that JVM actually reused the older value with literal string two. But when using the new keyword even though the same value has been assigned to the two string variables, they are not same.
You have already learned that the W call sign checks whether two objects are same or not and in this case the literal strings are actually same since they are using the same value from the pool and the object strings are different entities because they are not reusing the same values from the pool. Now depending on your necessities, you may go with either of these techniques but I would suggest that you go with the literal string technique if there is no problem with that because this will not only make your code easier to read. There is no new or there is no duplicate string written in the code but also it will let the compiler optimize your code a little bit. Other strings in Java are not primitive types.
These are object types and the strings are literally one of the most powerful types in Java. You will use strings a lot throughout your entire programming career and there are a lot of methods that we can use with these strings. Now I will demonstrate a few of those essential methods that you can use on strings and do fancy things with this. Depending on the type of software you are working on, you may or may not have to work a lot with string formatting.
Now let me explain this topic with an example. First I would suggest that you go back to the stacked layout from side by side because now our code will get a lot longer side OS and not vertically. Let's begin by removing everything and writing a single system.out.print.statement. In here we will write a pretty long sentence this time which is hello world.
I am for our Haseed Jodhury. I am from Bangladesh and I am 26 years old. Very simple program if we run it. We are getting the entire line without any changes.
Now we can take out a bunch of stuff from this line such as my name. Then my country name. Finally my age. Now to use these variables inside this string you can use the plus sign.
You may have already seen example of using the plus sign to slot in dynamic variables inside this strings. You can do the same here. I will get rid of Fahana's in Jodhury and in this string here. Now the first string starts here and ends here.
The second one starts here and ends right here. In between the two strings I put my name. Next I can take out the country name as well. I will separate the strings, put two plus signs and put country in here.
Finally the age. Same drill. Separate the string to plus signs and the variable name. Let's save the code across our fingers and run it.
As you can see the output is fine but I hope you are getting a sense of how complicated this string can get once you start adding more variables such as if I add my company name, the company work for company girls. Let's save free code camp. A really nice place to work at. So I can change it to I work for and then plus plus company.
Now you can put plus and a dot. Yeah works just fine. So the point I'm trying to get through is the fact that azure is string grows and you start to use more and more variables in it using the plus sign to concatenate strings or add them together becomes really clumsy. There is a better way to do this.
And that's formatting your strings. So let's declare another string called formatted string equals then we'll write string dot format. So my name is modulus s. I am from modulus s.
I am modulus t years old and I work for modulus s. So once we have written this line we will say comma. So my name is modulus s. So this modulus s or modulus t, these characters are called format specified.
So when the Java compiler comes and reads your line like this, my name is modulus s. The compiler knows that there will be a certain string here. And when it reads I am modulus d years old. The compiler will know that there will be an integer number here.
But the compiler doesn't know yet what string or what integer value will replace this format specifiers. So once you have finished writing your string along with the format specifiers, you will have to put a comma and then put in the variables in the same order of the format specifiers. For example, we have my name is modulus s and we want to replace this part with the name variable. So we will put name then we'll put a comma and then I am from modulus s and we want to replace this format specifier with the country name.
So country comma then we have modulus d which we want to replace with the age. Finally, we have one more modulus s that we want to replace with the company name. Let's put full stop here. There you go.
Now we have a formatted string. So instead of writing this along string with plus signs and variable names and what not in it, we can just write for method string. Let's run the code. And as you can see, it works out just fine.
So far you have seen the format specifiers for strings and integers. There are also certain format specifiers for floating point numbers and Booleans. So the format specifier for a floating point number be it a float or a double in Java is modulus f. So if I put in a double here like maybe by GPA equals 3.8, this is not real.
And I can write. GPA is modulus f and we can replace this modulus f with the value of GPA. Excellent. Finally, the format is specifier for a character is modulus c and a Boolean is modulus b.
Now I can't think of any fun example to demonstrate modulus b and modulus c. But I'll just go with it. Maybe character percent sign equals to put the percent sign here. And I can say I have attended 100% of my university classes.
Excellent. And after the GPA, I can just visit comma and put percent sign here. Cool. Then let's put a Boolean as well.
Boolean. And I am dealing the truth equals false. Now I'm not dealing the truth. I haven't attended 100% of my classes and my GPA is also not 3.8.
So am I dealing the truth? You're right. These are all modulus b claims. And I can put a comma here and then am I dealing the truth?
Yeah. That's a really horrible name to be honest. Let's run the program again. Excellent.
My name is Farhan Hensin Chaudhary. I'm from Bangladesh. I am 26 years old. I work for free code camp.
My GPA is 3.8. I have attended 100% of my university classes. These are all false claims. So as you can see, the string.Format method returns a formatted string by replacing all the specified format specifiers with your given values.
Now instead of saving this formatted string in a separate variable like I have done here, you can actually just copy the entire thing and paste it inside the println call. Although it works and you can do this if you want, but I would not suggest doing this because there is something called the printf function that you will learn later on in this course. That actually lets you use the format specifiers right in the print function. So for now, I would suggest that you save your format a string in a different variable and then print that out using println or use that however you see fit.
So remember, the format specifier for his string is modulus s or an integer number also for shorts and longs is for modulus t. For floating point numbers both floats and doubles. Modulus f or characters. Modulus c and finally for booleans modulus b.
While working with strings in Java, it's really common to check the length of a string or you may want to check whether his string is empty or not. Like a lot of things in Java, doing these two tasks is really easy. Let's start with a single string. Okay.
So extreme name Perhan Hasin Chodd. Now to check the length of this string, you can write first the name of the string which is name then dot length. The length is a method that remains inside every string that you're creating Java. Now if you run the code, as you can see the length of this string is 22 which means there are 22 characters in the entire name including the spaces in between.
Okay. Now you can also check whether his string is empty or not. To do so, you can just write the name of the string which is name in this case and then dot and is empty. This is another method that returns either true or false.
If the string is not empty, then it will return false and if it's empty, then it will return true. Let's run the code and the output in this case should be false. Since the string actually contains some characters in it. Now if I get rid of the name inside the string and just put two quotation marks with nothing in between them and run the code again, this time the string will be treated as an empty string and the output will be true.
Now the length and the is empty methods can be pretty useful in certain scenarios. So I would suggest that you remember them and practice their usage as you go along. You can also convert strings from lowercase to uppercase or uppercase to lowercase in Java. To do so first, you will need a string.
Then to convert this string to uppercase, you just need to write the name of the string which in this case is name, then a dot and two uppercase. This is a method and if you run this program, you will see that the name has become uppercase. However, you may think that these two uppercase method has actually changed the original string which is not true. So if we add another print element here, printing out the original name, you will see that the original name variable is actually unchanged.
You can also convert the name to lowercase by using the two lowercase method and this will convert the entire string to lowercase. There you go. In a previous lesson, I have taught you two ways to declare new strings in Java. There was the literal way that usually reuses the string value if it's found in the string pool and then there was the usage of the new keyword.
And I hope that you also remember that when you created a string using the new keyword like this equals to new string and the value can be something like ABC, then make a copy of it and put string two with the same value and try to compare them using the equals equals operator or the equality operator like this stem.out.println is string one is equals equals string two. You will see that the output of this operation comes out as false. This is because even though the value of the two string is same, these are not the same object and the equality operator usually checks whether the object on the left side is same as the object on the right side or the object on the right side is same as the object on the left side. Now to compare strings, you will have to instead use the equals method.
So you will first write the name of one of the strings then equals and string two. Let's run the program once again and this time the output is true. However, if you change the second value of ABC to capital ABC, sure the output will be false this time since the values are not same. But there can be cases where you want to check whether a string is equal to another string or not ignoring their cases.
So for those scenarios, you can use the equals case method instead of the regular equals method. So as you can see, even though the two strings have different casing, the output is still true. You can also replace a part of string in Java to do so. First, you will need a string such as the sky is blue.
And then say for example, we would like to replace the word blue with red here, system dot out dot print. And then string, which is the name of our string right now and then replace. You'd like to replace the word blue with red. Then run the program and see what output is.
As you can see, the word blue has indeed been replaced with red. Now, you may think that the replace method changes the original string, but it doesn't. There you go. What it actually does is it replaces the word blue with red in the string and returns the updated string as a new one.
So instead of putting it directly into the print element method, you can also do something like a string updated string equals to this. And then put updated string inside the print element method. So this will give us the same result as before. You may not always want to replace a sub string within a string, but you may want to check whether a string contains a certain word or a sub string or not.
You can do so in Java as follows. So we'll use our previous string, which says the sky blue and we'll check whether this string contains the word sky or not to do so. You will say string, which is the name of our string here. Then a dot and then contains.
And you will need to pass the string that you want to check for to the contains method. In this case, it's sky. So if the code and run it. Since the string contains the word sky, the output is true.
But if you put something that is not present within the string, such as free code camp and run the code, the output is false. Back when I was learning to code for the first time, one of the things that I learned and it gave me a sense of achievement was being able to take input from the user. So far in this course, you have learned about different types of data operators and outputting text on the console. In this lesson, I will show you how you can take different types of inputs from the user, as well as print out text on the console in some other formats.
If you are familiar with programming languages like Python, where taking input is a matter of a single line, you may be disappointed to learn that in Java, you have to write quite a bit of code to take an input from the user. Now, the first thing that you need to take input from the user is something called an scanner object. Now, a scanner is one of the classes in Java and you can use a new keyword to create a new scanner object from the class. So you begin by writing scanner.
Since the type of the object will be scanner and you can name it anything but I prefer naming it something simple like scanner. Then equals new scanner and you will have to let it know from where you are getting the input. So since you will get the input from the console or the terminal, you will have to write system.in. Now, the scanner class that you are seeing here, it doesn't exist in your program yet.
You will have to import it first. So before the first line where you declare the class, you will have to write import java.util.scanif. Now, you may be seeing this import statement for the first line here but it's nothing complicated. There will be scenarios where a certain class will not be a part of your current program or your current class and you will have to import it from somewhere else.
So the Java language comes with a lot of such classes that can be really useful in different scenarios. The scanner class is one of them. So once you have defined the new scanner object, you can take input from the user. So first, I would like to speed out something informative on the screen like system.out.println and then I will end the line here and I will say scanner.nextline.
That's it. Now, the scanner.nextline method can be used to take strings as input from the user. You will have to save this input somewhere though. So you can say string name equals scanner.nextline.
Then you can print it out. Let's print out the name for now. Let's run the program and see if it works or not. As you can see, there is a quickly line under scanner and if you hover over it, it says resource list scanner is never closed.
Well, what it essentially says is once you are done with the scanner, you will have to close it. It's like an open door. So if you do not close it, it will be active on the memory. So you will have to go like scanner.close and this quickly line should go away.
Yes, it did. Now the program is fine. Let's run it. Yeah, what is your name?
Perhan Assylchukri. Enter. And yeah, it prints out my name pretty nicely. Now you may notice that inputting my name after the prompt, like what is your name?
Then inputting my name in the next line may look a bit little bit weird. So instead of using the print element method, what we can use here is the print method. So the print method is actually similar to the print element method, but the main difference is that it doesn't have a new line character at the end of the line. Let me show you.
So as you can see, now the text prompt is right after that question mark. So I can say far hand. Yeah, enter. And yeah, that's nice.
Now in case of a print element method, there is usually a new line character at the end. So this causes the text puzzle to go to the next line. That's run the code to see how it changes our output. Yes, you can see now it mimics the behavior of the print element.
Okay. Now apart from the print method, there is another useful cousin of this print element method called the print F. In a previous lesson, I have showed you how you can create formatted strings using different types of formatting specifiers. And I also told you that there is a variation of the print element method that lets you use this formatting specifiers right within the print method.
Okay, that's that's the print F method or print formatted. Now instead of just printing out the name like this, we can say hello, modulus S. Now are you? And then we'll put a comma.
And we would like to replace the modulus S with the name. So we put name. I hope you remember all the different a formatted specifiers that you have already learned about. If not, you can just go back and rewatch that lesson.
Let's run the program again. The Farhan Cho-Turi. And yet now the program reads me and also asks how am I. Okay.
Okay, let's do something more. So you have learned that the next line method usually gives back a string from the user, but you can also ask for specific data types such as maybe an integer. So to do so, let's modify the next print affair. So hello Farhan.
How old are you? Okay. And then we would say int h equals to scanner dot next int. Yeah, nice.
And we would like to print out print. Yeah. And sorry, not printed on print F. Modulus D is an excellent age to start programming.
Okay. Like any age is like excellent to learn programming. So, you know, and we will put age here. So this modulus D part will eventually be replaced by the age variable.
Okay, let's run it. And that is your name. Okay. My name is Farhan.
How old are you? 26 maybe? Yeah. 26 is an excellent age to start programming.
Nice. I like it. Okay. Now so far so good.
Like the next line method and next int method, there are also methods for double like the scanner dot next double and next float and all those different types that you can think of. But one thing that I would like to draw your attention to and something that catches a lot of Java beginners occurred is a little quirk. So as you can see, I am asking for the name using the next line method. Then I'm asking for the age using the next int method and it works out just fine.
But let me show you what happens if I try to use another next line method after this next int method. Okay. So if I say system dot out dot print LN or pre-tiff. Okay, let's just reuse this line.
Okay. It's an excellent age to start programming. What language do we pray for? Yeah.
Yeah. And after that, we'll say spring language equals to scan dot next line. Okay. It's stem dot out dot print.
Not unless S is a very popular programming language. Okay. We'll stop. Same go.
Scan dot close. Yeah. Now, sorry, I miss the language here. Yeah.
Now, look carefully what happens when I run the program. Okay. So I run the program. So first it asks for my name.
Cheers. Perhan. Sure. Ask how old am I?
So 26. And then it is keeps the last prompt where I'm asking about the programming language preference and just in the program abruptly. And the worst part is there is no error or no failure at all, which can help you to debug this problem. Well, this is something this has to do with the way the next int and the next line method works.
So let me explain. So when you are saying a string name equals to scan dot next line. And I'm inputting my name, then I'm pressing enter. The next line method is actually taking the entire name along with my enter or my new line character at the end or the character when I press enter that goes as an input.
But when it comes to the next int method, it only takes the number or 26 as an input and leaves the new line character or carriage return in the buffer in the input buffer. So what happens is when I say 26 and then I press enter, this part will be consumed by this method next int. But the enter will be left in the input buffer. So so when the second next line call comes, it sees that there is already an enter in the input buffer and mistakes it as an enter key press from me.
So it assumes that the user has already inputted the text they wanted to input and ends the call right there. Okay, I hope it makes sense. Now there are multiple ways to like deal with this problem. And one of the ways is whenever you put a next int call or next double call or next float call, whatever it is except next line, then you will have to put an extra scan dot next line here.
So this just I clean up the input buffer. So this next line method eats up the enter that was left by the next int and cleans the input buffer. So if we run the program now. Okay, let's say for her and how old am I 26?
What language do you prefer? El java? Yeah, java is a very popular programming language. So this is something that you should keep in mind that whenever you are using a next int call, anything but a next line call and you want to put another next line call after that, like we have next int and the next line, you will have to put an extra scan dot next line call just to clean up the input buffer just to get get rid of that leftover enterprise.
Okay, otherwise your program may skip the next call. Okay, another way to deal with this situation is instead of using methods like next int or next float, you can just use next line for taking all the inputs and then once you have taken an input, you can just like convert it to something else. For example, instead of using the next int, if we use the next line method here and this will give us a string. So what we can do is we can say integer.parse int and then put the scan dot next line in there.
Okay, let's run the program and see what happens. 26.java, yeah, it works out just fine and we do not have to use any extra scanner objects as well. Now, if you had like instead of int, you may have like double here, you can do so double, say for example, if we want to take the GPA of the user equals to tup.parse double.parse double and then scanner dot next line and this will work out too. Okay, so all of the first method that we have in this classes like integer dot parsing double dot parsed double, we can use all of this.
Now, you may think that how would I know which method to use when you are trying to purse a number from a string. Well, one way that I suggest everyone is you can just google it saying how to purse integer from a string in Java or maybe how to purse a double from a string in Java and so on. Now, this is something that I would leave up to you to figure out because this is something that you do not learn in courses. Okay, so I hope you have learned about taking inputs from the user.
The main thing you need is a scanner object and you will have to let it know from how you are getting your input. You can also take input from a file and some other places but those are a bit advanced for what you know at the moment and you will also have to remember to import the scanner class first otherwise the code will just fail. Okay, if I comment this out and run the code, you will see the program simply fails to find the scanner class. It says cannot find symbol so make sure that you have imported the class at the top here and the risk is pretty simple like it.
So now that you have learned about taking input from the user and output in text on console using printf print and println. In the next lessons, we learn about something called the conditional statements and we'll make a very simple calculator project that we'll just show you how much you can do with what you have already learned. Now, you have already learned about the logical operators and taking input from user to have the most important things in programming. In this lesson, I will teach you something called conditional statements that lets you make logical decision based on some conditions and branch out your code in different ways.
For example, we'll make a calculator in this lesson and we'll let the user perform additions, subtraction, multiplication and division operations based on their inputs. So first, we will need this scanner of course and let's get rid of all this code. Okay, so we need to close this scanner as well. Okay, let's begin with a double.
Double number one equals to scanner dot next double and then we will also do number two scanner dot next double. We need to output something on this screen as well. Println. Sorry, let's use print here.
Enter the first number. Okay, and then we'll put enter the second number. And let's just output the numbers to make sure that the input is working fine. Number one and then let's make a copy of this line.
Number two. Yes, let's run the code. Five and ten. Yeah, looks like the input is working fine.
Now we need to ask the user what operations they want to perform for that. Let's speed out what a person you want to perform. And okay, we'll do sprint instead of println and then we will have to take a string input. So string operation equals to scanner dot next line.
So as I've already told you that this next double calls, we'll leave two next line characters in the input buffer. So we will need to clear them out first. So let's just put this extra calls here. And once we have taken this string operation, then we can check what it is.
Okay, so the if is statements in Java or in programming in general, let's you check whether a certain value meets a certain condition or not. For our case, we can say if then a set of parentheses operation dot equals sum. So if the user has written sum as a name of the operation, then what do you want to do is system dot out dot println and we will say not println printf modulus d plus modulus t equals to modulus t comma. So we want to replace the first modulus t with number one.
This should have been f actually since we are working a double-ser and not integers. Then number two finally number one plus number two. Spass them out in the line with the semicolon. Excellent.
Now let's check out our simple calculator and see if we can do the summation correctly or not. So the first input will be five. You can put anything you want. The second number will be 10.
What operation do you want to perform? Okay, sum. Yeah, five plus 10 equals 15. Now what happens if I put anything but sum?
Okay, for now we are checking if the operation is equals to sum or not this will return true. If it returns true, then the line inside the if statement will be executed. But what happens if we input something else? Let's check it out.
10, 2, maybe subtraction or sub. You see nothing happens. So for situations where an if is statement fails to fulfill the condition, we can put an else statement and we can print out system.out.println.printf.modulus s is not a supported operation. And we can put a semicolon here and we can say comma operation.
Let's see how it turns out. Okay, five, 10, sub. Sub is not a supported operation. Excellent.
Now I have already said that we will implement a summation, subtraction, multiplication and division. For that, what we can do is we can put LCF statement here. So if this condition fails, we can say else if and we can put another condition here. So operation.equals sub.
Then what do you want? Copy this line, put it here, change the plus sign with minus and also change the operation here. Nice. Then we don't want to close this gap, make it look good.
So now what will happen? The program will ask for the first number, then the second number, then ask for what kind of operation the user wants to perform. And then first it will check if the operation is equal to some or not. If it's equal to some, then it will print out the sum of the two numbers.
If it's not the sum, then the letter will check whether the operation is equal to sub or not. If it's sub, then it will perform the subtraction operation and give out the value. And if the operation is not sum and also not sub, then it will go into the else block and print out that this is not a supported operation. Let's check it out.
Okay, five, then sub, yeah minus five, since the second operandi is larger than the first one, the value is negative. Similarly, we can just implement the multiplication and division operations. So let's just do them. Else, if operation dot equals multiplication, then I'm just copy this entire line.
Yep. Yeah, that's it. Finally, the division operation is a little different, a person equals to div. Then first, we will have to check.
We'd put another if inside this LC, and this is called a nested if block. So we'll check if number two is equals equals zero. Then we want to print out system dot out dot print Ln. And we'll put Ln.
Cannot divide by zero, because you just cannot divide a number by zero. And then we'll put else and we'll perform the division side. Okay. And we'll bring up the else block here.
And now let's let's check out the division and multiplication operations as well. Let's put 10, 0 and d. Cannot divide by zero. Excellent.
Let's rerun the program. Enter the first number 10 to give five excellent finally, the multiplication operations. Then 8, m, u, l, multiplication, you're 80. Excellent.
So we have already managed to create a very simple calculator here, capable of performing the basic arithmetic operations using e-fails. Now, I'm not saying that this is the only way to implement a calculator. You can actually find even much better ways of making calculators. So far, what you have learned, this is a pretty good implementation of all your knowledge.
Now, when it comes to branching out your code based on one or more conditions, if else's statements are pretty common. But this is not the only way of doing things. There is another statement called switch case statement that can do the same thing as a complicated e-fails ladder. In this lesson, we will convert our calculator application to use a switch case statement instead of e-fails statements.
Now, before we dive into our code, I would like to go to settings and change our layout from stack to side by side because as I'm seeing, our code is becoming much longer vertically and it's becoming harder to read. We can also make the console smaller for now because we need to focus on our code. Now, we can retain most of our code from our previous example. We can keep the scanner, the inputs for number one and number two, the input for the operation.
And the only thing that we need to get rid of is the e-fails statements. Now, instead of removing the code entirely, what I would do is I will just comment it out. Now, to write a switch case statement in Java, you will have to begin by writing a switch and that within a set of parentheses, you will have to put the variable that you are trying to test. So, if you remember from our e-fails statement, we are testing out the value of the operation variable and see whether it matches one of the four operations or not.
So, inside the switch, put operation, then we will put a set of curly braces. Now, you may have already guessed from the name of switch case statements that there will be multiple cases inside a switch. Now, these cases are like this individual e-fails statements where you are checking the value of the operation variable against something. So, in the first case of this statement, we will check whether the value of the operation is some or not to do so you will have to write case and then the value you want to check against, which is some in this case.
Then you will put a colon here and on the next line, you can put the logic for the summation. So, I will just pop the code from our previous e-fails slider and put it here. Let's run the code and see what happens. Okay, enter the first number, I put 5, enter the second number 10 and stop.
Okay, it says 15, which means it works. Now, try to put a value that is not defined within the switch case statement like sub. Let's rerun the program. 5, 10, sub.
And as you can see, just like the e-fails statement when you didn't have an ill cell, it doesn't print out anything at all. Now, in case of switch case statements, you do not have else, but you will have a default case, which you can write as default and then you can just print out that this is not a support operation. Yes, let's run the program and see what happens. First number 5, 10 and stop.
Okay, so that is not a support operation. Fun. Now, so far, this looks okay, but let me show you a problem here. If I run the program, if I put the numbers and then say some, you will see the program not only prints out the summation of the two numbers, but it also prints out is not a supported operation.
Well, the ways switch cases are designed that if one of the cases match, then the program will not only execute that case, but also the cases that comes after that to stop the program from going through all the cases here. What you will need to do is you will need to use the break step. So when the program comes and it sees that the sum case has been matched, it will execute the logic here and then it will encounter the break statement and break out of this entire switch case statement. Okay, and it will go directly to scanon.close.
Let's test it out once again. Sorry, let's put 5, 10 and stop. So as you can see, it prints out the sum and breaks the program right there. Okay, that's cool.
Now, you can actually define the other cases such as case sub and we'll of course take the subtraction logic from our previous e-fills ladder. Put it here, put the break statement in. Let's just copy this best, best, okay. So the third case would be the multiplication case and it will change the minus sign, so the multiplication sign.
And finally, the division case. Now, I hope that you remember that we also had a check to make sure that the user is not trying to divide by 0. We will have to do that as well. And for that, we do not have anything fancy.
We will just need to rely on plain old e-fills statement. So we will write if number two is equals equals 0. Then we would like to print out. Cannot divide by 0.
Else, we would like to perform the division operations. Keep in mind that you should write the break statement outside of both the if and else block. Otherwise, if you put the break inside the if or the else, then it will only work if one of them are active. But if you put it out here, no matter what happens in this e-fills block, the break will always work.
Let's write it out and see if it works or not. Save the code and run it again. Okay, 10, 0 and df cannot divide by 0. Let's rerun the program and check if the normal division function works or not.
10, 2, df. Yeah, it works. Finally, let's check the multiplication. 10, 5, multiplication.
50, yeah, it works just fine. Now you can get rid of the comment out e-fills statements. Now, although e-fills statements and switch case statements are more or less to the same thing in the context of Java or in the context of other programming languages as well, a switch case statement is actually faster than an e-fills letter in Java. So if you can put your logic within a switch case statement instead of a really elaborate e-fills statement, try to do that.
So far in this course, you have only stored single values in single variables. But there is a way to put multiple values within a single variable. These are called arrays. Now, before I start working on arrays, let's do some cleaner.
You can get rid of more or less everything in our code. You can also get rid of the Java UD.scan. Now, to declare a new array, for example, if I want to declare an array of characters and I want to store all the vowels in English alphabet, you can do so like this. First, you will have to type out the type of the array, which in this case is car or character space.
Then the name of the array, which will be vowels and two is car braces. Then you will put an equal sign and new car. Then you will put another set of his car braces and inside of this square braces, you will have to put the length of the array. Now, we know that there are five vowels in the English alphabet, so you will put five.
Now, we have an array of characters, but it's completely empty. To insert a new value to this array, you will have to write files and then and index of the array, which in this case 0, then equals then the value you want to save in the array. Now, I have already told you that this array is of five length, which means it can store five characters in it. Now, these characters here can be stored like A, E, I, O, U, and each of these characters will have a number associated with them.
This number is called the index. Now, the first index of an array in Java is always 0. So, by putting vowels and 0 inside a set of square braces, you are essentially addressing the first place in this array. Then you put equals A and you fill it up.
Now, the other spaces are still blank. Now, you can copy this line and paste it to insert the other values as well. So, 0, then 1, then index 2 will be i, index 3, will be O, and finally, index 4 will be U. Now, you have completely filled this array with the five vowels of English alphabet.
You can also print out these individual files using the same square brace syntax. So, if I copy files 2 from here and write system.out.println and put files and two inside square braces and print it out, you will see i printed out on the console. As you can see, there is i. Now, you can also print out an entire array, but that's not as simple as printing out a single character or number or string.
As you may have already guessed, the print, printf or println function brings out stuff on the console as strings. So, before you can print out the array, you will have to convert it is string. To do so, import the arrays class like this, import java.util.arrays and then inside the print ln method call, you will write arrays.dot to string and then the name of the array. In this case, is files.
See, we have printed out the entire array. Now, you can also print out an array using loops, which you will learn in later lessons. For now, just be informed that there is also other ways of printing out an entire array to the console. So, I have already mentioned that this array has a length of 5.
And since its index count starts from 0, it will obviously end at 4. Now, if you try to put something in an index that doesn't exist, like 5, I can maybe put x here, run the program. You will see that it fails with an exception saying index 5 out of bounds for length 5, which means for an array of length 5, you cannot have an index 5. Let's get rid of that line.
And our code should be back to normal. Instead of declaring and defining your arrays separately, you can actually declare and define your array in one line. To do so, after you have written car, files, the pair of his car braces and equal, get rid of the new keyword and put a set of curly braces here. Then you can actually put the values and in the line with the same colon, get rid of this line here and run the code.
There you go. Now, you can also replace any of these values from the array at any moment. For example, if you want to replace the i with any other character out there, you can do so in this way. Favels, curly braces and the index of i is 0, 1, 2.
So, put 2 here equals and put x. Put the same colon at the end, run the program. And as you can see, the i has indeed been replaced with x. Another thing that I forgot to mention is the fact that when you are declaring and defining your array in a single line, the array will actually infer its length from the number of values you are defining it with.
So, since there are five values in the definition, the array's length will always be five. Now, like strings, arrays in Java are reference types. And like strings, arrays also have a bunch of useful methods in them. For example, if you ever want to know about the length of an array, you can do so by saying, let's get rid of this line first.
And you can write the name of the array, vowels and dot, length. I hope you remember that in case of string, the length was actually a method, but in case of an array, it's a property. So, if we run the program, and you can see the length of the array, one of the most common task regarding arrays that you may have to do again and again within your programs is sorting an unsorted array. Right now, we have ordered our vowels array according to the order of the later as they come in the English alphabet.
So, A, E, I, O, U. But if we change the order and kind of randomize it, so I put E first, then U, A, and I. So, A, E, I, O, U, then it's totally out of order. Now, there is a method called sort within the arrays class that you can use to sort your arrays in order.
To do so, you will have to write arrays dot sort and then put the name of the array, vowels. Then let's spring back our arrays dot do a string method and we'll say vowels. Let's run the program and see if it works or not. So, turns out that the arrays dot sort method takes an array as its parameter and it sorts the array in place.
So, it actually changes the original source array. By default, the arrays dot sort method performs the sorting on the entire array. So, it will begin from the first letter and go through the entire array until it reaches the last letter and sort them in order. But if you want to perform the sorting within a certain range of the array, let's say for example, if I want to keep the E and I as they are right now and I just want to sort the U, A, and O, I can do so.
So, after I have put the array name to define the starting and ending index of the sort method, you can let's just define to integer sayers. So, int starting index equals I'd like to start the sorting from U, so 0, 1. Then in ending index, I want to perform the sorting until O. But here is the thing.
If I put 0, 1, 0, 1, 2, 3, 3 as the ending index, the O will be left out from the sorting because the ending index is usually not inclusive in this case. So, I will have to write 4, which means the sorting will take place from U to O and it will actually not affect I. Let's test it out. After I have written the name of the array, I will put a comma here and I will put the starting index.
Then the ending index, save my code and run it. So, as you can see, the sort method has actually sorted A, O, U in order and did not touch E and I at all. So, this is one of the useful things that you should know about sorting arrays in Java. Apart from sorting an array, you may also want to search for a certain value within an array.
So, for example, we have EUAOI here and if you want to look for O in the entire array, you can do so by using the arrays.binary search method. One thing that you will have to remember is that this arrays.binary search method only works on sorted arrays. So, if you have an array that is not in order, make sure you have sorted it before performing the search. Now to search for maybe O within this array, I will say arrays.binary search and then I will put the name of the array that I want to perform the search on.
So, favels and then the key or the item I am looking for. So, I will write key and I create a new character here, rk equals 2 and I am looking for what I am looking for O. Same code. Okay, now this binary search method right here returns an integer which is the index of this key if found.
So, I will write int found item index equals to a list of binary search favels key. Excellent. Now, first I would like to print out the entire array and then I would like to print out the found item index. So, found item index let's save the code and test it out.
So, I mistack the name of the variable here. Mistakes like this can happen. So, in the array, aeaiou is at index number 3. So, we can verify that 0, 1, 2 and 3, O is at index number 3.
Like the sort method that you learned about just a few moments ago, the arrays.binary search method also take an starting and an ending index. To use them first, we will need to define the index integers like int starting index. I think I should have just kept them and I will start the search from 1. So, I put 1.
Then I will also create an ending index. equals to 4 because I want to perform the search within the middle three values and like the sort method, the ending index is not inclusive in this case as well. So, once I have defined the two integer numbers, I will save binary search favels and then the starting index comma the ending index and finally the key I am looking for. Now, let's see if it works or not run.
So, it says 3 which is correct in this case as well. I have found O at 0, 1, 2, 3. Now, so far in this lesson, I have shown you a bunch of searches and all of them has worked out fine. But what will happen if one of your searches fail to find the value you are looking for?
For example, we do not have an x in the entire array. So, if I get rid of the starting and ending index and look for an x within our array, you will see that the output is minus 6. Now, instead of looking for an x, if I look for a b within our array, you will see that the output changes from minus 6 to minus 2. So, you may have already guessed that depending on the item you are looking for and if it does not exist within your array, then the output can differ.
But one thing that is constant is if the search fails, you will always get a negative output. And if the search succeeds, you will get a positive output and that positive number will be one of the indexes from your array where the item you are looking for exists. Now, there is a way to actually calculate this value. There is logic behind why the output is sometimes 2 and sometimes 6.
But I will not get into that much details in this course. If you are interested about learning this, I will leave the link to this article on FrecoTcan under this video's description. So, you can follow that link and read more about it. Being able to sort an unsorted array and look for any certain item within an array is useful.
Now, another small but useful thing that you can do with arrays is that you can fill them with a certain value. For example, we have 5 vowels listed out of order within our vowels array. But maybe for some reason you want to fill the entire array with x or maybe empty characters. Now, you can do that by using the arrays dot fill method.
Before that, let's get rid of some of these codes and write arrays dot fill. Then put the name of the array that you want to fill, choose vowels and the character or the value that you want to fill the entire array with. Let's run the code and see if it works or not. Yeah, as you can see, the entire array has been filled with x's.
Now, you can also have starting and ending indices with this fill method. Starting index equals let's start from one and end ending index equals to four. This is the same drill with the other methods as well. The ending index is never inclusive.
So, if you want to perform the fill from one to three upon these three values, make sure to include the last one as well or the item that's just after the one you want to end the fill action at. Now, arrays dot fill, how far else, then we'll put the starting index, the ending index, finally, the value that you want to fill the array with. Okay, so as dot twisting vowels, let's see if it works or not. Yeah, it does.
The E and I is untouched and the UNO and A has been replaced with x's. I have already said that arrays in Java are reference types and one of the complexities that you get with any reference types out there is making copies of them. For example, if we have an array of integers this time just for changing our test a bit, I would write in numbers. Same thing equals then inside of a pair of curly braces, I will put one, two, three, four and five.
Then I will create another array saying int copy of numbers, which is an array equals to the numbers array. Okay, so ideally the copy of numbers array should be a copy of the original numbers array. Right. Let's see if that's true or not.
Print Ln, arrays dot two string numbers. Let's make a copy of this line and put the copy of numbers. Sorry. Let's run the code and see what happens.
Turns out I have made another type over here. I have Mr. D. Let's put it back and run the program.
So it seems like that the copy of numbers array is indeed a copy of the original numbers array. But I'm not convinced. Let's do another thing. Okay.
Let's make some changes to the original array. So we can say arrays dot fill numbers and I would fill the original array with zeros and then run the code. Let's see what happens. But this is unexpected, isn't it?
I have actually made some changes to the source arrays and the changes have somehow applied to the copy as well. Well, the reason for this is the fact that arrays in Java are reference types and when you use an assignment operator to make a copy of an array or any other reference type for that matter, it doesn't actually mix an entirely new copy of the source material. What it does is it creates a new variable and points that variable to the original source array. So although the second array has a different name, it's still pointing to the same value.
So you can treat this copy of numbers array as kind of an alias for the original numbers array. So how do you make a copy of an array correctly then? Now to copy an array properly, you will have to use the arrays dot copy of method. The method takes the name of the original array as its first argument and as a second argument, it asks for the length of the new array.
So the length of the original array as we can see is 1, 2, 3, 4, 5. So you can count that by hand or you can be a little bit clever and put numbers dot length as the length for the new array. Let's run the code and see whether the copy gets affected by the field call or not this time. So as you can see that the original source material and the copy of it are now two separate entities which we want.
Now instead of putting the same length as the original array, you can also make the array larger or smaller. Let's say if you make it larger within indexes, you can do so. So as you can see, the first five elements of the copied array are from the original array and the rest of the indexes has been filled with 0 which is the default value for integers. You can also make it smaller.
So 2 and the copy array can hold only two values while the original array could hold five. Now like the sword and the search method, you can also define the starting and ending indexes for the areas.copyof method. But for that, instead of using the copy of method, you will have to use copyof range. Now inside this method, you will have to first give it the name of the source array then an starting index and ending index.
And just like before, we'll have to define this integer int a starting index equals to let's 0, 1. Let's start the copy from 1 and int ending index equals to 4. Let's run the code and see what happens. So as you can see, the method has successfully copied 2, 3 and 4 from the source array.
Now one thing that you may have already noticed that in case of the copy of range method, you do not need to use a length for the newly copied array. So how can you increase the length of the new array if you want to? Well, right now we are performing the copy from index number 1 to index number 4, right? So if we put a larger value than the original length of the array, like 10, let's see what happens.
So as you can see, the copy works out fine. The method copies 2, 3 and 4 from the original array also 5 and 10 fills up the rest of the space with zeros. So although you cannot explicitly define a new length for your copied array, you can change the length of the new array by changing the ending index of the copy of range method. Just like copying a reference type is more complex than copying a primitive type comparing reference type is also a bit complicated.
I hope you remember from our lessons on string, we couldn't compare to string simply using the equals equals signs. We had to actually use the equals method. So it's kind of similar in case of arrays. Say for example, we have the original numbers array, then we have a copy of the numbers array.
Let's just use copy of instead, numbers dot length x length and get rid of the fill method and try to compare our arrays using the equality to operator. So we'll say numbers equal to 12 copy of numbers. Let's run the code and see what happens. As you can see, it says false, but we know for sure that the copy of numbers array is an identical copy of the original source material.
Now to compare to identical arrays like this or maybe to different arrays, what you'll have to do is you'll have to write arrays dot equals then inside this method, you'll have to pass the two arrays copy of numbers. Let's run the code and see what happens. Yeah, this time it comes out as true. Since there is no such thing as casing in case of an array, there is no equals ignore case method for arrays like we had for strings.
In programming, you may want to repeat a certain set of instructions again and again for your projects. You can do that by using loops. Now there are four kinds of loops in Java and we will start our discussion with a for loop. First, I will write out the code for a very simple for loop in Java that can print out the number from one to 10.
For that, I will write for this is the starting of our for loop. Then inside, I will take an integer int number equals to one. Now after the semicolon, I will write number is less than or equal 10 and then number plus plus. Then I will put a set of curly braces here and inside this block of code, I will write system dot out dot println number.
We do not need the arrays class import right now, so we will get rid of that and let's run the code and see what happens. Then I will explain each line of this for loop to you. As you can see, the program successfully prints out all the numbers from one to 10. So what's going on here?
Well, every single for loop usually has four parts. The first part is the initialization where we are initializing a certain variable in this case and integer with the initial value of one. Then there is a condition that we are checking against. So we are checking whether the number is less than or equal to 10 or not.
And if the number is less than or equal to 10, we will print out the number. So this is the loop body system dot out dot println anything that you write inside this set of curly braces will be the loop body. Then once we are done with the loop body, we will go to the third part here inside the set of parentheses and this is called update and we will update the value of the number variable. So I will repeat every single for loop will have four parts.
There is the initialization where we initialize a variable with a value. Then there is a condition that we will check in every iteration. There is the loop body and then there is the update. So when this loop runs for the first time, the value of number will be one.
And this condition will be true since one is indeed less than 10. So the loop will print out the value of number which in this case is one. Then the loop will increase the value of number by one and go back to the condition part and check whether the updated value is less than or equal to 10 or not. Well, two is less than 10.
So it will again go inside the loop body and print out two on the console. So like this, the loop will keep printing out all this number until it reaches 10. When the loop has printed out 10 on the screen, it will go back to the update part and increase the value of number from 10 to 11. And it will go back to the condition once again and check whether 11 is less than or equal to 10 or not.
In this case, the condition will come out as false and the loop will stop iterating. The program ends here and we get all the numbers between 1 to 10 printed out on our console. I hope that makes sense. You can also use a for loop to loop over an array.
For example, if we create an array here, int numbers equals to 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, then we can use this for loop to loop over this array and print out each of this number. To do so, we will need an integer and we can call that the index. So, we want to run this loop as long as the index is less than the length of this array. So, numbers dot length.
Number dot length, finally, we will increase the value of index by 1 on a iteration. Finally, inside the println call, we will set numbers and then we will put the index here. Let's see if it works or not. So, as you can see, the program actually brings out all the numbers from 2 to 10 and doesn't print out to 1 because since the index starts from 1, which is its initial value, it starts accessing the array elements from index 1.
So, if you change the value of index from 1 to 0, then you should get all the numbers from 1 to 10. So, what's happening here is you are initializing an integer with the value of 0 and then inside the condition part, you are checking whether the value of the index is less than the length of the number array or not. If it's less than the length of the number array, then you go inside the loop body and print out whatever number is in the current index. So, it starts from index 0, which means 1, then index 1, which is 2, then 3, 4, 5, 6 and so on.
You can also do some interesting things within this loop. Instead of printing out all the values, you can add them all together and print out the sum to the screen. To do that, what you will need is you will need another integer here. It comes to 0.
Initially, the sum will be 0. And then inside the loop, what we are going to do is we will say sum plus equals numbers and then the index. Finally, we will move out this system.out.println outside of this loop and print the sum on the screen. Let's see what happens when you run the code.
I forgot the same column here. So, the sum of all the numbers from 1 to 10 is 55. Now, let me show you two more interesting programs that you can write using a for loop. The first one is that you can print out multiplication tables of any number using nested for loops.
For that, what you need is a number. So, we will begin by taking a new integer in number 5. Then inside the for loop, let's get rid of all this code and rewrite the for loop from scratch. So, we will say for then another integer, the multiplier, we will begin from 1.
Then if the multiplier is less than 10, we will keep going and we will also increase the value of multiplier by 1. Then inside the loop body, we can say system.out.printf in this case, modulus d into modulus d is equals modulus d. Now, we will say number. Then the second part would be the multiplier and finally, number into multiplier.
Now, I hope you remember that the printf method doesn't have any new line character at the end. So, if you run the program at its kind of state, let's see what happens. As you can see, it prints out the entire multiplication table in a single line, which we do not want. So, what we can do is we can put a backslash n at the end of the line, which will print out each row in a new line.
Run the program. Excellent. Now, we can take it a bit further to the end. Let's get rid of the current code.
And let's begin with a new for loop. For int number equals 1. Number is less than 10. And number plus plus.
Then inside the for loop, we will have a nested for loop. I hope you remember that we have worked with nested if you statements in the past, we can also nest for loops within each other. So, we can do for int multiplier equals 1. Multiplier is less than 10.
And multiplier plus plus. And inside the loop body, we will say system.out.printf, modulus t into modulus t equals to modulus t. So, the first thing would be the number. So, since the nested for loop is inside the outer for loop, any variable declared within the outer for loop will be accessible inside the nested for loop.
But any variable that you declare inside the nested loop such as this multiplier here will not be visible to the outer loop. So, we can say number. So, we will replace the first modulus d with a number. Then we will say multiplier.
And finally, number into multiplier. In the line, save our code. And let's run it. Just like before, we have to add a new line character at the end to make it look a bit nicer.
So, as you can see, now we have successfully printed out the multiplication table for all the numbers from 1 to 9. But if you would like to include 10 here, you can say less than or equal. And then run the code. Yeah, it works fine.
And I also just noticed that we are missing 10 here. And you can fix that by saying multiplier is less than or equal to 10. So, let me explain what happens here. First, inside the outer for loop, you are initializing a number with 1.
And you are continuing to loop until the value of number exceeds 10. So, less than or equal to 10. And then inside the loop body, you have another loop. So, first it comes and sees, okay, number is equals 1.
It's less than 10. Then it goes inside the inner for loop. And it sees that there is a multiplier with the value of 1. Multipliers value is less than 10.
Then it goes inside the body. Once the body has been executed, it prints out 1 into 1 equals 1. And then it goes back to the update part of the inner loop. And it checks again, then it keeps looping within the inner loop.
Once, the value of multiplier has exceeded 10. The inner loop breaks and the program goes back to the outer loop. It increases the value of number by 1, which becomes 2 now. And it goes inside the inner loop again and prints out the multiplication table for 2.
Then it goes on to print out 3, 4, 5, 6, 7, 8, 9, and 10. So, if you're having difficulty deciphering this complicated code here, I would suggest that you write this code yourself and use a notebook to understand how these values changes in each iteration. Okay. So, finally, I would like to show you an example of using an if else statement within a for example, if I tell you to print out all the odd numbers from 1 to 50, you can do that by using a for loop and a single if else statement.
Let's begin. For int number equals 1, number is less than or equals to 50, number plus plus. So, this loop will begin at 1 and in that 50. Then inside the loop body, what we want to do is we want to check if number modulus 2 is equals equals 1, then system.out.print.n number.
So, if you divide a number by 2 and the remainder is 1, it's pretty sure that the number is an odd number. We all know that. So, what we are doing is inside the for loop, we are taking whatever the value of number is, we are dividing that by 2 and checking if the remainder is 1 or not. That's what the module operator is for.
I hope you remember. And if the number is an odd number, we will print it out and if it is an even number, we will skip that. Let's run the code and see what happens. So, as you can see, we have successfully printed out all the odd numbers from 1 to 50.
So, 1, 3, 5, 7, 9, 11, 13, 15 and it goes on to 45, 47 and 49. There is another variant of the for loop that makes looping over collections such as arrays much easier. For that, first we will need an array. Numbers equals, I'll just put the regular numbers there.
There. Now, to use this special type of for loop, you will have to write for. Then inside, you will say int number. This type has to match with the type of the array and then you will put a colon here and then you will put the name of the array.
Then inside the array body, you can say system.r.println number. Let's see what happens. So, as you can see, the loop successfully goes through the entire array and prints out each element to the console. Now, what's happening here is you are saying for every single integer number in the numbers array, you want to print them out.
So, instead of using an integer as an index and accessing the elements individually, you are kind of taking a shortcut and extracting each value from the numbers array and putting them in the number variable on each iteration. Now, you can do anything that you could have done in a regular for loop such as if you want the sum of all these numbers. You can do so like this. Some plus equals number and then system.r.println.
So, make sure you are putting the println call outside of the loop otherwise this will be printed every single time the loop iterates. Let's run the code and see what happens. There you go. Other than the for loop, there is also the while loop and do while loop in Java.
These are two different kinds of loops that can more or less do the same thing as a for loop but the for loops are a lot more common in the wild than the while loops. Now, I will show you two examples of using a while and two while loop. First, let's begin with the while loop. We will simply print out the multiplication table like with the in the case of the for loop but this time we will use a while loop.
Now, first you will need a number just like before. Then you will need the multiplier. Now, to write a while loop you will have to say while multiply.r is less than or equals 10. Then inside the loop body you will say system.r.printf modulus t into modulus t equals modulus t since all of the variables and integers in this case then you will put number then the multiplier finally the number into multiplier.
Excellent. Then once you have printed out the row in the multiplication table you will have to increase the multiplier by one. Multiplier plus plus. Let's run the code and see what happens.
So here looks like the program works just fine. We have to just put a new line character to make the output a bit more readable. There you go. Now, the main difference between a while loop and a for loop is the fact that the while loop only has one component which is the condition.
In case of a for loop we had the initialization we had the condition we had the loop body and we also had the update but in this case there is just the condition and of course we had the loop body. So you will have to do the initializations outside of the loop and you will have to perform the update or the implementation of the multiplier or maybe counter or whatever you are working with inside the loop's body. So this is how a while loop looks like. Now a do while loop works similarly but in a different order and also looks a bit different.
So in case of a do while loop you will have to write do then you will have the loop body which in our case is this two lines we want to paint out the multiplication table once again and also increase the multiplier and after the loop body you will say while multiplier is less than or equals 10. Let's comment out our old while loop. Make our console bigger and run the code. See it gives you the same output.
Now the main difference between a regular while loop and a do while loop is the fact that in this case first the loop body will be executed and then the condition will be checked. Whereas in case of a while loop the condition gets evaluated and then the loop body gets executed. So you will surely find usage of both kind of loops if you worked long enough but I can say from experience that for loops are a lot more common than while or two while. Let's just clean up our code before we leave from this lesson.
Yeah. So far in this course you have learned about only one way of putting a bunch of values together and that is the arrays. But arrays have some limitations and the biggest one of them is the fact that you cannot resize an array. The only way to make an array larger or smaller than it already is to copy it and change its length during the copy.
But there is another type and array list which is like a dynamic array. You can create an array list. You can put item in it or you can take away items from it and it will also adjust its length depending on how many elements it's holding. Now to use an array list in your code you will have to first import the array list class.
To do so you will have to write import java dot utl dot array list. Then to create an array list you will have to write array list. Then you will have to put a less than sign and inside you will have to write the type of the data you want to restore in this array list. Now I know so far you have been only seeing int and this is the first time you are seeing something called an integer used as a type.
I will explain what this is but let's just keep on typing and finish creating our new array list. So, a real list integer name of the array list which in this case will be number equals new a real list integer. That's it we now have an empty array list of integers. I forgot the case there.
Now what's this integer class here? I have taught you that data types such as int or double or float, boolean these are all primitive types but in java you can also make them as reference types using the wrapper classes. So, this integer class here integer is actually a wrapper class for the primitive type int. In other words integer is the reference type form of the regular int type.
So, just like integer you also have double, float, boolean and so on. And when you are creating an array list you cannot use the primitive int type you have to use the integer wrapper class. I hope that makes sense. Since we have an empty array list in our hand let's put some item in it.
Now to insert a new item in an array list you cannot just use the old curly braces syntax. Rather you will have to use that add method. In this way you will have to write numbers then dot add then the value that you are trying to add which in this case will be one and a semicolon. You can make a bunch of copies of this line and just add other numbers as well.
There you go. Now to print out an array list to the console you will have to write system.out.println numbers which is the name of our array list in this case then dot to string. Now the to string is a method that is present in every single reference type in Java and later on when you will learn about object-oriented programming you will also learn about creating your own to string methods within your custom classes. For now just remember that to print out an array list you will have to write out the name of the array list first and then the method to string.
Let's run the code and see if it runs fine or not. So as you can see the array list looks like an array in the console. Now you can also print out a single value from the array list if you want to but for that you will have to use the gate method. So you will set off then gate.
Then the gate method actually takes an integer which will be the index of the value you are trying to print. Like arrays, aralists are also zero based so the first index of an array list will always be zero. So the index of one in this case is zero to one to two three and four. So if you want to print out three on the console you will have to set numbers dot gate and then two here.
That's run the code. Beautiful we have three printed out on the console. I have already said that aralists are dynamic so you can add as many elements as you want using the add method and you can also remove elements from an array list. So if you say numbers dot remove and it will take a number which will be the index of the element you are trying to delete.
So if you want to remove three from our aralist we will say numbers dot remove and pass two. Then let's print out the entire aralist and see if she exists or not. Christian. Okay that's run the code.
Yeah, P has been successfully removed but you can also remove items by value. So for example if I want to get rid of four I can do so but instead of passing and primitive four if you write four here this will be a primitive integer type four. It will work as an index but if you pass a reference type four like this integer dot value of and then pass the primitive type which in this case is four and if we run the code you will see that we have successfully removed four from our aralist. Now an aralist can store anything starting from integers, Boolean, characters, the strings and your custom class objects anything that you can think of.
We will work with much more complex aralists in later lessons for now just let's get hang of the basics. Okay. Now you can also remove all the items from an aralist by saying the name of the aralist dot clear. This will clear out the entire aralist and make it empty.
There you go. So I have already showed you how you can add new items to an aralist, how you can get them, remove them, clear an entire aralist. Now let me show you how you can update and element inside an aralist. For that there is the set method.
So you will type out the name of the aralist then dot and it's a set and you will have to put an index here. So again let's update the three here and its index is two. We'll put two here comma then you will have to put the value that you want to replace three width and since the the aralist is of reference types you will have to use the integer dot value of method once again and we will say 30. So we will replace three width 30.
Let's run the code and see what happens. Excellent it it works out just fine. So like an array you can also sort your aralist. Right now we have added the numbers in a sequential order here but if we randomize them like for example if we put five at the top then one after three then two at the end okay let's get rid of this indices because now these are getting misleading.
Okay let's run the code and see what happens. So as you can see the numbers are all jumbled around. Now to sort this aralist you will have to write the name of the aralist the dot and then sort in the method. Now you can see the that there is a small squiggly line under the sort method name and this is because the sort method will actually take a parameter which is known as a comparator.
Okay so as you can see it says comparator in the parameter list. Let me explain what this is first let's import the comparator class. So it's import java dot utl dot comparator and then inside the sort method we will say comparator dot natural order which is a method inside the comparator class and what we are saying is that sort this aralist in its natural order okay let's run the code and see if it works or not. Yeah it works just fine we have successfully sorted our aralist.
Now you can also reverse the order of this aralist by saying comparator dot reverse order which is similar to natural order but this time all the values will be sorted in a reverse manner. There you go we have 54321 lift off. Now three very small but useful methods that the aralist have is the size method the contains method and the int method. First let's see what the size method does.
So if you ever want to know how many elements are there inside an aralist you can just say the name of the aralist and then size. Now this size method will return an integer after counting all the elements in the aralist. You can also check whether an aralist contains a certain value or not and to do that you will have to write contains and since these are all reference type numbers we will have to use the integer dot value of method and we will have to put for example one. Let's check if the aralist contains one or not.
See it says true which means it contains one and if we put 10 here the output should be false. And yes it does. Now there is another method that checks whether an aralist contains anything at all or not and it's the is empty method and since our aralist here actually contains some elements the output should be false and yes it is but if we clear our aralist just before checking for emptiness we will see it says true. Now the final thing that I would like to show you is the for each loop.
Now you have learned about the for loop already in a previous lesson and you know that you can use it to loop over regular arrays but when it comes to an aralist there is another kind of loop. Let me show you how it works. Keep in mind the for each loop looks and works a lot differently than the for loops but I'll try my best to explain them as loosely as I can. So you will have to first write the name of the aralist that you want to loop over such as numbers and then for each then here it says action what you will say is number then you will make an arrow like this and then a set of curly braces.
Now inside the set of curly braces you will say something like system dot out dot print ln and let's multiply each number with two just as an example so you'll say number into two and end our line. Now let's also print out the entire aralist at the end so numbers dot two straight. Yeah let's run the code for now and then I will explain what's happening inside the for each loop run. So as you can see we have successfully multiplied each value in this aralist and we have also printed out the original aralist here.
Now let me explain the for each loop for you so when you're saying numbers dot for each number you are saying that for each number in the numbers aralist you want to perform the actions within this set of curly braces or within this block of code. So imagine this arrow like we are ordering the compiler like for each number perform this action that I'm pointing towards. Now technically it's called a lambda expression if it's like a method that doesn't have any name. Now of course I'm oversimplifying stuff here but for now this is enough to understand.
Now as you can see that although you are multiplying each value of the numbers aralist we do inside the for each loop body. The original aralist remains unchanged. Now let's just for practice update the original aralist and replace each value with their multiply counterparts. Now to do that what we can do is let's first print out the original aralist we will say before and plus yeah we are going to use the plus sign once again in this case because it's a simple program and then we will take this out and we will say after plus and then numbers start to be string.
Now inside the for each loop what we want to do is we want to say numbers dot set and inside the set of parentheses we will say numbers dot index off which is another method that can return the index of a given value. So we'll pass number here number into two. So you are essentially using the index of method to get the index of the kind value of the number variable and then we are updating its element with the multiplied value. Okay let's get rid of the println call here and let's keep our fingers crossed and try to run the program.
Yeah seems like it has worked out we have successfully overwritten all the values of the aralist with their multiplied counterparts. Now this is one of the many fun programs that you can write to practice your skills. I would suggest that you go around the internet find interesting problems that feels challenging to you and solve them to flex those Java muscles. Okay now that you have learned about aralists let me show you another kind of collection that's pretty common and pretty useful in some scenarios.
These are called hash maps. Now hash maps are actually key value pairs and if you want to compare it Python then Python dictionaries are kind of similar to hash maps. Now to work with hash maps first you will have to import the hash map class to do so you will just write import java dot utl dot hash map. Let's get rid of all the aralists code and start working on hash map okay.
Now to create a new hash map in java you will have to write hash map and then just like the aralist you will have to first put the type of the key. So in my case I'm making a hash map where I will be storing the scores for my different subjects maybe at my school or summer. So the key will be string and the value will be the scores of the subjects so maybe English 98, math 85 and so on so this will be integers and then I will name the hash map something maybe exams scores equals to new hash map string integer that's it. We have successfully created an int hash map and since I have already discussed these wrapper classes in a previous lesson I will not repeat.
Now to put something in this new hash map you can use the put method. So exams scores dot put and first we will need to put the name of the subject so it will be string and maybe math and then a comma and then this course I'm not that good at math so maybe 75 then we will say exam scores dot put another subject maybe a sociology and 85 exams scores dot put English 95 and so on. Now to print out a hash map to the console you can say system dot out dot print Ellen exam this course dot to is just like you did with the at least. Okay let's run the code and see if everything works or not run.
Excellent. The hash map prints out so my score for English is 95 sociology 85 and math 75. I hope you have already guessed that the item you are putting into the hash map is not sorted so even though I have put math at first it comes out in the end so if I put some more subjects Bengali 100 and let's see what ordered the show up in the console see as they're actually showing up in random order but that's how hash maps are you don't have to worry about them now you can also print out a single value from a hash map to do so you will have to write the name of the hash map then adopt and get then you will have to pass a key in our case that keys are all strings so I will write let's get this score for English run and yeah we we are getting the score of English now apart from the put method there is also another method put if absent that first checks if a value already exists in the hash map or not and if it doesn't then it will put it otherwise it will just skip it now you can write exam scores dot put if absent and let's try out with math math and let's put a new value here maybe 70 and then I will print out the entire hash map here string nice so as you can see the value of math is still 75 even though I have tried to put a new value for it but since the put if absent method actually checks whether math already exists or not in the hash map it didn't override the original value now if you want to replace one of the values however you can use the replace method and it will take a key in this case we are still working with math and we are updating its value from 75 to 70 but a shame so as you can see the value of math has been changed to 70 now just like the put if absent method there is another method called get or default for example if I try to get a key that doesn't exist let's say for example religion we know that it doesn't exist in our hash map let's see what the output is as you can see it says null but if we say get or default and we give it a default value of 0 or maybe minus 1 and run the code so the program will return minus 1 if the given key is not bound now like an analyst you can clear a hash map by saying exams course dot clear and this should clear out the entire hash map there you go and now if you want to check the number of elements that exist on the hash map you can do so by saying the name of the hash map dot size this will return an integer after counting all the elements present in the hash map right now which is 0 because we have just cleared it out but if we get rid of that line it should be back to 5 excellent to remove an item from the hash map you can use the remove method like this exams course dot remove and then you should put a name of the one of these keys so let's get rid of sociology and I'll put it here semicolon then exams course start to be string let's run the code as you can see sociology is not present here now you may also want to check whether a certain item exists on the hash map or not and you can do that in two ways either you can check for a key or you can check for a value for example if I want to check if the math key exists or or not I can do so by saying the name of the hash map exams course dot contains key and then the key I want to check again so it is math in this case and it comes out as true now if I want to check if I have scored 100 in any of the subjects or not I can do so by saying exams course dot contains value and then the value I'm looking for which in this case is 100 now you can also put a reference type 100 here if you want to do that the value of and it shouldn't make any difference yeah it just works and I have also taught you that in case of a release 21 trying to update one of the values you need to pass the integer as a reference type you can actually pass a primitive type as well the set method will convert it to a reference type automatically but it's up to you what you'd like to do and what you want finally you can check if a hash map is indeed or not by using the name of the hash map which is exams course dot is empty and since our hash map is not this should return false yeah it returns as false hash maps also have for each loop just like a release and now I will show you an example of using them with hash maps to do so first you will need to write out the name of the hash map which is exams course in this case then you'll set dot for each just like at least you will create a new lambda method here but in this case you will say the key comma the value then the arrow and the curly braces now the key here is the subject and the value is this for so I'll just do it like this and then system dot out dot print ln name of the subject plus dash plus the associated score let's put a semicolon at the end get rid of the is empty call and see if it works or not okay I just noticed that there is a small squiggly line here that's because I didn't enclose the two variables within a set of parentheses here in case of an error list we had only one variable so it didn't need these parentheses but since we have multiple variables here subject and score we will need a set of parentheses around them let's run the code and see if it works or not okay seems like it works now what we are going to do we will loop over the entire hash map just like we did in case of the error list and we will update the value of each subject score just for the purpose of practice now to do that we already have the name of the subject which is the key and we also have the value which is the score to update the values we will say exam scores dot replace you have already learned about this then we will say subject which is the key and then we will take away then from each subject maybe for bad behavior or something then we will say system dot out dot print ln and exam scores dot fluid string okay I hope everything works out fine and I cannot spot any mistakes let's see the run button yeah so I have indeed taken out 10 from each subject so English was 95 and now it's 85 Bengali was 199 sociologist 75 from 85 computer programming has become 90 from 100 and finally math has become 65 from 75 again I would suggest that you go into the internet looking for problems that you can solve to just practice all the things you are learning in this course this will really make you confident in Java now that you have learned most of the basics of Java it's time that we start discussing about object oriented programming now the concept of object oriented programming in itself is really huge and to be very honest you cannot learn how to make good object oriented programs from a course or a book what I can do is I can teach you the basic concepts around object oriented programming and once you have learned them you will have to learn the rest from experience by making larger and larger software following good practices and so on at a higher level object oriented programming is about modeling your software around real life objects for example maybe we can build a book boring system where a user can come register and login check for a book's availability borrow it if it's available and they can also return it on time they can also check the list of the books they have borrowed so far now in this aforementioned system there can be two objects one the user and two the book we can store information such as the user's name and birthday and in case of a book we can store the books title and maybe the name of its authors and so on so let's begin by creating a user class in our software and as we keep working on this simple program we will learn about the different concepts around object oriented programming so first open up the files menu by clicking on the file icon here and click on the add file button name your new file user dot java in this file you will need to create a new class like we have done with the hello world file so write public class user now we are declaring this class as public because we want this class to be available within our entire program now inside the class we will store the user's name which can be string so public string name and we will also store the user's date of birth so we will set public local date which is a reference type for storing dates in java and with separate date now to use the local date class within our user class we will have to first import it so import java dot time dot local date by the way do not get intimidated about the amount of classes that java has built into it as you will keep working with java for months or maybe for years you will eventually learn about a lot of them now we have a new user class let's go back to our hello world class and create a new user object now creating a custom object like a user object is not very different from create ice cream so you will have to write user which will be the type of our object then you will have to name the object maybe let's name it younger user because we will have a older user as well later on equals new user and a set of parentheses now we have a user but this user at its current state doesn't have any name or date of birth since these variables are declared in the class level of the user class this will be initialized as null by default so they will get default values now variables like this at a class level are called properties and since these properties are tagged as public we can actually access them from outside of the user class and give some value to them so we will say younger user dot name equals farhan has seen junior excellent then younger user dot birth j equals local date dot purse and inside the purse method we will pass 1995 0 1 31 which means 31 January 1995 now the local date dot purse method can purse a date from a given string and convert it to local date type again for using the local date class here we will have to first import it so import java dot time dot local date then we would also like to print something out on the screen and for that we will say system dot out dot print f and inside the print f method we will say that modulus s was born back in modulus s then after the comma we will replace the first formatting specify here with the name so we will say younger user dot name and then after that we would like to replace the second formatting specify with the birthday but since the birthday is not a string you would have to first convert it to string by calling the two string method and I have already said that the two string method usually exists in all the reference types and any local date object is actually a reference type let's try running our program and see if it works or not so yeah it works just fine for hun has in junior was born in back in 1995 0 31 now I have already said once that using something called methods we can actually implement some dynamic behaviors to our classes for example since we have the birthday of the user we can use it to calculate their current age so we will create a new public method public because we want this method to be accessible throughout our entire program and then we will have to write the return type of our method which in this case is integer because age is always an integer then we will put the name of the method which is age and put a pair of curly braces now from inside the method we will calculate the age in age equals and for that Java actually has a pretty nifty class so we will import Java dot time dot period now this period class has some method that you can use to calculate the difference between two local date times so we will say period dot between and inside this method call we will put a starting date which is the birthday so we will say this dot birthday I will explain this this later on and then we will put local date dot now now this period dot between method call we will actually calculate the difference between the user's birthday and our current date and then we would like to return age dot get years because we want to return the age in years okay we do not want anything else let's go back to our hello world class and change this string to something like was born back in and he is now modulus s and modulus d years port so you will say that user was born back in the birthday and he is now ex years old so we will put a comma after the two is string call and say younger user dot age and we will put a set of parentheses because this is a method and you will need to put a set of parentheses to call any method in Java let's run the program and see if it works or not yeah looks like everything has worked out just fine it says for us in junior or was born back in 1995 0131 and he is now 27 years old excellent now what is this blue this keyword here how to explain this we will actually need two users so let's create a new user user older user equals new user and we'll say older user dot name equals farhan hasyn senior and then we will say older user dot birthday equals local date dot purse and let's put 1975 015 okay now we'll put this system out dot printf at line 10 and we'll make a copy of it at the end of our program was born back in okay all right let's replace younger user with older user let's run the code and see what happens okay so farhan has in junior or born 27 years old and this 47 years old nicely now you can see that we have two different users in our program and both of these users are actually created from the same user class so when we are trying to calculate the age of the user how would the computer know which user we are referring to or which date of birth we are referring to this is where the this keyword comes in you see we have two instances of the user cluster and the this keyword will refer to the current object being worked on so when we are saying younger user dot age then the value of this will be the younger user object and when you're saying older user dot age the value of this would be the older user object okay so let's get rid of the extra user here change the younger user's name to just user and let's start working on the book class let's go back to the files menu create a new file with the name book or chaffa now let's declare a new class public plus book and for a book we would like to store a public string title and public is string author yeah that's pretty much it for the book class now let's go back to the hello world again and we will say book book equals to new book and then book dot title equals to karmilla book dot author equals to sheldon the one let's put a semicolon at the end and now we have a new book so how about we implement the functionality of borrowing books I will put it in the user class so let's close this menu as we don't need that and we'll create a new method here public borrow and this borrow method will actually accept a parameter because this method has to know which book the user is trying to borrow right so we will say book book so this method is actually accepting variable of book type then let's create a realist of type book let's call it books equals new a real list and book close it and we'll also have to import the a realist class so import jaffa dot utl dot a realist okay then we can say this dot books dot add and book so you're adding the book we have received within the borrow method to our list of books okay let's go back to our hello world class and we will say user dot borrow and we will pass the book to it I think we have made a small mistake that is we haven't said what kind of data the borrow method is returning now as you can see the method actually returning nothing so we will have to say void which means it doesn't return anything at all there is no return statement whatsoever it just makes some changes to the books a realist okay let's go back to hello world and this looks all right so far let's update this print death method at age okay let's let's write another one system dot out dot print if and we'll say modulus s has borrowed these books and we'll send it to us s okay let's put a comma here and we will say user dot name has borrowed user dot books dot question okay let's also put a new line character at the end of our printed statements otherwise they may not look as good as we want them to be okay let's run the program and see what happens then we will go through what happening in this entire system once again okay just as I expected so as you can see it says farhan has seen junior was born back in 1919 and so on and then it says farhan has in junior has borrowed these books book at and then a large number but we are expecting maybe the name of the book or maybe the name of the author or something like that right but that didn't happen let me tell you why you can see that we have been using the method to string a lot right by using the method to string a lot and I have already said that this two is string method comes with every single reference types now our book here is a custom class and whatever book object we are working with are all reference types now since we have created the book class ourselves it doesn't have a built into a string method that's why we are getting some random values here now to solve this problem we will have to implement a two is string method we can do that by saying public string two is string and then we will return a string representation of this book like return is string dot format here and we will say modulus s by modulus s tenifle store and after the comma we will say this dot title and this dot author so whenever we are trying to access one of the properties within a class from a method within the same class we can use that this keyword let's try to run the program once again and see if it solves our issue or not let's make our console bigger yeah now it looks much much better so far harness engineer has borrowed these books Carmilla by Sheridan lefman i think that full stop there looks pretty bad because it's going to show up like a list of books let's get rid of that and also i think this is a good time to switch back to the stacked layout once again since our codes are getting bigger horizontally and this gives us a better look at our lights okay so what have we done so far we have created two custom classes representing our users and the books we have created a new user object we have given in the ability to borrow books from us we have also calculated their age using method we have implemented title and author for our books and we have also implemented a custom to string method so this is really a lot to be honest but we will do more so far we have been declaring all our methods and our properties as public but to be very honest this is not something you should be doing a lot let's learn about something called a constructor as you can see when you are trying to create a new user you are saying user then name of the user object equals new and then you are writing the name of the class once again and then a set of parentheses as if you are trying to call a method called user well that's kind of true every single class that we have in Java has a special method called constructor this method is responsible for initializing all the properties with their default values so what we can do is we can customize this constructor method and make it do things let's start by writing a constructor for our user class okay we will say user and we will not write anything like oblique or maybe some sort of return type nothing at all we will just start by writing what the name of the class is then we will put a set of parentheses and set of curly braces so this is our constructor method now let's think about what we want from the user when they are creating a new user object right we want their name so we will receive or ask for their name and we will also ask for their birthday now this birthday can be taken as a local date but we will take it as a string I will tell you why birthday now inside this constructor method we will say this dot name equals name and this dot birthday equals local date dot purse birthday so what we are doing essentially is we are asking the user for a name and we are storing that name in the name variable or name property within the user class then we are also asking for a birthday and we are storing that birthday in the budget property but since the budget property is of type local date we will have to purse the birthday from a string format to local date format now let's go back to our hello world class and make the necessary changes here we will say user equals user and we will put the name inside this constructor call and we will put a comma here and we will also put the birthday within the constructor call because now the user class is capable of accepting these two let's run the code and see if everything works just as before or not seems like I have made a small typo here the D should have been capital and it works just like before now since we can initialize the user with the name and the date of bird right at the creation process we can actually make the name and birthday private which means we can no longer do things like user dot birthday or user dot name but we still need to know the user's name and user birthday right for that we have something called getters so we will create a new method somewhere in this user class public get name and the return type be string and we will say return this dot name and we will also say public string get birthday and we will say return this dot birthday dot to string now let's go back to the hello world class and make use of these two getters we will come down to printf and we will say user dot get name and we will say user dot get birthday and we will get rid of the two string calls since the birthday will come back as a string by default now let's run the code and see how it works okay we also have to replace this name here and as you can see since we have made the name properties private the hello world class actually fades to access the user's name which is a good thing I will explain why let's just make it working again so yeah it's it's better normal now now since the name and birthday properties have become private no one can change their values from outside the user class which means these are now much more secure than they were before another thing that is now we can pass the name of the user and the birthday as it strings the hello world class has no business in knowing what is the actual type of the birthday is all the hello world class needs to know that if it passes a user name and a birthday in string format a new user will be created this is called abstraction so what we are doing is we are hiding the complexities of the user class behind this beautiful looking getter methods constructor methods you can already see how cleaner the user object creation looks compared to the book object creations let's make the same changes to the book class as well so we will go back to it and change the title and author to private then we will implement to getter methods so public get title return this top title the return type will be string and then we will say public string get author and we'll say return this dot author etc let's also implement the constructor so we will say book we will take the title as a string and then we'll take the author name as a string then we will say this dot title equals title and this dot author equals author nice let's update the creation process so we will pass the title of the book and the name of the author with the new keyword and get rid of that excellent the program already looks much cleaner now another thing that I would like to change is I would like to make the books list private and implement a getter for that as well so let's go back to the user class and let's say public and this time we will be returning a string borrowed books and we'll say return is dot books dot history excellent now the hello world class doesn't know about the complexities of the books list either we'll just say borrowed books did I meet it private yet no I didn't so you will make it private okay let's see if the program works just as before or not accident the program works just as before now I hope you can already see the beauty of object rendered programming and how cleaner the program actually looks in reality we still have to learn a few more concepts around object rendered programming such as inheritance now assume that our book boring system has multiple types of books there can be the regular books I mean the hardcover ones or the printed ones then there can be ebooks and there can be audio books now although they have some similarities they also have some differences such as the ebooks and the regular books have page counts where the audio books have runtimes also the ebooks have formats such as pdf or e-pub or so on so trying to implement different kinds of books using the same class can be cumbersome now you may think that you will make copies of the book class and add or remove the necessary properties methods to them but that's not a very good idea this is why inheritance comes in so we can make a default book class with the most common properties and methods in it and then we can make child book classes that will inherit all the properties and methods from the parent book class and we can also add some new properties and methods to them let's see an example first we'll add the page count property to the book so we will say private int page count and for that we will have to pass the page count to the constructor here so we'll set this dot page count equals page count we'll go back to our hello world class and we will say I don't remember the actual page count of the book but let's put two subject nice everything should be normal let's run that code and make sure that was a serious mistake I didn't accept the parameter here let's run the program and make sure excellent now we will create a new audio book class audio book java yes and we will say public class audio book extends book now since we are declaring this audio book class as an extension of the parent book class it already has all these properties and methods we have described here so what we need to add is a runtime so it's a private int runtime so runtime means how long this audio book is run so the runtime will be in minutes then we will have to create a new constructor here so we'll say audio book just like before and we will accept the runtime to say int runtime and then inside the pair of curly braces we will say this dot runtime equals runtime now here is a problem I have already said that since this audio book class is an extension of the book class it also inherits all these private properties which means we will still have to fill them up somehow but the audio book constructor doesn't accept any of these values okay let's see what we can do to solve this first we'll copy all these parameters from the book constructor and add them to the audio book constructor one of the problems have been solved we are now accepting all the necessary information for the parent book class now we will say super and we will pass title author and page count now the super keyword here actually refers to the parent class of our current class so when you are calling the method super we are actually calling the constructor of the parent book class so we have successfully filled up all the necessary properties of the parent class as well let's try out by creating a new audio book let's go back to the hello world class and after book we will say audio book equals new audio book and we will say Dracula and the author is Brahms Stoker and the page count actually we do not have to pass the page count here we can modify our constructor a little bit we do not need to accept the page count here instead we can pass zero as the page count yeah that would be better and we can just accept the runtime so for example maybe the Dracula book would run for 30,000 minutes so I put 30,000 there audio book see I have made a mistake Dracula and I think we should start naming our books so Carmilla okay so we have successfully created a new audio book here just for the sake of our code let's get rid of all the code that we do not need so we will get rid of the user.borocall we have seen examples of that we will also get rid of the system.out.printf calls we will get rid of the user as well because for now we will be focusing strictly on books audio books and ebooks so let's create a new system.out.printf method here we will say print a sorry Dracula.2 is free because remember that the audio book class already inherits the two-string method from the book class okay let's print out something on the screen so we'll say system.out.println and Dracula.2 is free let's run the code and see if it works or not yeah it works just fine okay now that we have an audio book class let's create a new class called ebook.shop okay again public class ebook extends and then within the set of curly braces actually we can copy a bunch of code from here let's copy everything to the ebook class and we will say private is free format and then we will accept everything and we will also accept the page count this time because ebooks have page count okay so we'll put page count and then we will also accept the format so we'll say string format this dot format equals format yeah nice yeah everything looks fine okay we have to change this to ebook now let's go back to hello world and try to create a new ebook okay so ebook so chiefs I will create a chiefs book new ebook carry on chiefs written by bg ord house ipo pangs page in his name correctly then the page count would be 28 i guess and finally the format will be pdf let's put a sim card on there and let's see if the book has been created properly or not so chiefs start to history okay so carry on chiefs by bg ord house so we have successfully created different kinds of books based on apparent class now this is what i had in store for this course in terms of object rendered programming i have taught you what are classes what are objects what are properties and methods constructor methods and you have also learned about inheritance now there are a lot of things that you will have to still learn like method overloading and overriding abstract method and whatnot but i would not like to overhand you with all these concepts in a single course what i would suggest that try to understand everything that i have taught you in this course as thoroughly as you can and then keep practicing make programs make bigger programs and try to understand whatever concept seems complex to you and as you keep working with java as you keep making more and more fun projects you will start to understand a lot of the complex concepts on object rendered programming and what not so i hope you have learned something good from this course and maybe someday i will see you in another course as well the till then stay safe and take care
Lesson FAQs
What is Java Programming for Beginners – Full Course about?
You're about to learn how to program in Java from Farhan Hasein Chaudhary. Farhan is an experienced software developer here at Freeco Camp. He is great at breaking down concepts for beginners. This is a great course if you want to learn Java. You can
What key concepts are covered in this lesson?
The lesson covers java, programming, beginners, full, course.
What should I learn before Java Programming for Beginners – Full Course?
Review the previous lessons in Java Programming for Beginners – Full Course, then use the transcript and key concepts on this page to fill any gaps.
How can I practice after this lesson?
Practice by applying the main concepts: java, programming, beginners, full.
Does this lesson include a transcript?
Yes. The full transcript is visible on this page in indexable HTML sections.
Is this lesson free?
Yes. CourseHive lessons and courses are available to learn online for free.
