Learn Java 8 - Full Tutorial for Beginners

Learn Java 8 - Full Tutorial for Beginners


Learn Java 8 - Full Tutorial for Beginners

Learn Java 8 and object oriented programming with this complete Java course for beginners.

⭐️Contents ⭐️

⌨️ (0:00:00) 1 - Basic Java keywords explained
⌨️ (0:21:59) 2 - Basic Java keywords explained - Coding Session
⌨️ (0:35:45) 3 - Basic Java keywords explained - Debriefing
⌨️ (0:43:41) 4 - Packages, import statements, instance members, default constructor
⌨️ (0:59:01) 5 - Access and non-access modifiers
⌨️ (1:11:59) 6 - Tools: IntelliJ Idea, Junit, Maven
⌨️ (1:22:53) 7 - If/else statements and booleans
⌨️ (1:42:20) 8 - Loops: for, while and do while loop
⌨️ (1:56:57) 9 - For each loop and arrays
⌨️ (2:14:21) 10 - Arrays and enums
⌨️ (2:41:37) 11 - Enums and switch statement
⌨️ (3:07:21) 12 - Switch statement cont.
⌨️ (3:20:39) 13 - Logging using slf4j and logback
⌨️ (3:51:19) 14 - Public static void main
⌨️ (4:11:35) 15 - Checked and Unchecked Exceptions
⌨️ (5:05:36) 16 - Interfaces
⌨️ (5:46:54) 17 - Inheritance
⌨️ (6:20:20) 18 - Java Object finalize() method
⌨️ (6:36:57) 19 - Object clone method. [No lesson 20]
⌨️ (7:16:04) 21 - Number ranges, autoboxing, and more
⌨️ (7:53:00) 22 - HashCode and Equals
⌨️ (8:38:16) 23 - Java Collections
⌨️ (9:01:12) 24 - ArrayList

🎥Course by Marcus Biel, an experienced software craftsman. Watch additional Java lessons from Marcus on his channel. Here is a link to watch the remaining episodes of the course:    • Java for Beginners 25 - Linked List d…  

🔗Check out a written version of this course with additional resources here: https://marcus-biel.com/java-beginner

🔗Get even more Java resources from Marcus here: https://java8course.com



Learn to code for free and get a developer job: https://www.freecodecamp.org

Read hundreds of articles on programming: https://medium.freecodecamp.org


Content

0.13 -> Hi, welcome to my free Java video course. Lesson One. My name is Marcos B. I'm a software
16.579 -> Craftsman with 14 years of experience in Java. My goal is to teach you Java in the easiest
23.349 -> possible way. Okay, we will start with a briefing, which is basically a lot of theory in the
29.309 -> beginning. Second, we will do a practice session, where we will actually write our first Java
36.09 -> program. Finally, we will do a short key briefing, where we will recap what we learned so far,
43.4 -> and add some more theory were needed. In this first lesson, I'm going to introduce you to
52.01 -> the following 15 Java key words or concepts, which you will need to understand your first
58.1 -> coding session later on. Please note, especially if you already know some programming, I really
64.859 -> focus on not using any term before I officially introduced it, getting a keyword explained
71.88 -> using concepts I don't know, something that always ticks me off in classes, so I aim to
77.479 -> do better in this aspect. Therefore, intentionally, I might explain a few things, not 100% academically
85.82 -> correct in the beginning. When necessary, I will add the academically correct later
91.369 -> on. As stated earlier, my goal is to teach you Java in the easiest possible way. If I
100.1 -> can achieve this by looking just a bit stupid, that's fine with me. Last but not least, this
107.509 -> is really only a first introduction. It's okay if you don't directly grasp everything.
113.34 -> We will go in more detail and recap the important parts later on.
120.67 -> A package or better package structure is like the file structure on your computer. It helps
130.19 -> to organize the different files of your program. The top root folder of a package structure
137.52 -> is usually the organization's domain name in a reverse order. In my case, that would
145.08 -> become Marco spiele. For example, if you don't have a domain for the program you're writing,
152.42 -> it's okay to invent your own domain name, but make sure it's a unique name. The reason
159.43 -> for this is that the name of a program file is actually a combination of its own name,
164.63 -> plus the full package structure of the package. It recites and there are millions of other
171.11 -> programs out there, and chances are high that someone else has already used exactly the
176.73 -> same program file name before you. As Java code is heavily shared worldwide, a strategy
184.97 -> was needed to come up with a unique name to prevent name clashes. Each domain names can
191.74 -> technically exist only once. Therefore, using a domain name as the prefix for your package
199.98 -> name as the default. Think of the package name, like an absolute file name of your program
205.78 -> file. Using your package name is optional, but I highly recommend you to do so even for
215.44 -> the simplest program. When used, the package must be declared on the first line of your
220.69 -> Java program. The package name is starting with a domain name in reverse order. As stated
230.95 -> before. The reason for this is that the package name from left to right gets more and more
236.96 -> specific. Using lowercase and singular for package names is the recommended default.
243.71 -> Last but not least, the package name also serves as a high level description of all
250.62 -> the Program Files related to a certain topic. code written for less than one of this Java
256.84 -> course would end up in a package called con Marco spiele. java course lesson one for example.
264.08 -> Please choose package names for fully. It's not just a stupid name. The package names
271.46 -> reflect the internal structure of your entire program. Last but not least, I recommend you
277.97 -> to choose package names related to your specific business topic. Rather than just using technical
284.56 -> terms. Good names are key. To simplify programming. Every program file will reuse existing code.
296.37 -> To do so you have to import the code into your program file. In our program file, the
303.84 -> import statement or import statements will follow directly after the package declaration.
309.68 -> Here you can also see how the package name must be included in the import statement,
315.68 -> as it is actually part of the programs falling. You may import specific files, or all files
324.44 -> of a certain package using the star symbol. Besides regular import statements, they are
333.39 -> also static imports, which we will cover in detail at a later time. A simple program can
341.05 -> easily consist of 1000s if not 10s of 1000s of code lines, it's very easy to get lost
347.639 -> in such a big pile of information. Therefore, it's really important to impose a structure
353.639 -> on the program code besides using packages, as explained before, in Java, the program
360.59 -> code is classified into different units of code. Such a unit we call a class.
369.86 -> The programmer is the one who may decide how to name and structure packages, as well as
377.01 -> classes. One aspect of Java is to improve cooperation between business clients and programmers.
383 -> The client is able or should be able to tell what he wants, the program is able or should
390.33 -> be able to know how this can be expressed in code. The closer this code is related to
396.46 -> the business easier, the cooperation between programmers and business people will be forming
403.21 -> a common language related to the business and use throughout the code is therefore of
408.9 -> utmost importance. By convention, the name of a class in Java should be a noun, starting
416.32 -> with a capital letter. opening curly brace defines the beginning of the definition of
422.25 -> the class, where we will later write all our code related to a car. The closing curly brace
431.58 -> defines the end of the definition of the class, a class should be focused on only one topic.
438.56 -> As a recommendation, keep your classes as small as possible to improve reusability as
444.54 -> well as readability. A class usually consists of one or more methods. As the name implies,
456.53 -> it defines a method of how to achieve a certain thing, like a method double could be defined
464.29 -> to calculate the double amount of an input given methods are sometimes also called functions.
470.97 -> For now, one at 100%. Academically correct, it's okay to use the terms interchangeably.
477.73 -> By convention, the name of a method should be a verb that best describes the purpose
483.05 -> of the method. Methods define the actions you can execute on classes, so they further
490.419 -> refine the structure of our program code. methods can do pretty much everything for
496.36 -> us. methods can operate not only in numbers, but also on text, colors, sounds, you name
503.77 -> it. A book would have chapters, every chapter would have paragraphs and every paragraph
511.59 -> would have sentences structuring your Java code in a similar way. Packaging name would
518.5 -> be like a chapter, a class would be like a paragraph, and a method would be like a sentence.
525 -> For example, methods internally can call other methods, which will then form a hierarchy
531.77 -> of methods calling each other. As a programmer. It's up to you of how you want to structure
539.12 -> your code, how long you want a method to be, which method will use which sub methods. I
546.01 -> would recommend however, to always think of the current level of abstraction, just as
551.36 -> if you would write a book. For example, a method prepared dinner could internally call
557.74 -> a method prepare appetizer, followed by a method called prepare main course, followed
565.11 -> again by a method called prepper. Desert. The prepare main course method for instance,
571.64 -> could internally call a method called boil water. Mixing the levels of abstraction work
579.07 -> for example mean to have a method prepare dinner, internally calling a method prepare
584.981 -> appetizer 30 followed by a method called warm water without having a proper main course
592.81 -> method surrounding it. Coming up with clean structure is key in programming. Make your
600.26 -> Code speak to you. Today with problems of millions of lines of code. The most important
606.95 -> part of programming is structure and readability for humans. As soon as you start to lose focus
613.91 -> and have difficulties in understanding what a program does, chances are high you will
618.95 -> misunderstand some concept of the code. And so you might introduce an error. Keep your
625.13 -> methods as short as possible. As a rule of thumb, I would recommend 123 lines with 20
632.899 -> lines as a maximum.
638.88 -> The definition of a method follows a similar concept of that of a class. First, we define
644.83 -> the name of the method. As stated before, he was a word and start with a lowercase letter.
651.31 -> The name of a method is followed by an opening and closing bracket. This is the place where
657.2 -> we mainly find the names of zero to an unlimited amount of input fields. When using the method
663.3 -> later on, you will need to choose a value for those values. These values are called
669.24 -> method parameters. In order to further improve the structure and readability of your code,
675.52 -> I recommend you to use as few as possible method parameters, with three to five parameters
682.83 -> as a maximum, everything more than that will not be readable. The opening curly brace defines
690.98 -> the beginning of the method definition. closing curly brace defines the end of the method
697.431 -> definition. Later, we will define the actual code of the method that will go into the space
704.36 -> between the curly braces. As the name implies, a variable is a variable value, a placeholder
716.3 -> for a value that you can set. The value of a variable may change while the program is
722.73 -> running. For example, when the third value is calculated over the lifetime of your program.
730.35 -> variables can be used as input or output values of methods. For example, variables can be
736.73 -> of different data types, like numbers or text. data types we will cover in detail at a later
743.12 -> time. Just for example, possible variable names for a car could be my old car, my pushy,
753.85 -> or mom's car. There are different types of variables, like instance variables, static
762.04 -> variables, local variables, parameters or arguments, we will cover the differences in
768.22 -> a later session.
774.76 -> Public is an access modifier that defines that any class from any package may use the
780.66 -> class or method with public access modifier. Besides public, there are also other access
786.2 -> modifiers like private default or protected. Here we are only skimming a topic. In a later
792.63 -> session we are going to cover access modifiers in detail. Here you can see the access modifier
802.12 -> public in action. The class as well as the method now posts have public access defined.
812.36 -> For every method, you actually have to define our return value. Ironically, even when you
818.87 -> don't want to return any value at all. In this case, you will send void as return value
824.7 -> of the method to explicitly define that the method will not return a value. Besides void,
831.209 -> a method can actually return any kind of data type. Here you can see the void return type
838.29 -> in action or drive method suppose to make the car drive which is expected to execute
845.04 -> an action but not to return any value to us. As a rule of thumb, it's good design to differentiate
852.48 -> between query methods, which will return a value but do not alter the state and command
859.22 -> methods which offer the state but do not return a value. In respect to this best practice
865.8 -> rule. Drive is a command method and therefore does not return any value. The Add symbol
877.55 -> indicates an annotation. We will cover annotations in detail in a later session. Just for now,
884.51 -> I want you to know that with ADD test, we indicate that a given method will be used
890.01 -> as a test. When a class a variable or method name consists of more than one word In Java,
900.88 -> you use an uppercase letter to indicate the beginning of a new word. This is called camel
907.98 -> case, as the ups and downs of upper and lowercase letters look like camel humps. In other programming
918.12 -> languages, and underscore is used to separate two words from each other inside a variable
924.39 -> name. In Java, however, camel case is used instead. To indicate the end of a sentence,
933.31 -> we use a thought in English sentences. In Java, however, the DOT has a completely different
939.769 -> meaning. The dot between the variable car and the method drive indicates that we want
947.351 -> to execute or we will alter. Alternatively, say call the method drive on car. As the.is
956.79 -> already used to indicate a method being called a colon is used to indicate the end of a statement
962.61 -> in Java. Here we can see an example of a test method that is expected to test that our car
970.519 -> drives. The method drive is executed on car with the value of 100. Colin says I want this
979.51 -> to be executed period. I talked about classes already. I said that a class is a way of structuring
990.269 -> code in Java, a unit of code. This is perfectly true. However, it's only part of the magic.
997.24 -> A class is like a template, like a definition of what you want the class to do for you later
1003.55 -> on when the program is running. The class car for example, defines the behavior of a
1009.48 -> car. However, when your program is running, we say at runtime, there will usually be a
1016.35 -> number of cars, each car may have its own unique set of values, one car might leak oil,
1024.39 -> so the value of oil could drop to zero while the program is running. So our classes like
1030.589 -> the human DNA, a definition of how something should be created when the program is running.
1040.75 -> When a Java program is running, it would usually create a certain number of objects that will
1045.6 -> exist as a set of values in the computer's memory. And those values might change while
1051.59 -> the program is running.
1058 -> Each program language for certain concept, Java is an object oriented language. Everything
1064.581 -> is focused around objects in Java. In Java writing classes is a way of defining a model,
1071.61 -> which focuses on necessary aspects to solve a specific problem. It needs the brain powers
1077.61 -> of a clever Java programmer to fully understand the problem and to extract a theoretical model
1083.86 -> from it and transfer this model into classes. The skills of the programmer will have high
1090.7 -> impact on how precisely a problem is transferred into a class model. Simply speaking, the more
1098.169 -> accurate this is done, the less code has to be written and maintained. The fossils or
1103.962 -> program will run, the less errors it will have. The power of Java is to be able to define
1110.7 -> an execute table model, like a virtual machine on your computer. With concepts and names
1117.419 -> taken from the real world, which heavily improves the communication of the programmer, and the
1123.15 -> business client, programmer and business client can both talk of a car. While the one is talking
1129.41 -> of a real car, and the other of the representation of this car on the computer, they will understand
1136.89 -> each other. Here we see a simplified definition of a class car. Now imagine a game where each
1147.42 -> player creates a car when the game starts. The program in this example, might create
1153.73 -> three different cars at runtime. Now I talked about classes and objects that will be created
1163.87 -> from those classes. But how will these objects be actually created? We will need a method
1170.61 -> that will create the objects for us. This is a very special method. It is called on
1176.641 -> a class and we'll create an object each time we call this method. But as soon as the object
1184.28 -> exists, we cannot call this method anymore. The special method is called a constructor,
1190.26 -> as it is used to construct objects from class files
1198.45 -> to create a new object of time car, you write new car. For example, the constructor in this
1205.66 -> case, just like a method is given two different numbers, one for the age of the car and one
1212.251 -> for the maximum speed. In our example, when the program is running and executes this line,
1219.58 -> a new object will be created in your computer's memory. We will, we talked about variables
1227.57 -> already. However, before we can use a variable, we need to define it beforehand. Call my Porsche
1237.96 -> Colin is an example of a variable declaration, we declare the variable which we called my
1244.05 -> portion of the type car. Now that we have a variable declared, we have to allocate the
1253.32 -> object we created a variable declaration, object creation, and allocation can all be
1261.71 -> done in one single line. So this line reads as when the program is running, and when this
1267.62 -> line of code is executed, create an object of type car with first of all you won, and
1273.919 -> a second volume of 320. Then create a variable of type car and give it a name my portion.
1281.84 -> Last but not least, assign the car object to the variable named my portion. After this
1287.99 -> line, whenever we use my portion, we actually referenced the object created in memory. Also,
1295.22 -> you might notice when looking at this line of code, we put two values into the constructor
1300.36 -> of car. But without looking into the code of the class car, we wouldn't even know what
1306.37 -> their meaning actually is. This is one reason why you should try to limit the number of
1312.289 -> variables used in a method as well as in a constructor, the less the better.
1318.35 -> In session, to have this free Java video course, we're going to write our first Java program.
1326.919 -> When we write code, we actually start by writing a program, which is actually testing the program
1332.5 -> or class we are going to write. We do this for two reasons. First, the test forces us
1339.85 -> to properly think our idea through which will improve our code a lot. Second, the main effort
1347.59 -> in the lifecycle of a program is actually not the first time effort of writing the program
1352.47 -> code, but to maintain the program, like extending or improving the functionality or fixing arrows
1359.65 -> called bugs in your code. Whenever you write code, there is a high risk you will introduce
1366.12 -> defects in your code. When your program is written once with the help of a test, this
1372.21 -> test will ensure that whatever happens, your program will continue to function as designed
1380.72 -> initially. To recap, in Lesson One of this free Java video course, I explained the necessary
1387.58 -> theory to code our first Java program, which we are going to do in a minute, we are going
1394.08 -> to use these 15 Java keywords and concepts described in detail in the prior session.
1400.47 -> If you haven't done yet, I would recommend you to start with session one before watching
1406.27 -> this practice session. Okay, so now I'm in my development environment. I've created a
1419.35 -> folder structure of calm Marcos build Java course, lesson two in a folder called test
1429.96 -> and also here source main. Java. com Marcos build Java course lesson two. This is where
1439.37 -> we will write our tests have already created the fall person test of Java. This here is
1447.909 -> where later we will have our actual program. But okay, so let's start person test. As described
1458.46 -> in Lesson One, we have to start with a package declaration. So I write and you see here,
1465.77 -> I actually get support by my environment, about the development environment. I'll tell
1473.1 -> you later. For now just see that it actually assists you. Actually, when you start learning
1479.549 -> to program, I would recommend you to start with a regular text editor because you need
1487.09 -> to learn all these keywords. And so I guess it's easier in the beginning. I mean not easier,
1494.83 -> but it helps you to learn the stuff from scratch. If you really have To focus and concentrate,
1501.99 -> and you don't get assistance. But as soon as you manage all these keywords, as soon
1508.48 -> as you know all them section environment is really helpful. Okay, so I use package, and
1516.33 -> then I have to define it. COMM macros, we'll see how it assists me again, it already knows
1526.29 -> the package, because I have here the folder structure, and the folder structure, and the
1533.53 -> package declaration in my file actually have to be the same. Otherwise, this would be an
1539.58 -> error. So actually, I don't even have to write it anymore. I can just follow. Okay, so this
1548.4 -> is my package. And you see, before we have an underline or red underline, which means
1555.58 -> something is wrong. Now, oh, editor seems to be fine with what I wrote so far. Okay,
1562.99 -> here we are. Later, we'll have imports, as described in lesson one. But we will add them
1570.679 -> later. Normally, you start defining your class first. See, again, I wrote public and see
1577.929 -> how it's underlined red, so something is missing. So I say class, and now I have to define the
1586.87 -> class name is a person test. So I call my test person test, it's a test for our first
1597.1 -> program, which is the class person. Okay, now I have to add the brackets. When I add
1606.59 -> the first one, my editor already adds the second one. Because for every opening bracket,
1613.51 -> you always need a closing bracket.
1616.289 -> Okay, so this is the beginning. And this the end of my person test.
1623.429 -> Okay,
1625.03 -> no at the annotation test. So that I define, I want to write a test. And see, magically,
1636.38 -> the input appeared. Because my environment already knows, I want to write a test. The
1644.909 -> test also, I mean, it's actually a class. And it even has package. And this is all three
1652.419 -> unit test. We'll talk much more about j unit in later lessons. But for now, we just know
1661.52 -> this is a test magically somehow. Okay, and we need to test the method. test method will
1666.98 -> be public. It won't return any value, so it will be void. And I will give it a name what
1675.179 -> I want it to do should return hello world. Hello World is actually like a running gag
1684.8 -> of programmers. Someone I don't know who once started. That first program you write in a
1694.53 -> language should return hello world. So we do that to write a test. For my first HelloWorld
1706.669 -> program, I expect my person to return hello world to me. And I'm going to test this. We
1714.94 -> haven't written any actual code for person. But we're starting reverse. So we're starting
1723.529 -> with the test, as explained before. So now I can just assume I was done. You see, it's
1730.6 -> red, which means we don't have a class person yet. But this doesn't matter. Now for this
1735.64 -> person, I need a variable name. And as my name is markers, just for fun, I call it person
1741.77 -> I call the person Marcus. Okay, now I have to create person markers. Remember, this was
1751.909 -> calling the constructor creating the object. And so this is creating the object of person
1759.799 -> from the type from the class person. And the equal sign assigns that object which is created
1768.64 -> in the memory of RPC to the variable, the reference variable person because this is
1776.45 -> a reference that we can later on use referencing the person.
1784.37 -> Okay.
1786.79 -> Now this is read, but we'll take care of this later. We just continue. Okay, so assuming
1794.75 -> we were done, what do we want? We want to test something And testing, we say we want
1803.25 -> to assert something, we want to assert that a method we're going to write is returning
1811.299 -> the hello world for us. So, we want to compare if our expectation is equal to what the method
1821.54 -> is going to return. So we say assert equals, this also is starting as red, because we will
1829.659 -> have to import more stuff. But for now, we just take it, I use this was again metric
1838.13 -> I add one quotation mark, and my environment already adds a closing quotation marks. This
1847.559 -> is what we call a string. And I say hello world, because I want my person to return
1855.72 -> HelloWorld for me, so, the first part here is the expected return Well, you know, I add
1863.26 -> a comma. And now I have to add what is going to be tested Marcus dot for calling a method
1876.909 -> Hello, world. So on the object, Marcos of class person, I want to call a method, hello
1890.5 -> world, with no parameters given and what is returned here, I want to assert that it equals
1904.51 -> to hello world. Now, this is not going to work. Because we still have some red stuff.
1913.89 -> For example, here, we don't have actually written the class. But here we will let our
1921.71 -> environment help us, you see. Now I just have to say create a class person. Sorry, again,
1933.799 -> create class person. And here, it already asked us destination package, create class
1942.11 -> person. COMM walkersville. java course lesson two. Okay, sounds good. Because our test,
1950.52 -> and the actual class of the test will be in the same package. This actually helps us a
1957.1 -> lot. But more about this later on. I say, okay, and magic magically, or first class
1966.24 -> got created. You see the package, and the class. This is actually kind of the smallest
1974.63 -> class possible, just with opening and closing bracket. But it doesn't do anything yet. Okay,
1982.09 -> but you see, it's not red anymore. So let's go to from next, assert equals, oh, it wants
1991.72 -> to import something statically. I said before, I will later on tell you what means static
1999.51 -> import. But for now. Just believe me, we have to import this. This is another import from
2011.82 -> org j unit. But this time, it's an assert. And so this is like a method. We import the
2022.26 -> method assert equals. But, um, don't focus too much on this. We'll go in more detail
2029.65 -> later. For now, what is important, we want to write our first test. So we still need
2037.47 -> to define a method. And it also tells us cannot resolve method HelloWorld. Okay, help us please
2045.29 -> create method HelloWorld. We had enough it moved the method to the wrong place, but I'll
2052.24 -> fix that. Of course, we need to have it here. Okay, no, nothing read anymore. And we can
2065.119 -> start calling our first test. I say run. And this actually executed our first test, which
2077.299 -> again executed our first class that was automatically written. And here we see we have an error.
2085.98 -> It tells us a missing return statement. So I said we want to return a string you see
2095.749 -> string. But as you see the method is empty. We don't return anything. So let's fix that
2101.849 -> fix that return. This is how we say it, we have to say return. And I just have to type
2110.789 -> Hello, world. exactly as I was expecting it, I get the column to say yes to it return hello
2117.829 -> world. Okay, now we switch over to the test. And I'll execute the test again. And that's
2130.48 -> green, all tests passed. This is our first test. And it worked on in our first class,
2140.24 -> Tara. Okay. Thank you. That said, lesson three debriefing. For debriefing, we will go back
2153.67 -> to our development environment, and have a look what we learned so far. Okay, now we're
2162.519 -> back in our development environment. And now let's repeat what we learned so far. The first
2169.95 -> line of our program is the package declaration. It must be unique. And it usually consists
2181.559 -> of your domain name in reverse order. So in my case, calm, Marcos, bu Java course, lesson
2188.259 -> two, and we ended with a color. Actually, it's not mandatory, it's optional. But please,
2198.15 -> I really recommend you to use a package name. Later on, you will probably see why you just
2205.519 -> need to have some practice. But for now, just believe me treat this as if it was mandatory.
2212.619 -> And always define a package name. After the package declaration, we can have one or more
2219.509 -> import statements. This just for our lesson, now I made up I created a new class called
2227.89 -> name. And this is an A sub package called lesson three. Actually, all classes that are
2236.279 -> in the same package. So person has an a package called macro spiel Java course lesson two,
2243.799 -> for all classes that are in the exactly same package, lesson two at the end, we don't need
2250.98 -> to import them, Java will find them automatically. But here I made this lesson three. So if we
2259.45 -> want to use the name class that I just wrote, we have to import it. Okay. Next thing is
2269.4 -> class definition public class person. And with these brackets, that says the class begins,
2277.609 -> this says the class ends. Public means all other classes, for example, my new class name,
2287.029 -> in any package can see the class person. What this can see means is still a bit work. For
2296.819 -> now, just take it as it is, I don't expect you to fully understand it yet. This will
2302.819 -> need some practice. And here for now, some new stuff, I added the class that I defined
2313.619 -> name, and I made it private, which is also best practice to have we call this a reference
2320.53 -> variable, because it is a reference to later on an object of type name. And I made it private,
2328.66 -> which means other objects that get created will not be able to see. See again, I say
2336.52 -> See, or access this field here directly. If they want to use it, they have to go using
2347.069 -> this method I also just created this one is public and it returns personally. So when
2355.48 -> they call person dot name, the method you can give it any name I just call it salt,
2363.329 -> but you could also call it I don't know.
2370.119 -> Return the name. So this can be anything um, and it will return the person's name. So here
2383.04 -> again we see return, which means I want this to be returned to whoever calls that method
2390.15 -> and the colon which means do it execute it. Okay. What else did we learn? We learned that
2401.44 -> this stream, and that having a class, returning HelloWorld is like a running gag in programming
2411.009 -> for the first program that you do. So this is why I made class person return hello world.
2418.19 -> I mean, actually, it might not make sense. But yeah, just was all made up. Then also,
2424.969 -> going to the test, we learned, we actually start with writing a test. When we wrote the
2432.54 -> test, we hadn't defined the class person yet. We hadn't defined the method HelloWorld yet.
2442.359 -> We did all this on the fly. In our development environment assisted us with some auto completion,
2450.119 -> it was able to create the class as well as the method. So this is really a handy way
2454.91 -> of programming. First of all, you define the test. So this gives you an opportunity to
2462.14 -> think about the property sign. And then you define what you need, and you don't have to
2470.89 -> actually even write it yourself. And when you did everything correctly, you can simply
2476.349 -> execute the test. And when it returns, okay, and it screen, you will see that you did a
2486.93 -> proper job. Okay, see, here, you'll see a green bar, which means the test executed successfully.
2498.849 -> So when testing we often speak of green or red bar, because the green bar is such a good
2509.319 -> signal that you understand your test passed successfully, that people got used to just
2516.39 -> speak of green and red bars. Okay, so we learned some more stuff, for example, that this is
2524.23 -> an annotation. And I told you, you don't need to know more details about it yet. We will
2529.41 -> go into details later. Besides on top of input static, and also, I just want you for now
2540.619 -> to know that something static exists, but we will go into details later. Okay. I think
2550.769 -> that's it. It's okay, if you don't understand everything perfectly yet, I don't expect you
2558.92 -> to. Um, so we'll go in more details later. And we will repeat all this stuff. So it's
2568.589 -> fine. I mean, the start is really tough. I know that I don't expect you to be an expert
2574.38 -> in Java yet. Um, this is just an introduction, and you will grasp it soon. lesson four. Okay,
2584.73 -> we're back in my ID E. Id is actually the short form for integrated development environment.
2592.529 -> And as this is much shorter, usually you just say ID e. m, let's recap what we learned so
2600.059 -> far. And the first one, you have the package. And the second line, you might have import
2610.489 -> statements, you don't necessarily need something I didn't tell you so far is here we use name.
2618.89 -> And we use the classes short name, because actually, the classes real full name includes
2627.109 -> always the package name, so that the name is of the class is unique. So we could also
2635.019 -> use its full name, including the package name, and then we would not need to import the class.
2642.549 -> But I mean, as you see, this is much more readable, much shorter, so also much more
2647.099 -> handy. So this is what you normally do. There's only one exception, which is a bit more advanced.
2653.67 -> So I will just shortly mention it. Sometimes it rarely happens that you would have two
2661.23 -> classes of the exact same short name
2666.239 -> but have different packages. And so to define which one you mean, then you would have to
2673.58 -> use one with the full package name. Okay. So next, we define the class. The class starts
2684.209 -> with a curly opening brace and ends for the curly closing brace. Um, we have here, we
2692.829 -> say it's an instance variable actually. And this is an instance method instance variable.
2700.309 -> And instance methods could be, of course, much more. But those together we call the
2705.259 -> members of the class, because they belong to the class. An instance is just like an
2715.779 -> object. So of one class, you can create various instances, like, one person could be Marcos,
2723.819 -> another person could be, could have the name of Peter. And you could have hundreds of hundreds
2729.54 -> of class of objects, sorry. And each one of these objects is an instance. And for the
2737.64 -> instance variables, this means that each instance has their own version of this variable, which
2747.369 -> each might have a different value does not need to. But it's like a duplicate version.
2755.539 -> There's also another thing, which is called a class variable. And a class method, which
2762.77 -> we do when we add static to it, we can add static here, as well as to the here. In this
2770.699 -> case, now when we create different instances, and we change the person name of one instance,
2778.269 -> this means that all other instances will also have the name change to the new value. This
2785.17 -> is a bit more advanced and static. We should talk about this in detail later. So I just
2792.92 -> shortly, just to be complete, wanted to mention it. For now, it's totally enough, if you know,
2800.009 -> this is an instance variable, and this is an instance method, okay. Besides that, I
2811.349 -> would want to add a constructor, I think I talked about constructors already.
2816.89 -> Okay.
2818.65 -> Opening and closing curly brace. This is what we call a default constructor. It does not
2829.699 -> have any parameter here, not any variable. And so this is the default constructor. When
2835.799 -> we want to create an object of type person of class person, this constructor will be
2842.76 -> called and everything that we would do in here would also be executed. So this constructor
2850.64 -> is actually used to initialize an object. Because for example, let's do something else.
2858.17 -> Now let's add a parameter, prison name. So this now gets a bit more dynamic, more interesting,
2868.229 -> because we could try to set the inner person name to the given person name. Now, you see
2879.609 -> something is wrong. Variable person name is assigned to itself. Well, of course, how should
2886.68 -> our ID or Java know? What do you mean? Here, we need something to differentiate to tell
2893.449 -> Java, what we want is we want to set this instance variable to the value of the parameter
2902.13 -> person name. One thing we can do to fix that, we could just rename the variable to see it
2909.859 -> works. Now we can automatically automatically resolve the problem. But usually you don't
2915.809 -> want that I mean, person name is better name, of course. And now what we have to do, we
2923.069 -> have to add this to one of them. And as we want to set the value of person name to the
2931.469 -> instance variable person name, we add this dot person name. And so Java knows that we
2939.859 -> mean this one here. And now, when someone calls the constructor to create an object
2946.9 -> of type person, it'll also have to add the person's name. And then the person named darts
2955.349 -> directly gets set at the time the object is created. Okay, one more thing that you should
2963.78 -> know is now that we have created our own constructor that has the parameter person name, this means
2973.059 -> this class does not does not have a default constructor, an empty constructor like I showed
2978.7 -> you before this one has gone. Java will automatically created when there is no constructor defined
2985.559 -> by us. But as soon as we have defined one, General will not do that. Now if you remember
2993.289 -> our test from the last version, we use the constructor without any parameter. So this
3000.68 -> will later on fail, but I want to show you so I will let it as it is. Okay, so, um, remember
3009.339 -> we had that method here HelloWorld, I told you that in the first program in every programming
3017.339 -> language has like a running gag, you return hello world. Hello World is actually a string.
3024.079 -> And here we say the method should return a string. Now, I want to do some more advanced
3031.74 -> on, I would like to have a method, I can give a parameter of string. And then I want to
3039.96 -> say hello, the person's name. Um, okay. And as you also might remember, usually we start
3048.88 -> with a test. So let's write a test for what I'm planning. Okay, so how do we write the
3056.229 -> test? So we have to first of all at the end here, and then say test. This is what we call
3065.18 -> it a notation. Much more. We don't know yet. And you don't need to know for the moment.
3071.019 -> I mean, this is all confusing. So relax. I'll repeat everything various times, you will
3078.549 -> understand that very soon. For now, let's just write the test. So I say should we turn
3088.72 -> Marcos.
3090.259 -> Okay, because this is what I want the method to do. Okay, now I have the opening and closing
3099.059 -> brackets for the method. Okay, so we need to create an object of type person. Last time
3107.369 -> I called it, Marcos. This time, I want to show you how we can use any name we want.
3112.88 -> So it's called person, new person. So with that new person, and the regular brackets,
3121.9 -> I call the constructor. And this is like a method that is being initially executed at
3129.599 -> the time when the object is created in our memory, and see something is read here. Because
3138.189 -> I told you the default constructor is gone. So if we want to do that, we have to go back
3143.529 -> to our class. And we have to add the default constructor again. We can add it at any place,
3153.549 -> put it here. Okay, and now this is empty, and it'll work. But having an empty method
3165.63 -> or an empty constructor might be confusing for a colleague. So usually what we do in
3171.519 -> this case, we leave a comment. To mention we haven't forgotten anything. We have done
3176.859 -> this on purpose. So let's see how do we do a comment actually.
3187.329 -> So I say empty. On purpose, default constructor. So what I have here is a multi line comment.
3201.769 -> There's also also a single line comment, which you do just like this single line, comment.
3213.16 -> But I really recommend you should prefer the multi line comment for various reasons. I
3220.019 -> will go in detail about comments in a later session. So for now, this is all I want to
3226.059 -> show you. Okay, so we have fixed the test. Yes, the red thing is gone. Great. We have
3236.44 -> created an object of type person, let me copy this to show you one thing. You can actually
3245.539 -> create various objects one after the other. But now, we already have one object that we
3254.9 -> called person. So this will not work. So we would have to give this for example, person
3260.839 -> two. And so like this, we could continue. We could create any number of objects, just
3267.779 -> so that you see. We have one class of type person. And we have two objects created calling
3275.009 -> the default constructor. And so we have two objects when this is executed later on. I
3283.18 -> will delete this again. I mean, this was just a short demonstration. Because we should remember
3288.199 -> what we want to achieve actually is we want the method to return Marcos. Well, actually
3293.509 -> I was wrong. I want to say hello, Marcos. Okay, so now let's assert again. assert equals,
3301.709 -> I want Hello, Marcos. And I want to say person dot Hello. And I want to give it here, when
3315.209 -> we use a variable here, we call it an argument. This is just to make it more confusing, and
3322.029 -> people use this interchangeably. But to be correct here, it's called an argument. But
3328.7 -> it's all about variables. So we add a string. And I add markers. Okay, and see something
3335.94 -> is missing our ID, he tells us something right here, we need to call him to finish this.
3342.4 -> So I want on the object of person we created in the line before, I want to call a method
3349.589 -> Hello. And you see it's red. And it also our Id even already tells us cannot resolve method
3355.9 -> Hello. It doesn't exist. But we are programming in a test driven style. And so we will have
3365.66 -> to create a method right now. Okay, I'm actually, with some magic, I can automatically make
3376.309 -> my array he created for us. Well, there are different IDs, and I will speak about it specifically
3383.729 -> later on. So for now, I just did this to speed up it up. Just believe me. I mean, you. I'm
3391.22 -> sure you could create that by yourself. Now and he did something it said return now about
3398.89 -> now this is something special. I don't want to talk now. I'll tell you later. Okay. Sorry,
3404.209 -> I don't want to confuse you. But I also don't want to tell you too much. So one after the
3411.339 -> other. And now, I would add well Marcus's a bit. Let's say name. Name, because it could
3423.789 -> be any name, not necessarily has to be Marcos, we could add any name we want. And what I
3429.44 -> want is I want to add name to Hello. What we say here we want to concatenate hello and
3437.14 -> name. And something is missing. Oh, it doesn't like it. What is missing is a plus. This is
3445.079 -> how you concatenate two strings together. So a new bigger string is created. And you
3452.089 -> can do this any number of time. But for now, I mean, all we wanted to say is Hello, and
3460.439 -> the given name. So this should be fine. Actually, there's a little back hidden, which you will
3465.939 -> see very soon. Which I did on purpose, because I want our test to fail.
3473.44 -> Let's execute it. Ah, so you see expected Hello, Marcos. But actual Hello, Marcus. So
3485.819 -> there's a space missing. So see, this is one reason why tests are really handy to help
3491.539 -> you to think about the stuff you code. But also when you do introduce a back an arrow,
3500.14 -> then you will directly spot it and you're able to fix it before it goes on production
3506.589 -> and destroy something. And yeah, this can be really expensive. So let's fix this. Let's
3515.15 -> go down to our method. And here was a space missing. Let's add it. We go back to the test.
3524.63 -> executed again. And now the bar is green. It's works. Oh, that's great. Okay. Um, yeah,
3538.359 -> I think that's it for now. Lesson five. So now, I would like to talk about modifiers
3547.41 -> first of all about visibility modifiers. Actually, we already talked about them a bit. One visibility
3555.529 -> modifier is private. Another one is public. So public, I think I already said this class
3563.059 -> is visible or usable. From all other classes in all other packages. This class now resides
3572.049 -> on the package comm Mako speelde. java course lesson two. So here, for example, name is
3579.289 -> in lesson three. So if we would go in the code of the name class, it could easily use
3585.64 -> person as long as it's public. A private class, we can try that. No, it says modifier private
3597.39 -> not allowed here. And of course how That makes sense. I mean, a class that's not usable anywhere.
3605.14 -> But just in this class. This doesn't make sense. But actually, there is one more option,
3612.809 -> we can leave the modifier away. And this will give us the default modifier. This is also
3619.729 -> why it's called default modifier, also package level modifier, because now, person can only
3627.23 -> be used from other classes within this package. And we can do the same for the variables,
3637.549 -> the constructors, we can even have a private constructor, we could have that public, we
3646.069 -> could have that method private. And this one default. And we can even call, let's use this
3656.339 -> one. Let's call HelloWorld. From this method here, all this is working. And this actually
3665.059 -> even makes sense. Because especially when your methods are growing, I personally would
3671.089 -> say not more than three or 10 lines. Then to break things up, you can split a long method
3677.759 -> into smaller private methods, and then calling the private method. Like, I mean, here, we
3687.859 -> have only two methods. So to make things up, you can call one method three times. But of
3695.059 -> course, I could define further methods. We don't have this now. And then you can call
3701.199 -> any number of methods later on. Okay, so to recap, visibility modifiers, we learned so
3716.999 -> far is public, private, and default or package level. Besides there are other visibility
3724.41 -> modifiers, one, for example, is protected. But we don't need this at the moment. So you
3732.89 -> should be perfectly coming alone, along with just public, private and default. So for now,
3742.96 -> let's just concentrate on these few. Let me fix the class shortly. Because very soon,
3750.979 -> we are going to need it in our test. And I don't want to adjust the test, I want to have
3758.679 -> the code as it was before. Okay, because now I want to show you a new concept. I have this
3770.609 -> idea. I have prepared the test should return number of persons. Let me create a few objects
3779.369 -> of type person, one person, person to
3788.849 -> person,
3793.339 -> we could also use the other constructor, but then I would have to create an object of name,
3798.529 -> as this at the moment is just too much work for me, I'm not doing it. And I can also give
3804.959 -> it a different name, like my person, just to show you, we can have any name for the
3811.429 -> variables. So what this means is when the test will be created here, after this line
3819.089 -> is executed, which is just after the column, we will have one object and memory two objects
3825.929 -> in memory. And after this line three objects in memory. So what I want now I want to test
3837.019 -> on a number of objects. Now I should have three objects created. And I want to create
3844.289 -> a method that tells me exactly that. Just dynamically, my person thought number of persons.
3854.179 -> Okay, still read, remember, we'll create it. And today Ah, int appeared. Because I mean
3866.819 -> three is a number. And a number in Java is an integer, or he In short, an int an int
3874.769 -> this actually a primitive. And the default of this is zero. So this is why my ID he put
3881.02 -> zero here. So it's not red anymore. We can have a first run. But this will not work of
3889.519 -> course, because it statically returns zero we expect three. So this is not what we want.
3896.369 -> Well of course we could say three statically. So, now this should work. It's a bit cheating,
3909.549 -> of course, greenbar Tada. But, I mean, I want this to dynamically work. So why not only
3918.499 -> have two persons, I want this to be two. And well, of course, I have to rename a variable.
3926.799 -> Let's copy it. And now when I execute it, of course, this is not going to work expected
3934.669 -> to, but it's still three. So my first approach the static one, always returning three. Nice
3942.88 -> gag, but yeah, not what we need. So what we need is, at the specific time, when each object
3950.309 -> is created, we need to count each object that is created. So what would be the place where
3958.799 -> the object is created, there is one thing, similar to a method that is called and this
3967.059 -> is, you might guess it, the constructor, we used the default constructor for creation.
3975.439 -> So we would have to do something in here. Now, I want to invent a variable, an instance
3982.66 -> variable, I also call it or let's call it person counter, person counter equals two.
3995.239 -> And now I say person counter, because I want the value it had before. And then I want to
4002.369 -> add one to the last value of person counter to have the new value dynamic. So on the left
4011.119 -> side, is the new value. On the right side is still the value from the prior calculation.
4020.429 -> And I add one to it. Now, this is a lot of code again. And this incrementation by one
4029.529 -> is used so often, that they invented short form for that, which is plus plus. So with
4037.87 -> plus plus, we say take the current value of person counter incremented by one and save
4044.109 -> it again into the value of person counter, it's still red, because we still have to create
4049.38 -> it. Let's do that. Make it private, of course, it's an int. I call the person counter and
4058.76 -> column. Because I don't have to say zero, I could also say equals to zero. But the default
4067.289 -> for end is zero anyway, so what we usually do is, we just put it here as is. So the idea
4074.589 -> would be it starts with zero. The first time this constructor is called, it's incremented
4081.029 -> by one, and so on. So that my method now should not statically returns three, but person counter
4090.97 -> instead. Okay, let's try that. Execute the method. Still not working it returned one.
4104.989 -> It didn't return zero. It didn't return three it returned one. How is that? We didn't say
4111.069 -> one anywhere. Maybe you guessed it already. So we started with zero, we incremented by
4118.5 -> one. Now I told you something in the prior session, which is this constructor is part
4127.13 -> of the instance. So each object has their own constructor has their own method. So this
4136.15 -> is called for each of the objects. So in the end, both objects would have the counters
4142.98 -> set to one. So what we need is more like a global counter. That is not on the instance
4151.359 -> level. But we say on the class level, because for all the objects of type person, there's
4157.299 -> only one class person and this we achieve with a modifier called static. Okay. However,
4171.309 -> as a recommendation because this will help you in the future, I won't go on details Why
4179.099 -> just believe me. As we have the variable of types of static, you should also have the
4185.969 -> method of type static, it would work also without that, it just better believe me. Okay,
4194.969 -> so now let's execute it. And this work Great. Let's try another thing. Let's add this time
4209.039 -> for
4210.039 -> free
4214.32 -> for for an exit executed and it works, I said actually person to why not saying person one.
4232.489 -> And it works? Well as you see this might be confusing I mean which variable to decide
4237.559 -> on. And also there is a recommendation. Actually what Java does is Java sees that number of
4250.07 -> persons as a static method, it sees that you have an instance variable off type person.
4258.32 -> And as this is a static method, it doesn't call the method on the object. Because as
4266.03 -> this method is static, it's not part of the object anymore. This is like moving it out
4271.8 -> of the object. This method now is part of the class. So Java does some magic here, is
4279.46 -> trying to be smart and is smart, and calls the right method of the class. So what we're
4289.119 -> doing here is working because Java knows how to do it properly, but it's not so nice. What
4296.5 -> is better is darkly saying person, so that everyone knows you're not going to any specific
4303.15 -> instance, we're just calling a static static method. On the person class, let's execute
4311.45 -> that again. And it's working. Thank you. So in lesson six of this Java course, I'm going
4322.61 -> to talk about the tools which I'm using. So first of all, let's start with this computer.
4327.989 -> It's an apple MacBook Pro. This ID that I'm using here is IntelliJ IDEA, which actually
4337.83 -> at the moment is my favorite ID. Before I was using many, many years, Eclipse clips
4344.719 -> is open source is also very popular at the moment, especially with companies because
4351.78 -> it's open source and free. However, I think intelligence here is really getting better
4358.099 -> and better every year. So I really like it and recommended. And they're not paying me
4363.23 -> for saying that. But I mean, this is your personal preference, and every person is different.
4370.69 -> So I would say just try it out yourself. There's also NetBeans. NetBeans is also very popular,
4378.42 -> and it's also for free. I'll just in a second, I'll show you where to get them. But let's
4387.55 -> have a closer look at my tests before. So in the tests, might have seen it already.
4393.57 -> I'm using j unit, which is a testing framework. framework means it's like a tool set. It's
4401.13 -> a set of tools to set of classes. And it's open source. So it's free to use. And I mean,
4409.77 -> writing such a framework, it's not really hard work. But why doing it if it's already
4415.82 -> done. So this makes it really easy to start with testing. J unit also is only one of a
4422.53 -> few testing frameworks. The second one I would tell you about is test and G, I think they're
4428.739 -> pretty much the same. And really depends on the company that you work in some use j unit,
4435.59 -> some use testing G or any other framework, I think between j unit and test ng g there
4442.01 -> knows not so much big differences. So it doesn't really matter. I just decided to use j unit
4448.07 -> in here. IntelliJ IDEA actually supports both of them out of the box. So you can easily
4454.55 -> try them. Um, I'm not going in much more details, by the way. I mean, this is a Java tutorial.
4462.3 -> So I focus really on Java. Just to be complete, I wanted to mention what I'm using here. But
4469.949 -> I do this in less than six because at the beginning, I think learning a new language
4474.909 -> is already quite difficult. So I wanted to focus on Java, but not that you puzzled. What
4482.87 -> the heck is that here? What are you doing? I wanted to mention this is J unit. And there
4487.98 -> is lots of documentation on the internet. Yeah, so you can read a lot about it. Okay,
4495.479 -> so maybe we just go to the browser now. and have a look. So first of all, I told you about
4504.369 -> intelli j idea for you pops up.
4510.85 -> So you can download, I would first of all, go with the free edition, and then see if
4518.56 -> you like it or not. Besides, of course, there's Eclipse. This one is open source anyway. And
4528.949 -> then you can choose your operating system, and 32 or 64 bit, whatever you need. Last
4539.701 -> but not least NetBeans. Just press the download button, choose your language, and operating
4555.719 -> system. And then also j unit, let's have a look on that. In most It is these days, you
4568.26 -> won't have to install it, because it would come pre installed anyway. But just for the
4573.51 -> record, I mean, this also has lots of documentation. So yeah, he you can download the most current
4581.11 -> version. Let's check documentation. Here. It also talks about Maven, which, by the way,
4588.96 -> also using so this way, you can define in Maven that you want to use the current version
4595.44 -> for 12 of j unit, which I actually did, because I'm also using Maven, which we're going to
4601.719 -> in a second. But after j unit, let's also have a look on tests and G
4615.21 -> test ng g on this page just provides the false for Eclipse. But as I told you in IntelliJ
4622.25 -> IDEA, it's included anyway. And I checked for NetBeans. I mean, I'm not so familiar
4628.119 -> with NetBeans, I have to admit that beans, but I saw there is a plugin, which you can
4639.34 -> download and install. So probably works just as well. Now let's talk a bit about Maven.
4647.17 -> Maven, there's what's called a build management tool. So as the name implies, it manages your
4657.69 -> build. Now, what's a build? Well, when you program your programming consists of hundreds
4664.099 -> of classes, and then you would want to release them on production or send them to a client.
4670.59 -> And then of course, you would not want to send each file separately. So the so you would
4675.57 -> usually do a package a single file out of all the tasks together. And in former times,
4682.4 -> and say in prehistoric times, this was done manually. And this is really not a funny job.
4688.48 -> So people very soon started to program, some little scripts to make this task easier. The
4697.619 -> first tool that I know of is probably make it's a Unix tool. And often make they came
4705.5 -> up with and and Maven again is the successor of Maven of m sorry. And Maven currently exists
4715.94 -> in version three. Besides Maven, there's also Gradle and other build tools, I'm using Maven,
4725.659 -> here you see it find that I'm using j unit 412. And also the find that my source encoding
4733.27 -> is UTF eight, because what this bill two also can do for you. I mean, it can do so many
4738.639 -> things is environment specific settings. So that I tell that my source encoding is UTF
4747.869 -> eight, I can do it here. And so much more. So also about Maven, you can visit the website,
4757.489 -> Maven. There, you can download it. They also have a free book, which is really a great
4766.619 -> book. You can download all the files, even the sources that you would need. And also
4775.139 -> check Maven book. I really recommend that. As far as I remember. It's available as HTML.
4784.52 -> And also there should be a PDF somewhere. All this is just too long. Anyway, I know
4793.17 -> there is also a PDF available which you can download. And so you can read all about Maven
4802.179 -> Last but not least, let's also talk about bit about text editors. Because I think in
4807.73 -> at least one of the lessons I did so far, I told you, you should start not with an ID.
4815.409 -> But you should start with a text editor instead, well, there are two that I would recommend,
4821.869 -> first of all testbed for Windows, I really like it using Windows. for Mac, it's unfortunately
4830.84 -> not available. In this, you can write your code, then you would save it. And then assuming
4840.179 -> you have already downloaded the Java JDK, which I have also not talked about, because
4845.739 -> I assume I should be easy, but maybe we could first, shortly go there. So for the JDK, so
4855.429 -> that you can download your code, you can just go here, say download, by the way that was
4859.989 -> NetBeans, if it was soiled, and you can choose your operating system and download it. I assume
4867.969 -> you have already done that. And so when you have installed a text editor, or like text
4873.179 -> pad, or sublime, you're on. Mac, I'm using sublime, which is also a great editor. Download
4883.869 -> button. It's also available for Windows and Linux. So using this text editor, here, I've
4893.42 -> loaded the class person that we saw before. I mean, it helps you a bit like see, I click
4900.119 -> on person's name, it highlights the variable person name and all forms, but it would not
4905.8 -> so heavily assist you, like you might have seen when I was in my ID, which for the beginning
4911.78 -> is actually good, I think. Because when your ID is too smart, then you don't have to use
4919.969 -> your brain cells too much. I mean, after some time, when you have coded too much, this is
4927.03 -> really welcome. But for the beginning, I really recommend to use your brain cells and so that
4932.83 -> you get used and familiar with all these keywords, public class, private static, should really
4939.539 -> get familiar with that. And so for the beginning, just use a text editor, then you can also
4945.469 -> go on the console and called Java arc and compile the class. Also, this is one show
4952.87 -> you because in this course really I only focus on the theory of Java. So yes, I think that's
4961.53 -> it really short introduction of the tools that I'm using.
4965.199 -> If you have any questions, send me an email as always, um, yeah. Lesson seven. So now
4975.73 -> let's start with the topic of this video, which is conditional statements, and of course,
4981.34 -> conditional statements, and Boolean. So a Boolean is a new data type. This one is actually
4990.699 -> a primitive and it can have two values, Boolean, true or false. And this is all there is to
4999.801 -> it. So conditional statements, I mean, there is a condition and it can hold true or not.
5010.46 -> And that is something is executed or not. I think, already from the wording, it makes
5015.9 -> sense, and you might easily understand it. But what exactly is a Boolean? Why is it called
5021.699 -> Boolean? I mean, this is a bit weird, I think, well, at least this is what I found. So I
5027.87 -> just looked it up on the internet. Here on Wikipedia, we have Boolean algebra, and I'm
5038.04 -> really not a big fan of mathematics. So let's go over this really fast. The only thing that
5044.309 -> matters to me is Boolean algebra was introduced by George Boole in his first book, blah, blah,
5051.48 -> blah whatsoever. So it turns out that the Boolean is called all the end because of this
5057.559 -> guy here. Um, I leave this as your homework, read everything about George Boole and Boolean
5065.75 -> algebra, of course, this is again a big topic by itself. We have folk focusing again on
5073.3 -> Java, I just wanted to help you that you get a feeling why Boolean is called a Boolean.
5082.67 -> So this thing here is really helpful when we want to say if something happens or something
5089.889 -> exists, some condition, then only execute a specific area of code. And then you can
5097.07 -> also say else if this condition does not hold true execute something else. So this is really
5104.849 -> the if statement is probably the most important statement, not only in Java probably in all
5111.64 -> programming languages, at least the ones I know of, because it allows us to, like really
5118.309 -> have a different execution flow each time. For example, we could say, I mean, B is a
5124.26 -> bit boring. Let's call this Monday. And let's add all the raining. I was raining. Let's
5136.82 -> also have Monday. Okay, so in this little example, it's Monday, and it's raining. And
5145.3 -> nobody could say if it's Monday, and percent twice,
5154.12 -> raining.
5155.489 -> So what these two M percent mean is, and so this tells Java to check on this boolean value,
5164.69 -> check if it's true, and only if the first boolean value. Or he could also be a function,
5173.119 -> like, is it Monday, which would have to return a Boolean. And if it does, only then Java
5184.84 -> would execute, go here. And check if this is also true. Which also could of course,
5190.1 -> be a function if Is it raining or whatever, right. And if both here are true, then this
5206.219 -> block here, starting with the curly braces, is going to be executed. Now. I mean, I don't
5212.719 -> want to implement the functions. So let's make this Monday again. And simply raining.
5221.19 -> Just to keep it simple, and then drink beer. Because rain. I mean, what else can you do?
5230.58 -> Um, but now let's make this more easy to drink beer. I'm from Munich, so I'm really a beer
5239.55 -> lover. So on Mac, I mean, as depends which platform you use. On Mac, you press just out
5249.25 -> and seven, twice. This is called the pipe symbol. And the pipe symbol symbolizes or,
5258.289 -> um, yeah, I know this is a bit weird. This, you just have to know by heart that this means
5265.55 -> or, again, as before with the two ampersands. When you repeat it twice, it's called the
5274.139 -> short circuit operator, which means if the first condition is already not true, for the
5285 -> end, at least, then it's not going to execute the rest. So whenever In a statement, it sees
5293.48 -> that a condition will cannot hold true anymore. It will stop at the beginning and they will
5299.19 -> not execute the rest, which is very handy. Because I mean, if before we had a method
5305.59 -> here, is it raining. Now imagine this method takes like two hours to execute, we could
5315.671 -> really save that time if we already see. This is only true if both are true. So this is
5323.23 -> why you use the ampersand twice. And the pipe symbol wise, this is I would say the default.
5333 -> So I want to even spend time to talk about the other alternative. But now this is so
5338.849 -> much nicer. If I have an orange here, if it's Monday, or if it's raining, I drink a beer.
5348.8 -> So this really increases my chance my chance to get a beer. So I personally liked the statement
5355.75 -> so much more. I'm just kidding. Um, so this is the difference. Or, and, and, and of course
5366.65 -> you can further combine that led so I don't know what to do. Let's say raining and let's
5378.5 -> say Tuesday and sunny. So we have to introduce these Boolean variables first. So Tuesday.
5392.659 -> Well, if it's Monday, it can't be Tuesday. So we will say false here. And Boolean, if
5403.5 -> it's raining, it can't be sunny. So sunny will be false. But of course, let's change
5411.11 -> this. Now it's not Monday. It's Tuesday. So this will be true. And I misspelled that sunny.
5421.01 -> Okay, now they're not red anymore. So now what do we have here? Monday is false. So
5428.139 -> if Monday is raining, but it's not Monday at the moment. So this is the whole thing
5433.54 -> here is not true. But here we have an or true Tuesday, this is true, Sunny is still false.
5442.59 -> So this is also false, which means the whole if statement is false. And we cannot drink
5449.139 -> a beer. But let's make this true. And now it's Tuesday. And it's sunny, and we can drink
5457.87 -> a beer Ray. Of course, I mean, when it gets more complicated, I'd recommend you to introduce
5463.889 -> more brackets to really tell Java first execute this. And the result when you have it, then
5473.1 -> only execute the next statement. I mean, if you go more in more detail on the algebraic
5480.29 -> logic, you will see there are preferences. And they're really rules on that. But if you
5486.969 -> don't know them, and if you always just add the brackets, you're on the safe side to show
5491.94 -> what you want. Okay, now, let's make this not so complicated. Because let's introduce
5502.079 -> something, something else. And this else is the else statement. Because if it's not money,
5512.63 -> we can do something else. And this is the new keyword that I'm introducing the else.
5520.47 -> statement. So here, we can say drink, milk. might also be nice. Okay, so, only on Monday,
5532.519 -> we drink beer. And on all other days, we drink milk. So that means we have to drink a lot
5538.82 -> of milk. So if you I mean, milk is really healthy. So I recommend you to drink milk
5544.079 -> like this. It's much better. But of course, let's introduce some more variation. If no
5553 -> sorry, else if, um, as you introduce a new day, let's say Friday. So we have to introduce
5566.099 -> Friday. At the moment, it's Tuesday, Tuesday. So we'll change that in a moment. Make this
5577.67 -> false. So else a Friday.
5585.909 -> Sorry.
5587.8 -> Drink water. Okay, so what do we have now? And I mean, you can format this in any way,
5598.58 -> but usually, you formatted like this, too, so that you can see this all this whole construct
5605.309 -> belongs together? Because it starts with if money. And if this is not true. Java has to
5614.61 -> check else is it Friday? If so, then call this function. And in all other cases, we
5623.039 -> still drink milk. So, okay, and you can have any number of L's if statements here.
5638.57 -> Else if I don't know some other condition, we could just say sunny. Um, if it's sunny,
5649.17 -> um, what should we do? go swimming, go swimming. Yeah, we can do anything here. Okay, so you
5663.119 -> can have any number of L's if statements. And you can have just one l statement, of
5669.929 -> course, but you don't have to, I mean, this is not obligatory. You can also leave it away.
5676.85 -> You just you cannot have AIDS if by itself because else what I mean, there has to be
5684.59 -> the whole statement has to start with some Eve. I'm okay. I think this pretty much is
5694.559 -> enough for if else if and else. Now let's do some more cool stuff. Let me Remove all
5700.489 -> that. Because normally, you evaluate some condition. And then when the condition is
5711.07 -> evaluated, this returns a Boolean. Under the, under the covers, I would say, for example,
5717.139 -> you could say in E equals to four. And then we could say end. j equals to three, omit
5731.179 -> that. Okay, so we have two primitive data types of the end, which are introduced in
5739.11 -> a form of video. And then I can compare those values. I can say, I mean, of course, as well
5747.73 -> as with the Boolean is it's obvious. But I mean, in a big program, it's not so easy.
5753.449 -> Normally, one function calls the other, and he would like have the user typing in nature.
5759.949 -> And then you don't know if the user typed in four, three, some in this is a really stupid
5765.21 -> example. I think we know that four is bigger than three. But let's assume that we don't
5770.349 -> know. And then I could say, if i greater than j, then do something. Else. Do something else.
5789.599 -> I mean, here, it's again, you can say ELLs, if you could say if j greater than I, what
5807.27 -> else can we say, oh, if i equal to j, which at the moment, of course does not hold true.
5819 -> This, by the way, you see there are two equal signs. The reason is this equal sign we use
5828.3 -> here when we assign the value of four to i, or j, so we can't use that again. Instead,
5836.92 -> in Java, here use two equal symbols to express I want to have a Boolean check. And what you
5848.03 -> also can do so so you see the result of this will be a boolean value, you can assign that
5854.52 -> boolean value are equal to a boolean variable. And this is actually quite often very smart.
5865.94 -> I mean, here, it's very easy to understand. But sometimes you have way more complex terms.
5873.4 -> And then if you give it a name, your code will be much more easy to read, because now
5879.249 -> you can say are equal. Okay. And then there is also greater or equal, smaller or equal.
5892.29 -> And then also unequal, which I will usually I'm typing like this, but it's actually the
5904.78 -> same. So not equal, you can say with the exclamation mark equal, or with greater, smaller, like
5913.09 -> this, it's both the same thing.
5917.51 -> I really prefer that one. I think it's more readable. Because this is like, exclamation
5923.429 -> mark, really easy to read. And with this, you can also whatever condition you have,
5932.92 -> if this no holds true, when you put the exclamation mark in front of it, that is false. If this
5940.44 -> before was holes. Now it's true. Thank you can even Yes, you can, you can add any number,
5950.119 -> exclamation marks, and every time the value is inverted. So from to false than true again,
5956.661 -> and false again, and so on. I mean, this is not really readable. So I wouldn't do it.
5963.84 -> Just to be complete. I wanted to mention this as possible. Okay, on. I think this pretty
5973.42 -> much wraps it up. We talked about Boolean. This is a condition. If it's true, we execute
5981.5 -> code that is in here. You see it can also be empty. I mean, it doesn't really make sense.
5987.889 -> I mean, I would really recommend you to write something, execute some method. You can also
5997.981 -> of course, you don't have to have an method in here, while again, I would recommend it
6002.789 -> because it might be much more readable. But in here, you can also do crazy stuff like
6009.11 -> i equals to eight, for example. J equals 299. So you see, now we have actually some code
6025.719 -> or plus class, the increment operator that I talked about, I think it was in less than
6032.499 -> five. So if j with three before, when this is executed will be four, or minus minus,
6044.409 -> it was three before it will be two. Okay, so you can have 30 Booleans. And here, what
6055.01 -> you cannot do is compare a Boolean to another data type like int, amin, this wouldn't really
6062.37 -> make sense what you can do, but, and this really, a lot of beginners do like to compare
6072.42 -> a boolean value let's make this Monday again. Monday. True. And now you could say, if Monday
6084.929 -> equals to true, what does this mean? I mean, this means if true, equals to true. Of course,
6093.739 -> this works. And if this was false, if false equals to true, false does not equal to true.
6101.969 -> So the whole thing is false. But I mean, this is one comparison too much. To say, if Monday,
6109.13 -> this is enough. Yeah. But really, comparisons like this false or true. I really see very
6118.05 -> often in code. So if you see that, you're free to refactor the code, and just shorten
6126.86 -> it. If it's true, then just say, if Monday, if it was, if Monday false use just say, if
6132.53 -> not Monday. So, see, this is not. Okay. Lesson eight, I would like to introduce you to loops.
6145.82 -> This is really exciting, because it's a very cool feature. It allows you to execute a repetitive
6153.3 -> task much faster than any human could do. So this really makes our programming very
6160.519 -> powerful. So it's very important to know how to program loops. So there are certain different
6167.55 -> types of loops. The first one is a for loop for because it says like, for a number of
6178.389 -> times, execute something. So this is why for and then sorry, this writing here will be
6186.989 -> a bit cryptic. I'm sorry. The reason is because this loop is really also a very old loop.
6194.829 -> That was also introduced before Java, actually, I think it's, for example, is part of C and
6201.929 -> c++, which are much older than Java, actually. So and when they invented Java, they just
6209.3 -> took over the same style. So this is why it's a bit cryptic. So
6216.8 -> we have three sections here. Let me first of all, type it and then explain. So this
6228.139 -> the three sections that this first loop usually has, which means First of all, introduce an
6237.76 -> int, and assign it a value of zero. calling this variable II, I sorry, is like the default,
6249.789 -> because I just for integer because the guys that invented programming, are sometimes also
6258.98 -> mathematics, mathematicians. So yeah, they really like short variables like AI. And it's
6266.42 -> so it's so common. I also used AI, but you could also call it like culture. It just that
6274.219 -> people would expect you to call it AI. In this type of loop. It's mostly always called
6281.039 -> AI or just why are some some variables short, just one letter. Okay, anyway. So this is
6288.94 -> our counter variable that defines how many times we want to execute a certain statement.
6297.039 -> Our statement that we want to execute is actually that Create a person object. And we want to
6302.59 -> do this four times. In programming languages, again, mathematicians, they're to blame. They
6312.4 -> don't start with one, but they start with zero. So if we want to execute it four times,
6319.139 -> we have to make sure that we stay that I stay smaller than four, because from zero to three,
6328.239 -> this is four times. And each time when we are finished at the end of the loop, I is
6335.639 -> incremented by one, see, this is the plus plus. So afterwards, it's incremented by one,
6343.13 -> and then the next round, it will be one, one is smaller than four. next one will be two,
6350.969 -> two is smaller than four, three is smaller than four, and four is not smaller than four.
6357.63 -> So for the fifth time, the loop will be exited. And so afterwards, the court will be here,
6369.25 -> the cursor kind of, and we will not execute it a fifth time. So I copied this into the
6376.73 -> for loop.
6383.37 -> And then this should make sure that four persons on the fly are created. Actually, because
6392.591 -> this variable is defined within the block, we cannot access the person object anymore
6402.21 -> in here, I think I showed you this, see it's red. This is about the visibility, what we
6412.389 -> could do is we could put the definition of the variable up here. This way, we can still
6425.65 -> access person one, but actually only the last one because the variable person will always
6432.159 -> be overwritten by the next one. I mean, for this little test here, this is okay. Because
6438.48 -> all we want is we want to calculate the number of times the constructor was called. So this
6447.789 -> works, as well as we could also define person in here doesn't make a difference. In our
6455.429 -> case, because this is a static method. We talked about this in the earlier lesson. So
6461.349 -> now, let's try that code. And it's green. Now let's try it to put the time here. This
6479.969 -> darkness does not work. Because see we expected for but actually, there was 10 times the person
6487.88 -> constructor was called because this is 10 a year. So this is how the first loop The
6495.349 -> for loop. The regular for loop usually looks to define an end, you give it a one letter
6502.679 -> name like I, you assign it zero, and then you compare it to some max value. In this
6514.01 -> case, 10. Before we head for so that the test is green again, you always have to separate
6523.719 -> these blocks with a colon. And then you increment i by one. You can also do any other statement
6533.749 -> in here. Like you could say, I equals i plus two. Which will then let's see. So I'll assume
6548.499 -> something. See now we only created two persons, because each time it was incremented by two,
6558.19 -> which means the number of times that we were going through the loop was only half the number
6566.269 -> of course. And if we add four or even I don't know 10 we will probably only executed once.
6574.32 -> Let's try that. Yeah, see actual one. Okay, so usually you could put any statement here,
6587.599 -> but the default is to just increment a counter variable by one. So, release. Try to stay
6598.199 -> with the default and do it like This, I could even further tell you crazy stuff. Like you
6605.73 -> don't even have to do all this can have this empty. This now would be an infinitive loop,
6618.44 -> you can try this at home, because this will, like probably crash your PC because it will
6624.989 -> create lots of objects.
6628.249 -> Um,
6631.03 -> but it is valid. Okay. But this is how it should usually look. So anyway, let's go to
6642.57 -> the second loop, which is the while loop, while some condition holds true, execute.
6652.82 -> And each of these loops have their specific reason to be used. I mean, actually, in theory,
6667.409 -> you could use always just the one loop like this loop or that loop, it just that when
6673.21 -> you want to count something, I mean, this really is helpful. Because it does all everything
6679.21 -> at once, if you want to do exactly the same code, we have to do it like this int i equals
6686.349 -> to zero. Well, I smaller than four. And then you have to say, at the end, I plus plus.
6699.239 -> So this is exactly the same. And you see, it's not so nice and short anymore. So this
6706.57 -> while loop, you would usually do one, for example, you have some condition that gets
6712.829 -> dynamically calculated, like we had the function here should drink beer. So if you had some
6726.61 -> function here, like should drink beer. This is when you would use a while loop. I mean,
6734.8 -> I have not defined those variables here. But I hope you get the idea. If you have some
6740.43 -> function that is always calculated, you will use the while loop. And then in here. You
6747.989 -> could also create person, and you don't have to do this now. Because we assume that this
6759.42 -> method sometimes would return false. And when returns false, this loop would be exited.
6767.61 -> Okay, but let's go back because actually want to run it once. And there is a bracket missing.
6782.65 -> Because I promise you we can do exactly the same thing. So let's try that. Okay, well,
6796.61 -> this probably will not hold true anymore, because then we have done it eight times.
6806.51 -> So let me remove that code. Okay. Let's check. Seems Okay. Let's see what j unit says. Okay,
6823.099 -> seems like this is okay. So it's the same one. And then last but not least, there's
6831.639 -> also another loop, which is called This is the newest loop because it was introduced
6837.28 -> as far as I remember, with Java five, this is the most simple and the coolest loop. However
6844.619 -> I'm sorry I cannot show you this one. Because for this I need to introduce you to arrays
6850.579 -> and collection which I will do in one of the next lessons. So for now just know there is
6863.29 -> another loop the coolest one actually. But yeah, so this was a very short introduction
6869.92 -> to two different loops. Well actually yeah, I could also show you the while loop you can
6875.699 -> also do it kind of let's say backwards. So you can say do while some condition um the
6890.33 -> regular while and the for loop I showed you that very common bows, but this one you will
6897.69 -> hardly ever see because Again, it's a bit more difficult to understand. What it does
6905.429 -> is it executes this statement the first time, sorry, without even checking a condition.
6912.829 -> So the condition is checked only afterwards. Of course, we also need to increment.
6921.89 -> Okay.
6926.09 -> So what we do here is we assert that number of persons equals to four, well, no, this
6937.019 -> is, this won't work, we have to sort it afterwards, sorry. So now we create the first person without
6952.099 -> even knowing how many times we have created, then we increment i. And at the end, we check
6958.769 -> that I is smaller than four. Let's try this and remove that.
6968.36 -> See, this also works. Um, this depends on the logic that you need. Sometimes you may
6982.229 -> use that. But actually, all the three different loops I showed you, they are like equivalent,
6989.729 -> you can do everything with each of those loops. So it's just the different style. And this
6999.019 -> depends on what you want to express what's easier for you to use. This you will get used
7005.3 -> when you're like, did a few months of programming, and you use each of them, you will get the
7012.159 -> hang of it. What's like usable in which situation. Lesson nine, I would like to introduce you
7020.71 -> to arrays. Arrays are also a very cool feature of many programming languages. And they also
7029.61 -> appear in Java. I kind of unofficially introduced them already in the last video, where I mainly
7039.61 -> talked about loops. And we stopped when I said there is one more loop the for each loop
7048.729 -> that is specifically designed for arrays and collections. So today I'm going to introduce
7055.389 -> you to areas at least. And so we can also see the for each loop. And so an array is
7062.96 -> really like container, a box, or let's say a list. So an array isn't is also an object
7071.289 -> is a data construct that can hold a number of primitive data types or objects. And as
7081.539 -> I already said, box, so far person, the way we define it is with these were brackets,
7094.789 -> which symbolizes something like a box, I think, which is easy to remember, because we will
7101.809 -> put our persons kind of in in here we could think and because this container will hold
7109.28 -> a number of persons, I will call this variable persons. Okay, now I say new person. But now
7121.88 -> there comes something new again. I don't use the regular brackets, or again use the square
7128.489 -> brackets. This does not call the person constructor. This would be done like this, and should not
7136.86 -> be working yet there's already a thread on the line. So I'm not calling any constructor
7143.699 -> here. This is a specific syntax that says Create me an array of type person that can
7155.749 -> hold a number of persons. And we have to now give the number which is four. That was still
7162.6 -> a red underline now it's gone. So now Java knows we want an array of type person that
7169.869 -> can hold four persons same thing we can do with it. And by the way, on a Mac, you have
7180.691 -> to press out five and six for the square brackets. So in that same way is equals to new end,
7194.949 -> which is also you know in this primitive but now I say new ends because I'm not creating
7201.42 -> again, I'm not creating an end, I'm creating an object, an end airy object. Okay. And you
7212.519 -> can also see that it's an object, because when I put it here, and I'll put down the
7219.62 -> button, I see a number of methods that I can call. And we are this is actually not a method,
7226.479 -> this is an attribute, which I can directly access. So if you remember, I think you I
7233.679 -> said you should have your attributes private, this is accessible, it's not private. So this
7239.999 -> actually violates that rule. And yeah, so this is also a very old construct, and shows
7247.01 -> us one place where Java itself violates the rules of good object oriented design, but
7256.289 -> we just have to live with it anyway. So what this does, and we will use it very soon as
7262.969 -> it gives us the number of
7268.57 -> like the the length of the array than the like, in this case for, okay, if this is three
7277.05 -> year, why intz dot length should return three. And in a minute, you will see what we use
7288.6 -> it for, let's remove the end. Because I want to continue with a person's I want to feel
7297.559 -> this error. And the way this is done, again, we need to break it we need a lot of times
7304.539 -> is I say zero here, oh, I said person, of course this is wrong, we don't have a person,
7311.349 -> we have only this one object, persons. And the type is person airy. So it's not a person,
7322.719 -> it's a person airy object. Okay, and here we can say new capslock. person. What this
7332.98 -> does is it creates a new person object in memory, and puts a reference to this person,
7346.8 -> which is like a remote control a way to access the person into the array at position zero,
7356.909 -> which is the first position. Let's copy and paste that four times. Three, four. So position
7368.71 -> one, position two, position three. Okay. If I would say position four, what you don't
7380.03 -> have, I would again, get an error, which we'll talk about in detail when I introduce exceptions,
7387.659 -> which is again, a new big topic. Oh, okay. So, and when you have done that, what you
7396.21 -> can also do is, you can do crazy stuff like at position three, put the object that is
7413.36 -> in the person's array, at position, whatever, zero or one or whatever. Right, because whenever
7427.289 -> you write on every ad position, as it contains a person, it's exactly the same as if you
7437.04 -> would say, person, my person equals to a new person. So now I created a person. And this
7455.57 -> object was assigned to this variable to this reference variable. And can also do it like
7464.749 -> this. So now, this variable can access that object, as well as all there's title. Persons
7476.409 -> at position three, can also access the same object. So we have like two references to
7483.559 -> like remote controls to this one object. Yeah, and you can do also the opposite. You can
7493.17 -> say, my person equals to I don't know something Let's take two persons at position two, which
7506.409 -> means the object that is at this position, the reference to it will be assigned to the
7515.889 -> reference variable, my person. So this, my person object now
7523.619 -> should still be here, if I'm not wrong, I mean, this really gets confusing. So, I mean,
7529.07 -> I'm just explaining this so that you get the hang of it. But in reality, don't make it
7534.42 -> too complex, because you see, the more complex the more box packs you could introduce. Okay,
7541.51 -> so I hope you get the hang of it. Um, one more thing I might mention. Of course, no
7549.78 -> one forces you to, to really define to set an object at each position. Now, when I left
7557.969 -> out position one, this position is empty. So what does that mean? What we say is at
7566.51 -> position one, there is now because knowledge the word like for nothing. So there is nothing,
7574.869 -> there is no reference. If we access it, we get an exception, because Java will not know
7581.03 -> what to do. Okay. So that much about now, which we could also specifically do, by the
7590.02 -> way, we could also now it, it's called, the wrong button. Sorry. Yeah, so now you can
7610.639 -> also write, so this is like, put nothing here. Or, here, that would mean that the beginning,
7619.3 -> you have the new person object at position two, later on, you kind of throw the reference
7627.42 -> away. And if no reference exists to an object anymore. In Java, there is something called
7636.329 -> a garbage collector, I will talk specifically about the garbage collector very soon, in
7641.8 -> a specific lesson only about the garbage collector. So this one is smart, and we'll throw away
7647.34 -> that object, we'll clean up the memory. For us, this is really a cool feature of Java.
7652.349 -> In other languages like c++, this doesn't exist. And so you have to take care of cleaning
7658.78 -> up the memory by yourself, which is really not fun. So this is really one of the coolest
7665.09 -> features of Java. But anyway, I guess I'm going too far, let's make this more simple
7670.34 -> again. Because what I actually want to do is now I want to take the for loop, and combine
7680.86 -> that with the arrays and introduce the for each loop. But let's start easy, let's first
7687.07 -> of all, go to the regular for loop, take that put it here. And now we have let's remove
7704.979 -> all that all we have is an object of person array called persons. And we have this for
7718.42 -> loop that may create for whatever in this case persons. And so we will use that dynamically,
7732.07 -> so because I will change while we go through loop, we'll start with zero will be 123. So,
7743.709 -> we can say persons at position I this is really a cool thing now, because this means this
7753.979 -> one line Let me clean this up. So we create each time an object of type person and we
7766.539 -> put it into the array dynamically add position I. So this will on the fly fill the whole
7774.719 -> array with persons. And what we can also do is in a different loop but also just in the
7785.369 -> same loop. We can access this object by saying persons at position I and call some method
7794.059 -> on it like hello world that we created in an earlier lesson.
7803.05 -> Um, okay, I think I have not introduced you how to print something on the console. But
7811.519 -> maybe I should not do this now, because I guess I feel it gets confusing with all this
7817.119 -> stuff with Aries, but would be handy now to show you that this can print all the name
7823.389 -> of something for each person. But maybe I will do this in a later lesson. Okay, so just
7831.58 -> believe me, if we would print that, we could like print, hello, and then a person name
7839.86 -> for each person. Okay, this is already nice, but it gets nicer with a new loop for each
7847.67 -> loop. And this is not so much different from the regular for loop. It was introduced only
7856.13 -> in Java five. And this works like that. person, person, and then colon and then persons. So
7875.55 -> what this does is it automatically under the hood, it does everything that this for int
7888.599 -> it does. And now we can also access person dot HelloWorld. Of course, this requires because
7898.369 -> now we are using it. So this requires that this has already run? Um, let me think. Yeah,
7909.949 -> so this is only for like reading it. I'm fulfilling it. Now fulfilling it, I wouldn't use it.
7920.159 -> Because you have to specifically say what you want to do. Because if this is empty,
7927.51 -> this would also be empty. Okay, so but we can call person HelloWorld on it, and see
7934.519 -> how much nicer This is really condensed. So this is the for each loop. And the for each
7941.449 -> loop is like besides areas, there's also other constructs, other container types, which I'll
7950.849 -> also soon introduce, like collections really a cool topic, because they're even more powerful
7959.309 -> than just arrays. And so this for each loop also works with these collections, whatever
7968.09 -> that is. And it does whatever is required. And it also does it in a very smart way. So
7977.139 -> it's really smart to use that for each loop, not only because it's more condensed, but
7983.42 -> also because it's a performance and proper way of doing it. Because Java will assist
7989.489 -> you in doing it. Okay, so I think this pretty much wraps it Oh, no, there is I have I have
8000.03 -> a not sorry. I didn't know Have I told you. I think I promised and then I didn't do it.
8008.469 -> Person start length. This attribute which is not private, I think is public. Yes, should
8016.469 -> be public. This gives us dynamically the four. So I mean, here, we know that it's four. But
8023.619 -> just imagine what can also be yours, you have a method, which just gets a parameter. And
8031.709 -> you don't know its size. So you couldn't say four. And so this just dynamically takes the
8040.17 -> lengths that you need. And as you see in this loop, we don't even need it because this is
8047.94 -> dynamically calculated by Java for you. Which of course also that's the person that links
8055.219 -> in the background. At least this is what I assume. Okay, lesson 10. I would like to introduce
8063.59 -> you to enums. enums and Java represent an enum eration. So they enumerate something
8074.499 -> they were introduced in Java five. Now, I want to further extend my explanation about
8083.199 -> arrays because there is one more cool thing and it also makes it easier for us.
8089.929 -> We can actually even on the fly out five, aisle six, well this is autocompleted id he
8098.69 -> already PR Since two equals two, and now I do something new, I say curly brace, this
8112.09 -> is alt eight and nine on my Mac, by the way, and see, there is no red marking anymore.
8121.829 -> This actually also works. So what does that mean? This actually is a shortened form. And
8129.769 -> this says there should be an array. And we don't have to say, a specific size, because
8138.599 -> the size is automatically calculated, because the brackets are empty. This means empty size,
8146.599 -> that would be the same as saying zero, which, of course, doesn't make much sense. But just
8155.28 -> technically, it's possible. So and we cannot feel this array. So and we don't have to set
8165.58 -> the size, this gets calculated automatically. So I'm just copying. I can also put your mouth
8175.749 -> if I want to, I can also create a new object. My let's call it my personal Sorry, I can
8199.42 -> also just to show you what's possible define a variable of type person and then assign
8209.34 -> now to it or talked about now, which is like nothing and put it here. So this actually
8216.479 -> is the same like that. And I mean, I want you to also see this, what this does is it
8224.059 -> does not or what is not is, it does not like combine this array and that array. Instead,
8232.179 -> it says what you have at position zero of this array, which in our case, is this person
8240.05 -> object. Take the reference to add and the reference, copy it here, which means this
8252.75 -> position as well as later on, persons, zero. So later on, after we have defined the array,
8263.54 -> if we say, person to zero, that will be exactly the same as persons zero. Because they both
8274.189 -> point to this object in memory. All this is a bit complicated, I'm sorry, I hope you can
8281.149 -> follow me. And I will do a specific tutorial only on memory management and show you how
8287.8 -> things look in the memory. For now, I just hope you can follow if not, it's not so important.
8296.199 -> I mean, we're talking here about areas and what I want you to understand is like this
8302.479 -> is an array and this is a way of defining the array and the specifics about the memory
8309.479 -> Don't worry, we can go in more detail later. And you will you will understand this very
8316.069 -> soon I'm sure let's do the same trick again just with a different position. You can actually
8323.24 -> even do it twice or any number of times can take another one or it doesn't matter let's
8330.309 -> put this or we can also remove them now put it here. So yeah, you can do what and you
8337.949 -> can also do it on the fly you can say new person. Now there is no a little difference
8343.519 -> which is this object that defined here.
8349.59 -> It sits somewhere in the memory and might error a person's to has a reference to it
8358.349 -> outside of my array there is no one who has a reference to it, which we can change after
8367.63 -> we have defined it. We could also say I have not to count 0123456 I hope I have counted
8379.069 -> correctly if not imagined I had counted correctly. Okay, so I said six. So at position six. We
8390.12 -> cannot copy this reference and I can say my let's call it secret person. Let's call it
8400.97 -> just VIP. So my VIP, now I have a reference to it outside of the airy. So I created it
8415.06 -> dirty on the fly in this line together with the definition of this array. And later on,
8424.779 -> just for the sake of it, I assigned it a variable, which we then also can use and work on it
8432.05 -> like hello world, which you can also do is, say, person two at position six dot HelloWorld.
8442.5 -> So you can really work with the areas at specific positions, just as if you had a variable,
8450.67 -> it's exactly the same thing, even though it looks a bit awkward. But yeah, you get used
8456.22 -> to it. Okay, anyway, I think this is a very handy short definition. Because see how much
8462.819 -> shorter This is here we find just for persons and area for persons. And this was actually
8470.33 -> five lines. Now in just one line, we have defined an area of six positions, and we have
8477.41 -> filled it, and this is all in one line. And I think it's still readable. I mean, readability
8483.729 -> is the most important thing. So it's not about making something short. It's okay to make
8490.439 -> it short, if it keeps being readable, or if it's even more readable. That is okay. Okay.
8498.01 -> And I might also already introducing new stuff, I might also introduce you to final final
8506.399 -> is another variable modifier. We already talked about public and private and static, not final,
8517.31 -> something new final says are like locked in this variable, I don't want to anyone to poke
8525.89 -> around with that variable. So if I later after saying final, say this, Java will say Oh,
8537.101 -> no cannot assign a value to a final variable person to. So this is like a protection. As
8545.529 -> you see, I have to say final. So this is one more keyword. And this is one key more keyword
8553.229 -> to read. This is one more keyword to write. And so I would only do it if it makes sense
8559.529 -> for a reason. And if you have code that is just like here, two lines. I mean, while doing
8565.93 -> that, I would assume you know what you do, and you wouldn't like put this to now if you
8571.26 -> don't want to just one line later. Where this does make sense is if you have something like
8580.6 -> some constant values, some status values, for example, you could have a process a program
8587.85 -> that operates on some values. And then you want to remember the state that your processes
8593.689 -> in Okay, let me give you an example. So for this, we will again define an array, but we
8604.13 -> would do it in the class on the class level, and we would not do it for the objects, but
8611.949 -> for all objects of the class. I mean, and this, of course, is static. So static, we
8623.05 -> talked about this already means we have just one of this type for all the objects and no
8631.7 -> final. So static and final, they're really close friends, they are used together very
8637.01 -> often. And all that say string
8641.81 -> because I want to have a string. But actually I want to have a string array. And I said
8647.699 -> we said the braces right after it so that we see it's not a string. It's a string array
8657.189 -> and I call it my state values equals and then the curly braces again. And now I can say
8674.72 -> like pending, processing and processed. I could of course sorry, brackets missing. Add
8693.96 -> many more. Just for now. I have a short example. So this is what we could do. Something is
8702.87 -> wrong here. Yes, comma. Okay. And this means now, and I've also, oh, I did something and
8710.89 -> didn't explain you why I did that. So far, all the variables that we defined, we had
8716.85 -> in lowercase letters here, use the uppercase letters, and the underscore. This is also,
8724.109 -> again, a best practice, because like, we would use this static final, somewhere down here
8735.39 -> in the code. And you see, now the definition is gone, we don't see it anymore. And so that
8742.88 -> a programmer working in here and knows what you're working on here is static final. So
8749.68 -> I don't want you to touch it, I just want you to read it. There, therefore, we use the
8756.739 -> capital letters, and we separate them with the underscores so we don't use the camel
8762.529 -> case. And then we could, again, of course, iterate through these values.
8771.56 -> For
8773.56 -> so let's do the for each loop, say, stream, nice date, or just stayed. And then the curly
8788 -> braces again, we could say, if we're talking about if state has a certain volume, will
8808.5 -> actually we can't on a stream, say equals, this is not going to work properly. Because
8819.979 -> the equals is working on on on primitive values like int, and it's comparing the value that
8827.85 -> is directly in the variable. Oh, no, sorry, I'm going really complicated. Um, I don't
8835.92 -> know if I, if I'm making it too complicated. But now that I already started, I might as
8841.04 -> well continue what we have to say for if we want to compare two strings is equals. And
8850.149 -> so we can compare that to some other value. So we can do it, state equals and then a string,
8860.149 -> some other value. So this is some that equals is a method that is directly given to us from
8867.72 -> the string class that we haven't written, but we're using it from Java. And the says,
8873.979 -> compare this string to some other something, blah, blah, blah. Okay, if they're both the
8884.12 -> same, we could do something. And then we could do this a number of times for each value.
8896.14 -> So we had, as far as I remember, something like pending.
8901.021 -> And
8902.021 -> processing. And, of course, uppercase and lowercase make a difference here. And I think
8918.439 -> it was processed, but I mean, this is just an example. So it doesn't really matter that
8921.979 -> much. So, and then we could do some some something, colo method. And here we would call a second
8937.83 -> method and the third method and so on. Okay, but actually, this is a lot of code. So there
8952.529 -> is a faster way of doing that. And this is the switch statement that are also promised
8958.79 -> to talk about. And second. This string here is also not so nice, because you could change
8968.35 -> it any time. You could say in here, state equals to love. And, of course with just a
8981.22 -> few lines. I'm sure no one would ever do that or hope. But he mentioned we only have always
8990.75 -> see a very short examples. We could have like a very complicated code, hundreds, if not
8996.02 -> 1000s of lines and we could like call other methods For what is two other classes, and
9002.479 -> then if someone in some other class, like changes your value, you might not notice.
9009.42 -> And you don't want that. You want actually to have the value final. But this with final
9017.85 -> doesn't work, because final only protects the variable. It does not protect the value
9023.149 -> in here, which you can change any time. And for this, we have the email. The enum allows
9031.949 -> us to define an enumeration. Oh, okay, oh, let me just remove that. Or we can keep it
9039.609 -> for the time being. But let's jump over I have prepared here class will actually it
9046.84 -> will be our enum and it will not be a class. Okay, so far have just said package. For less
9054 -> than 10, I have set less than 10. And now, like you know it with the class, the class
9062.72 -> we would say public class, logging level,
9069.17 -> and
9070.17 -> races. But this time we're not doing a class, we're doing something a bit smaller. And this
9077.29 -> is the enum. And now this is obligatory, you have to start with the status definition.
9087.99 -> And it's not a string. So we don't need the double codes that we would have for the string.
9095.109 -> Now this is really a value and enumeration value, which we define as our email. So we
9106.12 -> like we like program our own type. And we already program the allowed values pending,
9115.66 -> had processing. I think we had processed. Yeah, and then we end
9127.54 -> here.
9128.54 -> And now we have defined an email. And we can use that. Let's go back to our test. Let's
9140.47 -> say logging level logging level, or let's call it
9153.97 -> my
9156.62 -> state equals to logging level pending. So this is a lot looking like static. And this
9169.18 -> is already how it came. Because now we can use these static values, we can also iterate
9178.85 -> over them. But we cannot change this. I mean, we cannot. Of course we can change it. But
9187.17 -> we can only change it to the allowed level allowed statuses that we have defined beforehand.
9194.989 -> We can set pending, processed and processing, the order is different but still the same.
9202.37 -> It can only have one of the three values. We could not say here. something crazy, because
9211.71 -> it's not a string, we can only use the values that we have defined here. And this is really
9217.72 -> helpful and makes also our code more readable. Now we can again, iterate through this enum.
9231.729 -> In this case, it's a bit more complicated actually, because we have to call a method,
9238.149 -> which is called values. This method will give us something like an array of all the allowed
9246.96 -> values in here, pending processing processed. And then, of course, there's not a string
9253.229 -> anymore. We say let me also remove that. And then we can do the same. Now, it's okay to
9269.56 -> say equals, see this works. Of course, it does not make sense. I mean, a string will
9276.13 -> never be equal to an enum, but it's perfectly fine. You may compare any object to another
9284.8 -> object. Of course it makes more sense to say equals dot for example, pending and then here,
9299.25 -> processing and prose So let's put processing.
9314.22 -> Here.
9317.92 -> Let's put processed. Okay? Um, but this is not so readable. And we don't need equals
9324.91 -> here. This is so cool. Actually, for an enum, we can do the comparison, just with the double
9334.65 -> equals, again, this does work. Because yada yada, yada. Java DOES MAGIC under the hood.
9345.85 -> So for now, just believe me it's working. Because this is not an object, this is a static
9356.22 -> value. Okay. Let's just remove this. Okay. Now, you see, I think it already got so much
9370.72 -> more readable and shorter. That However, there's still a shorter form, which is the switch
9377.939 -> statement. However, we will not do this today. We'll do this in the next tutorial, the switch
9386.729 -> statement, because I think otherwise, it's just too much for one tutorial. Now we talked
9391.95 -> about arrays repeated the for each loop. Yeah, and I introduced the enum, which has here
9402.17 -> this values method. Actually, there's much more an enum can do. Maybe I should show you
9410.25 -> this one. We can also add these brackets here. Let me do this for a moment. And now we can
9419.819 -> put values in here. So what is this going to be? I'm adding a constructor, which must
9430.36 -> be private. Let me check if it may be default, but I think not. Well, let's just try it seems
9443.59 -> to be working so far, but I'm sure it may not be public, yet. This is not working. So
9449.27 -> default, visibility seems to be okay. Even though I think it's a bit awkward. And now
9456.819 -> see this. It says the end cannot be applied to this constructor. Because so far the constructor
9466.47 -> is empty. Because what happens is, this is calling the constructor. So let's put in here,
9483.76 -> and now it's working. So having the constructor here, you might also see I was kind of lying
9492 -> to you, of course this is an object. But it's just that for specific reasons, I don't want
9498.1 -> to go in detail, we can still do the comparison with the double equals here. Okay, anyway,
9505.359 -> so we have a constructor. And let's now assign the eye to some other variable. Of course,
9514.39 -> you see, this doesn't make sense, assigning eye to eye and we have already had that. This
9520.109 -> thought I know, of course, I have to define it. And make let's make this private. So now
9529.65 -> it's working. I don't like it, I want this private, this is just what he would do. Okay.
9536.96 -> And then I mean, this, this depends what this means could be some code of some form. So
9545.01 -> let's have a method that returns public code. And this was returned. I. So this enormous,
9558.689 -> really powerful, is allows us in dismissing to have methods to return something. But it
9570.4 -> has these static values that we can iterate over and that we can only choose from. You
9577.27 -> could also think of a traffic like light with like red, yellow, and green. You can also
9584.131 -> of course have more values here any number.
9588.979 -> I'm actually you don't have to have the enum in its own file. You could directly on the
9595.05 -> fly define it in line in a class, I would just not recommend you to do saw, I mean,
9601.24 -> forever, you're all there is an exception and find out these exceptions for yourself.
9606.95 -> But in 99% of the cases, you would be better off having it in your own class. So yeah,
9617.02 -> there's much, much more actually that you can do with an enum. But I think we already
9624.05 -> this tutorials already a bit long. And I think I want you to digest this for now. We can
9631.56 -> further extend this anytime, of course. So that's the name. With its constructor and
9640.27 -> a public method returning the I, you can also have more parameters in here like a string.
9649.93 -> But if you're if one of them has it, and all of them have to have it, and every parameter
9656.54 -> appearing here has to appear in the constructor string, some string or let's just say s. You
9664.609 -> may use it but you don't have to use it. But usually, of course, you would use it as equals
9670.51 -> s. And then something.
9673.66 -> Yeah. Okay.
9675.39 -> So I think that's enough for now. And the next tutorial, I'm pretty sure I'm going to
9685.06 -> show you the switch statement. Because this is really cool for using for iterating over
9692.02 -> these enum values, then the code gets much shorter. I am going to talk about the switch
9701.31 -> statement, which is another conditional statement. Very similar to the if statement. However,
9710.24 -> first of all, let's recap what I showed you in the last episode. Actually, in the last
9716.52 -> one, I covered a lot of ground, I think, I hope this wasn't too fast for you. So let's
9723.05 -> shortly recap. First of all, I showed you this new way of defining an array. So like
9732.439 -> the traditional, let's call it, the traditional one was this one, where you just said, person,
9738.26 -> square brackets, persons equals to new person have four chairs with the size of four. So
9746.779 -> this can hold four elements starting at zero. Well, this needs a lot of lines. And this
9755.439 -> actually is the short form just with the curly braces opening and closing. And with a comma
9763.13 -> separated list, you can define an array. And my recommendation is end with a comma at the
9770.93 -> end, so that you can easily extend the array at a later time. Also, I introduced a new
9782.16 -> modifier for variables, a final modifier, the final modifier kind of protects a variable
9789.75 -> for us. So what it does is when in a later line, I try to assign something new. Like
9803.239 -> let's use this area on top here, this is not going to work cannot assign a value to final
9809.97 -> variable persons to also we can try to assign now, which is like emptying the variable will
9818.859 -> also not work. This is nice ish. However, I personally prefer to not use it locally
9828.239 -> in a method. But instead to use it for static final variables that are used read only and
9837.899 -> are defined at the top of the class usually like this here. I hadn't said any modifier.
9848.43 -> So this at the moment is default visibility. Usually I would prefer, like having it private.
9856.1 -> And if you need other classes accessing it, I mean, this is supposed to be read only.
9862.81 -> So it would be okayish have this public. However, even better. If you really want to focus on
9871.3 -> clean code like I do. You could provide a public method returning the string array.
9880.479 -> I don't know some name. Let's call it states. And in here, first of all, let me finish this
9898.25 -> we could copy this out Because with a copy if someone else, because the final, what it
9905.449 -> does protect is as I set the variable, what it does not protect as the content. So it's
9912.17 -> safer if return a copy of the array. And there's actually a helping Claus, which provides of
9921.399 -> Java, Java util, which provides some static methods and really have a look, see, we are
9930.93 -> going to use the copy. But there's also many, many more methods like here for doing a binary
9936.23 -> search and so on. This is really a big toolbox of methods that you can use, play around with
9943.81 -> them. And I might show some of them at a later time. For now let's use the copy off. And
9952.33 -> then we take the array. And we have to state the size, which again, we take dynamically,
9961.939 -> array dot length, yeah, we also talked about this. But this is dynamically returning the
9967.04 -> length of the array, which in this case is three, because the array has three elements.
9975.46 -> So this is really a nice way of
9977.41 -> generating clean code and returning this array. Also, I told you, it's all in capital letters
9986.56 -> and using the underscore and not written in camel case, because this symbolizes that is
9995.47 -> a static final. So in short, you just talk of a static final, because this is how you
10001.319 -> write it. Okay. Let's go back to the bottom. I'm sorry, so not much about the array. I
10014.1 -> also very shortly talked about equals, because I had to, because for two strings, like ABC.
10023.13 -> And you if you want to compare them, you cannot do so with the double equals. This is not
10033.229 -> going to work, even if it's the same. Because the problem is that this comparison does not
10041.64 -> compare objects. And this is an object, instead, it compares the reference variable. So equals
10051.03 -> does work for int three, and then you can say three equals I, because the three is actually
10063.02 -> in here. But if you have a string, let's make it null for now. In here is not the object
10083.189 -> or now in here is the reference, which is something you can think of something like
10091.55 -> a number also will be saved in here. And when you compare with the equals the two equal
10100.06 -> signs, then you compare this variable, which means you kind of compare if it's exactly
10109.97 -> the same. So what will be true is if you would say my string equal equal my string, but this
10121.779 -> usually is not what you want to say. And so when you compare two strings, you have to
10128.39 -> say equals talking about equals usually in one sentence, you should always also talk
10135.659 -> about the hashCode method. This is already a very advanced topic. So let me keep this
10142.01 -> very short for now. It just that if you create a new class, like I created the class person,
10151.529 -> it's often a good idea all depends, but you might want to implement the equals method
10159.779 -> in your person object so that you can compare two persons. But if you do, so, you also have
10166.92 -> to implement the hashCode method. What the hashCode method is and all the details I will
10174.27 -> explain at a later time. Okay, so that much about the string comparison. Oh, one more
10182.5 -> thing. I made this now because I also wanted to make a point. What I see very often is
10189.93 -> people that would write equals like this, my string dot equals and then a static value.
10197.76 -> This is not so nice, because as you see this Might be now. And then this throws an error.
10203.31 -> And of course, we don't like arrows. So instead, always put a value in the front, which will
10211.71 -> never be now, like this string here. I mean, this is ACB, as a roll down, it will never
10219.149 -> be now. So ACB equals now, we'll just return false. But now equals ACB will always throw
10233.63 -> an error. Okay. So let's stop here. Then, actually, the biggest part of the last lesson,
10247.18 -> we talked about enums, which I introduced, I created this enum here logging level, let's
10254.76 -> go to the class. So public enum logging level, I do find, actually, the name is a bit awkward.
10264.24 -> Because it's not a logging level, I was thinking of something like info, warning, and error.
10276.22 -> But then I decided we haven't talked about logging either. So I
10283.08 -> instead took pending processing process. So this would more be more like a status. But
10288.97 -> I don't know, let's leave the name for now is just a stupid example. So this is the IEM
10294.75 -> that are introduced, which is a bit similar to a class, but has some limitations, but
10300.97 -> also has some features a class does not have. So it allows us to define these static on,
10309.02 -> let's call them labels that we can act upon in our code. So we can say if something is
10316.84 -> pending, to this or that, so it's not only more readable, it's also more safe. enon was
10325.52 -> introduced was Java five. And before that, people would have taken numeric values, like
10333.6 -> if something is equal to not to zero, or one. But then already people started to calculate
10343.439 -> these values, this really gets nasty and problematic. And I'm not showing you this because I want
10349.98 -> you to do it in the proper way. And that is using an enum. So this is really a cool feature.
10357.989 -> You can you don't have to also introduce a constructor, if you want to have extra values
10364.479 -> for each enum value. And you can provide methods that would return these values, or do whatever
10374.87 -> you want, which are also like to make the code more readable, is I often provide I mean,
10382.5 -> not always. Whenever your code and you design your code, always think decisions through
10391.37 -> don't make a decision just because this is never smart. So if for whatever reason, then
10398.47 -> the code you work on, for example, the pending value, and you need to ask is it pending,
10405.54 -> that it might be nice to add this method is pending.
10415.771 -> And then you can say return this, which is the minimum and not only the minimum, but
10422.05 -> the current value of the enum equals equals pending. So if in the code, you have an enum
10436.069 -> let's do this modern level, still I call it stage or status equals logging level, not
10453.399 -> take processing. And then I could say if stayed Dodd is pending, which now would be false.
10461.659 -> Some code would have to be executed. But what I want you to know is only add such a method
10472.77 -> if you really need it. So it would not be wise to always by default, provide a method
10479.93 -> for each of these values.
10484.109 -> People usually get lazy and when they see something is working, they tend to just overuse
10493.26 -> stuff and they just like I might be I might need this. So let's just ask Method just because
10501.35 -> no, never do that. Never add a method just because always think think it through, I mean,
10510.64 -> code lives. And you can always change your code later. And you always can add a method
10515.11 -> later. So only edit when you need it. Let's say no, we don't need it. So we will also
10520.89 -> remove it. Okay, I think this pretty much rounds it up. For enums. Actually, they allow
10529.1 -> much more crazy stuff, like each value could have their own method implementations. I hardly
10536.51 -> ever use it. So let's not show this for now. I think this is pretty much what you need,
10545.899 -> usually. And now, let's finally actually go to the topic of this lesson, which is the
10552.76 -> switch statement. So I think I already a bit introduced it. In the last lesson, I said,
10558.68 -> we want to shorten this here. So the switch statement is also a conditional statement.
10565.729 -> And that's pretty much exactly the same, like these ifs here, just in a shortened form.
10572.1 -> Okay, I mean, don't think about the exact meaning here. This is just pseudocode. To
10580.38 -> explain you something. Okay, this time, I will not use a for loop, I will directly operate
10587.5 -> on this state here. And then we can instead of saying if we can say switch, so we are
10596.439 -> operating on that value here. And then, instead of if we're saying case, so if it's the case
10610.229 -> that the state has this or that volume, case pending. So this is the same as saying, If
10622.13 -> equals pending. If you just have one, then if it's of course shorter. But the switch
10629.72 -> statement is usually used when you iterate through all or most of them, because you have
10638.26 -> this extra of saying switch, but then the more states you have, the easier or shorter
10645.54 -> it will get processing case process. Now I mentioned we will have 100 different ones.
10656.11 -> Let's format this. Now what happens is, I haven't put any method here, and I have not
10664.949 -> put a break statement here. So actually, what would happen here, now let's put the same
10673.399 -> method call, I mean, I have not implemented the method, just the method. Imagine this
10677.659 -> was a method. So for all these three different states, while there is a common reason, we
10684.04 -> would call this method. If imagine we use a switch statement within a private method,
10692.93 -> you could also like return a value. So this depends, the difference with a return is when
10701.63 -> you return something from a method, of course, you also leave the method, while I'm pointing
10706.76 -> this out is because normally usually, what you want is you want to do something and it
10718.5 -> might not even return something like printing something on the console. And you would call
10725.52 -> one method. And in here, you would call a second method or do a second something calculation
10735.37 -> or so. And here a third one. Now it gets problematic if you forget the break, because what then
10744.09 -> happens is a fall through this will be cold, as well as that will be cold. So this is really
10751.75 -> a big source of bugs. Very, very dangerous. So in this case, never forget the break. And
10759.13 -> if sometimes you'll want to have them together because you want all the three of them for
10766.479 -> example or to to call a certain method it's recommended to leave a comment false through
10776.75 -> so that you tell the next program I know what happens and I did this on purpose.
10785.8 -> Okay.
10790.08 -> So that much about follow through. And you don't have to set all possible values. You
10799.141 -> can also leave One out, if nothing is found, in this case, we will just leave the switch
10804.52 -> statement, and we'll just not do anything. What you can also do is you always have the
10813.199 -> possibility to adding a default, which will be called if none of the other case statements
10820.79 -> apply. And then people sometimes say, I don't know, call default method. Well, he, I really
10835.649 -> want to warn you. And of course, again, we had fall through would have to say, break.
10841.62 -> This is not so wise. The problem is, I mean, code lives. And who stops the next colleague
10849.54 -> from extending your enum adding, for example, an error state here for some text, your colleague
10863.04 -> would just do this would not know there is this switch statement. And now, you implemented
10870.551 -> the switch statement, you didn't think of the error case. And the error case might need
10877.14 -> a specific behavior. But now you would also call this method for this new error flag.
10886.42 -> So usually, we don't want that. So what I recommend you for the default statement, either
10893.26 -> you don't use it, or even better use it. But here, you would throw an error. He say, I'm
10904.7 -> not doing this now, because I haven't talked about exceptions yet. We will do at a later
10911.01 -> time. But this is the place where you would have like an exceptional case. And the good
10919.13 -> thing about this is when someone extends your income, and someone forgets to extend also,
10929.47 -> one or more switch statements, you will see this, I mean, you might say Oh, but then my
10934.08 -> program crashes. And this is so nasty. Well, of course it is. But there is a rule in good
10941.27 -> design. And this is called fail early, it's always better to have a high severe back on
10948.899 -> production even. And to have to fix this within let's say, seconds or hours than to have a
10956.319 -> high severe bug. And no one notices it. Because if it would not throw an error, it might calculate
10965.18 -> something in a wrong way. But a client might notice this, let's say three months later,
10971.739 -> and then the problem will be so so much bigger. So when programming, sometimes you just have
10978.92 -> to be brave. I also see people that try to prevent arrows and like return something,
10985.979 -> for example, return now. So this is actually just, instead of accepting I have done something
10993.399 -> wrong. And let's fix it. This is just like putting the problem to the future and making
10999.149 -> it bigger. So I want you to be brave and throw exceptions and handle them then this is always
11007.05 -> better. I mean, I'm not saying you should program buggy code. Of course, we should try
11012.87 -> and concentrate. But sometimes bad things happen. And then it's always better to fail
11017.439 -> early. And so you you notice the problem and you can fix it. This is always better than
11025.479 -> hidden bucks. Okay. I hope you got my point.
11033.37 -> Okay,
11034.72 -> so also here. Well, if you have an exception, you don't need to break because an exception
11041.52 -> always leaves the block. But what is important to always have a break, or, like here, we
11051.27 -> don't have to break, leave a comment for through to tell the next programmer, I know what I'm
11058.109 -> doing, I want this and Tommy about warnings. One more thing. don't overuse switch. as well.
11068.109 -> don't overuse the if statements, these conditional statements, you'll see how much the code grows
11073.92 -> also in combination with for loops and see how many levels This adds to the code. You
11082.149 -> have to understand this switch. And then there is different case statements or default. And
11088.25 -> then inside of the case statement, there might be a method called and so on. So this really
11095.3 -> complicates the code. Same as with the if statement. You have to See what is the condition
11101.97 -> for me to enter this blog, ha, then this method is called, you might click to the method,
11108.49 -> you might want to check here. So this all makes it more complicated. And actually, this
11114.85 -> is also like a, let's call it a relic from the past. This is what we call procedural
11120.96 -> code. Because it's like a procedure, it's like really, this makes you thinking like
11129.54 -> a machine, like a machine would switch a state. What's a case this dude that case this do
11136.67 -> that. But humans usually don't, they don't think like this. And the cool thing about
11142.62 -> object oriented programming is that the object oriented programming is very close to how
11147.89 -> humans think. And this allows you to like talk to business guys. And this really makes
11154.26 -> your code nice. And switch is not object oriented. There are some cases, corner cases where you,
11156.96 -> it might just be easy and fast to use it, but don't over use it. Really, I mean, there
11157.96 -> are people that would have maybe hundreds of lines in here, this is just crazy, really
11158.96 -> hard to read. This is also why I had here method, this is not yet perfect, but still
11159.96 -> better than just having huge switch statements. There are techniques, for example, just shortly,
11160.96 -> you could have an object representing the pending state, and an object representing
11161.96 -> the process state and so on. So they are at once techniques of how to prevent a switch
11162.96 -> statement. And it always depends, like, what's better? for very small switch statements?
11163.96 -> It might be okay. Just remember, they are a bit like evil and should not be overused.
11164.96 -> Okay, I hope I have added enough warnings of switch. And if statements. This is also
11165.96 -> one reason why I'm only introducing it now. Because I really want you to become a object
11166.96 -> oriented programmer. I will further continue talking about the switch statement. So I told
11167.96 -> you that it's used to iterate over the different values of enums enums, which are also told
11168.96 -> you were introduced with Java five, um, before that, the switch statement also existed, but
11169.96 -> you had to emulate enums. And the way this was done was by using int values. Um, this
11170.96 -> is not so optimal. And this is also why enums were introduced, because they're more typesafe.
11171.96 -> And I would also not recommend you to show to us ins in the switch statement. I think
11172.96 -> I already said that in the last episode. I even didn't want to show you but now I realized
11173.96 -> I think I should still show you. Because you will see it sooner or later. And so that you
11174.96 -> can understand code of others, I will show you, but just try to avoid it. Um, okay, anyway,
11175.96 -> with that warning, I'll show you. And now let's give it some name. Um, I call it my
11176.96 -> state.
11177.96 -> And now I give it some number 42. I mean, this is just an example. And could mean whatever.
11178.96 -> And this is already your problem. 42. What does it mean? Does it mean pending? Does it
11179.96 -> mean processed? How do we know? Well, to make it a bit better, they then introduce static
11180.96 -> final values, which I'll do right now also. So let's go to the top and on the class level.
11181.96 -> Let's introduce now this is a method. Let's do it here. Private static, final, let's call
11182.96 -> it processed, processed. Forgot to give it the type of the primitive type int and this
11183.96 -> is the 42. And we could also have pending so this is like a trick. But you see this
11184.96 -> is also where a normal use case From. So this is also why in enums, we usually use the capital
11185.96 -> letters. Okay, because it's a constant value that will not be changed. So now I will give
11186.96 -> this the name of pending cross cutting, let's call this processing and processed. Now, of
11187.96 -> course, we need different values, that could be a 40, then this could be a 41. And this
11188.96 -> would be a 42. And now I can copy that, go back down. And then I can say, my state oops,
11189.96 -> equals pending. And pending now, I think it was 41. And then I can now switch on the end.
11190.96 -> And now this is funny before depending was of the logging level. But Java is smart enough
11191.96 -> to realize, now we're not iterating on the enum anymore, but on the int and s, we also
11192.96 -> have processed there, as we have named it, it still works. Of course, I mean, just to
11193.96 -> show you, this is just because we named the variable the variable. So if we processing
11194.96 -> is not used, called is something then of course, we will have to use this something below here,
11195.96 -> because now you see pending as red, because cannot resolve symbol pending. Because we're
11196.96 -> not on the interim anymore. We only int something, the problem is that my status an end. So no
11197.96 -> one guarantees us that only these three values that we want to use are used. anyone at any
11198.96 -> time could say my state equals to 300. And then it will not be something it will not
11199.96 -> be processed, it will end up in the default. See. And this is also a reason why here you
11200.96 -> should not have regular code, but throw an exception instead. Which we'll talk about
11201.96 -> very soon, I hope. Okay, so anyway, this is what you can do with an int. And since since
11202.96 -> Java seven, I mean, at the time I'm doing this video we are, we have Java eight. So
11203.96 -> when they introduce Java seven, you now can also use strings on my string, give it a name,
11204.96 -> called also my string. Okay, not used yet. and copy it. And now we can also switch on
11205.96 -> strings. Of course, something doesn't work because it's not a string, it's an int. So
11206.96 -> now, I can of course start to use. Well, for example, the empty string or a blank string.
11207.96 -> I can use, again, something in lowercase letters. And of course, here also I can do a column
11208.96 -> labels, which then of course, are private, static, final string. And now I call it I
11209.96 -> don't know. I haven't used pending because here of change it to something.
11210.96 -> And I will call this pending. But it could also be any anything any string 42 Yeah, whatever.
11211.96 -> So of course, using that label, I'm only using one now I think you got the point on too far.
11212.96 -> Okay, so now, that label I can also use pending in here. Um, you might remember from the last
11213.96 -> session I talked about the fall through, which is you don't have a brief statement here.
11214.96 -> So if it's this case statement will be the same one as that statement, which will both
11215.96 -> then call this method and then break is called, which will leave the switch statement. So
11216.96 -> the court will continue online 122. The default is at the end. It could also by the way, be
11217.96 -> anywhere else. For example at the top which would not be also a full Through. So if it's
11218.96 -> not pending or something, or pending is, I don't even know anymore what we put there,
11219.96 -> I think it was 42. So, in this case, all the threes different cases would call a method,
11220.96 -> which he or we could have some other method. As always, I'm not going to implement the
11221.96 -> method. And then we could say break so that for the default, just this method would be
11222.96 -> called. And then we would end up here, leaving the statement and ending in Wait, where's,
11223.96 -> see, if I put my cursor at the beginning of the switch statement of the curly brace, I
11224.96 -> don't really see it ends up here. Because if you have a method, and this is also a reason
11225.96 -> why you should keep your methods very short. You see, the method seems to go until line
11226.96 -> 141. And this method now got so big, that it's really hard to see where it starts and
11227.96 -> where it ends. So yeah, I can't say it often enough, keep your methods short, I would really
11228.96 -> keep them at one to 10 lines at most. I'm, I'm really happy. If I'm able to keep them
11229.96 -> at one to three lines. Some say I'm really on my might be too strict on that. But you
11230.96 -> will very soon see the fruits of your methods are, the easier it is to understand them.
11231.96 -> And also, the easier it will be to reuse them. Yeah. Okay. But now back to the topic of the
11232.96 -> switch statement. So you can use it with strings. As of Java seven, you can use it with enums,
11233.96 -> like I showed you in the last episode, you can use it with ins and any other number types.
11234.96 -> So far, I've only showed you int. I'm actually there are others. I'm not sure if I should
11235.96 -> really talk about the others, because they're hardly ever used. They've just the range of
11236.96 -> the number ranges just a bit smaller. In 99% of the cases you would use it because I mean,
11237.96 -> it doesn't really matter these days. how large the ranges. So it is always fine. I mean,
11238.96 -> not but maybe I still show you. For example, this could be a bite. But now this is already
11239.96 -> not working anymore. Why is it because I have changed it on the string. Let's fix that.
11240.96 -> So the bite here. This is just smaller than the end. For example, if you put 3000 here,
11241.96 -> it says this is incompatible, because it's an int because it's too small. Um, yeah, but
11242.96 -> the three works. But I really don't want to go further in details. If you're interested,
11243.96 -> you can also read this on the internet. Because all you really need encode in 99% of the cases
11244.96 -> is the end. So okay, I think this pretty much rounds up the switch statement.
11245.96 -> So you can use it with a string and an int Oh, there's one data type, which I might show
11246.96 -> you. That's also interesting. And this is a car. A car is a string of a length of one,
11247.96 -> while it's not a string, but it's very similar. So it uses these single quotes instead of
11248.96 -> the double quotes. So if I'm using the double quotes, it's automatically a string. And this
11249.96 -> doesn't work anymore. Here it says incompatible types required car found string with a single
11250.96 -> quotes, it's a car. So it's a character of length one one single character. Of course,
11251.96 -> it could also be a or b. But it cannot be longer than one character. Because then it's
11252.96 -> not a character anymore. Too many characters in character literal. Okay, so we can also
11253.96 -> iterate over characters. This sometimes might be interesting. if you for example, parsing
11254.96 -> a string or what is parsing it's have a string five string equals something. And now you
11255.96 -> can take each single character, because a string is actually a combination of several
11256.96 -> characters. And then you can iterate over each character. And then you can switch over
11257.96 -> this. Um, yeah. This you might need at a later time. So I've also introduced car now and
11258.96 -> told you there are other number types. I would like to introduce you to logging. Well, actually,
11259.96 -> what is logging?
11260.96 -> Hmm.
11261.96 -> Well, first of all, let's tell you what my idea is. I have prepared this little test
11262.96 -> here. I have prepared a little class car service. I wanted to process this string, BMW, or Beamer.
11263.96 -> And in the class, this class so far is empty. My idea is I want to be notified in some way,
11264.96 -> like a print out on the console into a file, that database or maybe even an email or something.
11265.96 -> So I want to be notified in some way I want to monitor if someone calls this method, so
11266.96 -> that I, like later on, can go through all the course and can see if something happened.
11267.96 -> For example, if my system was hacked, I could go through a file and see what time what happened.
11268.96 -> And then yeah, analyze it. So that's the idea. And the way this is done, is by logging. So
11269.96 -> actually, logging for me this word was a bit weird. So I looked it up. Wikipedia is your
11270.96 -> friend. So let's do this. So logging is called logging for a ship's logbook. A logbook? Is
11271.96 -> this thing here, you know, of ancient times when the captain in his cabin was making plans,
11272.96 -> and was writing down at what time he was at which place and what speed the ship was going
11273.96 -> in that direction. So this is a logbook. So this is already like monitoring the state
11274.96 -> of the ship. And but still I was asking, why is the logbook called logbook. While this
11275.96 -> article here have a read just very fast going through it says it. The term originally referred
11276.96 -> to a book for recording readings from the ship lock. So what is a chip lock, let's click
11277.96 -> and ship block, also called common lock shaped lock or just lock is a navigation tool for
11278.96 -> marinas used to estimate the speed of a vessel through water. Interesting, so there's also
11279.96 -> an image. So this thing here is the shape lock from the end of the ship. And here's
11280.96 -> even a picture they were throwing out the ship luck and in equal distances they were
11281.96 -> not in this line in this long line and the faster the boat goes the faster Of course,
11282.96 -> this chip block is taken away. And by measuring the time they could measure the speed and
11283.96 -> this was done given by knots. So this is still why speed of a ship is given in knots even
11284.96 -> today. So here it says ship log and associated kit, the real of lock line is clearly seen.
11285.96 -> So it seems I don't know this, but I just guess it that it's called lock, because this
11286.96 -> really looks like a lock, like, like a three strong because it's this huge block. So I
11287.96 -> would guess that this is why it's called lock. So, this is why the ship lock is called ship
11288.96 -> lock. And this is why the act of doing like writing something into the lock is called
11289.96 -> logging. And as a programmer, you can think of yourself of like the captain of the code.
11290.96 -> And as such when you want to write on events that happen while your program is running,
11291.96 -> you are logging and this is what we are going to do today. So how is logging done in 2015
11292.96 -> and 15 Well, currently you would use SL for J. This is a framework for logging. I mean,
11293.96 -> of course, you could write your own logging. But this is a lot of work to make it
11294.96 -> work properly. And this has been done already for you. You can just use this framework.
11295.96 -> Well, actually, this is only for Sade, well, FSH is a design pattern that we haven't talked
11296.96 -> about. So two, we could say it like, allows you to use here is how it's used. you import
11297.96 -> the code, Ork SL for j logger and logger factory. And then, within your code, you say logger,
11298.96 -> logger, logger, factory, get logger. give it the name of the class. And you can use
11299.96 -> it with different implementation of logging. Because for many, many years, the most prominent
11300.96 -> logging framework was log for J. Well, this has changed. At the moment, you should probably
11301.96 -> better use lockback because it's a more powerful, and it's author is I don't can't pronounce
11302.96 -> it properly. But I try shakey Goku, and this is the same guy that actually implemented
11303.96 -> love for J. So he continued with lockback, because he wanted to make logging even better.
11304.96 -> So today, therefore, we use SL for j in combination with lockback. Because using this sl for j
11305.96 -> visade. will allow us at a later time, if there is a new logging framework introduced
11306.96 -> that is even better than lockback, we can easily each switch to the new framework without
11307.96 -> having to change the code. Because the code doesn't use the code of lock bag. It uses
11308.96 -> SL for J. So how is this done? Let's jump into the code. Okay, so first of all, I told
11309.96 -> you, I'm using Maven for the configuration of the dependencies. So here I've configured
11310.96 -> to use the dependency org. So for j, and lockback, classic. This is actually the implementation
11311.96 -> of SL for J. And this is the core code of lockback. So you need these three dependencies
11312.96 -> to get logging in your code. Okay. And then you should also have in source main resources,
11313.96 -> our file called lockback, dot XML. Here, you can define different things. Well, first of
11314.96 -> all, you can say, how should you lock where should you lock, in my case, I say, with giving
11315.96 -> this class console appender, that will result that my code is locked to the console directly.
11316.96 -> There are also other appenders, or other implementations for logging. So we can also look to the file
11317.96 -> to the database, to email. And if there's something you want to have locked to that
11318.96 -> doesn't exist. You can also implement your own implementation, like I don't know, maybe
11319.96 -> like logging into Twitter in some way, if that makes sense to you. Okay, and this is
11320.96 -> the pattern, how, when a message is written, in this case, to the console, it should look
11321.96 -> like so the patterns has, I mean, you have to read the documentation for details, but
11322.96 -> it's like, give me the time when this event occurred, the threat the logging level, because
11323.96 -> the logging level is like a mechanism. It's like a grouping mechanism. You can have different
11324.96 -> levels of logging. This is like a signal of the severity of the problem. Because debug
11325.96 -> is probably for debugging purposes, use that sparsely.
11326.96 -> Then there is a logging level info and error. So error you would use if there is an error
11327.96 -> in your code, info for general information, and debug, just for you know, some debug information.
11328.96 -> But this really should be used partly because for debugging. You can also use a debugger,
11329.96 -> like in your ID, or we haven't talked about debuggers either. But yeah, just for now.
11330.96 -> Now there are different levels. So, in your code, you can then say, I want to lock this
11331.96 -> on level debug. And here I have defined the package name. And I say here, this, when I'm
11332.96 -> when there's some logging of a class that is of this package, then I want to log it,
11333.96 -> if it's debug, I could to also put your error, that would mean only if it's an error, log
11334.96 -> it. Or I could put here info, that would mean only login, if it's info. info, of course,
11335.96 -> also, it would include arrows, because this is like more. So debug includes all includes
11336.96 -> debug, info and error, but error would only log messages that are locked on level error.
11337.96 -> So you see, this is really makes it more flexible. And you can even have here different loggers
11338.96 -> for different packages. So we could also copy this and, like have here a different package
11339.96 -> like Java course two, and so on. And we could then have this on the one on debug and the
11340.96 -> other one on error. So this is really flexible and can be changed. And here, this is the
11341.96 -> root level. So like, generally lock on info level just for this package. Log on debug
11342.96 -> level, this is what it means. Okay, this was only very short. There's much more information,
11343.96 -> of course, on the internet. But first of all, maybe a week go to our test. And we add the
11344.96 -> login details here into car service, I put it. So first of all, I need to import a few.
11345.96 -> Like we saw just before in the documentation here you see my ID, he already helps me SL
11346.96 -> for j because I said we want to import only SL for j and SL for j by itselves. knows that
11347.96 -> it should be used, I should use lockback because it will find the dependency of log back classic.
11348.96 -> This one here. So SL for j is really smart. So we don't have to tell it. Okay, so we say
11349.96 -> SL for j lager and we say import org SL for j.no. Just one dot logger factory. Okay, a
11350.96 -> factory, by the way, is another design pattern. At a later time, I will also do probably a
11351.96 -> course, only on design patterns. design patterns are like best practices on how you should
11352.96 -> program code. And when you know what a factory is, you will directly know what this thing
11353.96 -> he does. Okay, more about design patterns at a later time. Anyway, this is what we have
11354.96 -> to do. And now in our class, we would probably say private final lager. Let's call it log,
11355.96 -> because it's all log. And then we say logger factory. Get logger. So what this factory
11356.96 -> does like a factory. This is why it's called a factory. It gives us a logger. And we don't
11357.96 -> know how is it created on the fly is a longer reused, this is a smart thing and does all
11358.96 -> the necessary work for us. Now, we should still give it the name of this class. Because
11359.96 -> this will be used car service class. That sorry, in our log back XML XML file which
11360.96 -> is in source main resources. As I showed you, I mean, here we have a package, but we can
11361.96 -> even extend that and lock only for specific classes.
11362.96 -> So this is the test and this is the service. Okay, so this is how you generally find a
11363.96 -> logger. Now, in here, you can now use it log. Well actually, it's not static. I might just
11364.96 -> as well have this in lowercase log dot and in former times, like With log for j, some
11365.96 -> of you might know it, you would usually say like this is debug enabled. If it's debug
11366.96 -> enabled, only then log something, log dot debug. And now I could say, processing, car
11367.96 -> plus input. So the input given in our case, BMW, this will create a string, and then this
11368.96 -> will be concatenated. together. And all this will be locked, if the debug level isn't able,
11369.96 -> at the time when the code runs, which at the moment, as far as I remember, it is. So we
11370.96 -> can activate and deactivate this. The reason why we need this line, I mean, we could also
11371.96 -> do it without just like this. But this is not so good. I mean, in case of a string,
11372.96 -> it's not so bad. I mean, all that would happen is this string, and that string would be put
11373.96 -> together. But you mentioned the string could be really of in almost infinitive lengths.
11374.96 -> So Java in the background for you, this concatenation might take a lot of time, especially if we
11375.96 -> have some very big object here, that might internally consists of other objects, and
11376.96 -> so on. So this creation of a string, as stupid as this might sound can take a lot of time.
11377.96 -> And, of course, I mean, here, we just have a very stupid small program with just one
11378.96 -> debug line. But of course, you would log maybe not on debug, but on info or something, or
11379.96 -> error, maybe a lot of stuff in your application. And like, you could think of 1000s users concurrently
11380.96 -> calling this method. And then if this only takes, like, I don't know, 200 milliseconds,
11381.96 -> 200 milliseconds might not seem a lot of time. But if this is done 1000s of times, then this
11382.96 -> can really consume a lot of performance of your server or PC. And so we would only like
11383.96 -> to concatenate the string, prepare the string for logging, if this will actually be logged,
11384.96 -> because if we say log info, but then the logging framework finds out, well, this does not have
11385.96 -> to be locked, it would have to throw away all the strings that were concatenated. So
11386.96 -> we had done this without any need. And so this we would want to prevent. And this is
11387.96 -> why in lock for j, you would do it like is debug enable debug. Or you can also say is
11388.96 -> info enabled is error enabled, and so on, is info enabled. Now it's locked for j and
11389.96 -> SL for j However, there's actually even a smarter way. Because you see, this was three
11390.96 -> lines of code. And this is you can put here, these curly braces. And then you don't have
11391.96 -> to say plus, but you say comma. So within the framework, the framework decides, well,
11392.96 -> the user in this case, this would be us wants to log on debug, first of all check is debug
11393.96 -> enabled for this class. And if so, only then take this input converted to a string if it's
11394.96 -> not a string already, and only then concatenate this string with this string. So this is really
11395.96 -> a smart thing now. Okay, so another enough of talking. Let's try this out. Okay, let's
11396.96 -> check. We have the input given from the process method. And we want to say processing car,
11397.96 -> and then in our test,
11398.96 -> we put here BMW or Beemer. Okay, so let's also recheck our configuration file, log back
11399.96 -> XML. We said comarca spiele. java course, level is debug and the root level is info.
11400.96 -> So if we no log on debug, within this package, and comarca spiele Java course this is the
11401.96 -> package. This means we should log it. Okay, let's run the test.
11402.96 -> Okay, so something happened. Process finished with exit code zero. And here you see
11403.96 -> at this time, which is now on level debug from this class from this package car service,
11404.96 -> we wrote processing car column BMW. So this was logged. Okay. Now, let's try to deactivate
11405.96 -> it. Let's say we only want to log on error level for this package. Let's execute it again.
11406.96 -> Run. Process finished. On top, this is all information from lockback. When it gets configured?
11407.96 -> Well, you see there is no BMW locked. Okay, let's change that. We could say the root level
11408.96 -> is debug. And we could say or, let's have this on, let's have this on debug. And now
11409.96 -> let's change the package. For example, Java course two. Well, we're not in Java course
11410.96 -> too. But we are in the package called Marco spiele Java course, which means we should
11411.96 -> log on the root level, which is debug. So I would expect the test to log again. Let's
11412.96 -> try it run. And there you see it already. debug, call marks will Java course card service,
11413.96 -> processing car BMW. So this seems to be working. Okay. And here, again, you see the pattern.
11414.96 -> This is what's compared. Here, we have the minus that we have set here, minus and then
11415.96 -> the message, and then this n, I think this is for new line, so that when there's the
11416.96 -> next lowing a new line will be attached. Okay. And this is the console appender. So this
11417.96 -> is the console that we can see here, in our ID, if you would run this from the console
11418.96 -> with like, for example, a terminal here, you would only see it within the terminal. Okay.
11419.96 -> So let's maybe go back to the documentation, and check this a bit more. Okay, so here,
11420.96 -> you see, and you should really use read it. Now, I'm just really fast going through it,
11421.96 -> you can read it typical usage pattern for this is pretty much what we did. And here
11422.96 -> with the curly braces, we locked on debug. Well, we could also change maybe, after reading
11423.96 -> the documentation, let's also log on Arrow and info that you see this also works. And
11424.96 -> here, it's also explained what I showed you binding with a logging framework at deployment
11425.96 -> time. So it says here lockback Classic, you need this. If you want lockback as the logging
11426.96 -> framework, which we used. Yeah, so really have a look here and read this. And here you
11427.96 -> see the dependencies, this is what we did. You can also here you see you can use it with
11428.96 -> lock for J. But lockback, as I showed you is like the successor for for j and there
11429.96 -> is also documentation of lockback which should also have a look, by the way again. So the
11430.96 -> author is chechi Goku, and others. Yeah, so see they they worked on these frameworks for
11431.96 -> 12 years. I mean, you wouldn't want to work for 12 years and there are at least these
11432.96 -> three guys. So this is a lot of work and brain power that has gone in that logging framework,
11433.96 -> which you can use just by configuring it in your code. Okay. Yeah, and you see we have
11434.96 -> also done it import org. So for j logger, and logger factory, here they made it static
11435.96 -> which is also fine.
11436.96 -> And here they log on info level. Okay. And here's the configuration file. This I have
11437.96 -> also showed you Okay, and there are also other appenders I think I have put them here. Let's
11438.96 -> see, oh, there's also the explanation you can do it with logger is debug enabled, like
11439.96 -> I showed you, or you see better alternative with the curly braces. Because this is I mean,
11440.96 -> basically, it's the same thing. But this is three lines. And this like clutters your code
11441.96 -> easily. And this is only one line. So it's nicer. Because logging, I mean, it's important
11442.96 -> that you want to focus on the domain, on the business that you work in. And logging should
11443.96 -> just not be in the way of your business. The business is important thing. And logging is
11444.96 -> important. Yes. But it's like not as important as the business. So really have a look and
11445.96 -> go through all the documentation. It really explains this really nicely. Okay. So now,
11446.96 -> I promised you, and then we should finish already. We can also log on different levels,
11447.96 -> like you can see error. Well, as, as far as I remember, we're still on debug level. And
11448.96 -> error is included within debug, because debug is the finest logging level. So this should
11449.96 -> also look just here, I would expect to see not debug but error. So that we know, well,
11450.96 -> we would use this in case an error occurred. So that we can differentiate how important
11451.96 -> some logging event is. Now you see an error. So we would write, oh, some error occurred?
11452.96 -> Well, in our case, this is not an error. So we should also not log in on error. What else
11453.96 -> can we use? Let's see, we should also able to log this on worn for a warning. So you
11454.96 -> would use a warning for something very close to an error. But where no one has to manually
11455.96 -> interfere, then you could use one logging level. And info you would use for example,
11456.96 -> when your server starts when your program starts up, just so that the user of the program
11457.96 -> knows everything is fine. And like here, this is an info level. So we are informed lockback
11458.96 -> is just starting up. Okay. And here you see now we have one level processing car BMW.
11459.96 -> So now that we're using one level, let's put the root level to error. And now the package
11460.96 -> that we're not using as well as the root level are both on error. And it's printed to standard
11461.96 -> out, which is this appender the console appender which is this console here. Okay, and now,
11462.96 -> I would not expect to see any logging. And you see, just the info from doc back at the
11463.96 -> logging is gone. Which again, we can change. If we say here worn or let's change this back.
11464.96 -> Here also we can say worn. So now we should see the one locked again. Yeah, there it is.
11465.96 -> Okay, well, as I Oh, I think I promised you to show you the appenders and I have not.
11466.96 -> So let's finally go back to Firefox. And see I had it somewhere here found? employee No,
11467.96 -> this is not yet. But it's somewhere appenders. There, this is easy. Chapter four appenders
11468.96 -> is really a good read. So I'm really fast going over it. So outputstream appender, console.
11469.96 -> appender. This one we used. File append Not this one is of course very important to write
11470.96 -> into a file and go through it read it. So there you can set the encoding and all these
11471.96 -> parameters. And there are some really cool appenders like rolling file appender Well,
11472.96 -> that means that new files are created when like the file is has a certain size or like
11473.96 -> for every day we could have a new file. This is important for servers because otherwise
11474.96 -> if we're always writing into the same file, this very soon can reach
11475.96 -> tons of gigabytes. Yeah. And therefore on production for a server you very often use
11476.96 -> a rolling file appender so that thing is really important. Somewhere there should also be
11477.96 -> ODP appender that is supposed to To log into a database directly, really cool thing. And
11478.96 -> this is really very easy to be configured. Where is it, it was down somewhere. Somewhere,
11479.96 -> somewhere somewhere, maybe I've already missed it, there is an SMTP appender, I would assume
11480.96 -> from the name that is used for logging, sending an email when there is a lock event. And somewhere,
11481.96 -> that was also the DB appender. I know it is SMTP appender, blah, blah, blah, blah, ebf.
11482.96 -> There it is. So this allows you to directly write into a database, and you see all these
11483.96 -> databases are supported. So this is really great stuff, and so on, I mean, this page
11484.96 -> still goes on. So there are really a lot of appenders out of the box that you can use.
11485.96 -> And as I said, you can always extend it and write your own appender, which allows you
11486.96 -> to lock to any other source. So that pretty much rounds up logging. I would like to show
11487.96 -> you the main method of Java. The main method, as the name implies, is the method that is
11488.96 -> used to start a program initially. However, as this course, is done in test driven style,
11489.96 -> or TDD In short, so far, we actually never used it. Because we start programming by writing
11490.96 -> a test. And so far, we use the test to execute our code. Well, actually, as you might have
11491.96 -> guessed, at some time, when you're done with development, you would want to run the program.
11492.96 -> And for this, you will need a class that has a main method. So how does this main method
11493.96 -> look? Well, it's not so different from any other method. It is a public method, so that
11494.96 -> it can be started from outside of the class. It is a static method. Because we want to
11495.96 -> run the method without having an instance without having an object of car selector.
11496.96 -> Because the class car selector in this case here is only the like executer the, like the
11497.96 -> frame that we use to start our program. And therefore, I mean, we also only need, we don't
11498.96 -> need further instances of this class. And this is why the method is static has to be
11499.96 -> static by definition. The method is void because it doesn't return anything. And the name must
11500.96 -> be made. So that it can be found by Java. By the way, I might notice shortly, I always
11501.96 -> say noticed by Java. Well, actually, what I mean is noticed by the compiler, because
11502.96 -> the compiler will compile the program to bring it into an executable form. Well, compiler
11503.96 -> is a big topic, there are huge books, if not even libraries about compilers that you can
11504.96 -> so you could even study compilers. So I tried to prevent to keep you away from that topic.
11505.96 -> But maybe, if I keep talking about Java, executing something, I maybe should now say compiler,
11506.96 -> and at a later time, I might do a dedicated session on my bit of compiler details. So
11507.96 -> that you will know more about compilers. So anyway.
11508.96 -> Okay, so back to the public static void Main method. Now we add the brackets, but actually,
11509.96 -> they have to contain something, because when we start our main method, we want to be able
11510.96 -> to give it arguments that the program might need to run and this is obligatory. So these
11511.96 -> are arguments that come as input as strings, but as there can be a number of strings. This
11512.96 -> is an area here. So square brackets, and all the name of the string array. You can use
11513.96 -> any name, people usually would set here arcs. This is what you would see in documentation
11514.96 -> I usually prefer arguments, because this is more readable. Okay. And then of course, as
11515.96 -> always, for our method, you would have the curly braces, the opening and the closing
11516.96 -> curly brace. Um, yeah. And that's already it for the main method. Now, let's leave it
11517.96 -> empty for a moment. And now when you compile this class here, on the console using a terminal,
11518.96 -> you can execute this Java class. And it will then call this main method automatically.
11519.96 -> So this is the place where you like set up your whole program. In the last episode, I
11520.96 -> created a car service. So we can use this in here, car service car service. But I mean,
11521.96 -> technically, it also works to run just the empty main method, it will just not do anything.
11522.96 -> So let me directly say new car service, no title car service.
11523.96 -> Okay.
11524.96 -> And then you can call the method, car service dot process. Yeah, remember, and this requires
11525.96 -> an input. By the way, just to show you what is possible in Java. You can also do all this
11526.96 -> on the fly, you can say new car service thought process, the only difference is that, you
11527.96 -> will then just call the method, and you will not have any variable to access the core service.
11528.96 -> If you don't need it, that might be fine. Well, the only thing missing now is a string.
11529.96 -> And I mean, we could use any string here, like PVC. But I mean, to make it a bit more
11530.96 -> interesting, we could no, take the string array. And as as this as this is an array.
11531.96 -> Of course, we need a for each loop, which are also introduced already. So let's say
11532.96 -> string argument for one, colon arguments. So this is iterating through our array, that
11533.96 -> will be given to us. When the program runs at runtime, opening curly brace again, closing
11534.96 -> curly brace.
11535.96 -> Okay.
11536.96 -> That was formatting it. Okay, and now I can take that argument. And so dynamically call
11537.96 -> the process method, dynamically creating an object. While this is always creating a new
11538.96 -> object. So I mean, I wanted to show you that this is possible. But of course, it would
11539.96 -> probably be smarter to just create one object and then put a reference on this object. So
11540.96 -> this would be from the performance perspective, probably faster. But it's really hard to talk
11541.96 -> about performance. Because the compiler these days is really smart. It might, it often recognizes
11542.96 -> stuff. And when before a while it compiles it can optimize your code. So talking about
11543.96 -> performance is a topic by itself. And you would usually test for performance just by
11544.96 -> saying this will be fast or slow. You can hardly do but again, performance. Yeah, I
11545.96 -> could also do a course only on performance really a big topic. Um, yeah. So now I created
11546.96 -> an instance of car service. And in the main method, I have this for each loop. And then
11547.96 -> for each argument that is given to our main method when the program is run, we call the
11548.96 -> car service. Now let's execute this. Because now we can run this without actually a test.
11549.96 -> Well, I mean, in this episode, I want to show you the main method. But I mean, what I said
11550.96 -> still holds true, you should always start programming with writing a test. But anyway,
11551.96 -> see, now I have a run car, see, like the domain. And I can execute the main method directly.
11552.96 -> Here. This shows me the console directly in my ID. Well, it seems like there's nothing
11553.96 -> printed. This could either be because in the class, remember, we had the logging, the logging
11554.96 -> could be deactivated, but so far, I remember it's still active. It should log on worn at
11555.96 -> the moment. Well, the reason this doesn't work. Anything is a different reason. And
11556.96 -> the reason is, well, we didn't give our program any arguments. So I mean, this is running,
11557.96 -> this is not throwing any exceptions. By the way, we will talk about exceptions very soon.
11558.96 -> But it's empty. So the for loop will actually not be executed at all.
11559.96 -> When the program is run, so we will directly jump to line nine or 10, just after it so
11560.96 -> the program will directly exit. But we can change this easily using our ID, I can click
11561.96 -> on Run, and I say Edit configurations. And here, I can configure how my main class see
11562.96 -> this also contains always the full package name. So how this is run, I can give it some
11563.96 -> program arguments. So on the console, that would be car selector, and then whitespace,
11564.96 -> and then the program arguments. So let me put here a few car names. BMW, or shi. C,
11565.96 -> Mercedes. Yeah. And then Okay. And then let me run the main method again. And now you
11566.96 -> see, we have three warning loggings processing car BMW processing card pushy, and processing
11567.96 -> commerce. seeders. Yeah. So that's the main method.
11568.96 -> Um,
11569.96 -> one more thing just really slightly mentioned. What is also possible and not many people
11570.96 -> know is you can do this. Now what does that mean? And see, all the code is still working.
11571.96 -> This thing with the three dots here is called a foul arcs. Like a variable argument parameter,
11572.96 -> which means when this is defined like this, the code, the method that would call our main
11573.96 -> method, while in this case, it's directly started by the virtual machine itself. This
11574.96 -> would have the ability to directly put in strings that will be converted automatically
11575.96 -> by the compiler to an array. So this is very close to an array, but it's like just more
11576.96 -> convenient for whoever calls that method.
11577.96 -> Just so that you have seen this would also be possible. The question is, does it make
11578.96 -> sense because, well, Normally, you would not call the main method directly.
11579.96 -> So if you don't call the main method directly, it doesn't make a difference. But of course,
11580.96 -> you can write a test and you can call the method directly. And in this case, it would
11581.96 -> make a difference because you could directly call the method which just one string? Yeah,
11582.96 -> but let me talk about Fox arguments at a later time. Okay, so let's re add. Let's make this
11583.96 -> an array again.
11584.96 -> Okay.
11585.96 -> So now, string array arguments. Okay. So that much about the main method, now, maybe a bit
11586.96 -> of background knowledge for you. So I don't know if my Java course is actually the first
11587.96 -> Java course you ever listened to? I guess in most cases, you would probably already
11588.96 -> have heard another course or read the book about Java. And in this case, you might not
11589.96 -> directly understand why didn't talk about the main methods so far. I mean, this is Episode
11590.96 -> 14 already. So let me give you the reason for this. Because I really decided to do so
11591.96 -> specifically. Because this is really a main a main decision for me. Okay, so the reason
11592.96 -> is, first of all, I think, in the very first lesson, when you have never heard about Java,
11593.96 -> and its keywords, it's hard to directly be confronted with public static, void. This
11594.96 -> is just the name of the method would be okay, but public static void, and then even an array.
11595.96 -> All all this stuff for a very first lesson in Java is a bit much I think. Now in our
11596.96 -> episode 14, you should by now know what public means What static means what what means. And
11597.96 -> we have also talked about arrays. So I hope that by now, you can easily follow my explanations,
11598.96 -> and you understand what all this means. Okay? And then second, also, this is a static method.
11599.96 -> And I told you, I think various times, Java is an object oriented language, where you
11600.96 -> usually focus on creating objects, but static, this method is not object oriented. There's
11601.96 -> just one version of this method. I mean, of course, it might make sense. But, yeah, as
11602.96 -> you should try to avoid static, wherever possible, I think showing you a static method in the
11603.96 -> very first Java lesson might lead you to the wrong conclusions. Yeah. And then also, next
11604.96 -> reason is, um, even though, I mean, the main method is, on the one hand, very important,
11605.96 -> because you use it to actually execute your program to actually get your program running.
11606.96 -> For any program at hand, you would have only one main method. And usually programs would
11607.96 -> consists of hundreds, if not 1000s, of classes. And just one main method. And last but not
11608.96 -> least, I mean, this counts for Java, se. But if you like program a server application,
11609.96 -> what you usually do is you don't re implement all the server code. But you would like use,
11610.96 -> for example, an open source server implemented in Java, for example, Tomcat, and such a server,
11611.96 -> I mean, has already been implemented for you. And so you use that as like an infrastructure,
11612.96 -> even though it's software. And so the Java code you write will run within that Java software
11613.96 -> infrastructure. And therefore, when you program code for server, you usually don't write even
11614.96 -> a main method at all. So, for example, in my case, I mean, I have programmed in Java
11615.96 -> for pretty much 14 years now. But I have maybe, I don't know, 10 times 20 times, well, definitely
11616.96 -> less than 100 times I have programmed a main method, while I have programmed really 1000s
11617.96 -> of classes, I'm sure. So the main method is not so important. And, yeah, so we started
11618.96 -> with writing a test anyway. So you are also able to run your code, at least for testing
11619.96 -> without the main method. Of course, I mean, the tests. For example, let's look at this
11620.96 -> one. This one is based on the framework j unit. And j unit by itself is a Java program.
11621.96 -> So j unit does have a main method. Of course it does. But you don't see it. All you see
11622.96 -> is the test methods that we write. And his test method, they like plug into the whole
11623.96 -> j unit mechanism, bet so we don't have to write the main method. I mean, this is why
11624.96 -> just using a framework, like j unit is so handy, because it saves us from writing our
11625.96 -> own main method. Yeah, and I promise you, you can actually even execute even the main
11626.96 -> method as if it was a regular method. Now here you see I have prepared that he is an
11627.96 -> array of string arguments, BMW and Porsche. So this static method is called with the given
11628.96 -> arguments as execute the test. And yeah, you see, this works just as well processing car
11629.96 -> BMW processing car pushy.
11630.96 -> And,
11631.96 -> as one last thing, maybe you'll see I could change the signature of the method. Like I
11632.96 -> could say the method returns some end. In this case, just as an example 42 I could even
11633.96 -> not make it static anymore. I can change it in any way. This is okay as it's a Java method,
11634.96 -> it just will not be recognized as a regular main method. So this will will not allow us
11635.96 -> to execute it as a Java program, but our test can still execute it as it was before. I mean,
11636.96 -> now this is returning something. So we don't use the return value, but we could in return
11637.96 -> use equals to Yeah. So you see, it's really, we're calling the main method returning something.
11638.96 -> And we can still call it from the test. But if we want this to be really a main method
11639.96 -> that will allow us to start a program, then the signature must look like this. Okay, so
11640.96 -> I think that's pretty much all I can tell you about the main method, I'm really happy
11641.96 -> that we were finally able to have a look at the main methods. So now, with the 14 episodes
11642.96 -> that I've done so far, I think this course now really has gone quite far, by now you
11643.96 -> should really know quite a lot about Java, and should be able to write your own programs
11644.96 -> by now, I will, of course, add a few more things. But By now, you should really be able
11645.96 -> to write your own small programs. I would like to talk about Exception Handling in Java.
11646.96 -> So first of all, let's have a look at some theory, and some background information about
11647.96 -> exception handling. And then later on, we will as always, directly jump into my ID.
11648.96 -> And I'll show you how to do Exception Handling in practice. Okay, so as you see, this is
11649.96 -> the Wikipedia article about exception handling. So first of all, let's have a short look at
11650.96 -> the definition. So here this article says exception handling is the process of responding
11651.96 -> to the occurrence during computation of exceptions, and animals or exceptional conditions requiring
11652.96 -> special processing. Okay, let's stop here. Let's digest that. So, um, I think what is
11653.96 -> very important is two things. First of all, it is about exceptional conditions. Because
11654.96 -> in my opinion, this is something that many programmers get wrong. I mean, an exception
11655.96 -> is called an exception, because it should handle exceptional conditions. So the question
11656.96 -> really is what is an exceptional condition. While in my opinion, an exceptional condition
11657.96 -> is something that really, as the name implies, only happens exceptionally which means only
11658.96 -> really rarely, only in very specific situations. And those situations are an animal's soul.
11659.96 -> So for example, programming errors, you when your program, you introduce the buck, you
11660.96 -> forgot to like you have an array, and you have one field that is empty. And I talked
11661.96 -> about that means it has a field that is set to now. And then when you try to access this
11662.96 -> field, that, for example, can throw a so called null pointer exception. Well, that would be
11663.96 -> really an exceptional case, which you wouldn't have guessed it would happen. And yeah, that
11664.96 -> would be one reason for an exception. So exception handling is really the, as it says here process
11665.96 -> of responding to the occurrence of exceptions. So something exceptional happens. And then
11666.96 -> we need
11667.96 -> a way to react on that to handle that. Some special processing, which is not the normal
11668.96 -> program flow. But the cool thing about Yeah, this also sent here, often changing the normal
11669.96 -> flow of program execution. because ideally, we want like a central place that handles
11670.96 -> the exceptions. And so we want to leave the normal program flow and we want to just specifically
11671.96 -> take care of this exceptional case. Okay. And here continues, it is provided by specialized
11672.96 -> programming languages, which gives us a hint, it is not provided by all programming languages.
11673.96 -> Well, let's have a look at the history which will tell us. Yeah, software Exception Handling
11674.96 -> developed in Lisp in the 1960s and 1970s. Well, I think the first programming language
11675.96 -> was invented by Conrad Sousa in, like 1943, or something. So you see, it took a while
11676.96 -> until they finally came up with the idea of exception handling, that something like this
11677.96 -> is really necessary. And, well, maybe a bit more about the history and Java, because again,
11678.96 -> with Java, there was some something new introduced, and that is checked exceptions. Before all
11679.96 -> exceptions were unchecked, which means any line of code can throw any kind of exception.
11680.96 -> And there is no mechanism that forces you to handle it, if you don't handle it. That,
11681.96 -> for example, causes the program to stop. And well, therefore, as soon as exceptions were
11682.96 -> like introduced, many times nasty things happened. And so when they invented Java in like 1995,
11683.96 -> or something, they thought, well, maybe we should do this a bit better. And well, first
11684.96 -> of all, let's have a look. Check the exceptions here. The designers of Java device checked
11685.96 -> exceptions, which are a special set of exceptions
11686.96 -> here.
11687.96 -> Okay, and to make it short, so what's the difference about checked exceptions, he is
11688.96 -> also already an example and i o exception, which happens when there is a problem with
11689.96 -> an IO operation input output operation. The difference with checked exceptions in Java
11690.96 -> is they must be declared explicitly in the method signature, or be handled. If you don't
11691.96 -> do that, you will directly get a compile time error, which means you're not able to even
11692.96 -> compile your program. I looked at actually up I think it's here it's quite interesting.
11693.96 -> Like how it came with the checked exceptions. The Java programming language introduces the
11694.96 -> concept of checked exceptions, checked exceptions must be handled in a method, or the method
11695.96 -> must declare the exception in our throws clause. Now it continues, I think here it's even more
11696.96 -> interesting. According to Anvil wrath, who was there at the beginning, the credit for
11697.96 -> the Java exception scheme should mostly go to Jim Waldo. And then they go on. And here
11698.96 -> after some consideration, Java was retooled to have checked exceptions, only those exceptions
11699.96 -> for which there was no recovery, or reflect application errors would be unchecked, and
11700.96 -> the world was safe again. Well, so they thought. Now, in the meantime, it's 2015, which just
11701.96 -> like 20 years later, and it turns out, that was not so smart. Because the problem is,
11702.96 -> and this is also why stated at the beginning, maybe we should go back to the very top. Exception
11703.96 -> handling is the process of blah, blah, blah, blah, blah, blah, blah, exceptional conditions.
11704.96 -> And this is the important part. Because they had the idea to have still unchecked exceptions
11705.96 -> for something like programmer arrows for something that is, as the name implies, exceptional,
11706.96 -> and to have the checked exceptions for everything else. But now I ask, why have checked exceptions
11707.96 -> for these cases that can be handled? Why not? If you if you can handle a specific situation,
11708.96 -> why not that instead validating that situation? And not at all throwing an exception? And
11709.96 -> also, and now maybe we should already jump into the ad because I guess it goes too far.
11710.96 -> on too much theory. Let's directly jump into the code. So yeah, so here you see An email
11711.96 -> that I've written car stayed with a different states driving, waiting and parking. I've
11712.96 -> written this public static from method that converts a string to a car state using a switch
11713.96 -> statement. I told you, in a previous episode, that since Java seven, it's possible to use
11714.96 -> a switch inside air to use a string inside a switch. And I want you not to do it. This
11715.96 -> still applies. But in this case, I assume that we are getting input from the console.
11716.96 -> And input from the user coming from the console cannot be an enum must be a string. So this
11717.96 -> is all I mean, for every rule, there is an exception. So this is an exception to the
11718.96 -> rule, which is here, we do have a switch, switching on a string. But now here, we have
11719.96 -> the default case. And I also told you, I wouldn't, I will only throw exceptions and the default
11720.96 -> case, so that it cannot happen, that someone adds a new state. And this new state would
11721.96 -> then be handled by the default case without anyone noticing, to have the fail early principle.
11722.96 -> And so I told you to throw an exception, but I didn't show you yet. While we can do this
11723.96 -> now, and this is quite easy. You can just say throw new exception, because an exception
11724.96 -> in Java is just an A class. Like almost any other class, while it has some specific
11725.96 -> methods and stuff, but at least it's an it's a class and we create, we can create objects
11726.96 -> from it. Now, you know, you already see a checked exception and action. And you see
11727.96 -> how the compiler already wants me unhandled exception. java. lang exception. So this is
11728.96 -> also the package java. lang exception. And, yeah, this is the number one checked exception.
11729.96 -> Don't ask me why it's called exception. If it's actually a checked exception, something
11730.96 -> like a checked exception. I mean, the name was not used within Java Lang. So you just
11731.96 -> have to know that this exception is a checked exception. And on top, the default, unchecked
11732.96 -> exception is an is a runtime exception. This sorry, also not my fault. This also you have
11733.96 -> to know I mean, runtime makes sense, because something that goes wrong at runtime. And
11734.96 -> so you would normally use a runtime exception for things where you don't know how to handle
11735.96 -> them directly. And the idea was, as I said before, to have checked exceptions, for cases
11736.96 -> where you know how to deal with them. But as I said, if you know how to deal with them,
11737.96 -> why not dealing with them without throwing an exception beforehand, using validation?
11738.96 -> But anyway, let's continue. So how can we fix that compile time error? One reason is,
11739.96 -> at exception to method signature, let's use our ID to help us and here it adds throws
11740.96 -> exception. Now you see the compile time error is gone. Nothing is read anymore, it seems
11741.96 -> like we fixed the problem. So we told the Java compiler, we know there is a checked
11742.96 -> exception. We just don't care. The color should take care of it. And now I have this car service
11743.96 -> class here. And I made it to use the static from method that I implemented. And you see
11744.96 -> now this class has the problem. Okay, again, let's do the same thing. Add exception to
11745.96 -> method signature. Okay. And I guess you know, where this leads to. Now we are the main method.
11746.96 -> And again, we have the same problem. Well, we can notate This is all the wrong stuff.
11747.96 -> Seems like we're on the wrong line. But yeah, I can no here appears add exception to method
11748.96 -> signature. Okay. Well, sorry, I'm just lazy. I could of course have written that myself.
11749.96 -> But whenever you write something, you have the chance of introducing a typo like this.
11750.96 -> So whenever possible, I prefer to have my ID he helped me and to have code written automatically
11751.96 -> by the ID that can save From introducing bugs with typos for example. Okay, so now this
11752.96 -> will be, like fixed. But now the question is, what did it help us, we have here throws
11753.96 -> exception, we have here throws exception, and we have here throws exception. So three
11754.96 -> times we had to add this throws exception. And only because Java tells us this is a checked
11755.96 -> exception. But besides, we didn't handle it, which means what will happen when I execute
11756.96 -> the code, and the default case is chosen, the exception will be thrown, it will be Bob,
11757.96 -> it will bubble up to the top to the main method. And as the main method doesn't handle it,
11758.96 -> the program will stop. And we will see the exception stack trace. Yeah, same thing we
11759.96 -> could do, for example, with a runtime exception, throw new runtime exception. Also in in both
11760.96 -> cases, you can and you should add some meaningful message that tells us why the exception happened.
11761.96 -> So let's say on state, and concatenate that with a given state. Oh, okay. So now, I can
11762.96 -> still keep it. But I don't have to. It's not obligatory anymore, because this is not a
11763.96 -> checked exception anymore.
11764.96 -> Same here, I can remove all these. And this. So now I have exactly the same code. The only
11765.96 -> differences I mean, I'm not handling the exception, that my method signature doesn't get any longer.
11766.96 -> Because he mentioned again, I'm always bringing this example, you have a huge program of hundreds
11767.96 -> of classes. And as soon as one method has that throws exception, this is really contagious,
11768.96 -> which means another method, sooner or later, we'll use the method that says throws exception,
11769.96 -> will then also have to say throws exception, this method again will be used. And sooner
11770.96 -> or later, you will have that throws exception in each and every method. And then it doesn't
11771.96 -> help us at all. It just makes the code more wordy, let's say. And yeah, it's not really
11772.96 -> meaningful. So anyway, let's first of all provoke that exception that we see how such
11773.96 -> as exception stacktrace looks like for this to happen. I have to call the main method.
11774.96 -> And I have to give it some some argument that we don't know yet. Okay, let's go here run.
11775.96 -> I think I have prepared something already. Edit configuration. And yeah, flying parking,
11776.96 -> driving, driving ABCD E, F, G, because also, I wanted to show you, I mean, I've introduced
11777.96 -> the main method only in the prior episode. So here we have some valid states, as well
11778.96 -> as some invalid states. Also in lowercase letters, it will should be invalid. And as
11779.96 -> we're iterating through the arguments and a for each loop, we should see. Well, let's
11780.96 -> just let's just do it. actually still have to run it. And let's have a look what happens.
11781.96 -> Okay, so you see, the exception happened. I'm on state flying. So I would assume the
11782.96 -> reason is that this happened for the very first time the first argument was already
11783.96 -> flying. So this is our program stopped. This is the reason because it's not handled. Now,
11784.96 -> we could also handle it to show you what's the difference. Now the question is where
11785.96 -> to handle such an exception? Well, always as early as possible, like at the class that
11786.96 -> can do something about the exception. In our case, um, I just defined that. In the case
11787.96 -> that I get a wrong argument from from when the program is called as an argument. I want
11788.96 -> this to be printed to the console, so that the user knows which means I mean, I wanted
11789.96 -> to be printed here, which means the first place where I can handle this exception is
11790.96 -> only here on the very top. And so there is this new construct, I say, Troy, which is
11791.96 -> like telling the compiler, I know something evil can happen. And I just want to try it.
11792.96 -> But now I can say catch. And I can catch this runtime exception. Usually, I mean, I don't
11793.96 -> like really short variable names, because they're not readable. But in the case of an
11794.96 -> exception, because an exception log is always very, very short. The default is to call the
11795.96 -> exception for with E, for exception. And I think here, this exception is okay. Because
11796.96 -> we don't want too much with the exception, and the block will be so small that everyone
11797.96 -> knows the E is for the exception. Okay, so curly braces. And now we can do various things.
11798.96 -> First of all, we could say e dot print stack trace.
11799.96 -> Well, this is actually exactly what we have here. This is the stack trace, the stack,
11800.96 -> you can think of as a list of all the methods that were called in reverse order. So here
11801.96 -> you see main process from can also jump there. I mean, this is not, this doesn't hold true
11802.96 -> anymore, because I've no edits code. But at the time, we executed this code, and the exception
11803.96 -> was thrown. This told us exactly in each class, where the exception happened while he is still
11804.96 -> true. And he also, but in my car selector, I have adjusted the code, by the way about
11805.96 -> this. The fact that I've adjusted the code, also, when you sometimes have a stack trace,
11806.96 -> and you need to analyze where it came from, this is really often happening, that the code
11807.96 -> that is running on production is older than the code that you develop on, because of course
11808.96 -> development continues. And then you can only find out the exact place where the exception
11809.96 -> happened, if you keep the exact same code that you have running on production. Yeah,
11810.96 -> but this only really, I don't want to go into more details. Um, this would be a topic on
11811.96 -> its own, again, about revision control. And this is really a huge topic. But yeah, just
11812.96 -> that, you know, the stack trace is really helpful if and only if you have exactly the
11813.96 -> same code that was implemented at the time this code was running. I mean, that they're
11814.96 -> both in sync. Okay, so print sectors here wouldn't make sense, because in this case,
11815.96 -> it's just the default anyway. But this can be used. And it's often used to lock for example,
11816.96 -> in I don't know, was it Episode 13? I think I talked about logging. And so when you want
11817.96 -> to log an exception, you can do it like this. This is usually how you do it. Well, I haven't
11818.96 -> got the log class here. And I don't want to do log error or log one you will say and this
11819.96 -> depends error only when there is something that has to be done. For example, a database
11820.96 -> that has to be restarted. In other cases, probably one is also okay. Okay, message is
11821.96 -> the string that I added into the constructor of the exception
11822.96 -> here.
11823.96 -> And I have removed the stack trace, because this is actually done inside of the log object,
11824.96 -> which I want to add. Now. If you want to know more about logging, have a look at my episode
11825.96 -> 13 where I explain logging in detail. Okay, so logging is one thing we can do. But in
11826.96 -> this case, I say I don't want to log it, I want to directly printed on the console. I
11827.96 -> think also in the episode about logging, I want you not to do it always to prefer logging.
11828.96 -> But in this case, let's assume we have just a very small program only be used to run something
11829.96 -> from the console. And in this case, it can be okay to just say system error dot Clinton.
11830.96 -> Which I also wanted to show you once print ln For new line, and here, then I can say
11831.96 -> dot get message. Or I can also say e dot print stack trace, which doesn't make sense, because
11832.96 -> we already have that. So to alter the behavior, let's do this. Okay, let's run it again. Now,
11833.96 -> you see something else. You see the program hasn't stopped. But instead we see unknown
11834.96 -> state flying Unknown, Unknown state driving an unknown state abcdefg. Yeah, so all the
11835.96 -> invalid states were printed out. Without we don't even see the exception anymore. And
11836.96 -> it's red, because I use system error Clinton, I could also use out print on because this
11837.96 -> is a special channel, only for errors. And this is printing in general. See, now it's
11838.96 -> white. But really, I still warn you don't overuse system out or system error print on.
11839.96 -> Because Yeah, you can't configure it like you can configure logging. So in 99% of the
11840.96 -> cases, using a logger is better. Anyway. So let's have a look at the code now and think
11841.96 -> is this really nice. Now, we have a for loop, we have a try, we have a catch. Um, you see
11842.96 -> a lot of different hierarchies and a lot of different levels that we have to understand.
11843.96 -> And this is something I really don't like, this makes the code quite complicated. Okay,
11844.96 -> so this is something you should try to prevent. And, anyway, I can also, alternatively show
11845.96 -> you, we could do exactly the same.
11846.96 -> If this was throwing an exception. The only difference is that if we're not handling it,
11847.96 -> we have to add the signature
11848.96 -> throws throws. So yeah. Maybe also, I should now show you the alternative. If If we don't
11849.96 -> want to add the method signature, the exception signature, we can directly in here, say catch
11850.96 -> and then handle it. And then I mean, handling an exception does not necessarily always mean
11851.96 -> you have to print it, I mean, printing, it doesn't really solve the exception, it might
11852.96 -> be even better to really have a method that does something about the exception, and which
11853.96 -> I call no handle the exception. The only problem with that is, and I'm not implementing the
11854.96 -> method now. And this is what I said before, I'm the case that you're really able to do
11855.96 -> something about the exception, which in this case, I mean, what could we do, if the user
11856.96 -> typed in something wrong? There's not much we can do? Well, there is one thing, we could
11857.96 -> for example, ask the user to type in to fix the state he typed in. But this we couldn't
11858.96 -> handle here. So again, if we want to, like ask the user to do something about it, I would
11859.96 -> instead validate
11860.96 -> the state. So let's remove all that. Let's for the time being I add the runtime exception,
11861.96 -> but I will change it very soon, because now instead, I want a validation at it. And this
11862.96 -> can be done in the following way. I remove all that trycatch instead, I say Valley date
11863.96 -> argument and now I can implement that method. Create method validate my ad he helps me again.
11864.96 -> I'm
11865.96 -> now well actually I want to say is valid with a Boolean returned. Okay. Now, you see this
11866.96 -> is also interesting, by the way about the main method because this method is static.
11867.96 -> Also, this Method automatically esthetic. So because when this method is static, a static
11868.96 -> method cannot call a method that is not static, because an instance method can only be called
11869.96 -> when there is an instance. But for the main method, we won't create any instance, of course
11870.96 -> selector. So for this reason this is static, and it's private, because we don't need to
11871.96 -> call it from outside, only the main method will call it. Now how can we validate it?
11872.96 -> Well, for example, we could use a method directly provided to us from the enum class, and that
11873.96 -> is value of this is not implemented by us. But it's implemented, like automatically,
11874.96 -> when they implemented when they invented the enum and Java, this is one method that you
11875.96 -> get for free. So this will directly try to convert your string to an enum. So here I
11876.96 -> can say car stayed. Cars date. So this actually does exactly the same thing. Like our switch
11877.96 -> did. So actually, we won't need it anymore. Very soon. The difference to the method that
11878.96 -> I implemented is or bill, I did it actually also like this, when the conversion doesn't
11879.96 -> work, this will throw a runtime exception, I think, an in because they have different
11880.96 -> types of runtime exceptions. And I think it will be an illegal argument exception to tell
11881.96 -> us the argument that you are giving that you are giving to me, sorry, is invalid. But still,
11882.96 -> it's a runtime exception. So and because this will throw an exception, we have to add the
11883.96 -> try catch block here, because we want to handle this. Try catch. And then I say runtime exception
11884.96 -> he or I hope I'm right. I can directly say in valid on
11885.96 -> invalid
11886.96 -> human exemption, there it is. I think that should be the one if not, we will see it because
11887.96 -> the exception will not be caught. Okay, and then here, we can just return false without
11888.96 -> logging anything.
11889.96 -> Now,
11890.96 -> let's see, this is the wrong one, because we can't catch an exception that is never
11891.96 -> thrown. So invalid. Let's see what the lead catch. Now this is not what I want. Maybe
11892.96 -> it's an invalid state exception. Yeah, this works. So see, this is also how you see this
11893.96 -> value off may throw an invalid state exception if the argument given is unknown, in case
11894.96 -> of, for example, flying driving ABC. Okay.
11895.96 -> And
11896.96 -> to be honest,
11897.96 -> um,
11898.96 -> I think this is also not optimal, that we only have this value off method, I think it
11899.96 -> would be much, much nicer if the IEM base class will directly provide is valid method
11900.96 -> just returning true and false. But again, seems like the inventors of Java doesn't didn't
11901.96 -> listen to my opinion, crap, just making a stupid joke.
11902.96 -> So for this reason, we do have the exception, but we are able to convert it. So because
11903.96 -> we converting it directly. The exception doesn't be doesn't pollute our whole system, let's
11904.96 -> say like this. And we can now say here, return true. Which we could also put at the end of
11905.96 -> the method. This is exactly the same. Yeah. So wherever you have it. So and this is also
11906.96 -> the jump. I mean, imagine you could have lots of other code like system out print owns and
11907.96 -> just print something. So you could have many, many more lines. That would do lots of stuff.
11908.96 -> Let's just copy and paste that to show you many more lines. We could even reassign car
11909.96 -> state to something else. Let's just say now. So what happens if This line of code doesn't
11910.96 -> work out, because the argument is unknown, for example, flying. When the code is executed,
11911.96 -> the execution will jump from here, directly into the catch. So this is leaving the normal
11912.96 -> program flow, the normal program flow would go from line 2122 2324 25, and so on. But
11913.96 -> here we're jumping from line 21. To line 28. Yeah, and this is helpful, because, for example,
11914.96 -> imagine we have done this several times, for examples here. And there, even maybe in sub
11915.96 -> methods, then we have just one catch, that would handle all these different places where
11916.96 -> an invalid state exception could happen. That's the idea of exception handling. Okay, just
11917.96 -> to give you some more details, actually, I don't even need that. So I would remove it.
11918.96 -> We're only like, abusing that volume of method to have the information. Is that valid or
11919.96 -> not? Okay, and now I can react on that. I can say if not valid, or I can say only, like,
11920.96 -> only process it if it's valid. Yeah, maybe let's do this. Because you saw already hold
11921.96 -> the invalid states are printed. Now let's do something else. Let's only process valid
11922.96 -> arguments. The question, of course, is, does that make sense? Now we wouldn't even realize
11923.96 -> we have a problem in our code. So maybe we should also say else. Print that we have problem.
11924.96 -> system error dot print. ln M. invalid. argument given? Or let's say ignoring, ignoring invalid
11925.96 -> argument. So this, by the way, whenever you log, I think I'm not repeating myself, because
11926.96 -> I already talked about logging, but I can't say it often enough. Always add as many arguments
11927.96 -> as possible, so that whoever is responsible for a problem knows why this happens. Otherwise,
11928.96 -> yeah, it's really hard to understand why something doesn't work out. Oh, no, we still have an
11929.96 -> illegal argument exception. How is that? I don't know. And this is interesting, because
11930.96 -> we can now check. Like, this is what I told you. It's in car state. There's, ah, we still
11931.96 -> have the from it seems like we call it somewhere. But no, I'm wrong. Because the session line
11932.96 -> five, so this is not yet. Car state. Illegal Aha, this is why See, I was wrong. This is
11933.96 -> the invalid state exception. And what is actually thrown by Java is the illegal argument exception.
11934.96 -> So see, this is actually what happens most that we see it. No, no constant flying. So
11935.96 -> this is what Java gives us. It throws an exception. And this now we will catch. Okay, let's retry.
11936.96 -> See, this is how everyone introduces sparks. And this is why we need tests. Today, I'm
11937.96 -> not doing a test because I just want to show you exceptions. But
11938.96 -> yeah. We do need tests. Tests are very important. Okay, now it works. See, ignoring invalid
11939.96 -> argument flying ignoring new argument driving, ignoring invalid argument abcdefg. And the
11940.96 -> valid argument was processed. It just didn't lock just didn't do anything. Which of course
11941.96 -> we can change. Here we could say system out print. ln, again, this thing here is evil.
11942.96 -> Only use it in very rare situations. Yeah. I can say bellet. Stayed. Car stayed. executed
11943.96 -> again. Yeah, so you see three invalid states and two valid states. Okay. So of course,
11944.96 -> I mean, this was just an issue. Sample Normally, you would have some method doing something
11945.96 -> about the state
11946.96 -> further,
11947.96 -> do something with the car state. I mean, I'm just making this up, because all I want to
11948.96 -> explain you is exception handling, but I hope you get the idea. So anyway, there's one more
11949.96 -> thing. And then actually, I would like to, like, shortly recap the important points of
11950.96 -> exception handling. And the missing thing now is, oh, by the way, let's remove the from,
11951.96 -> because I showed you, we don't actually even need this anymore. Okay. Because what you
11952.96 -> can also do is finally, finally, this is very important, not in our case, now, I'm just
11953.96 -> making some something up. Finally, as the name implies, this is done. Finally, at the
11954.96 -> end, no matter even exception happened or not, this block will always be called. And
11955.96 -> this is important. When you have resources, when you have input output operations, or
11956.96 -> in short I O, which you have, if you communicate with a database, if you read something from
11957.96 -> a file from your hard disk, Yeah, something like this. Because when you like read something,
11958.96 -> especially from external systems, who can tell you that the external system is actually
11959.96 -> available, or like the hard disk could fail. And so with i o operations, there's always
11960.96 -> nasty stuff that can happen. But there's one important thing, which is, for AI operations,
11961.96 -> you need resources. And so you have to close them. In any case, otherwise, you really could
11962.96 -> have a problem with more and more resources lost. So yeah, this is a big topic, I can't
11963.96 -> explain it in like a second. But all I want to tell you for now, this finally is very
11964.96 -> important when you deal with IO operations that might fail. And in this case, you can
11965.96 -> close these resources and close resource for now I'm just giving you my resource, this
11966.96 -> stupid method. You can implement that yourself. But also they are very cool. Helping utility
11967.96 -> classes found on the internet, open source. Like for example, I Oh, utils. Oh, it already
11968.96 -> find something. But this is not the one I mean, the one I know of is for example, I
11969.96 -> think from Apache, and they will have something like close thing silently or so close resource.
11970.96 -> And then this will do all the nasty stuff for you. Okay, I'm stopping here, what is
11971.96 -> important is, and this I want to show you just by printing something system out, print,
11972.96 -> ln.
11973.96 -> And I will throw the exception again. Which means what you can also do is you don't even
11974.96 -> have to catch it. This also works try and darkly finally. Okay, formatted the code.
11975.96 -> So, now with the invalid argument, our program will be stopped, execution will be stopped.
11976.96 -> But in any case, let's say I am still running. And I can also show you this line will not
11977.96 -> be printed after exception. Well, it might be that this runs once if the first argument
11978.96 -> is a valid one. Because with the string airy, we never know for sure the order is not guaranteed.
11979.96 -> But so that you see, I would whatever happens for this vote for every time we call is valid.
11980.96 -> This will always be printed. So let's see what happens. Okay, oh, something's still
11981.96 -> wrong. Not Found. Yeah, because we have removed the from Yeah, sure. Um,
11982.96 -> so let's for now remove that. We at the moment, don't need it. And see, this is again, the
11983.96 -> reason why we need tests.
11984.96 -> I'm really doing some nasty hacking at the moment. Okay, and you see, I'm still running
11985.96 -> And then the exception comes. So this is what happens when the exception happens. We didn't
11986.96 -> catch it. So we see the stack trace instead. But I'm still running is printed before that.
11987.96 -> And this is the place where we can do some cleanup operations, like closing resources.
11988.96 -> But you could do anything in here, basically. Same thing, if we catch it, catch is a runtime
11989.96 -> exception, runtime exception, because it's also a runtime exception. We should talk about
11990.96 -> inheritance very soon. So that I can go in more details why that is. So now what is wrong?
11991.96 -> Yeah, we need the closing curly brace, and one less of this. So now we can say, oh, maybe
11992.96 -> I just have I will also show you print stack trace. So this should actually do the same.
11993.96 -> And now I will say, system out. print on.
11994.96 -> Hello, again.
11995.96 -> So you get an idea. In finally block.
11996.96 -> Oh, okay.
11997.96 -> Oh, no, something weird happened. And this is for all the invalid states flying driving.
11998.96 -> The stack trace was printed. And it's red. Because, yeah, it's the print stack trace.
11999.96 -> So it's printed on system error. Okay. And you see, this is the illegal argument exception,
12000.96 -> the first one, the second one, and so on. And you see at the end, hello again. Which
12001.96 -> comes after the whole stack trace. Yeah. And you'll also see this line will not be printed
12002.96 -> off to exception. Because it seems like I mean, we had different arguments in here.
12003.96 -> So for the valid ones, this line was printed. And you see also, I mean, now I'm really having
12004.96 -> a hard time knowing why this happened. So again, I violated my own rule. I didn't add
12005.96 -> the argument. So here I can say, our arguement. I say valid argument. Yeah, because if it's
12006.96 -> after the value of if this is printed, it means the exception did not happen. Now, let's
12007.96 -> call this again. And let me also remove the stack trace for now to make it a bit more
12008.96 -> readable for us. And let's run the main method again. Okay, see now it's more readable. So
12009.96 -> what do we have here? Hello again. So the runtime exception happened. And, again, I
12010.96 -> did not add the argument. In this case, I can also say get message, which gets us the
12011.96 -> message of the exception. I'm not sure if our illegal argument exception has a message.
12012.96 -> But we'll try this.
12013.96 -> Yeah, see, this is the message Hello again. And the message is no II non constant car
12014.96 -> marktspiegel car stayed flying. So now you see he can understand the problem so much
12015.96 -> better. And after this we under finally block then comes the valid argument parking. In
12016.96 -> this case, we're also ending in the finally block. Then comes a second valid argument.
12017.96 -> Also in the finally block. Here again comes in invalid state
12018.96 -> thriving,
12019.96 -> but we're also in the finally block. And the last invalid state also in the final block.
12020.96 -> So the finally block is always executed all K. I think this pretty much rounds up everything
12021.96 -> I wanted to tell you about Exception Handling today. Now because this was quite a lot. Let's
12022.96 -> go Shortly through the most important gotchas, okay, so, in Java, there are runtime exceptions,
12023.96 -> which are unchecked exceptions, unchecked means they are not enforced by the compiler
12024.96 -> to be handled, you can just throw them, and also Java will throw them for you. For example,
12025.96 -> a very famous or infamous exception is the null pointer exception, you should never throw
12026.96 -> that yourself, Java will throw that for you, if you try to access something that is at
12027.96 -> the moment now, just now for the exception is probably the most famous exception, because
12028.96 -> when it happens, you will not be very happy. Okay? So unchecked exceptions, or runtime
12029.96 -> exceptions. And they can happen at any line, because any line can also be null. And they
12030.96 -> don't have to be handled in code. If they're not, then in the worst case, the program will
12031.96 -> stop, like we saw before, because the exception will bubble up all to the top. And if it's
12032.96 -> not handled in here, the program will stop. And it will by default, print the stack trace.
12033.96 -> Then Java was the first and actually also the last programming language that introduced
12034.96 -> checked exceptions. Checked exceptions are exceptions, that are enforced by the compiler,
12035.96 -> that you do something about them, or you add a throws with the exception name. In your
12036.96 -> method signature. There are various checked exceptions. One of the most famous ones is
12037.96 -> probably the i o exception. That will be C, it's in Java i o package. This one will be
12038.96 -> thrown if you have any problems with i o operations, which is again a topic on its own. Okay, um,
12039.96 -> and I said Java was also the last programming language that introduced checked exceptions.
12040.96 -> So this really shows us indicates us that checked exceptions were not so smart. Because
12041.96 -> you see, all they help us in the end, is they add noise to the method signature. And the
12042.96 -> case that to use them for cases that you can handle them. Well, I say, if you can handle
12043.96 -> them, why not taking care of the problem beforehand, for example, by using validation, validating
12044.96 -> the case, the given argument, and then handling that without actually even throwing an exception.
12045.96 -> And then maybe last but not least, for every rule, there's always an exception, we saw
12046.96 -> that. I've removed it, unfortunately, yeah, let me go back. We saw that with the switch
12047.96 -> on the string were set in a prior episode. Don't do that, while I did it here. And, um,
12048.96 -> we also saw saw that
12049.96 -> here,
12050.96 -> where I use the value of method of enum, which throws an exception, and I said, Well, we're
12051.96 -> trying to validate it. So if we are validating as we don't need the exception, it just that
12052.96 -> we can't do anything about it how the method was written by the inventors of Java, so we
12053.96 -> just have to live with that sometimes an exception is thrown where we will just validate it.
12054.96 -> But what we can do is we can catch the exception and then return true or false, for example,
12055.96 -> so we can convert the exception into a valid return value. Also, there is a hack. If you
12056.96 -> have a library, like an old library that will still throw a checked exception, like an IO
12057.96 -> exception. What you can always do is you can wrap we say wrap a checked exception into
12058.96 -> our runtime exception. And this is like this. Let's create more ioexception Let's create
12059.96 -> an ioexception shortly. So see, you can also just create them like any other object. And
12060.96 -> now on that exception while it cannot be called IE because we already have that I can now
12061.96 -> say throw new runtime exception and okay. Give it the IO exception. And this is why
12062.96 -> we wrap it. Because we put this exception into the constructor of runtime exception,
12063.96 -> which means this is the wrapper, it wraps around the other exception. And now our compiler
12064.96 -> will be fine. Because we're not throwing an IO exception anymore. We're throwing a runtime
12065.96 -> exception. Well, this is a nasty hack. But I think it's still better than having checked
12066.96 -> exceptions all over your code. And yeah, I'm going to talk about interfaces in Java. Well,
12067.96 -> interfaces are probably the most powerful feature of object oriented languages. Well,
12068.96 -> before I continue, first of all, some organizational stuff. So this is divided into three parts.
12069.96 -> Part One, I will first of all, talk about the definition, what does actually the word
12070.96 -> interface mean? And tell you a bit about the history. Like how were interfaces introduced
12071.96 -> into Java. I'll make this part as short as I can not to put you to sleep. And then second,
12072.96 -> we'll jump into my ID, he will do a short coding session, and I'll show you how to practically
12073.96 -> use interfaces in Java. And then last but not least, I'll do a short discussion about
12074.96 -> the pros and cons of interfaces from a clean coder perspective. Okay, so let's start to
12075.96 -> jump into the topic interface. So what does interface actually mean? So I've opened up
12076.96 -> the dictionary page. And the definition is an interface is the point of interconnection
12077.96 -> between entities. And interfaces do not only exist in programming, but also in all other
12078.96 -> kinds of areas, for example, in chemistry and physics, and there is defined as a thin
12079.96 -> layer or boundary between different substances. And I think this perfectly also applies to
12080.96 -> interfaces in object oriented languages and Java. Because it's really a very thin layer,
12081.96 -> you will see, there is not much code needed to define an interface. And it also forms
12082.96 -> a boundary. When I say boundary, I think of something like the Chinese wall, which was
12083.96 -> a big protection from the hordes that were invading from the north.
12084.96 -> And this is also what an interface is, it can protect a class from other classes, but
12085.96 -> more of this later, okay. And then maybe we should also look at the object oriented point
12086.96 -> of view. So in object oriented programming, it's a piece of code, defining a set of operations
12087.96 -> that other code must implement.
12088.96 -> So yes,
12089.96 -> all this holds true for interfaces in Java. But now, enough of the definition. Let's have
12090.96 -> a look at the history. For this, I actually had to do some research on the internet. Finally,
12091.96 -> I found this page here from Oracle, where Oracle says the concept of an interface in
12092.96 -> the Java language was borrowed from the Objective C concept of a protocol. Well, pretty much
12093.96 -> everyone says are things that Java was actually the first language introducing interfaces.
12094.96 -> Well, actually, Oracle itself says that this is not true. It was birthed from Objective
12095.96 -> C. I find this quite interesting. Objective C. I thought we should also have a look on
12096.96 -> Objective C, then. So I found this page here saying, Brad Cox and Tom love created the
12097.96 -> Objective C programming language in the early 1980s. So actually much older than Java. Java,
12098.96 -> was released as far as I know, in 1995. So 15 years later, in an effort to get people
12099.96 -> to write cleaner, more modular and clearly Separated code. Yeah, that sounds actually
12100.96 -> quite good. Now, what is interesting is here, this paragraph also says, into interfaces
12101.96 -> were introduced to Java to enhance Java's single inheritance model. So whatever single
12102.96 -> inheritance model means
12103.96 -> they didn't say
12104.96 -> they had introduced the interfaces to get more cleaner, more modular, and clearly separated
12105.96 -> code. There is a different reason. Well, I haven't told you what inheritance means yet.
12106.96 -> And this for a reason. Because, um, well, Java was released in 1995, said before, and
12107.96 -> now we have 2015 20 years later, actually, in the meantime, the especially the clean
12108.96 -> code community does not believe so much in inheritance anymore. Because, of course, inheritance
12109.96 -> has a lot of advantages. But also many disadvantages about this, I'll tell you, and one of the
12110.96 -> next episodes when I'm going to talk about inheritance in Java. But anyway, so when Java
12111.96 -> was introduced, Java is the successor of c++ we could say. And c++ still had a model using
12112.96 -> multiple inheritance. So multiple inheritance is even more complicated than single inheritance.
12113.96 -> And here they write. multiple inheritance created too many problems for programmers,
12114.96 -> as well as compiler writers, because it's actually not so easy to implement multiple
12115.96 -> inheritance in into a compiler. So it seems, because they did not support multiple inheritance,
12116.96 -> they added interfaces to Java s, like replacement for multiple inheritance, to like, fix that
12117.96 -> Java did not support multiple inheritance. And this is quite funny. And let me say it
12118.96 -> in different words, I would say, it seems like the really powerful feature of interfaces
12119.96 -> was introduced into Java by kind of accident, because they said before, they didn't think
12120.96 -> about cleaner, more modular, clearly separated code, but mostly just to have a way of having
12121.96 -> something similar to multiple inheritance. Okay, let's stop here, and jump directly into
12122.96 -> my ID. Cuz I felt you were already feet been falling asleep. Um, so here, this is my car.
12123.96 -> So it was test that I've used in earlier episodes. Also, I've added this should demonstrate interfaces
12124.96 -> method, as the name implies, just for demonstration purposes, I'm still using the car service
12125.96 -> that I've implemented, also in one of the earlier episodes, and I've added a drive method
12126.96 -> to it. So the idea is to have a service class. And when I call the drive method, that this
12127.96 -> should, like start the engines of several cars, and make them drive. So for this, in
12128.96 -> my car service, I have now a method drive. It creates First of all, three different cars.
12129.96 -> I mean, this is just an example you mentioned, were hundreds of cars. And now I call the
12130.96 -> drive method on each of these cars.
12131.96 -> Okay, actually,
12132.96 -> all these classes are in the same package. This is why I don't have to import any class.
12133.96 -> But imagine each class would be in a different package. We would have to import each class
12134.96 -> separately like BMW and Porsche GE and mercy is and so on. So what we say here is actually
12135.96 -> this car service at the moment is really Deeply coupled to these car classes, this is something
12136.96 -> that we don't want more about this later. And also, you see, we need a lot of code to
12137.96 -> make all the cars drive. And this is something that we want to improve with using interfaces.
12138.96 -> Now what, again, what is an interface? Well, an interface is also like an abstract type
12139.96 -> definition, what this type should be able to do. In our case, we have an I mean, I'm
12140.96 -> already saying it three different cars. And all these cars can drive and you see it already,
12141.96 -> I have three different drive methods. I mean, the way they hold how they are driving might
12142.96 -> be different because of course, a BMW has a different engine than a pushy, and again,
12143.96 -> a different engine than ms cedars. But they have some certain specifics, like, for example,
12144.96 -> they would all have four wheels, and they can all drive which we can make something
12145.96 -> like a contract off. So in this way, let us introduce an interface and I've prepared something
12146.96 -> here, car dot java. So far, we only have the package declaration, we have to extend that.
12147.96 -> So let's start. Let's start as if we would write a class. So let's say public class car.
12148.96 -> And then opening and closing curly brace, and now public void drive.
12149.96 -> Okay.
12150.96 -> And then in here, we could do something. Well, the problem is if we do it like this, this
12151.96 -> is not going to work, because then all the different types will have to drive the same
12152.96 -> way. But this is not what we want. For example, He in pushy, I have implemented already the
12153.96 -> drive method. I mean, this is just a stupid example. I still want you hardly ever to use
12154.96 -> system out print line. But here for our example, I just wanted to show you that each method
12155.96 -> is implemented in a different way. Here it says masseter striving there it says Porsche
12156.96 -> driving, the BMW actually even has three different methods. These ones we will actually use at
12157.96 -> a later time. And it also has the drive method, which says BMW driving. Okay.
12158.96 -> So now,
12159.96 -> maybe before,
12160.96 -> I'm going to
12161.96 -> continue with doing the interface, we could also try to execute the code as it is. Let's
12162.96 -> do this. Now, just so that you see the code should be running by now already. So it says
12163.96 -> BMW driving Porsche driving Mercedes driving. So what I want to achieve is exactly the same
12164.96 -> just using interfaces with less and more readable code. By the way, exit code zero means everything
12165.96 -> is fine. If there is a problem, an exception thrown, it would be exit code one. Okay. So
12166.96 -> back to what at the moment is still a class. Now there is a very easy way to make this
12167.96 -> an interface. And this is I say interface. But now it seems there is still a problem.
12168.96 -> It says interface methods cannot have a body, or what is the body, the body is this part
12169.96 -> here in blue. So the body is actually the method implementation. method also has a method
12170.96 -> signature. This on top here is called the method signature, public void, and the name
12171.96 -> of the method is drive. Okay. Sorry. So it seems like it cannot have a body. How is that?
12172.96 -> Well, I guess even makes sense. Because we said we just want to have a definition, like
12173.96 -> a contract. But we don't want to actually implement it. The implementation will be done
12174.96 -> by the specific implementations by BMW by Porsche and by my seniors. And we have already
12175.96 -> done the implementations. So let me remove the body. Now there's still something wrong
12176.96 -> and you see it. Here it even says it It wants now, the semi column because the semicolon
12177.96 -> now says, I'm finished. I'm done. This is all I want to say. So now we have an abstract
12178.96 -> definition of a method that other classes may implement. And when they implement the
12179.96 -> interface car, we can also say they play the role of a car. Because actually a class can
12180.96 -> implement more than one interface. A class can implement any number of interfaces. And
12181.96 -> remember, before I spoke about multiple inheritance, well, multiple is, this is why it's similar,
12182.96 -> because it also allows to have,
12183.96 -> like,
12184.96 -> multiple implementations in a way, but more of this later. So a class can also implement
12185.96 -> multiple interfaces. Okay. And when I click here, you also see modifier public is redundant.
12186.96 -> Why is it redundant? because by definition, all methods that we define in an interface
12187.96 -> must be public, they are always public. So even if I remove it, well, if you still remember,
12188.96 -> the episode I did on the visibility modifiers, you might now think, Well, now that there
12189.96 -> is no modifier defined, it must be of default, or package level visibility, no, it is still
12190.96 -> a public visibility, because it always a method is always have public visibility. Another
12191.96 -> modifier that is implicitly here is abstract, can put it abstract just means what we have
12192.96 -> here, that the method is not implemented, and that it just consists of the method signature,
12193.96 -> and that the body is left away, and that we have to semicolon here. So also, this is redundant,
12194.96 -> we can and we should remove it. Always define your methods without public and without abstract,
12195.96 -> you should just know that implicitly, they're there. Okay. And then there's one more thing
12196.96 -> you can do in an interface. Um, but I warn you not to do it. This is actually an anti
12197.96 -> pattern. But still just to be complete. I let me show you. And this is you can add public
12198.96 -> static, final. So you can add constants, for example, Max, Max speed. I don't know 320.
12199.96 -> And however, you shouldn't do so. And when you think about it, I guess you will easily
12200.96 -> find out why. Because for example, the BMW might only do a max speed of 240. Porsche
12201.96 -> Yeah, maybe a Porsche can maybe do 320, but maybe also even more than Mercedes, I don't
12202.96 -> know. So this is actually not part of this should not be part of the interface, because
12203.96 -> this is an implementation detail. And such an implementation detail should be hidden
12204.96 -> within the class, or even better. In an email about this, let me also shortly show you a
12205.96 -> little page I found on the web. And this is here it is on the page of sonar. Well, actually,
12206.96 -> it's called sonar cube sonar cube is really a very cool tool. It's actually one of my
12207.96 -> favorite tools for static code quality analysis. I'm pretty sure very soon, I'll do an episode
12208.96 -> on sonar cube alone. For now, let me keep this as short as possible, because we still
12209.96 -> want to talk about interfaces. But in this sonar cube, it's actually a rule that checks
12210.96 -> that you don't use constants in an interface. Here it says console should not be defined
12211.96 -> in an interface. And there was also or there is also very smart, cool guy, Joshua blah,
12212.96 -> the author of Effective Java, which is, by the way, also a must read, I have a link to
12213.96 -> that book on my blog, on Marcus minus bo.com, where you can directly buy it from MSN. So
12214.96 -> if you have the time, you can also read all this, but I think I already explained the
12215.96 -> important parts. Here, we can also look at it. So noncomplying code is to define the
12216.96 -> variables directly in the interface. And you see here they even didn't say public static
12217.96 -> final because this is again, every variable you define, is implicitly a constant. So you
12218.96 -> don't even have to say public Static final. But this is not good. Anyway, the much better
12219.96 -> solution is to use an enum we have talked about enums already. So I won't go in more
12220.96 -> detail here. Another possibility, which I would not recommend, you can also have something
12221.96 -> called constant classes, which you make final.
12222.96 -> And then in the class, you have the public static final constants. This is possible,
12223.96 -> but it's always better to have small enums. Because usually what happens is in these constant
12224.96 -> classes, they would grow. And they would grow and have contain all kinds of different constants.
12225.96 -> While this only contains the constants of this status here. And also, I mean, talked
12226.96 -> about this when I talked about enums is type safe. Well, here, you could change any number.
12227.96 -> Okay, so anyway, so now back to our code. So, here, you already see it's redundant.
12228.96 -> All this is redundant, and should be removed. But this should also be removed. As I said
12229.96 -> before, because it's an implementation detail, this is not part of our contract. Because
12230.96 -> the car should just define what needs to get done, what behavior class implementing that
12231.96 -> behavior has, like it should drive, but the way how it's how it drives, if it drives fast
12232.96 -> or slow. This is part of the class and not part of the interface. This is really important
12233.96 -> when you want to do clean coding. Okay. So now let us implement, use the interface. So
12234.96 -> now, when I say implements car, when you you can now use BMW as a car. And when you do
12235.96 -> so, BMW plays the role of being a car. And as I said before, you can also implement several
12236.96 -> interfaces, which we're going to do very soon. But first of all, let me finish this quarshie
12237.96 -> implements car. And Marie cetus implements car. Well, the compiler was directly happy,
12238.96 -> I hadn't got to do anything, or implements car. Because the work I've done beforehand,
12239.96 -> implementing the method will normally let me know that this just to be faster in my
12240.96 -> here, code example. You won't do it like this, you define a class, you say it implements
12241.96 -> an interface. And then you see I already have a problem with the compiler, which tells me
12242.96 -> I have to implement the abstract method, Dr. Okay, and then you do this. And the compiler
12243.96 -> is happy. It has to be exactly like defined in the interface. You cannot, for example,
12244.96 -> say int as a return value, because this is not how it was defined in the interface. Okay,
12245.96 -> now, let me also show you, oh, there's still a problem with car. It seems there's the curly
12246.96 -> brace missing, somehow. Okay, it seems like I probably deleted too much. Okay, see how
12247.96 -> small is is well, actually, by the way, I'm an interface should have at least one method.
12248.96 -> While this is also not true, there are even something called market interfaces that don't
12249.96 -> even contain a single method. This is a specialty, which I'm not going to go in detail now. But
12250.96 -> usually they would have at most, at least one method, and maybe even many more methods.
12251.96 -> But again, I want to warn you, I see often interfaces with 10s of hundreds of methods.
12252.96 -> And sometimes it's just too much. It's better to have many, many interfaces and to have
12253.96 -> your classes implement several interfaces at once, so that you can decide what role
12254.96 -> your class is going to play. And lo let's implement more interfaces in here. I've already
12255.96 -> prepared again, adding these methods, because I have also what interfaces one interface
12256.96 -> is the lockable interface, which I defined. The idea for such an interface is
12257.96 -> for example, you want to do logging, you want to do you want to lock several different objects,
12258.96 -> could have cars, persons whatsoever, everything can be lockable. And I defined that in order
12259.96 -> to be likable. Such a class must implement a method called message, which I then later
12260.96 -> in my learning framework can call. Because I know that whenever I have a class that implements
12261.96 -> luggable, it will then have a message method that I can call and it returns me a string
12262.96 -> that should be used for logging purposes. Then also, well took me a while to come up
12263.96 -> with examples, because what other roles could a car play, I said, it could also be a property.
12264.96 -> And such a property would have an owner, for example, the owner of the BMW I made myself
12265.96 -> I mean, I want to have a BMW, how cool is that. And one more interface, I said, I just
12266.96 -> came up with the idea, we could also have a role of being an asset, an asset would have
12267.96 -> a value. And so my BMW also has a value. So I cannot easily say, implements luggable.
12268.96 -> Think this one I have not implemented yet. And I still have to do No, not twice implement
12269.96 -> car, comma luggable, comma, asset, comma property, the order doesn't matter. But now you see,
12270.96 -> I've implemented already the value method and the owner method, the message method,
12271.96 -> I still have to implement. And as I said before, the order is not controlled, so I can put
12272.96 -> it in any order message.
12273.96 -> And, yeah,
12274.96 -> here, we just return something
12275.96 -> on the car.
12276.96 -> Okay, now, I have a class implementing 1234 different interfaces. OK, now let's use my
12277.96 -> classes implementing the interfaces. For this, we go back into my car service, what I can
12278.96 -> already do is now my variable my reference variable is at the moment of type BMW, the
12279.96 -> class so my BMW can do everything that a BMW can do, which at the moment is drive message
12280.96 -> owner value, these are methods that we inherit, see, there is inheritance already, from the
12281.96 -> object class more of this very soon, but these were the classes that we have directly implemented
12282.96 -> in the BMW class, so I can use all of them. Or let me show you a message, we can use them.
12283.96 -> Now, what I can also do is, now that I've implemented the car interface, I can say my
12284.96 -> I create an object of type in W, but I put a reference on it of type car. And now, this
12285.96 -> will change the behavior. Now, I can just call drive on it, because now my BMW just
12286.96 -> plays the role of a car I can also say luggable and then I will not be able to drive the car
12287.96 -> because in the context of logging, I don't care about driving all I care is about login
12288.96 -> and for logging, I would need such a message okay.
12289.96 -> So,
12290.96 -> now, let me make all these cars and this is also something you should do I mean, the object
12291.96 -> is the object, but the variable when you have an interface, always try to like reference
12292.96 -> with the with an interface to the object. Because this way, you can more easily exchanged
12293.96 -> your code like imagine the BMW would come as an argument to the method. Now, at the
12294.96 -> moment we have these three cars, imagine at a later time someone in when so very cool
12295.96 -> Marquess car, then when the when the method is operating on the car interface type, this
12296.96 -> method will work even with new classes introduced without even knowing them at the time, we
12297.96 -> wrote our car service. So whenever possible, use the interface type. Okay. So now, I want
12298.96 -> to have a for each loop. And for this, let me put All these cars into a car array. We've
12299.96 -> also already talked about array called as cars equals two. And now the short definition
12300.96 -> I can even do it on the fly. Make it even more shorter. You W, you're pushy.
12301.96 -> You're more serious.
12302.96 -> Okay.
12303.96 -> Hello, on this array, I can now easily iterate. And I can now say car dot drive. And, or as
12304.96 -> said before, each car will drive differently. But this will be handled by the object. Now
12305.96 -> our car service does not know any specific implementation anymore. This is the coupling,
12306.96 -> decoupling the code is not coupled so much to the specific implementations, my car service,
12307.96 -> all that it uses, all that it knows is now the car interface. Okay, and with these few
12308.96 -> lines, I iterate over all the cars and I drive them. Let's execute this code to and have
12309.96 -> a look if it works. Yeah, see, this is exactly the same as before, my BMW is driving or a
12310.96 -> Porsche he is driving and marmet cetus is driving. Now let's also have a look at the
12311.96 -> car reference. As you see, we can only execute drive on it. That is defined by the car interface.
12312.96 -> And we do have a BMW as the first element in our area. But this headline 10, we don't
12313.96 -> know. All we know is we have an area of cars. Okay, so we cannot call any BMW specific method.
12314.96 -> In here. I can also not say BMW, because this is not competitive compatible. We need a car.
12315.96 -> And we don't need to be in w because this array is of type car. Okay, so let me fix
12316.96 -> that.
12317.96 -> Okay.
12318.96 -> So
12319.96 -> I think this pretty much wraps up my explanation of interfaces in Java. A really cool feature.
12320.96 -> And now let's have a discussion about the pros and cons about the advantages and disadvantages
12321.96 -> of interfaces in Java. Well, first of all, let's start with the disadvantages. And actually,
12322.96 -> I can tell you, there are not so many. Well, you see, for every interface that are introduced,
12323.96 -> I have to type down this code. And, of course, this is here, not much, it could be of course,
12324.96 -> much more. So, and each class that wants to use an interface has to implement this interface.
12325.96 -> So there is some added complexity. Also in my car service, I'm using now the car interface.
12326.96 -> And whenever you introduce complexity, this complexity must be justified. So if it makes
12327.96 -> sense, if it helps us with something, for example, here, I'm not able to easily iterate
12328.96 -> over all the cars. And you mentioned there could be many, many, many, many more. But
12329.96 -> my for loop would just be the same. So this would be for example, a justification. But
12330.96 -> my car service at the moment does not implement an interface. Well actually, this is kind
12331.96 -> of an exception to the rule. Most services should implement an interface. Very often
12332.96 -> this makes sense, because it's specifically for testing so that you can exchange the concrete
12333.96 -> implementation just here. In my example, it does not make sense because I just want to
12334.96 -> explain you interfaces and I want to have it really short and neat and not too complicated.
12335.96 -> And I know I will only have this one class here for demonstration purposes. So why Would
12336.96 -> I implement an interface here? So at the moment, I don't see a reason to make my car service
12337.96 -> implemented interface. Sometimes, of course, there are corner cases, we're not sure. My
12338.96 -> personal point of view there is, if I know that for the next months, I'm not going to
12339.96 -> need the interface. My probably leave it away. Because code, I mean, it lives you are allowed,
12340.96 -> you can change it, you can refactor your code. So if at a later time you, it turns out you
12341.96 -> need to interface then edit at a later time. Just don't do arbitrary decisions. There are
12342.96 -> people that like they love interfaces. And for this reason, they do something I would
12343.96 -> call interface readers, like an illness, blindly adding an interface implementing an interface
12344.96 -> always just because, and I think this is not too smart. And then really, interfaces can
12345.96 -> be a disadvantage, because they just make everything more complex. But now, this is
12346.96 -> already pretty much it. To the advantages, so the advantages, I think a few ones are
12347.96 -> already mentioned, while explaining the interface. Probably one of the most important ones is
12348.96 -> that it decouples your code, as I explained before, like now, the car service only uses
12349.96 -> the cotton Well, no, I was actually like, sorry, of course, as it is implemented at
12350.96 -> the moment, we still say new BMW new Porsche new messages. So of course, at the moment,
12351.96 -> it would still be coupled. But normally, of course, he would also not do it like this,
12352.96 -> what he would usually do is you forward an array that is already filled, only then. Now,
12353.96 -> our core service is not coupled to the specific implementations. So it really allows to decouple
12354.96 -> your code much better than without interfaces. And this decoupling also helps with other
12355.96 -> things, for example, team cooperation. Imagine you have a big team of 10 2030 developers,
12356.96 -> and you have a big project that you have to work on for weeks or months.
12357.96 -> And then you would probably form smaller sub teams. And then each sub team would work on
12358.96 -> a specific area. For example, one team in our example here, could work on the car service,
12359.96 -> while there would be another team implementing different car types. Now the problem is, the
12360.96 -> car service is then or might be dependent on specific car implementations to test it.
12361.96 -> And on the other hand, the team that implements the different car types might need a car service
12362.96 -> for testing, and for integrating their code with the other code. So it's like, each team
12363.96 -> is dependent on the other team. And so each team blocks the other team. So nothing can
12364.96 -> be finished. And interfaces can be a solution to the problem. Because when you introduce
12365.96 -> an interface here, for example, in this case for the car service, then the team implementing
12366.96 -> the different cars would just do a very stupid dummy implementation, something similar like
12367.96 -> I did here, where you don't have real code, or just something where you see it's working.
12368.96 -> And then the other team can independently also work on their code. And also add dummy
12369.96 -> implementations where needed. And only when both are finished, they can be brought together.
12370.96 -> So interfaces really help in team cooperation. And then next advantage is interfaces really
12371.96 -> include increase your flexibility, because as you see, as I have changed it now we have
12372.96 -> the cars array as a parameter to our drive method. So actually at runtime, in this case,
12373.96 -> in our test method, we have this drive method. So now at runtime, I could have something
12374.96 -> some condition if it's sunny, just making this up. Then I want to drive in my Porsche.
12375.96 -> And so I create a pushy here, so I would say car car And then I would say if sunny car
12376.96 -> equals to new Porsche else if it's not Sunny, well, I hope I had so many cars, then I would
12377.96 -> say I take the BMW instead. Because it's better for rainy weather. Knew, of course, and now
12378.96 -> I don't want to make an error, let me change the method. And I don't implement sunny nose.
12379.96 -> So I just say true here, just to have it simple. So in this case, Now, of course, you wouldn't
12380.96 -> be cold. And in my drive method to make this work, make this a car to have it simple. And
12381.96 -> I would call drive. So now at runtime, we will decide what kind of car this is. So this
12382.96 -> really adds a lot of power to our code.
12383.96 -> So
12384.96 -> it might be a pushy, and it might be a BMW that is given to the Dr. method. Really cool
12385.96 -> feature.
12386.96 -> Okay,
12387.96 -> I guess there are many, many more advantages of interfaces. Let me know if you have more
12388.96 -> to add. But I think this is enough for the moment so that you get an idea of what interfaces
12389.96 -> are. And all the advantages interfaces have. Just also, again, the warning don't fall into
12390.96 -> our interface, serious illness. This will also be not wise. But I think this pretty
12391.96 -> much wraps it up. I'm going to talk about inheritance in Java. inheritance is actually
12392.96 -> a very powerful feature of object oriented languages. Similar to interfaces, inheritance
12393.96 -> allows to handle a group of similar objects in a uniform way. On top of that, however,
12394.96 -> it also allows to prevent code duplication, by inheriting the members of a class from
12395.96 -> a parent class to its child classes. I'm the members of a class in case you don't remember,
12396.96 -> are the instance variables, and the instance methods. So everything that is not static.
12397.96 -> Okay, well, I guess that sounds very promising. The problem is, I think inheritance is just
12398.96 -> a bit too powerful actually. Well, if used incorrectly, inheritance, can severely damage
12399.96 -> your code. So really take here and use inheritance sparsely. I mean, there are definitely justified
12400.96 -> cases to use inheritance. But whenever in doubt, I would not use it. Okay. And also,
12401.96 -> it actually requires some experience to know when to use inheritance, and when to avoid
12402.96 -> it. To give you a real world example, I'm at the moment I'm working on a project of
12403.96 -> about maybe 15,000 lines of code. And there. I used inheritance, maybe once. Yeah. So there
12404.96 -> are alternatives to using inheritance. I'm about this. We will talk at the later time.
12405.96 -> Yeah. Well,
12406.96 -> let's stop here for a moment. Because now the introduction is almost over. You see me
12407.96 -> in the button right corner talking to you all very soon disappear, because I'll jump
12408.96 -> into the code. And I'll show you how to implement and use inheritance. Before that one personal
12409.96 -> request. I'm doing this videos for you. So that you can learn Java, I hope they useful
12410.96 -> to you. If so, I would be very happy if you could give me your thumbs up in the bottom
12411.96 -> right corner of this video. And remember, you can also subscribe to my YouTube channel.
12412.96 -> Okay, well enough of advertisement Now, let's really do a coding session and jump into the
12413.96 -> code. Okay, so here you see I have prepared this CEU test class for you. We are actually
12414.96 -> not really testing something now. This is just for demonstration purposes, any arbitrary
12415.96 -> example. Um, this example is actually taken from the book, headfirst Java, from Kathy
12416.96 -> Sierra, she is really my favorite author of any Java related book, highly recommended
12417.96 -> to read
12418.96 -> this and any other offer books. In case you want to know, you can find a link
12419.96 -> to her books on my blog on market minus b.com. I have a must read section there, you can
12420.96 -> find her books. Okay. Now back to the code. So I have here the SU class. So the idea is,
12421.96 -> we have here an area of animals, similar to the area of cars I had in the last episode,
12422.96 -> where I introduced you to interfaces, and I had a car every with BMW and Mercedes and
12423.96 -> a pushy, now we have an animal array with a dog, a gorilla,
12424.96 -> and a line and a tiger. So you should already see interfaces and inheritance in Java. When
12425.96 -> you use them, here, it looks quite similar. And this, by the way, is called polymorphism.
12426.96 -> You might have heard that.
12427.96 -> And the idea of polymorphism is that on the left side, you have a variable a reference
12428.96 -> variable of this super type a parent class
12429.96 -> animal. But Polly Morphe. I mean, this also works with interfaces. So the idea is just
12430.96 -> that you have an interface or a super or parent class.
12431.96 -> And on the right side, an animal can be a dog, a gorilla, a line, a tiger, anything,
12432.96 -> so different things can be assigned to the left variable. Because the polymorphism means
12433.96 -> like, many sides solve can have different implementations on the right side. And they
12434.96 -> will all be handled uniformly here, I have prepared this feed animals method. Let's maybe
12435.96 -> jump here. Okay, so you see I've prepared this for each loop, everything that is read,
12436.96 -> we still have to implement, I have only prepared it. So we're iterating through my array, we
12437.96 -> still have to implement the eat method. And we still have to implement the H method. Now,
12438.96 -> again, totally stupid, arbitrary example. But just to have something to show you. And
12439.96 -> to have variation. My idea was, I mean, totally arbitrary. Really, this depends on the design
12440.96 -> of your code that like because code is always like a model of the real world. And so it
12441.96 -> totally depends on the example that you're working on. Well, in my example, I just defined
12442.96 -> that I said, Well, every animal, a dog, a gorilla, a line, Tiger, they all eat in a
12443.96 -> different way. Because for example, a gorilla would probably eat, I don't know what it eats
12444.96 -> grass, or leaves or something will align. I don't know. It's some kind of meat. So therefore,
12445.96 -> my idea was to have an implementation, a concrete implementation of the eat method in each different
12446.96 -> animal subtype. And further, my idea was to have this H method. Well, every animal can
12447.96 -> be of a different age. But the calculation Well, normally, you wouldn't probably calculate
12448.96 -> the age. But I mean, this is just my stupid example, I made it a method. So the calculation
12449.96 -> would be the same for every animal. So my idea is to have this as a concrete method,
12450.96 -> an animal and have this as an abstract method, because this is something here, where interfaces
12451.96 -> are different. Sorry, yeah, but interfaces are different to inheritance. In interfaces,
12452.96 -> you only have abstract methods. And because you have only abstract methods, the abstract
12453.96 -> keyword is not needed. But here we can enhance inheritance, we can mix it, maybe I should
12454.96 -> already jump now to the animal class. So an animal class this is still just a stupid simple
12455.96 -> class totally empty. So you can use inheritance with just a simple class. And now let's implement
12456.96 -> two methods concrete
12457.96 -> methods, public void, eat Later on, I'll make this abstract. But for now, I wanted concrete.
12458.96 -> public void. Ah, oh, okay. So now maybe we should also do something in the method. And
12459.96 -> again, avoid system or print boom, just, if you're like me doing an example, showing something.
12460.96 -> This is the exception polluter rules and it's okayish to use system or printable, but avoided
12461.96 -> in real code. Okay, so I say, animal is eating. Well, this is not what we want. So it's just
12462.96 -> step one, I said every animal is eating in its own way. And here is say, h is cold. collated.
12463.96 -> Okay, it's here the dots to just for fun. So now, see, this class looks totally like
12464.96 -> a regular class, you have seen so many times before. Now, I go to the dog class, and I
12465.96 -> want the dog to be an animal. Well, if this would be an interface, I would say implements
12466.96 -> you remember, but it's not it's a class and we extend the class and therefore the keyword
12467.96 -> is extends really, totally easy. Okay, so we say extends animal. And all this is already
12468.96 -> using inheritance. Now it's looks like as if the dog class was empty. But in fact, we
12469.96 -> can already use these two methods in dog Okay, let's continue doing this for all the other
12470.96 -> subtypes
12471.96 -> gorilla
12472.96 -> extends animal line extends animal. These by the way are two interfaces, I also want
12473.96 -> to show you and I might just as well do it now, we can mix using interfaces and using
12474.96 -> extending classes using inheritance we can mix them the question is should we first say
12475.96 -> extends or first implements, well, there is a rule it must be that we say extends first
12476.96 -> and then implements because in Java, we have single inheritance. So, we can only extend
12477.96 -> a single class, but we can implement any number of interfaces, and therefore, this is a comma
12478.96 -> separated list. And therefore, to make it a bit easier, it's at the end. So, we say
12479.96 -> implements and I can say this interface lockable and comma printable. So, an interface plays
12480.96 -> a role. So Aline can play the role of being a lovable, when like, he mentioned, the code
12481.96 -> is running on production at a certain time where we want to lock the line or we want
12482.96 -> to print it and therefore we can implement this interface. Again, this is pulley Morphe
12483.96 -> that align can be a luggable Okay, so, you see there is something red, because now we
12484.96 -> have a lot of methods that we have to implement. First of all, from the animal, I mean, the
12485.96 -> order is arbitrary. We can also start with a printable. So there was a public void. Um,
12486.96 -> was it print I hope method. And then there was a public void I think message for luggable.
12487.96 -> This might have Yeah, you see, so the rule is, when we implement an interface method
12488.96 -> as well as when we, when we implement an abstract method from animal, the signature, the method
12489.96 -> signature must be exactly the same. We can't say what year because the interface said it
12490.96 -> must be a string, return something just for our little example. Okay, and in here, I say
12491.96 -> system dot out.
12492.96 -> Print.
12493.96 -> ln
12494.96 -> printing,
12495.96 -> okay, get the idea.
12496.96 -> So, now, there is still the eat method missing. No, actually, it's not because we made it
12497.96 -> concrete. So we don't have to implement the method I'm already a bit too fast.
12498.96 -> So see the red is gone. Everything so far seems okay. But there's still a problem and
12499.96 -> Sue test. Let's check this are the tiger, we still have to do the tiger extends because
12500.96 -> the tiger was not an animal yet. Maybe we should look at this again. I mean, this is
12501.96 -> interesting. So see, all those classes are all already extending the
12502.96 -> animal. And so these are already animals, but the tiger is not yet required, we need
12503.96 -> an animal with found is a tiger. Okay, so let's make this also an animal. Now it's an
12504.96 -> animal, and now it's working, the red is gone.
12505.96 -> Okay, but we still haven't done what we want it. Because I said I want this method abstract.
12506.96 -> Now, you probably remember from when I explained interfaces, an abstract method does not have
12507.96 -> this method body, the implementation, but just the method signature, this here on the
12508.96 -> top,
12509.96 -> the method signature. So let's remove the body. And we have to say abstract in the interface
12510.96 -> we didn't have to, because in interface, all the methods are,
12511.96 -> by definition abstract. But here I mean, how would Java Nope, there's a concrete method.
12512.96 -> And this one is supposed to be abstract. So therefore, in inheritance, we have to explicitly
12513.96 -> set abstract. But now there is a difference. Because if one method is abstract, the whole
12514.96 -> class has to be abstract.
12515.96 -> Now,
12516.96 -> what does this mean? Because actually, this changes a bit of the behavior. And this, again,
12517.96 -> depends on your personal design of the program that you're writing. An abstract class cannot
12518.96 -> be instantiated. Now, we cannot say the compiler will not allow us We can't say new animal.
12519.96 -> An abstract class is like just the contract, just the protocol. Pretty much the same as
12520.96 -> an interface is just the raw definition. But we cannot create instances from an abstract
12521.96 -> class, we can only do so from concrete classes. But concrete classes cannot have abstract
12522.96 -> methods. So this is something that you have to clearly think of. And also amin, I said,
12523.96 -> another warning, I said that this can be used to prevent code publication. Now you might
12524.96 -> think, well, cool, I just create some tool class. And this has any method that I'm like
12525.96 -> needed anytime for example, age. And then I can say animal extends tool. Because even
12526.96 -> the inheritance can have several layers. So even though talk says extends animal animal,
12527.96 -> again, could extend some class. So now we could say, extend some to class haven't implemented
12528.96 -> that. But I hope you get the idea. Well, even though you can do so you should not do so.
12529.96 -> Because the rule is you have to apply and is a test. Also, this is from
12530.96 -> the book of Kathy Sierra had first Java. They you say an animal is a tool? No, it's not.
12531.96 -> So because it's not a tool, we don't say tool. Because otherwise, this can really get nasty.
12532.96 -> And so you shouldn't do that as a recommendation. But really a strong recommendation. Okay.
12533.96 -> So yeah, it still has to be made abstract because of this abstract method here and we
12534.96 -> have to remove new animal as I said, doesn't work. Okay, not everything read has gone.
12535.96 -> Now,
12536.96 -> let's go into our classes again. See, now there is a problem. Now that this method is
12537.96 -> abstract, we also forced to implement it. So we have to say, public void, eat. And we
12538.96 -> have to implement this method. And again, stupid examples system called print ln dog
12539.96 -> is eating dot dot dot Okay, So gorilla is eating in a different way. It's, I don't know,
12540.96 -> grass or something reuleaux is eating leaves. Um, next one line, the line is eating something
12541.96 -> again, and the tiger is eating something. So in this case, they all implement the eat
12542.96 -> method in their own unique way. So in reality, you wouldn't, of course have your system out
12543.96 -> print on but some specific, Tiger related logic that only fits for tiger. And this is
12544.96 -> why we have it here. And all the logic that fits for all animals you put here. And this
12545.96 -> by the way, I mean, on the one hand, this is handy. But to me, this is really a double
12546.96 -> double sided sword. I mean, this is handy and can help. But on the other hand, it also
12547.96 -> is really complex. Because when you're in a class like Sue, how do you know which animal
12548.96 -> implements eat, and which animal just inherits the eat method, same for the H method,
12549.96 -> because we could of course, again mix that. And we can also override a method. So for
12550.96 -> example, ah, this one is implemented. But we could say, gorilla is implementing the
12551.96 -> age by itself are not something. So this is like, how you could define an exception to
12552.96 -> the rule. You could say, well, my gorilla does not use the H method. But instead, the
12553.96 -> H method is replaced by exactly this method.
12554.96 -> And the way this is done is, the signature must be this method signature here must be
12555.96 -> pretty much looking the same. You can't like change the return value or the parameter
12556.96 -> values.
12557.96 -> Well, you see, you can, but it's just not using inheritance. Now, this is also why it's
12558.96 -> not yellow, but gray. Um, this is called overloading a method. overloading a method means you implement
12559.96 -> a method that has the same name as another method. But it's just something completely
12560.96 -> different. So this has nothing to do with inheritance. If you want to inherit the method
12561.96 -> and override me override it, it has to have the same signature. Okay, there is one exception.
12562.96 -> And for this, I have to introduce a new visibility modifier. I think shortly, I talked about
12563.96 -> it in an earlier episode, but I didn't really explain you what it means. And this is protected.
12564.96 -> Now what means protected? protected, means it's visible, on the one hand, similar to
12565.96 -> default, or package level visibility, and the whole package. So now we can use the H
12566.96 -> method. In Su. See, this is not read. It also means it's visible in any class that extends
12567.96 -> animal. In our case, now, we have all the classes in the same package. But he mentioned
12568.96 -> we had a car sitting, extend animal, I mean, of course, we should not this would be stupid.
12569.96 -> But just technically not from a design perspective. We could then use the H method, because it's
12570.96 -> protected. So the visibility is to any class that inherits from animal on top, any class
12571.96 -> that is in the same package. And this again, makes it complex. Do you see how much I have
12572.96 -> to explain? so that you understand, and this is why I would avoid using it. So I just want
12573.96 -> you to passively know when someone else uses it. But I would really avoid it. But so protected
12574.96 -> visibility is less visible than public. And what I am allowed to do is I can increase
12575.96 -> the visibility in a child class. So where was I? Here? So I'm allowed you see it works.
12576.96 -> I can say public void. Now this is still not inherited. Nowadays, it's yellow again. So
12577.96 -> I can say public And now I can also say protected, which at the moment is the same visibility
12578.96 -> as in parent class animal. But I'm not allowed to say private, this will give me a compiler
12579.96 -> error, attempting to assign weaker access privileges. It was protected. So you're allowed
12580.96 -> to make it public, but not less than protected. The idea behind that is, I mean, an abstract
12581.96 -> method defines a contract a protocol. Exactly. Like with interfaces, by saying extends animal,
12582.96 -> you promise any other class in the Java universe? I am an animal, and you have a method that
12583.96 -> is public. And you can call it. And me. You mentioned the crazy stuff that would happen.
12584.96 -> If there is one class that just does not fulfill this contract. So this is why it's not working,
12585.96 -> it has to have the same visibility. Oh, okay. Then also, I mean, I said, we inherit the
12586.96 -> members of a class. And I said, the members of the class are the instance methods. These
12587.96 -> are the instance methods, and the instance variables. So you can also have here a protected,
12588.96 -> I'm in H. And this will also be inherited. We can now say, directly access is in here.
12589.96 -> I mean, this is the H method. Maybe I should now here have a public void. h method instead
12590.96 -> of the eat method.
12591.96 -> Okay.
12592.96 -> And now I can say this dot age, or just age? Or a statement? Yeah, of course not. It's
12593.96 -> not finished
12594.96 -> 45. So this would now we'll set the age to 45. Or just age because here, we don't need
12595.96 -> this. Because we know what we mean.
12596.96 -> Um,
12597.96 -> even though this is possible, we inherit the age field, I would not make use of it. Well,
12598.96 -> first of all, because I don't like protected as I said, and second, because I think this
12599.96 -> kind of violates the capsulation because the animals should be the only one working on
12600.96 -> its internal variables. Okay. So avoid protected and avoid like, making the variables the members
12601.96 -> the the instance members visible. If we have a static method, public static, something.
12602.96 -> Well, I have to implement it. Of course, this can be used static void. For example, by saying
12603.96 -> animal dot something can also be used now. From Zoo or wherever. So we could say, animal
12604.96 -> dot something. Yeah, you see, it's also formed formatted differently. So we don't really
12605.96 -> see this as a static method.
12606.96 -> But this will not be inherited. So you cannot, like override this or so. And the gorilla
12607.96 -> class again, you can say animal dot something
12608.96 -> will actually you can even say and this is a bit weird. Gorilla dot something. But this
12609.96 -> is not inheritance. It's just Java is a bit smart. Here. The compiler is a bit smart.
12610.96 -> It knows gorilla is an animal. So it realizes this is an animal and then it takes the static
12611.96 -> method.
12612.96 -> But this is still not inheritance. Oh, K. Let me remove that. I hope I haven't confused
12613.96 -> you too much with that static.
12614.96 -> Just remember, we only inheriting the members of the clause. The instance methods and the
12615.96 -> instance variables. All Okay. Well, I think this is pretty much it. Maybe I should execute
12616.96 -> it again. And now we see dog is eating. He is calculated. Gorilla is eating gorilla is
12617.96 -> implementing the H by itself. This was I was overwriting the H method in gorilla, and only
12618.96 -> in gorilla lion is eating, he has calculated Tigers eating ages calculated. So inheritance
12619.96 -> really is a complex beast. And in conclusion, use it sparsely. Only use it when you can
12620.96 -> say, when you can apply the is a test. A dog is an animal, a gorilla is an animal, a lion
12621.96 -> is an animal, a tiger is an animal, a tool is not an animal. So you will not say tool
12622.96 -> extends animal never. Um, if you're just looking for something to like, not copy and paste,
12623.96 -> to not duplicate code, you can do something else, put your code into its own object, a
12624.96 -> tool object. And then always you can use composition. You could say, for example, a tiger has, I
12625.96 -> don't know, um, has a leg. If that makes sense or not, I don't know. So leg, leg.
12626.96 -> And then you if you have a method, for example, walk, you can say leg dot walk. And if you
12627.96 -> have another animal that also needs up it called eat still. So this would be walk. So
12628.96 -> now if you have another animal that should also use the lecture also use this method,
12629.96 -> you can also make it to have
12630.96 -> this member. And this by the way can and also should be an interface. So that really makes
12631.96 -> it much more flexible actually, even than inheritance. Because using an interface, you
12632.96 -> can exchange the behavior at runtime. This is something I showed you in the last episode
12633.96 -> talking about interfaces, where I said you could have some condition, if I don't know,
12634.96 -> Sunday.
12635.96 -> He was
12636.96 -> this implementation and otherwise the other implementation. I mean, this is just not real
12637.96 -> code. Just very fast. Else. I just hope you get the idea. I could say if Sunday, like
12638.96 -> equals to my fast leg, legs, you know.
12639.96 -> And
12640.96 -> the other days, I'm not so fast. I say used to slow lag. And then after the instantiation
12641.96 -> I would say like dot walk.
12642.96 -> Okay,
12643.96 -> so of course I mean this if else again introduces some complexity. So whenever you design something,
12644.96 -> there's always pros and cons, you have to think, what do I really need? But so you can
12645.96 -> use this, just to give you one example to not use inheritance and still not duplicate
12646.96 -> your code. Oh, okay. Let me remove that. Don't want it to be read. Wanted to be working.
12647.96 -> Okay, now, let's maybe recap before I finished this video. So we talked about inheritance.
12648.96 -> We talked about polymorphism. I showed you you can use composition. And there's also
12649.96 -> actually design principle it's called favor composition over inheritance. As I showed
12650.96 -> you you can mix using inheritance with was that one of these classes? Yeah. With interfaces,
12651.96 -> I showed you can implement several interfaces, you can only extend one class. So I cannot
12652.96 -> say it already. When I do the calmer Something is wrong. So I cannot say this animal to this
12653.96 -> doesn't work. Just believe me for now. Or I mean, yeah, this is also a class, which
12654.96 -> is implemented. Yeah. So you see class cannot extend multiple classes. This works in C plus
12655.96 -> class. And it's even more nasty than Single inheritance. This causes something called
12656.96 -> the deadly diamond of death. But I will not continue. This is too, too much for now you
12657.96 -> can google this deadly diamond of death. Because Java doesn't support multiple inheritance.
12658.96 -> I'm going to talk about the method finalize of the class object. The class object is the
12659.96 -> root of the class hierarchy. Every class in the whole Java universe inherits the methods
12660.96 -> of this class. So this is what makes those methods here, very important. Which is probably
12661.96 -> also the reason why those methods are very often used in Java developer job interview
12662.96 -> questions. So one way or the other, I hope I have now raised your attention. Also, you
12663.96 -> should now that this episode, as well as the following ones talking about all those methods
12664.96 -> are based on the really great book, Effective Java second edition from Joshua block. I think
12665.96 -> I mentioned it already earlier. Now I have to say it again, buy this book read it. Even
12666.96 -> better would be if you read it twice. It's full of condensed information. Advanced Java
12667.96 -> developer must know my episode is supposed to give you an introduction to the topic.
12668.96 -> But for more detailed information, it's necessary that you read this book. Okay. So let's already
12669.96 -> start talking about the finalize method. The finalize method is actually a hook method.
12670.96 -> What is a hook method? a hook method is a method that, um, there is an empty implementation
12671.96 -> provided in the class object. And the idea is that when you want this method to be used,
12672.96 -> he would provide an implementation in your own class, by inheriting by overwriting sorry,
12673.96 -> by overwriting this method. And then this method will be called by the JVM. But before
12674.96 -> I go in more details, the one the most important takeaway from this episode is, this method
12675.96 -> is flawed. So the best you can probably do, generally speaking, is not overriding this
12676.96 -> method. So not using it because it has its flaws, will, in this episode, see? Why. I
12677.96 -> mean, there are some few valid users, at least according to Joshua blog.
12678.96 -> I can tell you, I'm developing in Java since 2001. So quite a few years already, I have
12679.96 -> never ever overwritten this method. So today is probably the first time to demonstrate
12680.96 -> you what it is what it does. Okay. So maybe we should already jump into the into the code,
12681.96 -> because it might be easier to understand for you, or maybe before we read here, this description.
12682.96 -> So the finalize method is called by the garbage collector of an object, when garbage collection
12683.96 -> terminate determines that there are no more references to the object. So again, next question
12684.96 -> was probably what is the garbage collector? Well, the garbage collector is really a very
12685.96 -> cool thing of the Java language. Other languages such as c++, don't have it. As the name implies,
12686.96 -> it collects the garbage what's the garbage the garbage is or objects that you created,
12687.96 -> worked on them. And after some time, the process will be finished, at least on certain objects,
12688.96 -> he will not need them anymore. And so it helps to free up those memory resources. So that
12689.96 -> you hopefully never run into out of memory exception. And this is all done behind the
12690.96 -> cover as synchronously by the garbage collector for you. But here is already the problem of
12691.96 -> the finalize method. Because I said it's, it's called just before the garbage collector
12692.96 -> runs. The problem is the garbage collector is running as synchronously so you can't influence
12693.96 -> when or if the garbage collector is running. It is like its own smart beast. And you have
12694.96 -> no influence to tell it that it should run. You can only give it recommendations. But
12695.96 -> you have no guarantee that the garbage collector will ever run. And so you also have no guarantee
12696.96 -> that the finalized method will ever run. Yeah, and what would you usually do in the finalize
12697.96 -> method, the idea was, you will also clean up stuff, they're just not memory related
12698.96 -> resources, but not memory real related resources. For example, if you have a connection to some
12699.96 -> i o resource, like a database or a file, those are also system resources. And all resources
12700.96 -> are limited. So if you don't want to get in trouble, and if you don't want that your system
12701.96 -> totally, totally freezes. You have to, again, free up resources when you don't need them
12702.96 -> anymore. So the idea was to do that in a finalized method. Now the flaw is, you don't have a
12703.96 -> guarantee that runs. And this already says it's not working as intended. Okay. Besides,
12704.96 -> Joshua Bloch also gives other reasons. For example, He somehow measured that creating
12705.96 -> an object and destroying it, again, is 430 times slower when you have an finalizer method
12706.96 -> implemented. So again, don't use it. And now let's jump into the ID and look at it in more
12707.96 -> detail from a practical point of view. Okay. Also, just before, in the API documentation,
12708.96 -> you might have seen, this method is actually protected. Here. Again, we can see it protected
12709.96 -> void finalize, I mean, this Java API is just written into the source code. Here, you can
12710.96 -> see the source code of object dot java. So you see, it's also just a regular Java class.
12711.96 -> And you'll also see this method is empty. This is what I said, it's a hook method. The
12712.96 -> idea is that you override the method and that you provide code that is executed for cleaning
12713.96 -> up non memory resources.
12714.96 -> And Java, try to prevent that you directly call the finalize method, because as I said,
12715.96 -> the idea is that you don't call it but that the JVM calls it for you. So this is why this
12716.96 -> method is actually protected. Protected is quite hard to understand. One way you can
12717.96 -> use a method that is protected is if you are in the same package. So let's check this class
12718.96 -> isn't a package Java Lang. So I thought being nasty, I can just as well create a class in
12719.96 -> this package. And this is what I did here, test Java. In package Java Lang. You see,
12720.96 -> everything seems fine. I don't have any exception from the compiler. So now, let's try to call
12721.96 -> this method. And you see, this dot finalize, seems to be working. I mean, this is not working,
12722.96 -> because this is a static method. So we would actually need a non static method. Or I could
12723.96 -> also say, new object. Well, there is an exception, because it can throw a throwable as we see
12724.96 -> here at the bottom. I'm not going to handle this now, because I only wanted to show you
12725.96 -> from a theoretical point of view, this is possible. There's just one problem. Let me
12726.96 -> now surrounded with a try catch to get the compiler happy. So see, this would be now
12727.96 -> directly calling finalize, from a class that is in package Java Lang. So I'm within my
12728.96 -> public static void Main method. So I execute it. Bam, I get an exception, security exception.
12729.96 -> It's prohibited. I cannot use Java Lang as a package name. So this is not working. Okay,
12730.96 -> I just thought I should show you. I think this is quite interesting. Now, let's close
12731.96 -> this again. And let's complete remove this method. Okay, so what you should also know
12732.96 -> I mean, I said object is the root class, but it's also a concrete class, you can create
12733.96 -> objects of the class object. What I don't like here is that the word object is used
12734.96 -> twice, because the class is called object. That's a bit confusing. So anyway, you see,
12735.96 -> you can call all those methods. But here within the class car selector, we cannot call the
12736.96 -> finalize method. Okay. So for this, I have here, this portion class, that's also close
12737.96 -> the object class. And now let's override the finalize method, public void finalize, without
12738.96 -> any parameter. So to override a method, it is very important that you do it exactly.
12739.96 -> Like in the superclass, the only difference is, and this is allowed, I don't make it protected
12740.96 -> anymore, I can make it public. Because public is more visible than protected. This is fine.
12741.96 -> Okay. And now, the idea would be that in here, I do clean up my resources. Let's imagine
12742.96 -> I had some i, o reader, i, o reader, reader, Peter, I'm not going to implement this, just
12743.96 -> so that you get the idea. So the idea was that within here, he would like for example,
12744.96 -> close those resources for this, usually I already use provide a closed method. Now there
12745.96 -> are several problems for one, I said, you don't have a guarantee that this method is
12746.96 -> ever called. This is totally in control by the JVM, and you can not influence that it's
12747.96 -> running out of your control, it's running as synchronously. And therefore, it doesn't
12748.96 -> really serve our purpose. Second flaw is, if within here, we have an exception that
12749.96 -> is not caught,
12750.96 -> the
12751.96 -> process here will be stopped. And our objects will remain in some weird, let's say zombie
12752.96 -> state. Yeah. Okay, so the question is, what's the alternative than to using the finalize
12753.96 -> method, the alternative would be, if you have a class that you will use that uses resources
12754.96 -> that you want to be closed before it's cleaned up, you could provide, like I told you here,
12755.96 -> the reader would do. You could and you should provide some closed method. And then in here,
12756.96 -> you do clean up i o resources. I'm going to implement this now. And then make this compilable
12757.96 -> in car selector. Let's imagine this was a client of using Porsche. When we have Porsche,
12758.96 -> Porsche, a new Porsche you use a try Finally, we talked about Exception Handling array.
12759.96 -> And I think, there in this episode, I told you also, you can say try catch and finally,
12760.96 -> but you can also use the finally without a catch. Now, if we need a catch or not, this
12761.96 -> is a different discussion. What is important is that at the end, you have finally because
12762.96 -> the finally the cool thing about the Finally, even when there is an exception happening,
12763.96 -> it will always be executed. Because this was our problem, we need to make sure that the
12764.96 -> non memory resources get cleaned up. Okay, so try finally. And then in here, we could
12765.96 -> say Porsche e dot close to clean up the resources. This is how you probably do it in Java. Okay.
12766.96 -> Also, shortly, let me show you what I think is interesting. Let's go back what I had before
12767.96 -> and the finalize method. What I also want you to know is I mean, I said we overriding
12768.96 -> the method from the class object which is empty. And there's actually an annotation
12769.96 -> that is quite helpful here. And this is the annotation, the override annotation. See,
12770.96 -> when I put the ad, there is override. So about annotations. We have haven't talked a lot
12771.96 -> yet. So let me explain that. In short, this is actually some meta information for your
12772.96 -> compiler, that you say, Well, my intent here is I want to override some method. If this
12773.96 -> has a different name, some other name. Here, you see, you get an exception method does
12774.96 -> not override any method from its superclass. Now, you might not understand what this helps
12775.96 -> us. So let's, again, call it finalize. Now the thing is, you only override a method if
12776.96 -> the signature is the same as in the superclass. Now, if I add the parameter here, this is
12777.96 -> not overriding anymore, but overloading the method, because it's just a method that has
12778.96 -> the same name. But as it has a different parameter, it has a parameter string, and not no parameter.
12779.96 -> This is not overriding anymore. And now we get a compile error. So you will directly
12780.96 -> notice. So this helps us to have the problem directly at compile time while we're still
12781.96 -> in our ID. And we will not because otherwise it could happen, you think you have implemented
12782.96 -> a method while you have not. And then you're still using the superclass method. And this
12783.96 -> you will only see when your code runs on production. This is why whenever you override something
12784.96 -> at this override, annotation. Okay. So I think this is pretty much it, talking about the
12785.96 -> finalize method. In short, again, generally speaking, don't use it. Instead, to free up
12786.96 -> non memory resources use a try Finally, I'm going to talk about a method clone of the
12787.96 -> class object,
12788.96 -> a class object I said before, is the superclass of all the objects in the Java universe. And
12789.96 -> this is why you can use the method clone in all your objects. Now, the question is, should
12790.96 -> you Really? And the short answer is, you should not at least generally speaking, and this
12791.96 -> is similar to the finalize method that we talked about in the last episode, which is,
12792.96 -> again, the reason why I'm talking about clone today, because in this aspect, they're both
12793.96 -> quite similar. Okay, but before going in more details, maybe first of all should clarify
12794.96 -> what actually does the clone method do. And clone as the name implies, it creates an identical
12795.96 -> copy of the object that you call clone on. So what it does not do is, if you have an
12796.96 -> object, you can always assign it a second or third, how many references ever you want.
12797.96 -> The problem is with references, that when you work on this reference, all other references
12798.96 -> will have will be influenced by your changes. And sometimes this is not what you need, you
12799.96 -> want an independent copy. And for this reason, you could use the clone method. However, there
12800.96 -> are actually better alternatives, which I'll tell you later. But now enough of talking
12801.96 -> Anyway, let's jump into my ad and look at the code. Okay, so, here you see my Porsche
12802.96 -> test, you might remember the pushy and the other cars from my earlier episodes. Before
12803.96 -> I show you the nasty stuff, I wanted to show you one case, where actually I think using
12804.96 -> clone is actually good. And this is here I have prepared an array of strings 123 and
12805.96 -> here, I mean array is also an object. So it also has the clone method and for the string
12806.96 -> for the array, it was already implemented the way it should be. So you can and you should
12807.96 -> clone your array. So I can say string copied array equals to array dot clone. And then
12808.96 -> I can assert not same, which means this check checks. Now, if we just have a reference.
12809.96 -> In this case, it would be the same
12810.96 -> airy
12811.96 -> and copied airy. Which, to show you that their friends I can also call, assert same and use
12812.96 -> twice the same reference. So this should be true. They should with not also be true. So
12813.96 -> there are two different instances.
12814.96 -> You see, it finished with a green bar, this is what we want to see. So it seems error
12815.96 -> and error compared to itself, it's both the same reference, they're both referring to
12816.96 -> the same object. But the copy is not the same reference, it's not the same object, it is
12817.96 -> a new object. And now, I mean, I want to make this short. But I want to show you at least
12818.96 -> system out, print ln. And then, you know, this is not I just want to show you the first
12819.96 -> element and then I just hope you believe me, or you can do it at home can print out the
12820.96 -> whole elements in in an in a loop. Now I'm just showing you the first element of my copy,
12821.96 -> and you see it's one. So the other ones are also or unlike just as well. Otherwise, you're
12822.96 -> telling me copied error. This way, you also learn how you can print out the whole array.
12823.96 -> And this is now I can print odd STR and this will then in the loop and a for each loop,
12824.96 -> print out all the strings
12825.96 -> for us.
12826.96 -> So I hope this is working now. 123 C, out. Okay. So for now this should be enough. This
12827.96 -> was just a very short demonstration of a good case of clone. Actually, I found on the internet
12828.96 -> and very interesting article Actually, it's a newsletter article from Dr. Heinz Cabot's,
12829.96 -> he's really a very cool guy. I love his newsletters. And he actually made a test and found out
12830.96 -> that clone for very small areas might be a bit shorter, f slower. However, for large
12831.96 -> arrays, it's actually faster than any other method. Well, I can't go in more detail, we
12832.96 -> don't have the time. And this is also very, very advanced already. And we're still on
12833.96 -> beginner level, approaching more advanced. So anyway, let's continue with our portion.
12834.96 -> And this is now really test driven style programming. Because I start with an empty test. The code
12835.96 -> is not finished, we start with writing a test to test Well, first of all we read, and then
12836.96 -> we are working our way to get the test screen. Okay. So I say Porsche Porsche equals to new
12837.96 -> Porsche, actually, this is something you can't know. Before doing this episode, I have extended
12838.96 -> adjusted my class a bit. I mean, you might remember the Porsche from my last episodes,
12839.96 -> because it was empty. Initially, there was no attributes, no instance members. So this
12840.96 -> I had to change because I want to show you something that we copy. So I added a string.
12841.96 -> And I said, it's the owner, the name of the owner. And well, which name should I choose?
12842.96 -> Because I always wanted to own a Porsche. I thought I might just as well make me the
12843.96 -> owner of the Porsche. And because you probably also want to own a Porsche. I thought I should
12844.96 -> make you the owner of our copy of our clone. Because I will not give you my pushy, but
12845.96 -> I might just as well copy mine and then give you this copy. Well, in real world, this is
12846.96 -> pretty much impossible. However, here in Java, See how easy that is? Only problem we have
12847.96 -> is I don't know your name. So for this example, I just assume your name is Peter. So I say
12848.96 -> Peters for xi equals to new pushy. But this is not what we wanted to do. Right? We wanted
12849.96 -> to clone. Yeah, because this is no easy. I can just say Peter, and then you have your
12850.96 -> pushy but this is not the original idea. So let's remove that. And now let's say Porsche
12851.96 -> dot clone. And interesting enough, really, I mean, we can see what happens behind the
12852.96 -> covers, because this is done really, by the JVM. And we don't care too much, as long as
12853.96 -> it works. But there is never a constructor actually cold. So this is really internally
12854.96 -> copied from the memory. It's just see, we still have this read something is still wrong.
12855.96 -> I mean, I said, we start with a not working test. So it says clone has Protected Access
12856.96 -> and Java Lang object. And this is something we have to fix. So the method that says the
12857.96 -> method is already there. The problem is, it's not visible to us, because it is protected.
12858.96 -> Protected would be visible in the same package. The class object is in the package, Java,
12859.96 -> Lang, as I showed you last time. But here we are in a different package. Also, my Porsche
12860.96 -> test does not inherit anything from Porsche. Because this is from Porsche, so I can't use
12861.96 -> clone in here. Okay, but what I can and what I will do, I can override the original clone
12862.96 -> method. But still, I want the code the implementation of the class object. But let's already jump
12863.96 -> into the Porsche class. So I will override it, public, Porsche, because I wanted to return
12864.96 -> a Porsche to me,
12865.96 -> clone.
12866.96 -> And then you might still remember from my last episode, we can and we should put the
12867.96 -> override here to have a check from the compiler side, that we actually did everything correctly.
12868.96 -> Now, let me format that. Okay. And you see, there's nothing red. So it seems like so far,
12869.96 -> everything is fine. We'll actually went into one interesting thing is the original implementation
12870.96 -> says object, because in object, what could you return, you don't know. The object that
12871.96 -> the method always is exactly copying whatever object there is. And in our case, we have
12872.96 -> a Porsche. So the so it is also fine to directly make this return pushy. But now we have an
12873.96 -> empty implementation. And we have to return a Porsche. Or we could say return new Porsche.
12874.96 -> But again, this would not be a clone. So this would, our test would fail in this case. So
12875.96 -> this is not what we can do. So we have to say super, super means. I want to call a method
12876.96 -> from superclass in this case object. And you will see already here I see clone is actually
12877.96 -> the first method, because my ID is already smart, it knows the name of this method is
12878.96 -> clone. So it assumes I want to call super clone. Okay, so and then I want to return
12879.96 -> it. So all we did so far is we override the method. And then again, we said, well, actually,
12880.96 -> I don't really want to override it. All I want is I want to use the method of class
12881.96 -> object. So all we did so far is we made the visibility public so that we're able to use
12882.96 -> it this is all we did so far. But now, you see there is still a problem unhandled exception
12883.96 -> Java Lang clone, not supported exception. And this is already in my opinion, a flaw
12884.96 -> because, like, why does this Now throw a clone not supported exception, if we do support
12885.96 -> clone. So, anyway, this is how it is. And now we have to fix that the way we fixed that
12886.96 -> is we say try, because there is an exception that could happen. And we will catch the exception.
12887.96 -> Catch. And there my ID Egan helps me clear not supported exception.
12888.96 -> I usually give it the name here. Okay, now, what should we do here? Some people say return
12889.96 -> now. Because we have to return something. This is just the signature forces us
12890.96 -> to return something. But this is not so nice. I mean, actually, we assume this is hopefully
12891.96 -> never happening. But if it for whatever reason is happening, we really want to see that it
12892.96 -> is a problem. So in this case, and I kind of copied that from Josh block. Because again,
12893.96 -> my episode here about clone is based on his book, Effective Java second edition. And it
12894.96 -> was exactly the same with a finalized episode. So I can only give you a short introduction
12895.96 -> to the topic. Um, Josh block in his book, he has like, I think eight pages only on the
12896.96 -> clone method. You should really buy the book and read it. So for this, you can go to macros
12897.96 -> minus bu.com, click on mastery, it's, and there you will find the book and you can buy
12898.96 -> it directly. Yeah, also all the books in the must read section. I mean, I have picked the
12899.96 -> name for a reason. Those are really books. I want you to read them all. They're really
12900.96 -> classics, the best of the best best Java books you could find, in my opinion, at least. So
12901.96 -> if you trust me by that book and read it, okay, anyway, so what he did and what I will
12902.96 -> do the same, as he said, throw new assertion error. Because if this happens, this is not
12903.96 -> even an exception. Is this really an error? We really have a big problem here. If we get
12904.96 -> this clone, not supported exception. Okay, so this year now seems fine. But there's still
12905.96 -> something wrong. And this is it says I'm calling super dot clone. And as I told you, this is
12906.96 -> the method from object, an object returns an object, at least from the signature of
12907.96 -> the method. But we are smarter we know actually, it's safe to say pushy, because this object,
12908.96 -> I mean, the super type is object. But the subtype is a Porsche. So we do an explicit
12909.96 -> cast, and we cast it to Porsche. This is safe here. Yeah, if it was not safe, it would throw
12910.96 -> a class not support F. Class cast exception. Sorry. But in this case, believe me, we'll
12911.96 -> see. It'll it should work. Okay, well, are we done? It looks like we were. Well, actually,
12912.96 -> as I said, this method is flawed. So we are not done, we still have to do some more thing.
12913.96 -> But this I want to see. I mean, my idea was to implement the method I did that. So now
12914.96 -> let's go back to our test, you see, everything is? Well, I can't say green, but the red stuff
12915.96 -> has gone. So I can execute the test. But I haven't asserted anything yet. So the first
12916.96 -> assert that I want to do is I want to assert not same. This is just a shorter, Handy form
12917.96 -> of saying not equal. So it won't be the same if we say pushy, not equal to Porsche Peters
12918.96 -> pushy, because the idea is that when my clone word that I have a new object. And because
12919.96 -> it's good to have a method that already from the method name tells us what it does, I use
12920.96 -> this one. And I compare not pushy to Peters pushy. So my first test is just asserting
12921.96 -> that this reference here is not referencing this Porsche here now. But something else,
12922.96 -> this isn't our first test all I want to achieve. Okay, so I execute the test.
12923.96 -> And bomb.
12924.96 -> You see the assertion error? I said, Well, everything will be saved law when it's not.
12925.96 -> And this is why tests are so great. Yes. And now we can see what happened. And think about
12926.96 -> why did this happen? Okay, so by jumping here, see, line 28. I see this happened. Problem
12927.96 -> is here in this case, without further knowledge, it would really be hard to know why this happened.
12928.96 -> So here, sorry, I have to help a bit. Thing is, I mean, I told you this method is flawed.
12929.96 -> It's not enough to use the power of inheritance here. On top you have to use, you have to
12930.96 -> implement an interface here. So we are already implementing car. But for interfaces, I told
12931.96 -> you in the episode about interfaces, we can implement several interfaces. So here I have
12932.96 -> now to implement the cloneable interface from Java Lang also. Now, funnily enough implementing
12933.96 -> the interface, normally, I would expect that I would have to implement some method. Well,
12934.96 -> in this case, it's different. We don't have to implement anything. And this is a specific
12935.96 -> case, this interface we call a market interface. So this interface is actually empty. There's
12936.96 -> nothing in there. It just tells the JVM. I'm implementing cloneable. So you can call cloneable
12937.96 -> here, it's a clone here it works. And this is a bit awkward, because normally when you
12938.96 -> implement an interface, you would on the Reference Now, like I can now say that I implement cloneable,
12939.96 -> I can also make this a cloneable. So that my pietras portion now plays the role of being
12940.96 -> a cloneable. The problem is, this doesn't help me anything. I don't have the method
12941.96 -> cloneable. Here, all I have is the other methods of the class object, which we're not using
12942.96 -> now. So because I can also say car, I mean, I'm implementing, also the car interface.
12943.96 -> And then I can call the methods of car, which is drive, plus all the methods of class object.
12944.96 -> Okay, well about macros interface. That's also another topic. This is a design pattern.
12945.96 -> haven't talked much about design patterns yet. Marker interface really has good users.
12946.96 -> So a marker interface, generally speaking is not bad. It just here in this case, it's
12947.96 -> a bit weird that you have to implement a market interface and then on top, you have to override
12948.96 -> the method. Okay, so I make this portion again. But now, and now the same as already, again,
12949.96 -> working because otherwise you could not compare different things. Let's try it again. And
12950.96 -> see, now we have the green bar process finished with exit code. So my first assumption is
12951.96 -> correct. Peters pushy is not the same instance, as pushy. Okay. So now I want to see who is
12952.96 -> the owner at the moment of Peters, Porsche, Peters, Porsche, Dodd, s string. And this
12953.96 -> is why before I prepared this method, because it returns Porsche II off plus the owner's
12954.96 -> name, because at the moment, we don't have another way of seeing the content of owner's
12955.96 -> name. So I wrote this method to see who is owning it at the moment. Okay. And my expectation
12956.96 -> when we're finished is that the name would be Peter. So I would say it should return
12957.96 -> partially off, Peter. So let's write a test for this. assert, equals, first, the expectation,
12958.96 -> you also see it expected. So I'm expecting it to say pushy off Peter. Okay. And then
12959.96 -> comma. And I put here pushy, Dodd as string, which is calling the method. So I expect the
12960.96 -> method to return portion of pizza later on. I mean, there's also again, a method called
12961.96 -> equals. In an later episode, I'll talk about this and we will have a better way of comparing
12962.96 -> that for now. I'm using the S ring method, because we haven't talked about the equals
12963.96 -> method yet. So there's still something missing.
12964.96 -> Okay. I can remove that. So let me also execute this test now. And it should be read. Yeah,
12965.96 -> oh, there's an error. I have missed a semicolon. Again, sorry. Yeah, comparison failure. Expected
12966.96 -> portion of Peter bar is still mine. Now this is even cooler for me. Now I have actually
12967.96 -> two portions. But okay, I said you get one. So let's change that. And for this, I will
12968.96 -> now change the owner. So I will sell on my second car. Okay, and I will sell it to Peter.
12969.96 -> Which means I mean, I just made this method up before I assign the owner's name the new
12970.96 -> owner. Okay. Also, by the way, I mean, here I'm using string to have this as simple as
12971.96 -> possible for our example. Usually, I would prefer to have this proper object also, like,
12972.96 -> name, for example, and I also already have that here. But in this fast example, I use
12973.96 -> string. But more object oriented would be if you have name as an object there. Okay,
12974.96 -> so I sell it to Peter. And now I expect the test to be green. Let's try it again. Okay,
12975.96 -> it's green,
12976.96 -> it worked.
12977.96 -> But now I have a fear. What if now my pushy would not be mine anymore. So on top, I want
12978.96 -> to assert that the The original pushy is still mine portion of macros to the original portion.
12979.96 -> K, which also worked. And this tells us now starting from my pushy macros, I called the
12980.96 -> clone method, it created a new object in memory. And this new object was assigned to the reference
12981.96 -> Peters Porsche he inserted that they're not the same object to different objects. And
12982.96 -> then I changed the second object. And I gave it the owner of Peter. So and I asserted that
12983.96 -> now, the owner's name is Peter, by comparing the string. And second, I asserted that what
12984.96 -> I was working on the second object, the copy was not influencing my policy. So this is
12985.96 -> like proving that our clone operation did work. But now let's look at the code. What
12986.96 -> we needed to do for this, I had to say implement cloneable, I had to override the clone method,
12987.96 -> I had to call the super clone method, I had to catch the clone, not supported exception.
12988.96 -> This is a lot of lines for only this. And actually, there's more to it. Because actually,
12989.96 -> what this does is it creates only a shallow copy, and not a deep copy. Now, again, this
12990.96 -> is a more advanced topic. So I try to keep this as short as possible. What's the difference
12991.96 -> between a shallow copy and a deep copy? Okay, well, a deep copy for this, I have prepared
12992.96 -> here a more complex object BMW. And here I'm using actually the object name. And I'm even
12993.96 -> using a second object color. And let's make this a bit bigger. So you see more, a deep
12994.96 -> copy would mean that not only BMW is copied, but also all the objects inside of BMW are
12995.96 -> copied. So that they are also independent, that they're not referencing the same object.
12996.96 -> But a shallow copy will here, only copy the reference. And the object for name, as well
12997.96 -> as the object for color will still be the same objects for shallow copy. Sometimes this
12998.96 -> is okay. And sometimes it's not, it really depends on your implementation. However, in
12999.96 -> short, if you're using clone want to make a deep copy, you will also have to call clone
13000.96 -> on the internal objects, and this here, I have prepared. So here, I'm calling clone
13001.96 -> actually, three times. Now, one more problem of the clone method is what I'm actually doing
13002.96 -> here is, first of all, I cloned BMW, and then on this attribute, and this one, which is
13003.96 -> already fully functional, I assign a new value, which only works if this is not final. So
13004.96 -> it turns out not to in order to make a deep copy, it only works if your internals are
13005.96 -> not final, and sometimes you want them to be final. So this is really a limitation of
13006.96 -> the clone method. And also, I mean, how complicated it is, is not so nice. Okay. Um, and for this,
13007.96 -> there are alternatives I told you. I've written here a lot of code. I have written this code
13008.96 -> so I could show you what to think. Yeah, I would want to make this episode not as long,
13009.96 -> because I noticed many of you are only watching like the first minutes. So 95% will already
13010.96 -> be asleep anyway. So let's keep this short. So in short, let me show you alternatives
13011.96 -> to using the clone method. There are two alternatives. The first alternative is using so called copy
13012.96 -> constructor, and this is this thing here. The copy constructor has one parameter, and
13013.96 -> this is the same object. And then you see here, I say new name, on owner's name, new
13014.96 -> color on BMW dot color. So I'm taking the internals and I'm creating new objects on
13015.96 -> it.
13016.96 -> And so in the end, I will have a new object that has the same values as the original object.
13017.96 -> This is One alternative. The other alternative would be, and this is actually my preferred
13018.96 -> one to use a so called static factory method.
13019.96 -> And this is this here, it's a static method. So you can directly say BMW as the class name
13020.96 -> dot new instance, you can give it the BMW object you want to copy. So in this case,
13021.96 -> probably Marquess BMW. And then you You see, I again, call the constructor, new BMW. But
13022.96 -> here, this is a more complex object. So I have to recursively we call this recursively.
13023.96 -> Because again, I say new instance. And he also new instance. And I have to again, call
13024.96 -> those methods to also cop copy the owner's name, because now I'm actually doing a deep
13025.96 -> copy, I could have also just assigned the values, this would be a shallow copy, but
13026.96 -> it's safer to have deep copies. Okay, so And for this, we can also have a short look into
13027.96 -> name and color. Because there again, I do the same thing. Here I have my new instance
13028.96 -> method. So this is taking a parameter of name, and then says new name, first name, dot last
13029.96 -> name. Now, first name and last name are both strings. And strings are also objects. So
13030.96 -> why do I not need to copy down? Okay, now it gets more and more complicated, I'm sorry,
13031.96 -> um, thing is a string as an object, but it's actually an immutable object. And immutable
13032.96 -> means whenever you change the object, like you assign, instead, first name, Marcos, you
13033.96 -> say, Peter, you will not influence the other reference. But instead, whoever said make
13034.96 -> this, Peter will get a new object. So this was really helpful. And for string, this is
13035.96 -> done for you. Actually, you can do this for your own objects too. And in order to achieve
13036.96 -> this, you just have the limitation that you don't offer any method to the client that
13037.96 -> allows the client to change the values in here. But instead, you will always for any
13038.96 -> change, return a new instance. And then you have an immutable. For this, I have also here
13039.96 -> an immutable test. Because there's another class that actually does it, which is big
13040.96 -> integer. Big integer is similar to an int, that we already looked on it just a bit better.
13041.96 -> First of all, because it can work on ends of, well, at least theoretically, any length
13042.96 -> until your memory is full. And there you have operations to add and subtract, for example.
13043.96 -> Now, when you say one, add one, this is returning a new object to but the original object will
13044.96 -> not be influenced by this operation, you can also subtract, but everything that you call,
13045.96 -> every method that you call will never influence will never change how the object looks. So
13046.96 -> it's created once with the constructor, this will like assign one to it. But after this,
13047.96 -> you can never ever changed it again, which is very helpful. In many cases, it's really
13048.96 -> a good design principle to use immutables whenever possible. Um, yeah, and it's also
13049.96 -> very good to use multiples when you do code multi, multi threading. We haven't talked
13050.96 -> about multi threading yet, we will at a later time. But there immutables are also very helpful,
13051.96 -> they will make everything more easy. So, maybe you take one more thing with you from this
13052.96 -> episode. And this is favor immutables try to design your objects your classes in a way
13053.96 -> that they are not mutable, that they cannot be changed after they were created. Or came
13054.96 -> here at the same thing with string. Maybe I can show you so I call so assigned twice
13055.96 -> Hello, which in memory is actually the same object. But when later on here, I Say hi.
13056.96 -> This will influence the string one, and not influence a string to let's execute this shortly.
13057.96 -> So you see, like the speaker so we can see Bo's bigger even. Okay. So now I see the first
13058.96 -> string here printed Hi, the second string printed Hello. And so they're not equal, the
13059.96 -> first one has high, and the second one has Hello. And if I remove this, this is why I
13060.96 -> had commented it out. Let's execute it again. Of course, now they both have Hello. So that's
13061.96 -> the difference. And this is one example of an immutable strings are, by definition immutable.
13062.96 -> Maybe we could also call this here. So I print out any n 01. And two. And also, I assert
13063.96 -> to do a few things. So the input value of one is one, the input value of two is two,
13064.96 -> and the end value of zero is zero. Well, I'm operating on these objects, they will always
13065.96 -> return a new object, return a new object, they will not influence the original object,
13066.96 -> this is an immutable, this is something that you should try always to achieve our K, let's
13067.96 -> go back to Chrome. Let's recap. So in order to properly use clown, you have to first of
13068.96 -> all, override the clone method so that it is public. Second, you don't have to, but
13069.96 -> it's recommended. Use not object here, but use the type of the class that you're in,
13070.96 -> then you will have to do an explicit cast to the class here. Catch the claw not supported
13071.96 -> exception, thrown your assertion error, which will show you in case you forgot to implement
13072.96 -> cloneable, which you will also have to do. However, what this is going to achieve, it
13073.96 -> will create a shallow clone for you. Which means if there are objects that are not immutables,
13074.96 -> and you then operate on those objects, this can break another object, because still you're
13075.96 -> not totally independent, you're only potentially independent, you're only on the first level
13076.96 -> independent. But if here you have name, this will only copy the reference and the object
13077.96 -> here would still be the same. If you also want to achieve this, you have to implement
13078.96 -> a more complex clone method, you have to also call clone on the internal objects and then
13079.96 -> assign the new clone values to your internal attributes, which will only work if they are
13080.96 -> not final. So this already limits the way you can implement your code. See if this is
13081.96 -> not working now. So and this is one of the one of the many, sorry, one of the many reasons
13082.96 -> why you should not use clone, other than to clone an array. And I showed you two alternatives.
13083.96 -> One is use a static factory method. I call the new instance. Same like Josh block in
13084.96 -> Effective Java that you should buy. And here, I call the constructor. And again, recursively.
13085.96 -> I call again, a factory method on name. And again, a factory method on color, which even
13086.96 -> creates a deep copy. Or I can do the same thing with a constructor. But you see this
13087.96 -> is actually shorter. So this is why I would prefer to use the factory method. But it both
13088.96 -> works. Okay, so here, I call twice a new constructor, I create a new name object, and I create a
13089.96 -> new color object. Okay, and then in name, we can also look. You see, I do the same thing.
13090.96 -> And this now is strings and I said strings. Now we don't have to call clone because a
13091.96 -> string is immutable. So you have to do this recursively until you reach either an immutable
13092.96 -> object or a primitive. If this were again, like first name object, we would have to continue
13093.96 -> with cloning, or copying, like calling the constructor until you reach either a string,
13094.96 -> or a primitive value or another immutable object. See here also implemented clone.
13095.96 -> And then we can also look at color one last time. For all of them, I have done the three
13096.96 -> different implementations here with a static new instance method, here with a clone method.
13097.96 -> And last but not least, here with a copy constructor, it receives a color object, and then it retrieves
13098.96 -> the string from the original object, which is a string, which we don't have to clone
13099.96 -> any further. I'm actually going to talk a bit about various smaller topics. We're still
13100.96 -> on track, talking about the class object, and all its methods. The last two methods
13101.96 -> I need to tell you about are hashCode. And equals. Actually, they're one of the most
13102.96 -> important methods in Java, I think. However, hashCode and equals are a bit more complicated
13103.96 -> to explain. So before I can tackle them, I decided to push an episode in between to straighten
13104.96 -> things up. And to talk a bit about the missing pieces in this episode. Okay, so let's start.
13105.96 -> As you see, I have prepared this demo test class for you. Actually, we're not really
13106.96 -> testing something today. This is really only to use to demonstrate those few small missing
13107.96 -> things. So let's do one by one. And the first thing is, I want to talk about static imports.
13108.96 -> You might remember, I think I talked about static imports, in the first three episodes,
13109.96 -> and I kind of promised you to later on give you more details about it. The problem at
13110.96 -> this time was we hadn't talked about static. Well, in the meantime, we have, I just didn't
13111.96 -> have any better opportunity to talk about it. And I felt a bit guilty. So I think now,
13112.96 -> I should really finally tell you what exactly is a static import, how you can use it, and
13113.96 -> what it helps you. So actually, we used it all the time. And you might have seen it.
13114.96 -> Here on top, I have this import static org j unit assert dot star, it's just grayed out
13115.96 -> because at the moment, I'm not using it. This is also set here unused import statement.
13116.96 -> Now you can see it. And you can also see here, the regular import or j unit test sub question
13117.96 -> is, what's the difference between the two of them? So this one imports the code of the
13118.96 -> whole test class? Well, this one here, a static import just focuses on all the static methods.
13119.96 -> Because in j unit, you know, when we want to test, we always use these assert methods.
13120.96 -> assert equals assert true.
13121.96 -> Let's do that now. Like assert. True, you see, it already helps me true. I mean, when
13122.96 -> true is always true. There's a stupid, but I just want you to see the method. And the
13123.96 -> thing is, this is only not working because I have this here assert and seeing, it's not
13124.96 -> great anymore, it turns white, because now it's in use. So let's actually have a look
13125.96 -> at this class, I can jump there, you see even it says it extends object will no wonder all
13126.96 -> the classes extend object anyway. So here you see, I see the decompiled code. This is
13127.96 -> what my ID he can also do to show me the code. This is very helpful, so you understand better
13128.96 -> what happens behind the cover. So you Here you see a lot of static methods. So this class
13129.96 -> actually like groups them and makes them usable to me. And as you might know, from static
13130.96 -> when I talked about static, the way you would use a static method would be normally you
13131.96 -> say class name, dot assert true. Now you can either use the full fledged class name, which
13132.96 -> is org dot j unit dot assert, and then assert true or if you don't want to use the package,
13133.96 -> you would import the class and then you can just say assert dot assert true. Of course,
13134.96 -> there are also other methods, you can have a look on those, by yourself. actually quite
13135.96 -> complicated ones like you can even compare areas, and so on and so forth, not equals
13136.96 -> equals, with message without is equals, and so on. Well, we have used some of them. So
13137.96 -> this means I can also say, assert dot assert true. But now you see this is not working,
13138.96 -> because I have not normally imported the assert class. So if I would want to do this, I would
13139.96 -> have to say org, J unit dot assert, and then import it like this. Now you see it's not
13140.96 -> used anymore, because now I'm not statically importing it, but regularly, and I'm using
13141.96 -> the class name to use the method. But I mean, when they introduced it, I think this was
13142.96 -> with Java five. The reason to introduce this where it was to just make these statements
13143.96 -> shorter, because you don't always want to write assert dot all the time.
13144.96 -> Okay,
13145.96 -> and you could also do it as said before, without any import, this would even be more longer
13146.96 -> than you could go without the import. Now, they are not see, but there it is working.
13147.96 -> That's the difference, because now I don't do any import. Let's put it back. And then
13148.96 -> we can go with or without. And if you wanted like this and the shortest form, you need
13149.96 -> the static import and not the regular import. So that is a static import. And the dot star
13150.96 -> means just input all the static members or members, static is not members, all the static
13151.96 -> functions and also the static variables of the class. So if you have variables you want
13152.96 -> to import that are static. This also works with the star operator here. But you can also
13153.96 -> say you import only specific functions or attributes. So this is up to you. Okay, so
13154.96 -> that's all I can tell you about static imports, I think sometimes they're helpful. More often,
13155.96 -> it actually happens, then you would think that you would import several methods or attributes
13156.96 -> that are the same in different classes. If you have that it's exactly the same, like
13157.96 -> I told you about the imports, you can only import one method name once by using a static
13158.96 -> import. If you're not have a second class that has the same method, you will then have
13159.96 -> to use the full fledged, or at least a class name so that the JVM, the compiler knows,
13160.96 -> in this case, I want the assert true method from this class. And in the other case, I
13161.96 -> want the assert true from another class. Okay, so you can't I mean, there must be a way that
13162.96 -> the compiler understands what you're trying to do. If I only import this statically once,
13163.96 -> I mean, then it's just obvious the assert true is part of the assault class here. Oh,
13164.96 -> okay. So that much about static imports. The next small thing I want to talk about, let's
13165.96 -> open this up is default values for different data types. I think this is quite important.
13166.96 -> And also interesting. Because I see many people that would have here, member variables defined.
13167.96 -> And then they would say something like, here, or for cards, different weight. Like for the
13168.96 -> Boolean, they would say false. Or for the object, they would say novel. And you don't
13169.96 -> have to do that. Because now for object, as well as false for a Boolean is the default.
13170.96 -> So this is in my eyes, this is just clutter, you write code that you don't have to. I mean,
13171.96 -> for every rule, there's always an exception. For example, if this is very important that
13172.96 -> this is set to false. And this is really a specific case and you want to give a message
13173.96 -> with it. It might make sense to sometimes right here explicitly false. But then it also
13174.96 -> maybe you should name your variable a bit different so that it says why this is important.
13175.96 -> And because my Boolean now I mean, this might be the problem. It doesn't say why this is
13176.96 -> always false. Okay, so And now let's have a look at all the different defaults. But
13177.96 -> when I say default, this really only applies for these member variables up here. If you
13178.96 -> for example, have a local variable Like Boolean, B, you can't do that, if I'm not trying to
13179.96 -> use it, this is not going to work. If b, this will give me a problem variable b might not
13180.96 -> have been initialized, but it does work with the Boolean up here. This is going to work,
13181.96 -> see, and now it will count as false. So the if would not be executed the branch. Okay,
13182.96 -> but now enough of talking, blah, blah, blah. You might already be asleep, so wake up. Okay,
13183.96 -> so let's make this a bit bigger, so we can see it properly. Okay. Now, so you see, by
13184.96 -> default value, short default value, those are all zero.
13185.96 -> Actually, there are many number types that we haven't talked about. And this is also
13186.96 -> what I'm just going to introduce right now. Because we totally focused on end, because
13187.96 -> this is actually the one that is most times used. But as you see here, there are also
13188.96 -> others. I think I shortly once showed you bite, and I also showed you one's car. Um,
13189.96 -> but there are also others. In my opinion, this is just the smaller data types, we will
13190.96 -> see the ranges very soon are only here because I think like this or similar, they existed
13191.96 -> in other programming languages before Java, like maybe c c++. In my opinion, this is a
13192.96 -> The reason is probably because like something like 30 years ago, the memory was so expensive.
13193.96 -> And that was really the memory space was so limited, like you would have a memory of,
13194.96 -> I don't know, a few kilobytes. Now with gigabytes of RAM, this is totally a different issue.
13195.96 -> So the space end users actually a bit more bytes. But the space is really not relevant
13196.96 -> these days, in 99, and probably 99.9% of the cases are always use int. So wide and short,
13197.96 -> in my personal opinion on something like deprecated. I mean, this is not true, actually, because
13198.96 -> I'm sure someone can tell me there is a specific case where you would need them. It just that
13199.96 -> on average, generally speaking, you should be fine with an int. And we will look at actually
13200.96 -> the sizes of these types in a second. So yeah, that long is actually bigger, can save longer
13201.96 -> numbers than end. This sometimes might be needed, but also not so often really, I think,
13202.96 -> now float and double, as the name implies, at least for float, they're both floating
13203.96 -> numbers. And double, I think the name comes because it's like double the space or something,
13204.96 -> then that of a float. Actually, also these I hardly use, because first of all, I personally
13205.96 -> did not worry too much with these kinds of floating point calculations. And second, in
13206.96 -> case I did, for example, calculating on money that you would need that. But they are they
13207.96 -> are quite problematic, actually, because they don't calculate properly on the scent, it
13208.96 -> can happen that when you have something like two euro 20 multiplied by, I don't know, divided
13209.96 -> by a number of people that in the end, you lose or you gain a cent. And like in India,
13210.96 -> in the financial industry, this is just not okay. So therefore float and double can't
13211.96 -> use be used there. The reason I can't perfectly tell you but I think it has to do with internally
13212.96 -> these numbers of course stored in a binary format, you know, a computer only knows zero
13213.96 -> and one. And then when, from this format, it's transferred to our decimal format. For
13214.96 -> those floating point numbers, then there are rounding issues. And therefore, when you really
13215.96 -> need to have a correct floating point result, there are various other solutions. One is
13216.96 -> to store the number without the floating point, for example, as a long or end or alternatively
13217.96 -> even as a string. And then you do your calculation, and when it's finished. You insert the floating
13218.96 -> point visually at the place in the UI where it's needed. Which is also dependent on like
13219.96 -> local settings, like numbers are formatted differently in different languages. So therefore,
13220.96 -> this is usually the way you would go, at least definitely in the credit card or in any financial
13221.96 -> industry. Okay, so anyway, float and double are both floating point numbers. What is interesting,
13222.96 -> by the way, is like, when you have a constant value,
13223.96 -> like 34 43.31, this here, I mean, this is a value of constant value. And if I just write
13224.96 -> this down like it is at the moment, this is now by definition automatically a double.
13225.96 -> If I want to have this as a float, I have to say, the capital a lowercase F, at the
13226.96 -> end, which makes it up float. So, if I have like float my float node equals to this, or
13227.96 -> he really have to say f at the end, because if you leave it, I would get a problem, because
13228.96 -> it says it found a double, but float is required. And the same applies actually for int, short
13229.96 -> bite, there is just the other way around, because there is the default. And when you
13230.96 -> want to use a short short as equals to 43. This just works implicitly because Java sees
13231.96 -> the space is fitting. And then it will just implicitly convert the end because this is
13232.96 -> really an end to a short. Ever. Let's try the same thing with a long, long for d3. This
13233.96 -> also works because now you try to store the smaller thing, the end into a long, which
13234.96 -> should always fit. Okay. So what else, so we have object, the default value is now as
13235.96 -> I said before, Boolean, the default value is false. Car. Now this is interesting, it
13236.96 -> depends on if you safe if you display this as a car as it is. And then this is I think
13237.96 -> it's called the null character. And I think this is just nothing or maybe space here you
13238.96 -> see there is something it just can't be displayed by my UI. I mean, here, if I try there's nothing
13239.96 -> blue. But here when I go over it, it's displayed as blue because there is actually something
13240.96 -> it just not visible. And I can convert this character, the default character to an end.
13241.96 -> And then it's a zero. Okay? Now, so these were the default values of the different number
13242.96 -> data types as primitives. Okay, and now, as the next topic, I also want to tell you never
13243.96 -> told you so far, all these number types, they in parallel also exist as objects. Let's have
13244.96 -> a look, and then see and discuss why that is. Okay, so you would have bide my, this
13245.96 -> is used already on top. So let's call, let's just call it b
13246.96 -> equals to bite dot value of now, this is a static method method, which can and should
13247.96 -> be used to convert convert, sorry,
13248.96 -> a byte primitive to a byte object. You can also say new byte. But this is just not recommended
13249.96 -> because this might use more space. So, I don't want to go in details because then I could
13250.96 -> talk forever for performance optimization. But this is just creating always a new object,
13251.96 -> while the other one might reuse an existing object of the same value. So, this usually
13252.96 -> is good enough. Okay, there's also other methods, static methods like pars. The difference is,
13253.96 -> this works not on a string as far as I know, let's try to Yes. And let's go into the function
13254.96 -> See, I can Also see it here. And this converts it not to the object, but again to the primitive.
13255.96 -> This is the value of it converts it to abide. He even you can give the radix, like the radix
13256.96 -> of 10, or eight or 16, or whatever. This usually, well, I never really needed. But there are
13257.96 -> a lot of lot of functions. What is also interesting is that these objects, they all extend the
13258.96 -> abstract type number, abstract class, we talked about inheritance already. So you're here
13259.96 -> you can see all these different functions that each of those number types have to implement.
13260.96 -> So each of them, you can convert to an int, long float, double as the primitive value.
13261.96 -> The green stuff is, by the way, the Java API documentation that you can also read online,
13262.96 -> short. So this, all these types automatically will have. Okay, so back. Now, besides offering
13263.96 -> these cool methods, that might be helpful. There is also another reason why these exists
13264.96 -> as objects. The reason is, I think, mainly because there is something called collections
13265.96 -> that we will talk about very soon. I think I even mentioned it shortly, it's something
13266.96 -> similar to an array, it's like an array on steroids. It's just a container that you can
13267.96 -> throw in objects. And that's really it, you can only throw in objects. And so you could
13268.96 -> not throw in any primitive. And therefore, this is also called a wrapper type, because
13269.96 -> this object then will wrap around this primitive type, and can be wrapped and unwrapped. Which
13270.96 -> by the way, in the past, when working with primitives and collections was needed. So
13271.96 -> before putting it into the collection, you would have converted your primitive data type,
13272.96 -> like the CMI byte, input, the object would then have, let's just say collection, let's
13273.96 -> just say add, I mean, in reality, it looks a bit different. But just so that you get
13274.96 -> an abstract idea, you would have added this thing here. And later on, when you wanted
13275.96 -> to retrieve it again, you could then say, wide dot, get the byte value. And then again,
13276.96 -> there were people saying all this is just too much work. And so I think also, with Java
13277.96 -> five, there was an auto conversion introduced, that now Java can work with a primitive and
13278.96 -> an object, and will automatically behind the covers convert a primitive to an object and
13279.96 -> an object to a primitive, whatever is needed by a certain function. Now, this is heavily
13280.96 -> in used by almost every developer, I really don't like it, and I really activate in my
13281.96 -> ID, that I get displayed these conversions. Because for one, this could even be an issue
13282.96 -> with performance, because I see functions that would like convert from a primitive to
13283.96 -> an object, and to a primitive and so on back and forth several times, which is just stupid.
13284.96 -> Second, for a primitive, you have the default value of a zero, that is safe, that will never
13285.96 -> throw a null pointer exception. Ever for an object. When it's not initialized, like here,
13286.96 -> the value will be now and then when you on an object call, b dot byte value, this will
13287.96 -> actually throw a null pointer exception. The problem is you don't see it, because it'll
13288.96 -> be automatically be inserted by the compiler for you. You only see it at runtime and then
13289.96 -> you get a nullpointerexception. So really be careful with these automatic conversions.
13290.96 -> I personally hardly ever use them.
13291.96 -> Okay, but so, so that you know of each of these primitive number types There is also
13292.96 -> the same type as an object. The names are pretty much always the same, like there's
13293.96 -> a short object. For int, it is integer. So there's an integer. For long it's long. For
13294.96 -> float is float and double, it's double. And also Boolean exists as an object. Which by
13295.96 -> the way, also has static Boolean object values. So you can even say Boolean be laughter Remove
13296.96 -> the bite. Because this is also B, Boolean b equals to true, or equals to false. But
13297.96 -> now this is an object. I can also show, you know, the automatic conversion works. Even
13298.96 -> though this is an object, the aesthetic value here, can even jump there you see public static,
13299.96 -> final Boolean false equals to new Boolean false. So the cool thing when you use this
13300.96 -> is there's only one object that is always reused, and you don't always say new Boolean,
13301.96 -> to save some space. Okay. And now you see, I can assign this object to the primitive
13302.96 -> type, because internally, the compiler will do this for you, you just don't see it. Okay,
13303.96 -> so that's, I think, all I can tell you about the different number types and their object
13304.96 -> variants. Now let's have a look at their ranges. I said for example, byte In short, they have
13305.96 -> smaller ranges. But enough of talking, I think the best is I just show you. So execute the
13306.96 -> test. And we see, let me scroll this down. I think this makes it easier. Because then
13307.96 -> we can see the test and the code in parallel. Okay, so here, I used the system print long.
13308.96 -> Remember, don't use it avoided. Just try test, it doesn't really matter. I just shortly wanted
13309.96 -> to show you the results. Otherwise, in productive code prefer logging, because it's more flexible
13310.96 -> and would probably lead generally speaking to more performance, okay, but enough. So
13311.96 -> here you see. So there are signed types and unsigned types. Signed means you see, there
13312.96 -> is a minus, so it goes from minus 128 to plus 127. Interesting is, this is not 128. But
13313.96 -> 127. While he is 128. This actually is for all the sign types. The reason is, the JVM
13314.96 -> in your memory of your computer will actually need this one number to store the information
13315.96 -> if it's a minus or a plus. And this is why they had to take one number away. And they
13316.96 -> just decided that minus has one, one more number than Plus, I mean, they could have
13317.96 -> also done it the other way. But this is how it's done in Java. Okay, so you see, this
13318.96 -> is only for very small numbers. 120 minus 128, two plus one and 27 short is already
13319.96 -> much bigger. It can store 32,000 something plus and minus again, one less here on the
13320.96 -> right side in again is much bigger. I think this is like 2 billion or so long, again is
13321.96 -> much bigger. I don't even know how long this number is. Um, yeah, usually you should be
13322.96 -> fine with int can in some rare cases you need a long Yeah, actually, sometimes I needed
13323.96 -> a long Okay. And then there's his float floating point number with the exponent minus and plus
13324.96 -> and the double see here even is much bigger 324 to 308 minus plus and the car this one
13325.96 -> is unsigned. So, this is why there is no minus which is also why the size here is 65,000
13326.96 -> something is the double size down to the short because the short has the same space, but
13327.96 -> it needs to have it in a signed form with a minus and a plus. So this is why here we
13328.96 -> can store zero to 665,000
13329.96 -> Okay, and car as you have seen before, usually is used not to store numbers, but characters.
13330.96 -> But if you convert it to an end, you can also use it to store numbers unsigned from zero
13331.96 -> to 65,000 something okay. I think this is actually interesting to see all these ranges.
13332.96 -> Okay, so these were the ranges let's go to the next. And so, in order to be able by the
13333.96 -> way to show you see here I converted this two intz and also our This is also interesting
13334.96 -> you see here I used actually the object, the objects and the These are static values, which
13335.96 -> gives me the min and max value. This is really handy. When you need those ranges, you can
13336.96 -> just use them out of the box and say min value max value, because I wouldn't know them. Yeah,
13337.96 -> directly, I can just look them up. And Java will tell me then, okay, let's close this
13338.96 -> now. And go to our next test. Because now, what I want to show you is actually, you can
13339.96 -> also save your numbers, not only on the base 10, but also on the base to base eight, and
13340.96 -> base 16. So now it depends. I don't know, if you had this already in school or university,
13341.96 -> I'm assuming you had, they should be really easy for you to understand that, for example,
13342.96 -> with the base two, you would store you would display a number would be displayed differently,
13343.96 -> then with the base 10. If you never heard of this, then don't don't mind this really
13344.96 -> is not so important. I think I never needed to display the number in one of these formats,
13345.96 -> decimal was always fine to me. I mean, this is also the way the value will be stored here
13346.96 -> on the left side is always the same, no matter which bass you use. So this might just be
13347.96 -> used, because you are in a certain domain and a certain business area where you need,
13348.96 -> for example, the hex. And so you would, for example, have documentation that speaks of
13349.96 -> a hex value. And so you could have the same value as you have them in the documentation
13350.96 -> here in your code, which would make it easier possibly to look at the code. However, this
13351.96 -> has nothing to do with how they're stored. I mean, they're still stored on your computer
13352.96 -> in your memory. And your computer can always only store them as zeros and ones. So internally,
13353.96 -> no matter what format, you use them internally, they're saved always in the same format. And
13354.96 -> by default, they're also when I print them out, which I'll show you in a sec, they will
13355.96 -> also always be printed out on the base of 10 just like a regular number like you know
13356.96 -> them. So this is only a displaying issue in the code. If you want to display them in the
13357.96 -> binary format, you need specific formatting options. This will be an episode on its own.
13358.96 -> So I will not go in detail on this. Now. Also, I think this is not needed in many cases.
13359.96 -> What is also interesting, by the way, I mean, the space two was introduced with Java seven
13360.96 -> only. So this only recently got added. Speaking as of 2015, before, you had only the option
13361.96 -> to store, base 10, base eight and base 16. Now the Edit base two besides to make this
13362.96 -> stuff more readable. I mean, especially with base two, you will get these long strings
13363.96 -> here of zeros and ones. So that you could easily read this. And also for something like
13364.96 -> credit card numbers, you can add these underscores actually as many as ever you want.
13365.96 -> You're just not allowed to do it at the beginning of the string and at the end of the string.
13366.96 -> But I mean, I don't see how this would make any sense, because this wouldn't help to read
13367.96 -> it. So this is why you put them here in between, you can also add more like here. Now the question
13368.96 -> is, is that more readable? In this case? Of course not. But I think it can be quite helpful,
13369.96 -> especially for something like credit card numbers for long numbers that you can read
13370.96 -> them more easily, like on the phone talking to a colleague, and you want to read out the
13371.96 -> number nine you can talk about the blogs makes it easier. But these underscores again, this
13372.96 -> is just the displaying issue in the code. The way they are stored is exactly the same
13373.96 -> like before. So now let's execute the test. So I mean, so that this gets printed out,
13374.96 -> and we can have a look at it. Okay, so here you see the first one ob this just indicates
13375.96 -> I'm storing the number in binary. The number is given in a binary format. So this is just
13376.96 -> the zero. You can use the capital and a lowercase it's supposed to same. So this one is an apple
13377.96 -> On this long thing here, so ob four is binary format, and undo redo Do you do all this,
13378.96 -> you can use your calculator and calculate it. And in the end, you will see this is this
13379.96 -> number in decimal format.
13380.96 -> Or K.
13381.96 -> By the way, of course, just shortly, binary format means you can't, for example, use a
13382.96 -> three, this will give you an error, integer number two large, because now we are in binary
13383.96 -> format, indicated by the B and zero here with the base eight, and scroll down. It, it started
13384.96 -> with a zero only. So zero and seven means this is a seven now, but 010 is actually the
13385.96 -> eight in the on the base of eight. As I said, if you know it from like school or university,
13386.96 -> you will understand what I'm talking about. If not, doesn't matter. Not important. Yeah,
13387.96 -> you will hardly ever need it. Let's have a look at it. So as I said, this is the seven,
13388.96 -> this is the eight. And this is some large number. So these underscores are not displayed
13389.96 -> in here. This is just to help so that it's more readable in the code. And the base 16
13390.96 -> hex code is started with zero and x. And then the zero is 01. The F, you know in Latin,
13391.96 -> no, I think our numbers are not Latin, their Arabic numbers. And these Arabic numbers,
13392.96 -> they are based on the base 10. So nine is the last number. And when you want to say
13393.96 -> 10 you need one zero, while on the hex, you don't have any more Arabic numbers. So therefore
13394.96 -> they used ABCDE, F for 10 to 16. So the F is actually the 16. Let's execute this. Well,
13395.96 -> I was lying to you. It's the 15 in this case, because we start with the zero. No, yeah,
13396.96 -> it's the 15. Because the 16 again, would be one zero. Okay, yeah. can get really easy,
13397.96 -> confusing. Sorry. So anyway,
13398.96 -> I mean,
13399.96 -> I think it's not so important. It's just interesting to show off. I mean, like in a job interview,
13400.96 -> I think you really should know, Java inside out. And so I think you should know that this
13401.96 -> is possible. The question if you personally will use it, because you personally in your
13402.96 -> project will need it. I don't know, depends, maybe you need it. But if you need it, it's
13403.96 -> here to be used. Okay. So now, I think really did an in depth view on all these small topics.
13404.96 -> And I think this is really now a good base to talk about hashCode and equals. Going to
13405.96 -> talk about the two methods equals, and hashCode. This tutorial actually concludes my presentation
13406.96 -> of all the methods of the Java Lang object class, equals and hashCode both follow a contract
13407.96 -> that ties them closely together, which is also why I'm talking about both methods in
13408.96 -> just one episode. Knowing all the details about these two methods, will make you a better
13409.96 -> programmer today. So get yourself some popcorn, and listen carefully. So let's start with
13410.96 -> the equals method. What does it do? What's it actually useful for? the equals method
13411.96 -> is used to compare two objects for equality, similar to the equals operator, which is used
13412.96 -> for primitive values. But before I'm going into much more detail, let's first jump into
13413.96 -> my ID and see this in action. Now in my ID, let's first of all, see, what do we need the
13414.96 -> equals method for anyway, because so far, we happily used the equal equal operator,
13415.96 -> and this was working. Let's see this again, with two primitive values, I equals four,
13416.96 -> and J equals four. So now I assert, with the equals operator that they're both equal. And
13417.96 -> we get the green bar. Old tests passed, everything is fine. So i equals to J. Now let's do the
13418.96 -> same thing with strings. Here we have a constant value of Hello, and another constant value
13419.96 -> Hello. And each has assigned to its own string, reference variable. Now, we all Want to compare
13420.96 -> these two strings with the equal operator? Let's try this. And Ted Ah, this is also working.
13421.96 -> And I told you a string is an object. So as this is working, it seems we don't need the
13422.96 -> equals method at all. Well, with a string, it's a bit tricky, actually. Because with
13423.96 -> a string, there is some optimization going on in the background for constant values,
13424.96 -> because for this constant value, there's actually only one and both variables, they both point
13425.96 -> to the same object in memory. The variable is stored in a memory area called stack, the
13426.96 -> object is stored in a memory area called heap. And there's only one, but things get quite
13427.96 -> differently. As soon as I add a new string variable, and always say, string hello, three
13428.96 -> is only age. And then I say at runtime, hello, three equals two, hello, three, plus, concatenate
13429.96 -> ello to it, which will be Hello, at runtime. And just to be sure, let's also print this
13430.96 -> that we can see there is really Hello. In the variable, hello, three. And then let's
13431.96 -> assert, hello, one, equal operator Hello, three. And this is not working, we get the
13432.96 -> red bar, nasty, nasty. So now they're not equal. But here you can see it printed out
13433.96 -> Hello. So from our expectation it should have been equal. So this is something really tricky
13434.96 -> with string.
13435.96 -> And ensured you should not use equal operator on objects, also not on strings. Instead,
13436.96 -> for strings, there is the equals method. Let's try this. Hello, one equals Hello, three.
13437.96 -> This works, it seems like using that method, they're both equal. Now, let's have a look
13438.96 -> actually at the method. Here we are clustering. And there is a method equals operating on
13439.96 -> an object. It says things like if this equals to the object given return true. So if it's
13440.96 -> the same reference, if it's the same object, this is actually a performance optimization.
13441.96 -> Now it checks that the object is actually a string. This is achieved by the instance
13442.96 -> of operator so that we can safely cast the object to a string. And so that we can compare
13443.96 -> both strings. Interesting thing about instance, of By the way, which not many people, many
13444.96 -> developers know, or at least not all, yet. This also includes a check for now, if an
13445.96 -> object is now this will never be a string will never be true and will return false.
13446.96 -> So anyway, without going into further details, there's this while loop. And this compares
13447.96 -> character by character of both strings. And only if they're completely equal, it will
13448.96 -> return true. So this is how equals was implemented in the class string. But actually, I told
13449.96 -> you, the equals method is a method from the class object. And yes, it is. Well, it turns
13450.96 -> out string is also a subclass of object and the string class overrode the equals method
13451.96 -> here. So then it works on strings as expected. Okay. So it seems like for strings we can
13452.96 -> happily use equals, so that we know that a string like hello one and hello three is equal.
13453.96 -> Now, how are things with classes that we implement ourselves? Like here I have created a class
13454.96 -> car with owner Marcos. It is a Porsche and it is it has the color silver So it seems
13455.96 -> like it has both instances have exactly the same attributes. So I would expect them to
13456.96 -> be the same car. Now let's first of all, try it with the equal operator, like before. And
13457.96 -> this is false. It's not working test failed. Well, of course, because we have two different
13458.96 -> instances here. Let's try the positive case. portion one, equal operator, my Porsche one
13459.96 -> again, comparing it to itself. So yes, this is working, of course. But it seems like for
13460.96 -> to be able to compare Porsche one and Porsche to we again need to use the equals method.
13461.96 -> Let's do this now. For sheet one. Oh, let's first of all, I want to push it to here. But
13462.96 -> let's also do this, my portion one equals my portion one,
13463.96 -> I would expect that to be true. And yes, it is true. My Porsche one, so it is equal to
13464.96 -> itself. Now, let's compare my Porsche one to my Porsche e two. And let's see if this
13465.96 -> works. Huh,
13466.96 -> it's not working. We have the nasty red bar. This was so nicely working with a string,
13467.96 -> why is it not working with our car? Let's jump to this method again. And you see, we're
13468.96 -> in the class object. Because in our car class, we have not overwritten the equals method.
13469.96 -> So what happens is, the original method of the class object is used. And as you can see
13470.96 -> here, internally, what happens is, we compare this which is the object itself, in this case,
13471.96 -> my pushy one, we compare it using the equal operator to the object that is coming into
13472.96 -> the method, which was pushy to. And this compares only the reference variables and not the objects.
13473.96 -> So this is false, because we have two different reference variables.
13474.96 -> What by the way, is also possible. To make this true again, we could assign my portion
13475.96 -> to the reference variable of my portion one, which would mean this object is somewhere
13476.96 -> in memory, no variable is assigned to it. And there is this one object
13477.96 -> here in this line, and both variables, point to it. Let's try this. And see if this works.
13478.96 -> Because now actually, we only compare the same object with each other. Like here. This
13479.96 -> compares the reference variables, which now have the same value. So this would be working.
13480.96 -> But this is not what we want. So let's remove that we really want to compare both objects.
13481.96 -> We want to compare this one with that one. Okay, so let's have a look at the class car.
13482.96 -> This is a small class I wrote. And it just has a constructor and these attributes for
13483.96 -> now. And there is no equals method overwritten. So this is what we have to do. Public Boolean
13484.96 -> equals now, I want to compare a car car. No, this you cannot do in the class object. There
13485.96 -> is object. So we have to say object here. And then later on, we have to cast it to a
13486.96 -> car, like we saw on the class string.
13487.96 -> And then it's always good to add the override annotation so that we make sure we have properly
13488.96 -> overwritten the method. Now, I mean, this is not a true implementation. I always return
13489.96 -> false, just to see that when I'm in my car test, not jump there. See, it jumps to me.
13490.96 -> I overridden method. Now, of course, when this always returns false, this will also
13491.96 -> not work. So we will have to implement it. But actually implementing such an equals method
13492.96 -> is not so easy. And we need some more theory for this before we can continue. So let's
13493.96 -> first of all, jump back to my slides. Before we are able to implement the equals method,
13494.96 -> we need to come up with a proper design first. Actually, many developers just skip the design
13495.96 -> phase, and simply click on autogenerate. But this may lead to severe bugs, or at least
13496.96 -> two sub optimal performance. Let me show you how you can properly do it. First of all,
13497.96 -> you have to define what it is in your specific program that makes two car instances equal
13498.96 -> or unequal. In your program, are two cars equal when they have the same manufacturer,
13499.96 -> maybe when they have the same manufacturer in color, or the same engine, the same number
13500.96 -> of wheels, the same top speed, the same vehicle identification number, or when In short, based
13501.96 -> on a knowledge of the business you are working in, you have to decide which fields are identifying,
13502.96 -> and which fields are redundant, and not helpful for the equal comparison. Besides for improved
13503.96 -> performance, you need to define in which order you want to compare the attributes. Are there
13504.96 -> any fields that have a high chance to be unequal? Are there fields that may be compared faster
13505.96 -> than others? To implement a meaningful equals method, you must first analyze all these aspects
13506.96 -> in great detail. Let's go through this process. With my example. I would assume that the car's
13507.96 -> top speed relates to the type of engine and some form. So that seems to be a redundant
13508.96 -> field, that will not be helpful for the equals implementation. So let's just remove it. Let's
13509.96 -> just say the number of wheels is always for in our specific example. So number of wheels
13510.96 -> would also not help us to differentiate the car. What about the VIN?
13511.96 -> Well,
13512.96 -> this again depends on the type of program you want to create. For a public authority
13513.96 -> like the police, this one is probably the only proper way of identification. But what
13514.96 -> about a program used by the manufacturer itself. While the car is still being built, and not
13515.96 -> sold yet, I would assume the witness of less importance. But I personally wouldn't know
13516.96 -> that in detail. This is what you will have to clarify with the business people of your
13517.96 -> company or your department. Based on their knowledge, you have to select which attributes
13518.96 -> to compare in which order. In my artificial example here, I'm the developer as well as
13519.96 -> the business analyst. So for my example, I just arbitrarily define that two cars with
13520.96 -> different wind numbers can be seen as equal. Therefore, I will not include this field in
13521.96 -> my equals comparison later on. Now, before you think that's it, I'm sorry, there's actually
13522.96 -> some more theory to cover. In the introduction, I already told you that there is a contract
13523.96 -> of equals and hashCode we have to fulfill. First of all, there are five conditions, our
13524.96 -> equals implementation has to comply with, believe me, it looks much more scary than
13525.96 -> it actually is. Let's go through each of them slowly. reflexivity. An object must be equal
13526.96 -> to itself, so that when I call my old car equals my old car, it returns true. I think
13527.96 -> this makes sense and should be easy to understand. symmetry to objects must agree whether or
13528.96 -> not they are equal. If my old car equals some other car, then some other car equals my old
13529.96 -> car must also return true This sounds obvious and very simple, when in fact, it is not such
13530.96 -> a simple condition when it comes to inheritance. If you have a car class and a BMW class, which
13531.96 -> is extending the car class, it could happen that your BMW is equal to a car. But the same
13532.96 -> car is not equal to the BMW is every BMW is a car. But not every car is a BMW. So you
13533.96 -> see, the symmetry rule can actually lead to some nasty problems. There are quite a few
13534.96 -> interesting articles online discussing potential symmetry issues of the equals method. cover
13535.96 -> each contract condition with a dedicated unit test to make sure your class is fully compliant
13536.96 -> with a contract. Our next condition is transitivity. If one object is equal to our second, and
13537.96 -> a second is equal to a third, then the first must be equal to the third again. This rule
13538.96 -> sounds much more complicated than it actually is. If object A is equal to object B, and
13539.96 -> object b is equal to object C, they should all be equal to each other so that C is also
13540.96 -> equal to a consistency. If two objects are equal, they must remain equal for all time,
13541.96 -> unless one of them is changed. So when you repeatedly compare the same two objects with
13542.96 -> a equals method, it should always return the same result. In other words, calling the equals
13543.96 -> method should not alter the object in any way. The last rule model returns false is
13544.96 -> what Josh Bloch calls nonlocality. When knowledge is given as a parameter to any equals method,
13545.96 -> they should always return false and never throw a null pointer exception. So now, you
13546.96 -> know quite a bit about the equals method. But what is the hashCode method actually useful
13547.96 -> for? For processing similar objects are usually put into a collection. Such a collection in
13548.96 -> Java is like a more powerful array, or an array on steroids, as I often call it.
13549.96 -> Besides other things, it allows you to look up objects not only based on their index position,
13550.96 -> but also based on their specific values. This is where the equals method comes into play.
13551.96 -> To speed up this lookup process, the Java creators added specific hash based containers
13552.96 -> that will use the hash value as a grouping mechanism to reduce the number of equal comparisons
13553.96 -> needed. In the optimal case, each object that is considered unequal by the equal method
13554.96 -> will also return a different hash code. This hash code is used to group the objects in
13555.96 -> so called buckets. Now, in this optimal case, you will be able to find each object simply
13556.96 -> by a lookup based on its hash value. However, there may also be something called hash collisions,
13557.96 -> where two unequal objects will share the same hash code, in which case they end up in the
13558.96 -> same bucket. Now, if I'm looking for that scar, I have to look up the correct bucket
13559.96 -> based on the hash code minus 391. That car will return. However, as there is a hash collision,
13560.96 -> I will on top have to do an equals comparison on a list of two cars in this case, illegal
13561.96 -> but inadmissible bad performing hash code implementation could statically returned 42
13562.96 -> for all objects. In this case, however, the whole hashCode logic would not help at all.
13563.96 -> In the end, you would have to do an equals comparison on the entire list of cars just
13564.96 -> as if the hashing logic had never existed. Okay. Now that I have talked about the general
13565.96 -> idea of the hashCode method, I have to further tell you about the contract that the hashCode
13566.96 -> method has to fulfill. The first condition that has to be fulfilled by the hashCode method
13567.96 -> is for any two objects return same hash codes when equals returns true. To achieve this,
13568.96 -> use the same idea Define attributes for both methods in the same order. Don't worry too
13569.96 -> much. Now, if you don't fully understand what I mean. As soon as I'm finished introducing
13570.96 -> you to the hashCode contract, I will jump back in my ID and show you a practical example.
13571.96 -> When hashCode is invoked more than once on the same object, it must consistently return
13572.96 -> the same int value as long as the object is not changed. This role is similar to the equals
13573.96 -> consistency rule, I introduced to before both equals and hashCode methods must return consistent
13574.96 -> results. To fulfill this contract, you should override hashCode whenever you override equals,
13575.96 -> and vice versa. Also, when you add or remove attributes from your class, you will most
13576.96 -> probably also have to adjust your equals and hashCode methods. Last but not least, aim
13577.96 -> to return different hash codes when equals returns false. This is not a hard and fast
13578.96 -> rule, but it will improve the performance of your program by minimizing the number of
13579.96 -> hash collisions. to the extreme, the hash code contract would allow to statically return
13580.96 -> 42 for all objects, as Josh block states in his book Effective Java, however, this could
13581.96 -> result in quadratic rather than linear execution time, and therefore, could be the difference
13582.96 -> between working and not working. Actually, the hashCode method is a rather complicated
13583.96 -> beast, I couldn't practically fit in all the details without risking that you would fall
13584.96 -> asleep. Therefore, I have done a follow up tutorial, that will give you an in depth view
13585.96 -> on the hashCode method, which you will need to understand to become an expert in Java
13586.96 -> programming. Below this video, there's a link, you can click to watch my follow up tutorial
13587.96 -> for the hashCode method. For now, that's all the theory, you need to be able to implement
13588.96 -> your own hashCode and equals methods. to round up this topic, let's jump back into my ID
13589.96 -> to show you some practical examples of hashCode and equals methods. So back to my ID II, you
13590.96 -> can see I've implemented both equals, and hashCode based on the fields manufacturer,
13591.96 -> engine, and color, also here and hashCode, manufacturer, engine, and color. So I've implemented
13592.96 -> them based on the decisions I made during the simulated design phase that I did during
13593.96 -> the theory session. So the car clause has fields like Vehicle Identification Number,
13594.96 -> Manufacturer, engine, color, and number of wheels. But in the design phase, I decided
13595.96 -> that number of wheels and Vehicle Identification Number are not helpful for the way I want
13596.96 -> to compare a car. Of course, this is totally arbitrary. So this is not how you would do
13597.96 -> it. I really can't stress that enough. In your case, in reality, you have to talk to
13598.96 -> the business people and find out what is important and what is not. Also totally arbitrary is
13599.96 -> the order that I've chosen. I just thought about it. And I thought that while there are
13600.96 -> millions, or however many colors that for usually for cars, there are not so many colors.
13601.96 -> I think most cars are either black or white, silver, blue, red. A few might even be green,
13602.96 -> or yellow. But that's probably it. So I thought they there are probably more different manufacturers,
13603.96 -> and also more different engines. And I want the equals method. If I compare two objects
13604.96 -> which are not equal, I want to leave the method as early as possible, because the earlier
13605.96 -> I leave the method, the faster the entire code will run. If two instances are equal,
13606.96 -> then usually it has to go till the very end. So in this case, it doesn't make a difference.
13607.96 -> But it does make a difference if it's not equal. If we can leave the method here. So
13608.96 -> for perform performance optimization I have chosen this order
13609.96 -> on.
13610.96 -> So this is what I would also ask you to do, think about a good order to improve the performance.
13611.96 -> And if the performance is important, then you should test it, because you never know
13612.96 -> for sure until you test for the performance. What is important that the order is the same
13613.96 -> hashCode and equals. And now, we should also talk about all this stuff here on top. This
13614.96 -> mostly is also a performance optimization, at least here, this equals object. So, if
13615.96 -> I compare the object to itself, I want to directly return true, because then the reference
13616.96 -> variable references the same object in memory. And so I directly know it's the same object,
13617.96 -> I don't have to compare all these things. So, this is why I have this here. If you have
13618.96 -> a specific case, where you know that you will never ever compare an object to itself, you
13619.96 -> might even leave this if a way. Yeah, this is the this depends. Generally, this is done,
13620.96 -> because such a check doesn't also cost a lot, then this object equals null return false
13621.96 -> is actually very important here. This is the last rule that we have to fulfill that when
13622.96 -> an object that we compare is now that we always return false, which is also important because
13623.96 -> otherwise object dot get class would throw a null pointer exception that this cannot
13624.96 -> happen, because now we are already, we have already left the equals method with false.
13625.96 -> Okay. And then the third, if check compares both classes. So that we make sure that the
13626.96 -> object that is coming in to all equals method is also a car. So that we're not comparing
13627.96 -> bikes and cars, for example, or cars and apples or whatever, right? Because otherwise, also,
13628.96 -> this explicit cast to car would also throw a class cast exception. But now that we have
13629.96 -> made sure that they both have the car class, we can safely caused the object to a car.
13630.96 -> And now I think this is quite interesting. Because now I can easily say manufacturer
13631.96 -> equals other dot manufacturer. This field here is private. But because we are here in
13632.96 -> car, even though that this is another instance, but it's also an instance of car, I can directly
13633.96 -> access this private field. So I don't have to use any method, I can directly access the
13634.96 -> field. This works and makes the code I think, much more readable and shorter. So if it's
13635.96 -> not equal, then I can directly leave the method and say return false. I do this with all the
13636.96 -> fields. And if I'm here, that I'm sure that all the three fields are equal. So I do not
13637.96 -> compare number of wheels as well as we equal identification number, because as I said,
13638.96 -> about them, I don't care because number of wheels, in my specific example would always
13639.96 -> be four. So would be the same anyway. And we equal identification number, that might
13640.96 -> be two different cars. But just like, if I'm only interested in the price of a car, for
13641.96 -> example, or the look, then I wouldn't care that actually, they are physically two different
13642.96 -> cars. I would just say well, this is a BMW with I don't know, that kind of engine and
13643.96 -> Lou. So for me, this is the same car. Period. Yeah. Okay, so that much for the equals method.
13644.96 -> Now the hashCode method. This is actually very complicated, I'm sorry, and it's so complicated
13645.96 -> that I've decided to do a follow up tutorial, as said before, which I really recommend you
13646.96 -> to watch. There is a link below this video, you can click to watch the follow up. So he
13647.96 -> only in short about the hashCode method. The 31 year is a prime number and a prime number
13648.96 -> he is multiplied with always the result. So this continues to take the hash code of a
13649.96 -> field, which will return some in number
13650.96 -> will edit, starting with one, and then multiply it with 31. And this for each attribute. The
13651.96 -> reason is this is an optimization to have less collisions, because I told you about
13652.96 -> the collisions, that this can decrease the performance. As you see, I'm actually not
13653.96 -> really doing something here, I'm just calling recursively hashCode for each class. And this
13654.96 -> is why now we should jump in the other classes, at least, I can show you all the classes,
13655.96 -> but I've chosen engine here in this case, to see how it's actually hashCode implemented
13656.96 -> in one example. So let's jump to engine. Okay, so the equals method is pretty much the same,
13657.96 -> or at least similar. Then in car, the only difference is here, I added something that
13658.96 -> I called optional field, because I defined that this optional field could also be now.
13659.96 -> So therefore, my check here for equals has to be a bit more complicated. Because I have
13660.96 -> to save it's now then I check if the other field is also now, if it's not now, then this
13661.96 -> field is now the other is not so it's not equal. And if it's not now, then I can compare
13662.96 -> both fields. So I'm doing all this again to prevent another pointer exception. In the
13663.96 -> other case, when I don't check for now, my assumption is that, well, this is a primitive
13664.96 -> field, so it can't be null anyway, but for car, my assumption was that a car always needs
13665.96 -> a manufacturer, engine and a color. So my assumption is, those fields will never be
13666.96 -> now, if someone would introduce a bug. And would forget to set these fields then, of
13667.96 -> course, this could produce a nullpointerexception. But checking for something that is exceptional.
13668.96 -> This is what I call rocket code. Because it's like extra safe code, this is just cluttering
13669.96 -> your code, you have to have certain assumptions, like saying mighty sign for bits that these
13670.96 -> fields, these fields can never be now. And so I trust on that. Otherwise, well, the program
13671.96 -> will crash, okay, we have to fix it. But then the problem is already fixed. And the code
13672.96 -> stays clean. And this is important, because your code should be really readable and maintainable.
13673.96 -> Okay, so only four fields where you know, they can be null at these extra null checks.
13674.96 -> Okay. So that much for the equals method, everything else here should be the same as
13675.96 -> in car. Now for the hashCode method. Here, you see there is some more stuff going on.
13676.96 -> Because here, I cannot forward to a hash code method. But instead, I have here a primitive
13677.96 -> long. And for that, because the primitive fields there, you actually have to calculate
13678.96 -> some hash code. And this is a long, and so we want to like convert a long to an int.
13679.96 -> A long has that has like 64 bits, while an int has only 32 bits. So you want to like
13680.96 -> make the long to half its size, and you want to make it in a way that will result in the
13681.96 -> least possible number of collisions. And therefore, this weird line here. This here does it. This
13682.96 -> is actually based on again, Josh blocks book Effective Java there, he explains it. One,
13683.96 -> actually, he doesn't explain it too much. If you want an in depth explanation again,
13684.96 -> watch my follow up tutorial about hash code there, I can explain you. Now here only insured.
13685.96 -> This is a shift by 32 bits. And then this is an X or Y you again, come like let's say
13686.96 -> combine this field. And last but not least, you do an exquisite cast from long to end
13687.96 -> where you throw away Half of the long, but this whole thing can't explain you in like
13688.96 -> one minute, you have to watch really the extended tutorial. But this is really a very performant
13689.96 -> good way to create an end hash code from alarm. This is the standard default way of how this
13690.96 -> is done today.
13691.96 -> And the second field here is a string as it can be now, I need this extra knowledge check.
13692.96 -> And I'm not sure if I have shown you this before. This is like in if it's just shorter,
13693.96 -> because otherwise the code would even be longer. So you have to read it as is optional field
13694.96 -> now. If true, then return zero, else return optional field dot hashCode. So this again
13695.96 -> calls the hashCode method of string. This I showed you in the beginning of this episode,
13696.96 -> where the code was like in a while loop, going over each character of the string, and then
13697.96 -> calculating an int value for the string. So as this is already done for us, we can simply
13698.96 -> call the hashCode method. Okay. So, again, you also see, I have, in this case, two fields.
13699.96 -> And in this case, I decided to use both to differentiate if an engine is equal or not.
13700.96 -> And so as I use type an optional field and equals, again, I use type an optional field
13701.96 -> and hashCode in the same order and same fields. Okay, last but not least, some class now this
13702.96 -> is this doesn't mean anything, this is really totally abstract, I just wanted to it very
13703.96 -> short, show you all the different primitive types they are plus the string object. So
13704.96 -> that you see like how the different cases of equals and hashCode could be calculated.
13705.96 -> So let's first of all look at hash code. So this with long we have already seen, same
13706.96 -> one here, float, well float has the same size 32 bits like an end. And then there is a native
13707.96 -> function, which will convert the float to an int to be used for the hashCode. Double
13708.96 -> A has the same length as a long. So this is done in two steps. First of all, it's converted,
13709.96 -> again, with a native function too long. A native function is a function that is not
13710.96 -> implemented in Java, but in machine dependent code. So I can't show you. But again, for
13711.96 -> details, watch my follow up tutorial. But anyway, so long we take and again, we do this
13712.96 -> weird line here to convert it to an end. Next one Boolean. Here again, this weird stuff
13713.96 -> here. If it's true, question mark, then 1231. And if it's not true, then take this number.
13714.96 -> All this stuff is really technical might be a bit hard for you to understand. This is
13715.96 -> just really important for performance optimization to have the least number of collisions. Um,
13716.96 -> car is just taken as it is because it can be handled like a number. For string again,
13717.96 -> we call this hashCode method. And for the other fields, everything that is as big as
13718.96 -> an end or smaller than an end, that's relatively easy because you can just take the value as
13719.96 -> it is because a byte will always fit into an end short will always fit into an end.
13720.96 -> And an end of course, should also fit into an end our K so I know this was really rough
13721.96 -> really short. I'm just not enough time to go in more details. But exactly For this reason,
13722.96 -> I have done the follow up tutorial you can watch. I hope then it will be more easy to
13723.96 -> understand. Now last but not least, let's have a look also at equals. So I think for
13724.96 -> the primitive values here, it's pretty easy because you don't have to use equals If you
13725.96 -> can just use the not equal operator.
13726.96 -> So if it's if the bytes are not equal, just looking at the variables without any objects
13727.96 -> involved, false is returned. And also see this is the order I've chosen, I start with
13728.96 -> the smallest possible values, because here checking them is probably faster than doing
13729.96 -> all this crazy stuff down here. And this is why I've chosen the order. All K, with a short
13730.96 -> end, long, this is all easy. With float, it's a bit more difficult, we have to convert it
13731.96 -> first to an end, that will has to be converted to a long, um, Boolean is, again, easy. Well,
13732.96 -> actually, if this was a real whoops, if this was a real implementation, I would have done
13733.96 -> it differently, I would have put it to the top. So this order is also based to explain
13734.96 -> you the different types. So in reality, I would ask you to really think about the order
13735.96 -> based on what the business tells you what is easy to differentiate. And like, then also
13736.96 -> you have to think, like, from the performance, what takes longer to calculate. Um, of course,
13737.96 -> it depends if you really need the performance. And if you do, then always test performance,
13738.96 -> because you might think something is fast. But when you tested, it turns out, it's not
13739.96 -> as fast as he would have thought, okay, because what I'm telling you here is just a rule of
13740.96 -> thumb, but I might be totally wrong in a specific case. So this is also what I'm doing, if I
13741.96 -> need a certain performance, I test for it. In all other cases, I just do how I feel like
13742.96 -> it. Or I just use my gut feeling to sort the values, as I think could be fitting out. Okay,
13743.96 -> so I hope you liked this episode about hashCode. And equals I'm sorry that this is all so complicated
13744.96 -> and so long. I just wanted to put in everything possible, because this is really such an important
13745.96 -> topic that he should really understand in detail. Of course, there is way more actually.
13746.96 -> So I would also ask you go to my blog, www dot Marquess minor spiel.com. I will put up
13747.96 -> some links to some extended articles on the topic on and also you might consider buying
13748.96 -> Effective Java from Drush blog, he also talks about it quite extensively. So
13749.96 -> here
13750.96 -> I will give you a high level introduction to the Java collections framework. Unfortunately,
13751.96 -> there are several overloaded uses of the word collection. Let me clarify the various meanings
13752.96 -> up front. The different use cases are a collection without any it relevance as a compilation
13753.96 -> or group of things. Second, the Java collections framework, a library of different interfaces
13754.96 -> and classes. Third, a collection as a data structure. Think of a box or container that
13755.96 -> can hold a group of objects, like an array, for example. For us, the Java collections
13756.96 -> interface, one of the two main interfaces of the Java collections framework, and fifths,
13757.96 -> Java util collections, or utility class that will help you to modify or operate on Java
13758.96 -> collections. This episode is based on chapter 11 of the OCA OCP study guide. The book is
13759.96 -> packed with knowledge. As a great fan of the author is Kathy Sierra and Bert Bates. I recommend
13760.96 -> you to read this book, even when you don't plan to get a certified programmer. So what
13761.96 -> is the Java collections framework? from a high level perspective? First of all, it's
13762.96 -> more like a library a toolbox of generic interfaces and classes. This toolbox contains Various
13763.96 -> collection interfaces and classes that serve as a more powerful object oriented alternative
13764.96 -> to arrays, collection related utility interfaces and classes that assist you in using the collections.
13765.96 -> I'm going to describe both parts in detail now. On the next slides, you will see the
13766.96 -> interface and class hierarchy for collections. Unlike arrays, all collections can dynamically
13767.96 -> grow or shrink in size. Except before a collection can hold a group of objects, a map can store
13768.96 -> pairs of objects that have some kind of relation, which ties them together, named key and value.
13769.96 -> A value
13770.96 -> does not have a specific position in this map, but can be retrieved with the key it
13771.96 -> is related to relax if you don't get it now. We will look at it in more detail later on.
13772.96 -> So here you see the hierarchy of classes and interfaces, extending or implementing the
13773.96 -> collections interface. Just try to remember some of the names listed here. This is just
13774.96 -> an overview so far. As you can see, the collection interface sits on top of a number of sub interfaces
13775.96 -> and implementing classes. A collection can hold a group of objects, the collection interface
13776.96 -> is extended by the interface of set list and queue. A set is defined as a group of unique
13777.96 -> objects. What is considered as unique is defined by the equals method of the object type the
13778.96 -> set holds. So in other words, a set cannot hold to equal objects. A list is defined as
13779.96 -> a sequence of objects. So unlike a set, a list can contain duplicate entries. Besides
13780.96 -> a list keeps its elements in the order, they were inserted into the list. A queue has two
13781.96 -> sides, entries are added to the end and removed from the top of the queue. This is often described
13782.96 -> as first in first out, which is pretty much like a waiting line in real life works. The
13783.96 -> first person queueing up will also be the first person leaving the queue. Now let's
13784.96 -> have a closer look at the interfaces and classes that extend or implement the set interface.
13785.96 -> Hash set linked hash set and three set are all implementing the set interface. Hash set
13786.96 -> is the default implementation that is used in the majority of cases. Linked hash set
13787.96 -> is like a mix of a hash set and the list as it does not allow duplicate entries like a
13788.96 -> set. But it returns its elements in the order in which they were inserted. Like your list
13789.96 -> would do. Chrisette will constantly keep all its elements in sorted order. But keep in
13790.96 -> mind, there is no free lunch. So every edit feature comes at a certain Cost Of course.
13791.96 -> After looking at the classes implementing the set interface, let's also have a look
13792.96 -> at the two extending interfaces we haven't talked about yet. As the name implies, sorted
13793.96 -> set is a set that is constantly sorted. The navigate will set interface was added which
13794.96 -> Java six, it allows to navigate through the sorted list. For example, it provides methods
13795.96 -> to retrieve the next element greater or smaller than a given element of the set. Next, let's
13796.96 -> have a closer look at the classes that implement the list interface. Every list is the default
13797.96 -> implementation of the list interface. Like any list implementation, it does allow duplicate
13798.96 -> elements and it does allow to iterate the list in the order of insertion. As it is based
13799.96 -> on arrays, it is very fast to iterate and read from an every list. But adding or removing
13800.96 -> an element at a random position is very slow, as this will require to rebuild the underlying
13801.96 -> array structure. vector is a class that exists since JDK one which is even before the collection
13802.96 -> framework, which was added with Java two. In short, its performance is sub optimal.
13803.96 -> So So please never use it. Use ArrayList or linked list instead. So let's directly remove
13804.96 -> it and forget about it. The next list implementation is linked list. As the name implies, its implementation
13805.96 -> is based on a linked list, which makes it easy to add or remove elements at any position
13806.96 -> in the list. Last but not least, let's have a look at the classes implementing the queue
13807.96 -> interface. We already talked about link list, as it also implements the list interface.
13808.96 -> However, the fact that it's based on a double linked list makes it quite easy to
13809.96 -> also implement the queue interface. linked list is the default queue implementation.
13810.96 -> priority queue is a queue implementation that keeps its elements automatically ordered.
13811.96 -> It has similar functionality like a tree set, but it does allow duplicate entries. Now let's
13812.96 -> look at the map interface. This interface has no relation to the collection interface.
13813.96 -> A collection operates on one entity, while a map operates on two entities. A unique key,
13814.96 -> for example, a vehicle identification number, and an object that is related to this key
13815.96 -> for example, a car object with the help of the key you can retrieve the object it relates
13816.96 -> to. The interface map is the root of a lot of interfaces and classes, which we'll look
13817.96 -> at now. The class hash table was the first collection in Java JDK one that was based
13818.96 -> on a data structure hash table. So the Java creators called a hash table. Unfortunately,
13819.96 -> this makes it a bit hard to differentiate between the two. Like vector the class is
13820.96 -> deprecated, because of its sub optimal performance, so let's also remove it and forget about it.
13821.96 -> Instead, use one of the other classes that implement the map interface. hashmap is the
13822.96 -> default implementation that you should use in the majority of cases. A map usually does
13823.96 -> not make any guarantees on how it internally stores its elements. An exception to this
13824.96 -> rule is linked hash map, which allows to iterate the map in the order of insertion. Last but
13825.96 -> not least, tree map is a constantly sorted map. Now let's look at the interfaces that
13826.96 -> extend the map interface. As the name implies, the interface sorted map extends the map interface
13827.96 -> and defines the contract of a constantly sorted map. navigable map again extends the sorted
13828.96 -> map interface, and adds methods to navigate through the map. This allows you to retrieve
13829.96 -> all entries smaller or bigger than a given entry, for example. Actually, there are many
13830.96 -> similarities between the map and the set hierarchy. The reason is that the set implementations
13831.96 -> are actually internally backed by a map implementation. Last but not least, you might have noticed
13832.96 -> the Java collection classes often contain the data structure there are based on in their
13833.96 -> name. To choose the best collection for a given situation, you have to compare the specific
13834.96 -> characteristics of data structures like array, linked list, hash table or tree first. In
13835.96 -> short, there is no single best option. Each one has its very own advantages and disadvantages.
13836.96 -> I promise to talk about this very exciting topic in a later episode. So stay tuned. This
13837.96 -> overview of the collection and map classes that only show you a part of the whole story.
13838.96 -> In a later episode, I will introduce you to the concurrent containers of the Java collections
13839.96 -> framework. generics is a topic at least as big as the Java collections framework. In
13840.96 -> the context of this episode, I will therefore only explain you the bare minimum you need
13841.96 -> to understand the collections framework. It's okay if you have a lot of open questions after
13842.96 -> my brief overview. Give both of us some time. I promise to explain everything one after
13843.96 -> the other I would recommend you to subscribe to my YouTube channel to be informed as soon
13844.96 -> as I upload the next episodes of the Java collections framework. Now fasten your seat
13845.96 -> belts. Here, it's going to be a bumpy ride, I promise. You see this weird stuff in angular
13846.96 -> brackets. Just relax. Actually, it's much easier than you might think. And the first
13847.96 -> line, you see I have defined a list variable my list. And with a string parameter in ANGEL
13848.96 -> brackets, I tell the compiler that my main list reference variable is supposed to be
13849.96 -> used only with strings.
13850.96 -> Then I create an object of type ArrayList. And again, I tell the compiler that this object
13851.96 -> is only supposed to be used with strings, and the compiler will ensure that no one ever
13852.96 -> tries to put anything else than a string into my list. In other words, this is what makes
13853.96 -> the container type safe. Also, note that I use the interface list for the variable and
13854.96 -> not ArrayList. This makes your code more flexible. Only at one place you create the object, but
13855.96 -> at various places in your code, he will use it. When you use list instead of error list
13856.96 -> for the reference variable. You could later replace the error list by a linked list, for
13857.96 -> example. And all
13858.96 -> you had to adjust was this one line of code. In case you don't really need to specific
13859.96 -> methods of a list,
13860.96 -> you could also use the collection interface instead. Always use the least specific interface
13861.96 -> for the reference variable. Oh, by the way, I'm sure you notice the integer 100 that I
13862.96 -> use as a constructor argument. This I have added for performance optimization. As said
13863.96 -> before, the collection classes can dynamically grow and shrink in size. However, aerialist
13864.96 -> and all hash table based collections are internally operating on arrays. When an array based collection
13865.96 -> grows in size, it will internally on the fly, create a larger array and transfer all contents
13866.96 -> from the old to the new array. This of course takes some extra time. What on hardware is
13867.96 -> so fast, that is usually should not be a problem. But on the other side, if you already know
13868.96 -> the exact, or at least the approximate size of your error based collection, this is usually
13869.96 -> better than trusting on the collections default size. In the next episodes, I will look at
13870.96 -> the data structures that the Java collections are based on, which will help you to better
13871.96 -> understand performance considerations like this one. However, to me, taking care of such
13872.96 -> small little details, makes the difference between a developer and a software craftsman.
13873.96 -> So I wanted to let you know as early as possible. Okay, enough, blah, blah, blah.
13874.96 -> Let's get back to the topic of generics. Now in the second line, you see how a hashmap
13875.96 -> is instantiated accordingly. As said before, a map is basically a relation of one identifying
13876.96 -> key to one value element. Both these elements can be of different types. Like you in my
13877.96 -> example, I use Vin, the vehicle identification number as the key and the car object as the
13878.96 -> value. This has to be added as a comma separated list in ANGEL brackets. And the compiler again
13879.96 -> will check that this holds true. If you create the instance reference variable and the object,
13880.96 -> both in one line, you can also leave the second pair of angel brackets empty, as it can be
13881.96 -> inferred from the generic type of the reference variable. This was introduced with Java seven
13882.96 -> and is called the diamond operator. Because the empty Angel brackets in a way, look like
13883.96 -> a diamond. Actually, I'm sorry. That's not the whole story. There are two parts. And
13884.96 -> what I just showed you. This was actually part two, the usage or invocation of a generic
13885.96 -> class when you lock in the contract parameter to be used. But this is only possible if the
13886.96 -> method, the interface or the class was defined to be used in a generic way beforehand. Here
13887.96 -> you see a generically defined interface. In the first line, the interface is defined as
13888.96 -> an interface operating on two separate generic types that have to be specified at a later
13889.96 -> time. However, when these types are locked in, this will automatically also specify the
13890.96 -> type, the types, interface methods we'll use. So, if you see some weird one letter types
13891.96 -> in one of the next slides, just remember it means this is a method that can be used in
13892.96 -> a generic way. Okay, now we are ready to look at some additional utility interfaces of the
13893.96 -> Java collections framework. They are implemented by classes of the collections framework or
13894.96 -> the JDK in general, but they can also be implemented by your own classes, making use of the power
13895.96 -> of the collections framework. Well, strictly speaking, the interface Java Lang iterable
13896.96 -> is not part of the framework. But more precisely, it sits on top of it. It is the super interface
13897.96 -> of Java util collection. So every class that implements Java util collection, will also
13898.96 -> implement the Java Lang iterable interface. Okay, anyway, let's now look at each interface
13899.96 -> in detail. an iterator is an object that acts like a remote control to iterate through a
13900.96 -> collection. Let's look at its methods. Boolean has next returns true if the collection has
13901.96 -> more elements. ie next returns the next element in the iteration. And void remove removes
13902.96 -> the last element returned by this iterator from the underlying Collection. This interface
13903.96 -> provides only one method, which will return an iterator every collection that implements
13904.96 -> this interface can be used on the for each loop, which greatly simplifies the usage of
13905.96 -> your homemade collection. In order to plug in your collection into the for each loop,
13906.96 -> you will have to execute two simple steps. First create an iterator that is able to iterate
13907.96 -> over your collection with methods like hasnext. And next, as we saw on the last slide. Second,
13908.96 -> you need to implement the iterable interface by adding an iterator method that will return
13909.96 -> an instance of this iterator implementing the interface Java Lang comparable defines
13910.96 -> a sort order for your entities. The interface contains only one method you need to implement
13911.96 -> which is int compared to if you want to define a natural sort order for an entity class,
13912.96 -> make it implement this interface. return a negative integer if the object is less than
13913.96 -> a given method argument, zero if the object is equal to the given method argument, and
13914.96 -> a positive integer if the object is greater than the given method argument. What means
13915.96 -> smaller or greater is for you to define. For numbers, that would probably mean that one
13916.96 -> is smaller than five, for example. But for colors, This all depends on how you want to
13917.96 -> sort your entities. When you put objects of an entity that implements the comparable interface,
13918.96 -> into a tree set or tree map, it will use your compare to method to automatically sort all
13919.96 -> elements you put into the collection. As you can see, the Java collections framework has
13920.96 -> been greatly designed for extension. It offers a lot of possibilities to plug in your own
13921.96 -> classes. This interface is very similar to the comparable interface. It allows you to
13922.96 -> define additional sorting orders like a reverse ordering. So the sorting logic is not directly
13923.96 -> implemented in your entity, but in an external sorting strategy class that can optionally
13924.96 -> be added to a collection or sorting method to the Find an alternative sorting order for
13925.96 -> your collection of entities. The rules of the interface contract are pretty much the
13926.96 -> same as for comparable. return a negative integer if the first argument is less than
13927.96 -> the second argument, zero if both arguments are equal, and a positive integer if the first
13928.96 -> argument is greater than the second. Last but not least, let's look at the two utility
13929.96 -> classes, collections and arrays, like a Swiss Army knife. They provide static helper methods
13930.96 -> that greatly enhance the general usefulness of the collection classes. Java util collections
13931.96 -> offers methods like sword shuffle, reverse search, min or max. And Java util arrays operates
13932.96 -> on areas and not on collections actually, similar to the collections class, it allows
13933.96 -> us to swap areas or to search through areas for example, I'm going to take an in depth
13934.96 -> look at ArrayList. And the second half, I'll do a practical coding session. Okay, let's
13935.96 -> get started. Error list is the default implementation of the list interface. As with any implementation
13936.96 -> of list, you can have duplicate elements in your array list. And you can go from element
13937.96 -> to element in the same order as the elements were inserted. As it is based on Aries, aerialist
13938.96 -> provides fast access, but inserting or removing an element at a random position requires more
13939.96 -> time, as this will require to reorganize the list. fast access however, is crucial for
13940.96 -> most applications, which is why ArrayList is the most commonly used collection. to store
13941.96 -> data that changes frequently. However, consider using an alternative container, for example
13942.96 -> linked list. I will talk about this as well as other containers in the upcoming episodes
13943.96 -> of my free Java video course. Okay, before I continue, let me introduce you to two different
13944.96 -> terms, which are important to understand in context with error list, size and capacity.
13945.96 -> Size is the number of elements the ArrayList currently holds. For every element you add
13946.96 -> to the list, the size will grow by one capacity or ever, it's the number of elements the currently
13947.96 -> underlying array can hold. The capacity of the array list grows in intervals. The error
13948.96 -> list starts with an initial capacity. Every time you exceed the capacity of the array,
13949.96 -> the ArrayList copies the data over to a new array that is about 50% larger than the previous
13950.96 -> one. Let's say you want to add 100 elements to an aerialist have an initial capacity of
13951.96 -> 10. As the list grows, the system will create six more areas
13952.96 -> to take the place of the first. First one area that can hold 15 elements, then one for
13953.96 -> a maximum of 22 elements. Then areas with a capacity of 3349 73 and finally 109 elements
13954.96 -> to hold the growing list. These restructuring arrangements can negatively impact performance,
13955.96 -> you can instantly create an array of the correct size to minimize these merging activities
13956.96 -> by defining the correct capacity at creation time. In case you don't know the final size
13957.96 -> of the ArrayList at creation time, estimated as close as possible. Choosing a too large
13958.96 -> capacity however, can also negatively impact performance. So choose this value carefully.
13959.96 -> I advise you to always explicitly set the capacity at creation time as a documents your
13960.96 -> intentions. For most projects, you won't have to worry about optimizing performance to too
13961.96 -> powerful hardware. But this is no excuse for sloppy design and poor implementation. Here
13962.96 -> you can see a simplified extract of the class aerialist. Keep in mind, the real class looks
13963.96 -> a bit more complicated. This is just meant to give you a more concrete idea of what the
13964.96 -> class ArrayList looks like. As you can see, error list is just a class anyone could have
13965.96 -> written. Given enough time and knowledge, there is no black magic, you can find the
13966.96 -> actual source code online. However, don't rely too much on internals that you spot them
13967.96 -> the source code as they may change any time if they're not defined in the Java language
13968.96 -> specification. Default capacity is the initial size of the array, when you don't specify
13969.96 -> it as I recommended before element data is the array used to store the elements of the
13970.96 -> ArrayList in size is the number of elements the ArrayList currently holds get add and
13971.96 -> remove are some of the many functions ArrayList provides, we will look at those methods now.
13972.96 -> So, let me give you a short overview of the methods of the ArrayList class. To make things
13973.96 -> easy for you, I have broken up the overview into methods belonging to the Java util collection
13974.96 -> interface, and methods belonging to the Java util list interface. When I talk about other
13975.96 -> containers in later episodes, implementing the list or the collection interface, I will
13976.96 -> refer back to this episode. Instead of repeating myself over and over again. Make sure you
13977.96 -> are subscribed to my YouTube channel. So you will be informed when I release episodes about
13978.96 -> these classes also. Okay, so let's start with the methods belonging to the Java util collection
13979.96 -> interface. The contract of the collection interface does not guarantee any particular
13980.96 -> order, and therefore does not provide any index or order related methods. So here you
13981.96 -> can see the first set of methods that implement the collection interface. So what I say about
13982.96 -> these methods does not only apply to ArrayList, but also to all classes that implement the
13983.96 -> collection interface. The method Boolean ad appends the element to the end of the collection
13984.96 -> to the next empty cell of the underlying array. Boolean at all appends all given elements
13985.96 -> to the end of the collection. The stuff in ANGEL brackets is related to generics. In
13986.96 -> short, it ensures that no one can call such a method with the wrong arguments. From now
13987.96 -> relax. I will tell you more in my upcoming episode about generics. Boolean remove removes
13988.96 -> the first occurrence of the element you specify from the collection. Boolean remove all removes
13989.96 -> the given elements from the collection. The iterator method returns an object usually
13990.96 -> use an a loop to move from one element to the next element of the collection. Step by
13991.96 -> step you say I iterate over the collection. Hence the name iterator. incise returns the
13992.96 -> number of elements of the collection. Boolean contains returns true if the collection contains
13993.96 -> at least one instance of the element you specify.
13994.96 -> Wide clear removes all elements from the collection. Boolean is empty. This returns true if the
13995.96 -> collection contains no elements. And to array returns an array containing all of the elements
13996.96 -> of the collection.
13997.96 -> Alright, let's move on to the methods of the Java util list interface. The methods are
13998.96 -> similar in part to the methods we just looked at, but they differ in that they require an
13999.96 -> order on the elements of the list. So here again, you should know that everything I say
14000.96 -> about these methods does not only apply to every list, but to all classes that implement
14001.96 -> the list interface. This add method with an index parameter. It's actually more like an
14002.96 -> insert method. It allows you to insert an element at any index position of the list.
14003.96 -> Instead of just adding the element to the end of the list. And the process the elements
14004.96 -> of the underlying array will be shifted to the right and migrated to a larger array if
14005.96 -> necessary. The remove index method allows to remove an element from any index position
14006.96 -> of the Similar to the Add method we just looked at, this might require to shift the remaining
14007.96 -> elements of the underlying array to the left. The get by index method returns an element
14008.96 -> from any given position of the list. The index off method takes an object and returns the
14009.96 -> index of the first occurrence of the element in the list, or minus one if the element is
14010.96 -> not found. In last index of returns the index of the last occurrence of the element in the
14011.96 -> list, and SP four minus one if the element is not found. List sub list returns a view
14012.96 -> of the list starting with the position you specify as from index and ending one possession
14013.96 -> before the one you specify as to index. Last but not least, the sword method sorts the
14014.96 -> list following the order of the given comparator. Alright, so let's end the lecture session,
14015.96 -> time to move on to some practical coding. So now I'm in my early and you can see I have
14016.96 -> prepared a little test method. So we can do some practical coding with ArrayList. I have
14017.96 -> already created an instance of ArrayList. And I've assigned it to a reference variable
14018.96 -> of type collection. Now, this might be a bit counterintuitive at first, because why is
14019.96 -> that not ArrayList? Or at least list. While there is a reason to it. And let me cite Robert
14020.96 -> C. Martin, he says, a good architecture is one that maximizes the number of decisions
14021.96 -> not made, or the number of decisions D fared. And this is such a situation, because by making
14022.96 -> this collection,
14023.96 -> I mean, you would create this instance for a reason, of course, and you probably would
14024.96 -> forward it to either other methods and or other objects. So now, if you make this an
14025.96 -> ArrayList, this will really limit all your other objects, because they all only have
14026.96 -> to work on an ArrayList. But now, the requirements of your business, I mean, requirements, usually
14027.96 -> they change very fast as you know. And if they change, like for example, an ArrayList
14028.96 -> can hold duplicate elements. But now there might be a new requirement that tells you,
14029.96 -> you cannot have duplicate elements, you have to prevent that you have duplicate elements.
14030.96 -> So you might want to use hash set here. Now, if you use list or every list everywhere in
14031.96 -> the code, it will be very tough to change your mind, you will have to touch a lot of
14032.96 -> code, which is very dangerous. But if this is a collection, a collection can be so so
14033.96 -> many things. And so it will be much easier to change your mind. Because all you will
14034.96 -> have to do is change the instantiation of the object that is actually being used. So
14035.96 -> if you can, like of course, this limits the number of functions that you can use, because
14036.96 -> the collection interface is less powerful than the list or the error list interface.
14037.96 -> But if you can, like if you only need the methods of the collection interface, well
14038.96 -> then do it like this. later on. We will switch here to a list interface because I will also
14039.96 -> show you methods that only appear in the list interface. But we'll start with a reference
14040.96 -> variable of type collection. And then you'll also see the difference. Okay, what else can
14041.96 -> you see in the single line? Besides you might spot that have used generics in the angel
14042.96 -> brackets, so we have created a collection of type string. And here, you might spot the
14043.96 -> so called diamond operator that was introduced with Java seven. Well, because we do both
14044.96 -> in one line, we do the object instantiation. And we create the reference variable in one
14045.96 -> line. The compiler directly sees this must be a string. And this is why here we can use
14046.96 -> the diamond operator. But we could also do it the old way by typing here string. This
14047.96 -> is just a bit shorter. Okay, and last but not least, you should notice here I wrote
14048.96 -> initial capacity, which is a constant, which I have defined here as private final int,
14049.96 -> initial capacity five. Now you might say well, you could have also said just five I mean,
14050.96 -> this is faster. Well, at first, it might seem so but this is a so called magic number. And
14051.96 -> this is evil, because it makes it so much harder for the next developer to know what
14052.96 -> this five actually means. Like not everyone knows that an aerialist has an initial capacity.
14053.96 -> But if you use the constant value here, you document in the code your intentions. So this
14054.96 -> is actually quite good. And I recommend you to do it also. Okay, but now let's already
14055.96 -> start using some methods. I mean, we're not doing I'm not going to properly program something,
14056.96 -> but we're just playing around with the methods, so you get a better feeling of like what aerialist
14057.96 -> is all about. And as this is now, a collection reference very Oh, of course, you'll only
14058.96 -> see all the methods of the collection interface. And we'll start simple with ADD. Of course,
14059.96 -> like one limitation that we have now is we don't see any index based methods, which was
14060.96 -> also the reason why before in my slides, I divided the methods into methods that are
14061.96 -> related to the collection interface, and methods that are related to the list interface. Because
14062.96 -> now I can also go back to the slides and compare, because now we're doing the methods of the
14063.96 -> collection interface. So this is a collection of type string, so I can add a string. So
14064.96 -> let's add B, capital B. Let's add some more.
14065.96 -> A
14066.96 -> later on, I'm also planning to sort the error list, which aerialists allows. But right now,
14067.96 -> with the collection reference variable, we will not be able to sort it. But stay tuned.
14068.96 -> I'll do it soon. Oh, okay. And I mean, even though we have a reference variable of type
14069.96 -> collection, still, the fact that we have an ArrayList influences that we can have duplicate
14070.96 -> elements. So let's do that. Maybe I should also add one eight here. Okay, and now let's
14071.96 -> count how many numbers elements I added 123456, the initial capacity or ever is five. So that
14072.96 -> means when you add the sixth element, internally, within the execution of this method, the error
14073.96 -> list will realize, well, the capacity is insufficient, will then create a new array of a larger size,
14074.96 -> and will then migrate all the existing data to the new array. Before the next element,
14075.96 -> the second he is added, which costs some extra time. But really don't worry, I mean, in the
14076.96 -> regular situation like this five, six elements, the performance difference is altra altra.
14077.96 -> Low. So never, I'm never worry, in such situations, this should really be only, like only think
14078.96 -> about this when it gets a problem. And usually, this could get a problem if you have like
14079.96 -> 1000s or 10s of 1000s, if not a million of elements. So it always depends on the amount
14080.96 -> of elements, you have the amount of iterations that you do. Okay. So and then we can also
14081.96 -> print the error list as it is now, there are two different ways ArrayList has also a two
14082.96 -> string method. So I could directly say system, out print ln elements. But I'm doing it a
14083.96 -> bit more complicated, because I want to show you how we actually iterate over the ArrayList.
14084.96 -> And this is because every list, and every collection implements the iterable interface,
14085.96 -> which is used in this new for each loop. And so we can iterate over the array list by saying
14086.96 -> string string, and then column and then elements. And what is required to iterate over this
14087.96 -> list will be done here inside and you don't see it. This is all done by the compiler for
14088.96 -> us internally. In short, I can tell you, there is an iterator method that I showed you showed
14089.96 -> Before, which will then be used. You might also check my last episode where I introduced
14090.96 -> you to the iterable. And the iterator interface, both will be used here. For now. I mean, it's
14091.96 -> enough, if you see, you can use the ArrayList and the for each loop. And now we can print
14092.96 -> out each element separately, which of course gives us a bit more flexibility. Like I could
14093.96 -> print something else here also. Okay. So this is called iteration going over the collection,
14094.96 -> element by element. And I also want to show you, let's comment this, oops, let's comment
14095.96 -> this out. I also want to show you that which is a feature of list, this order, how we added
14096.96 -> the elements, AB AC E, will be also exactly the same order as the elements are printed
14097.96 -> out, which would be different if we had a set. Okay, but enough of talking, let's already
14098.96 -> execute it and see it in action.
14099.96 -> Okay, so here you see a B, A, C, E, exactly like we added that, which is a feature of
14100.96 -> list. Okay, now that we added elements, we could also remove some elements, which is
14101.96 -> also just as easy we move. And now on the collection interface, I can't remove by index.
14102.96 -> But I can remove by stating the object that I want to be removed, which by the way, internally
14103.96 -> uses the equals method. If you don't know about the equals method, I also have a video
14104.96 -> about the equals method. So it goes over each element and checks by using equals, which
14105.96 -> is implemented in the string class. If there's a is equal to one of those elements here,
14106.96 -> and will then remove it. You might also notice I have two A's. So now it's interesting to
14107.96 -> know, like will the first a be removed will the second AB removed of or both be removed?
14108.96 -> And there is another tip I have for you. Like if you have such questions, you can look for
14109.96 -> a book for video tutorial, you can look in the API and so on and so forth. But you will
14110.96 -> never be as Sure. And probably also never be as fast if you just write a simple test
14111.96 -> like this. And you just try it out for yourself. I mean, how pragmatic How cool is that? Because
14112.96 -> the code doesn't lie. If you see it, he will be sure that it behaves like you can see it.
14113.96 -> So let's do this and check which element is removed. And here you see B, A, C E. So the
14114.96 -> first a is missing? So the answer is the first element is removed, not all A's are removed.
14115.96 -> Okay, so what else can we do? Let's check. We can also ask for the size. Let's make this
14116.96 -> a bit simpler now. To have it as short as possible. So now we have 1234 elements. I'll
14117.96 -> copy that copying some code that you will reuse is just safer not to introduce any typo,
14118.96 -> or K. And as long as you're just copying the code and not duplicating the code, it's also
14119.96 -> fine. So this supposed to give us the number of elements. Let me document this out. So
14120.96 -> we just see the number of elements. Let's also do it directly after instantiation of
14121.96 -> the object. So I expect here to see a zero, no elements included. Or I mean this would
14122.96 -> be another alternative possibility that this would throw an exception if the list is empty.
14123.96 -> So let's check that execute the test was actually not really a test. I'm just experimenting
14124.96 -> but here. So you see it return zero and the first line and then four. So this is the size
14125.96 -> method. You can even ask, Are you empty? Which should probably here say Yes, true. And here
14126.96 -> probably false. And there is true and false. Okay. So let's now switch Over to the list
14127.96 -> interface. And let's also play a bit around with that. You see, I have not a reference
14128.96 -> variable of type list. And I can use all the methods exactly like I used them before, because
14129.96 -> the list interface
14130.96 -> extends the collection interface. So it includes all the methods that the collection interface
14131.96 -> has. But on top of that, we now have more methods
14132.96 -> than just the methods of the collection interface. For example, I can insert an element by giving
14133.96 -> an index position. So I could for example, say, at index position zero, at me, I don't
14134.96 -> know T and S at index position two. And then let's use the simple fast print odd method.
14135.96 -> Let's remove this because it'll format the list in a one liner. But let me just show
14136.96 -> you what I mean. Okay, we still have the true we can also remove this. Okay, but for now
14137.96 -> it's fine. So we have T, because we added that at index position zero, which means this
14138.96 -> will be inserted where a was before. Before I added that at index zero, this was the index
14139.96 -> zero. So this, put it to where a was before and then shifted everything else to the right.
14140.96 -> And this is why now this is nice to see it like this in one line. Because you see, this
14141.96 -> is all shifted to the right, which when I remove an element, the opposite happens. Like
14142.96 -> if I remove the s, everything will be shifted to the left. But let's see this later. Okay,
14143.96 -> and we added the S at index two. So now this is index 01 and two, which again shifted the
14144.96 -> rest to the right. Okay, so let's also remove something, let's do this here. Let's say I
14145.96 -> remove index. And now let's see, I remove index one, which is which should be the B.
14146.96 -> Okay. And there, it seems I am wrong because the a is still there. And the B is still there.
14147.96 -> Let us see. Well, of course, because it's a bit confusing. As I added the T at index
14148.96 -> position zero, a is now index position one, and this one was removed. So removing by index
14149.96 -> is always not so easy. Really, I have to tell you these index based methods, I hardly ever
14150.96 -> use them. Normally, you're fine, actually with most of the methods of the collection
14151.96 -> interface, which again tells you like, often it's a good idea to use collection here. Okay,
14152.96 -> so this actually inserts an element. Okay. By the way, let's increment this a bit, just
14153.96 -> for demonstration purposes. I mean, this is not so flexible. I mean, really, as I said
14154.96 -> in my slides, you should really think carefully the number of elements that you need. Just
14155.96 -> here, it's different because we're playing around, because I want to show you the difference
14156.96 -> again in the example between the capacity and the size, because the size of the list
14157.96 -> is the number of elements. Let's do this here, and not the capacity, because my area with
14158.96 -> a capacity of 100 the area will be 100 elements big even though they're empty, but the size
14159.96 -> however, will be much smaller. And here you see the size is four and not 100. So there
14160.96 -> is a difference. Okay. Now we can also ask for the index of a certain element. Let's
14161.96 -> do this here. Index off and there is also last index off and also is empty. Yeah, this
14162.96 -> we should also use. So index off. Let's use the aim. Yeah. Which is maybe we should remove
14163.96 -> that. to not make it too confusing to keep the A where it is. So now index off gets you
14164.96 -> the first index of an element. So I would expect that to be zero now, let's see this.
14165.96 -> And they receive zero. And we can also say last index of, which should be the second
14166.96 -> a.
14167.96 -> Check that. And you might ask, Well, what do I need the index for? All you can use that
14168.96 -> to more flexible, like combine the methods now that you have the index, you could also
14169.96 -> say like, like, remove this index or so on, I don't know, might be helpful. Okay, so now
14170.96 -> I can also show you the clear method. And the is empty method. I think the is empty
14171.96 -> method we already saw. But now let's use rim
14172.96 -> clear. This method is void, so I cannot cannot print it. But I can put it here, clear, will
14173.96 -> empty the list. And then we'll ask
14174.96 -> is it empty now. And we can also print out the list. An empty list, which is also interesting,
14175.96 -> because this would be another question. Can I print out an empty list? Or will this again
14176.96 -> throw an exception maybe? Let's test it. And you see yes, it is empty. And you can print
14177.96 -> it. It's just the square brackets and there's nothing in there. So this was an empty list.
14178.96 -> Okay. So I think that's already it. A really short introduction, some practical coding,
14179.96 -> I really recommend you to do the same fire up your ID or your text editor and play around
14180.96 -> with the methods of earliest. I know there are many, many more methods of course, it
14181.96 -> just that in this video i don't have all the time. So this is just meant to give you some
14182.96 -> motivation to play around with it by yourself. Okay, that's it for this episode. If you have
14183.96 -> any questions, leave them as a comment below this video. And please remember to give me
14184.96 -> a thumbs up before you go. Thanks for watching, and see you next time.

Source: https://www.youtube.com/watch?v=grEKMHGYyns