0% found this document useful (0 votes)
302 views220 pages

(English) Learn Java 8 - Full Tutorial For Beginners (DownSub - Com)

This document provides an introduction to a free Java video course. It outlines the structure and content of the first lesson, which will introduce 15 key Java concepts. The lesson will start with an overview, then have a practice coding session, and finish with a recap. The instructor aims to teach Java concepts in the easiest way possible, even if explanations are not fully accurate at first. Understanding the concepts is more important than academic precision.

Uploaded by

mouad elatmani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
302 views220 pages

(English) Learn Java 8 - Full Tutorial For Beginners (DownSub - Com)

This document provides an introduction to a free Java video course. It outlines the structure and content of the first lesson, which will introduce 15 key Java concepts. The lesson will start with an overview, then have a practice coding session, and finish with a recap. The instructor aims to teach Java concepts in the easiest way possible, even if explanations are not fully accurate at first. Understanding the concepts is more important than academic precision.

Uploaded by

mouad elatmani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 220

Hi, welcome to my free Java video course.

Lesson One. My name is Marcos B. I'm a software

Craftsman with 14 years of experience in Java.


My goal is to teach you Java in the easiest

possible way. Okay, we will start with a briefing,


which is basically a lot of theory in the

beginning. Second, we will do a practice session,


where we will actually write our first Java

program. Finally, we will do a short key briefing,


where we will recap what we learned so far,

and add some more theory were needed. In this


first lesson, I'm going to introduce you to

the following 15 Java key words or concepts,


which you will need to understand your first

coding session later on. Please note, especially


if you already know some programming, I really

focus on not using any term before I officially


introduced it, getting a keyword explained

using concepts I don't know, something that


always ticks me off in classes, so I aim to

do better in this aspect. Therefore, intentionally,


I might explain a few things, not 100% academically

correct in the beginning. When necessary,


I will add the academically correct later

on. As stated earlier, my goal is to teach


you Java in the easiest possible way. If I

can achieve this by looking just a bit stupid,


that's fine with me. Last but not least, this

is really only a first introduction. It's


okay if you don't directly grasp everything.

We will go in more detail and recap the important


parts later on.

A package or better package structure is like


the file structure on your computer. It helps

to organize the different files of your program.


The top root folder of a package structure

is usually the organization's domain name


in a reverse order. In my case, that would

become Marco spiele. For example, if you don't


have a domain for the program you're writing,
it's okay to invent your own domain name,
but make sure it's a unique name. The reason

for this is that the name of a program file


is actually a combination of its own name,

plus the full package structure of the package.


It recites and there are millions of other

programs out there, and chances are high that


someone else has already used exactly the

same program file name before you. As Java


code is heavily shared worldwide, a strategy

was needed to come up with a unique name to


prevent name clashes. Each domain names can

technically exist only once. Therefore, using


a domain name as the prefix for your package

name as the default. Think of the package


name, like an absolute file name of your program

file. Using your package name is optional,


but I highly recommend you to do so even for

the simplest program. When used, the package


must be declared on the first line of your

Java program. The package name is starting


with a domain name in reverse order. As stated

before. The reason for this is that the package


name from left to right gets more and more

specific. Using lowercase and singular for


package names is the recommended default.

Last but not least, the package name also


serves as a high level description of all

the Program Files related to a certain topic.


code written for less than one of this Java

course would end up in a package called con


Marco spiele. java course lesson one for example.

Please choose package names for fully. It's


not just a stupid name. The package names

reflect the internal structure of your entire


program. Last but not least, I recommend you

to choose package names related to your specific


business topic. Rather than just using technical

terms. Good names are key. To simplify programming.


Every program file will reuse existing code.

To do so you have to import the code into


your program file. In our program file, the

import statement or import statements will


follow directly after the package declaration.

Here you can also see how the package name


must be included in the import statement,

as it is actually part of the programs falling.


You may import specific files, or all files

of a certain package using the star symbol.


Besides regular import statements, they are

also static imports, which we will cover in


detail at a later time. A simple program can

easily consist of 1000s if not 10s of 1000s


of code lines, it's very easy to get lost

in such a big pile of information. Therefore,


it's really important to impose a structure

on the program code besides using packages,


as explained before, in Java, the program

code is classified into different units of


code. Such a unit we call a class.

The programmer is the one who may decide how


to name and structure packages, as well as

classes. One aspect of Java is to improve


cooperation between business clients and programmers.

The client is able or should be able to tell


what he wants, the program is able or should

be able to know how this can be expressed


in code. The closer this code is related to

the business easier, the cooperation between


programmers and business people will be forming

a common language related to the business


and use throughout the code is therefore of

utmost importance. By convention, the name


of a class in Java should be a noun, starting

with a capital letter. opening curly brace


defines the beginning of the definition of

the class, where we will later write all our


code related to a car. The closing curly brace
defines the end of the definition of the class,
a class should be focused on only one topic.

As a recommendation, keep your classes as


small as possible to improve reusability as

well as readability. A class usually consists


of one or more methods. As the name implies,

it defines a method of how to achieve a certain


thing, like a method double could be defined

to calculate the double amount of an input


given methods are sometimes also called functions.

For now, one at 100%. Academically correct,


it's okay to use the terms interchangeably.

By convention, the name of a method should


be a verb that best describes the purpose

of the method. Methods define the actions


you can execute on classes, so they further

refine the structure of our program code.


methods can do pretty much everything for

us. methods can operate not only in numbers,


but also on text, colors, sounds, you name

it. A book would have chapters, every chapter


would have paragraphs and every paragraph

would have sentences structuring your Java


code in a similar way. Packaging name would

be like a chapter, a class would be like a


paragraph, and a method would be like a sentence.

For example, methods internally can call other


methods, which will then form a hierarchy

of methods calling each other. As a programmer.


It's up to you of how you want to structure

your code, how long you want a method to be,


which method will use which sub methods. I

would recommend however, to always think of


the current level of abstraction, just as

if you would write a book. For example, a


method prepared dinner could internally call

a method prepare appetizer, followed by a


method called prepare main course, followed

again by a method called prepper. Desert.


The prepare main course method for instance,
could internally call a method called boil
water. Mixing the levels of abstraction work

for example mean to have a method prepare


dinner, internally calling a method prepare

appetizer 30 followed by a method called warm


water without having a proper main course

method surrounding it. Coming up with clean


structure is key in programming. Make your

Code speak to you. Today with problems of


millions of lines of code. The most important

part of programming is structure and readability


for humans. As soon as you start to lose focus

and have difficulties in understanding what


a program does, chances are high you will

misunderstand some concept of the code. And


so you might introduce an error. Keep your

methods as short as possible. As a rule of


thumb, I would recommend 123 lines with 20

lines as a maximum.

The definition of a method follows a similar


concept of that of a class. First, we define

the name of the method. As stated before,


he was a word and start with a lowercase letter.

The name of a method is followed by an opening


and closing bracket. This is the place where

we mainly find the names of zero to an unlimited


amount of input fields. When using the method

later on, you will need to choose a value


for those values. These values are called

method parameters. In order to further improve


the structure and readability of your code,

I recommend you to use as few as possible


method parameters, with three to five parameters

as a maximum, everything more than that will


not be readable. The opening curly brace defines

the beginning of the method definition. closing


curly brace defines the end of the method

definition. Later, we will define the actual


code of the method that will go into the space
between the curly braces. As the name implies,
a variable is a variable value, a placeholder

for a value that you can set. The value of


a variable may change while the program is

running. For example, when the third value


is calculated over the lifetime of your program.

variables can be used as input or output values


of methods. For example, variables can be

of different data types, like numbers or text.


data types we will cover in detail at a later

time. Just for example, possible variable


names for a car could be my old car, my pushy,

or mom's car. There are different types of


variables, like instance variables, static

variables, local variables, parameters or


arguments, we will cover the differences in

a later session.

Public is an access modifier that defines


that any class from any package may use the

class or method with public access modifier.


Besides public, there are also other access

modifiers like private default or protected.


Here we are only skimming a topic. In a later

session we are going to cover access modifiers


in detail. Here you can see the access modifier

public in action. The class as well as the


method now posts have public access defined.

For every method, you actually have to define


our return value. Ironically, even when you

don't want to return any value at all. In


this case, you will send void as return value

of the method to explicitly define that the


method will not return a value. Besides void,

a method can actually return any kind of data


type. Here you can see the void return type

in action or drive method suppose to make


the car drive which is expected to execute

an action but not to return any value to us.


As a rule of thumb, it's good design to differentiate
between query methods, which will return a
value but do not alter the state and command

methods which offer the state but do not return


a value. In respect to this best practice

rule. Drive is a command method and therefore


does not return any value. The Add symbol

indicates an annotation. We will cover annotations


in detail in a later session. Just for now,

I want you to know that with ADD test, we


indicate that a given method will be used

as a test. When a class a variable or method


name consists of more than one word In Java,

you use an uppercase letter to indicate the


beginning of a new word. This is called camel

case, as the ups and downs of upper and lowercase


letters look like camel humps. In other programming

languages, and underscore is used to separate


two words from each other inside a variable

name. In Java, however, camel case is used


instead. To indicate the end of a sentence,

we use a thought in English sentences. In


Java, however, the DOT has a completely different

meaning. The dot between the variable car


and the method drive indicates that we want

to execute or we will alter. Alternatively,


say call the method drive on car. As the.is

already used to indicate a method being called


a colon is used to indicate the end of a statement

in Java. Here we can see an example of a test


method that is expected to test that our car

drives. The method drive is executed on car


with the value of 100. Colin says I want this

to be executed period. I talked about classes


already. I said that a class is a way of structuring

code in Java, a unit of code. This is perfectly


true. However, it's only part of the magic.

A class is like a template, like a definition


of what you want the class to do for you later

on when the program is running. The class


car for example, defines the behavior of a

car. However, when your program is running,


we say at runtime, there will usually be a

number of cars, each car may have its own


unique set of values, one car might leak oil,

so the value of oil could drop to zero while


the program is running. So our classes like

the human DNA, a definition of how something


should be created when the program is running.

When a Java program is running, it would usually


create a certain number of objects that will

exist as a set of values in the computer's


memory. And those values might change while

the program is running.

Each program language for certain concept,


Java is an object oriented language. Everything

is focused around objects in Java. In Java


writing classes is a way of defining a model,

which focuses on necessary aspects to solve


a specific problem. It needs the brain powers

of a clever Java programmer to fully understand


the problem and to extract a theoretical model

from it and transfer this model into classes.


The skills of the programmer will have high

impact on how precisely a problem is transferred


into a class model. Simply speaking, the more

accurate this is done, the less code has to


be written and maintained. The fossils or

program will run, the less errors it will


have. The power of Java is to be able to define

an execute table model, like a virtual machine


on your computer. With concepts and names

taken from the real world, which heavily improves


the communication of the programmer, and the

business client, programmer and business client


can both talk of a car. While the one is talking

of a real car, and the other of the representation


of this car on the computer, they will understand

each other. Here we see a simplified definition


of a class car. Now imagine a game where each

player creates a car when the game starts.


The program in this example, might create

three different cars at runtime. Now I talked


about classes and objects that will be created

from those classes. But how will these objects


be actually created? We will need a method

that will create the objects for us. This


is a very special method. It is called on

a class and we'll create an object each time


we call this method. But as soon as the object

exists, we cannot call this method anymore.


The special method is called a constructor,

as it is used to construct objects from class


files

to create a new object of time car, you write


new car. For example, the constructor in this

case, just like a method is given two different


numbers, one for the age of the car and one

for the maximum speed. In our example, when


the program is running and executes this line,

a new object will be created in your computer's


memory. We will, we talked about variables

already. However, before we can use a variable,


we need to define it beforehand. Call my Porsche

Colin is an example of a variable declaration,


we declare the variable which we called my

portion of the type car. Now that we have


a variable declared, we have to allocate the

object we created a variable declaration,


object creation, and allocation can all be

done in one single line. So this line reads


as when the program is running, and when this

line of code is executed, create an object


of type car with first of all you won, and

a second volume of 320. Then create a variable


of type car and give it a name my portion.

Last but not least, assign the car object


to the variable named my portion. After this
line, whenever we use my portion, we actually
referenced the object created in memory. Also,

you might notice when looking at this line


of code, we put two values into the constructor

of car. But without looking into the code


of the class car, we wouldn't even know what

their meaning actually is. This is one reason


why you should try to limit the number of

variables used in a method as well as in a


constructor, the less the better.

In session, to have this free Java video course,


we're going to write our first Java program.

When we write code, we actually start by writing


a program, which is actually testing the program

or class we are going to write. We do this


for two reasons. First, the test forces us

to properly think our idea through which will


improve our code a lot. Second, the main effort

in the lifecycle of a program is actually


not the first time effort of writing the program

code, but to maintain the program, like extending


or improving the functionality or fixing arrows

called bugs in your code. Whenever you write


code, there is a high risk you will introduce

defects in your code. When your program is


written once with the help of a test, this

test will ensure that whatever happens, your


program will continue to function as designed

initially. To recap, in Lesson One of this


free Java video course, I explained the necessary

theory to code our first Java program, which


we are going to do in a minute, we are going

to use these 15 Java keywords and concepts


described in detail in the prior session.

If you haven't done yet, I would recommend


you to start with session one before watching

this practice session. Okay, so now I'm in


my development environment. I've created a

folder structure of calm Marcos build Java


course, lesson two in a folder called test
and also here source main. Java. com Marcos
build Java course lesson two. This is where

we will write our tests have already created


the fall person test of Java. This here is

where later we will have our actual program.


But okay, so let's start person test. As described

in Lesson One, we have to start with a package


declaration. So I write and you see here,

I actually get support by my environment,


about the development environment. I'll tell

you later. For now just see that it actually


assists you. Actually, when you start learning

to program, I would recommend you to start


with a regular text editor because you need

to learn all these keywords. And so I guess


it's easier in the beginning. I mean not easier,

but it helps you to learn the stuff from scratch.


If you really have To focus and concentrate,

and you don't get assistance. But as soon


as you manage all these keywords, as soon

as you know all them section environment is


really helpful. Okay, so I use package, and

then I have to define it. COMM macros, we'll


see how it assists me again, it already knows

the package, because I have here the folder


structure, and the folder structure, and the

package declaration in my file actually have


to be the same. Otherwise, this would be an

error. So actually, I don't even have to write


it anymore. I can just follow. Okay, so this

is my package. And you see, before we have


an underline or red underline, which means

something is wrong. Now, oh, editor seems


to be fine with what I wrote so far. Okay,

here we are. Later, we'll have imports, as


described in lesson one. But we will add them

later. Normally, you start defining your class


first. See, again, I wrote public and see

how it's underlined red, so something is missing.


So I say class, and now I have to define the

class name is a person test. So I call my


test person test, it's a test for our first

program, which is the class person. Okay,


now I have to add the brackets. When I add

the first one, my editor already adds the


second one. Because for every opening bracket,

you always need a closing bracket.

Okay, so this is the beginning. And this the


end of my person test.

Okay,

no at the annotation test. So that I define,


I want to write a test. And see, magically,

the input appeared. Because my environment


already knows, I want to write a test. The

test also, I mean, it's actually a class.


And it even has package. And this is all three

unit test. We'll talk much more about j unit


in later lessons. But for now, we just know

this is a test magically somehow. Okay, and


we need to test the method. test method will

be public. It won't return any value, so it


will be void. And I will give it a name what

I want it to do should return hello world.


Hello World is actually like a running gag

of programmers. Someone I don't know who once


started. That first program you write in a

language should return hello world. So we


do that to write a test. For my first HelloWorld

program, I expect my person to return hello


world to me. And I'm going to test this. We

haven't written any actual code for person.


But we're starting reverse. So we're starting

with the test, as explained before. So now


I can just assume I was done. You see, it's

red, which means we don't have a class person


yet. But this doesn't matter. Now for this

person, I need a variable name. And as my


name is markers, just for fun, I call it person
I call the person Marcus. Okay, now I have
to create person markers. Remember, this was

calling the constructor creating the object.


And so this is creating the object of person

from the type from the class person. And the


equal sign assigns that object which is created

in the memory of RPC to the variable, the


reference variable person because this is

a reference that we can later on use referencing


the person.

Okay.

Now this is read, but we'll take care of this


later. We just continue. Okay, so assuming

we were done, what do we want? We want to


test something And testing, we say we want

to assert something, we want to assert that


a method we're going to write is returning

the hello world for us. So, we want to compare


if our expectation is equal to what the method

is going to return. So we say assert equals,


this also is starting as red, because we will

have to import more stuff. But for now, we


just take it, I use this was again metric

I add one quotation mark, and my environment


already adds a closing quotation marks. This

is what we call a string. And I say hello


world, because I want my person to return

HelloWorld for me, so, the first part here


is the expected return Well, you know, I add

a comma. And now I have to add what is going


to be tested Marcus dot for calling a method

Hello, world. So on the object, Marcos of


class person, I want to call a method, hello

world, with no parameters given and what is


returned here, I want to assert that it equals

to hello world. Now, this is not going to


work. Because we still have some red stuff.

For example, here, we don't have actually


written the class. But here we will let our
environment help us, you see. Now I just have
to say create a class person. Sorry, again,

create class person. And here, it already


asked us destination package, create class

person. COMM walkersville. java course lesson


two. Okay, sounds good. Because our test,

and the actual class of the test will be in


the same package. This actually helps us a

lot. But more about this later on. I say,


okay, and magic magically, or first class

got created. You see the package, and the


class. This is actually kind of the smallest

class possible, just with opening and closing


bracket. But it doesn't do anything yet. Okay,

but you see, it's not red anymore. So let's


go to from next, assert equals, oh, it wants

to import something statically. I said before,


I will later on tell you what means static

import. But for now. Just believe me, we have


to import this. This is another import from

org j unit. But this time, it's an assert.


And so this is like a method. We import the

method assert equals. But, um, don't focus


too much on this. We'll go in more detail

later. For now, what is important, we want


to write our first test. So we still need

to define a method. And it also tells us cannot


resolve method HelloWorld. Okay, help us please

create method HelloWorld. We had enough it


moved the method to the wrong place, but I'll

fix that. Of course, we need to have it here.


Okay, no, nothing read anymore. And we can

start calling our first test. I say run. And


this actually executed our first test, which

again executed our first class that was automatically


written. And here we see we have an error.

It tells us a missing return statement. So


I said we want to return a string you see

string. But as you see the method is empty.


We don't return anything. So let's fix that

fix that return. This is how we say it, we


have to say return. And I just have to type

Hello, world. exactly as I was expecting it,


I get the column to say yes to it return hello

world. Okay, now we switch over to the test.


And I'll execute the test again. And that's

green, all tests passed. This is our first


test. And it worked on in our first class,

Tara. Okay. Thank you. That said, lesson three


debriefing. For debriefing, we will go back

to our development environment, and have a


look what we learned so far. Okay, now we're

back in our development environment. And now


let's repeat what we learned so far. The first

line of our program is the package declaration.


It must be unique. And it usually consists

of your domain name in reverse order. So in


my case, calm, Marcos, bu Java course, lesson

two, and we ended with a color. Actually,


it's not mandatory, it's optional. But please,

I really recommend you to use a package name.


Later on, you will probably see why you just

need to have some practice. But for now, just


believe me treat this as if it was mandatory.

And always define a package name. After the


package declaration, we can have one or more

import statements. This just for our lesson,


now I made up I created a new class called

name. And this is an A sub package called


lesson three. Actually, all classes that are

in the same package. So person has an a package


called macro spiel Java course lesson two,

for all classes that are in the exactly same


package, lesson two at the end, we don't need

to import them, Java will find them automatically.


But here I made this lesson three. So if we

want to use the name class that I just wrote,


we have to import it. Okay. Next thing is
class definition public class person. And
with these brackets, that says the class begins,

this says the class ends. Public means all


other classes, for example, my new class name,

in any package can see the class person. What


this can see means is still a bit work. For

now, just take it as it is, I don't expect


you to fully understand it yet. This will

need some practice. And here for now, some


new stuff, I added the class that I defined

name, and I made it private, which is also


best practice to have we call this a reference

variable, because it is a reference to later


on an object of type name. And I made it private,

which means other objects that get created


will not be able to see. See again, I say

See, or access this field here directly. If


they want to use it, they have to go using

this method I also just created this one is


public and it returns personally. So when

they call person dot name, the method you


can give it any name I just call it salt,

but you could also call it I don't know.

Return the name. So this can be anything um,


and it will return the person's name. So here

again we see return, which means I want this


to be returned to whoever calls that method

and the colon which means do it execute it.


Okay. What else did we learn? We learned that

this stream, and that having a class, returning


HelloWorld is like a running gag in programming

for the first program that you do. So this


is why I made class person return hello world.

I mean, actually, it might not make sense.


But yeah, just was all made up. Then also,

going to the test, we learned, we actually


start with writing a test. When we wrote the

test, we hadn't defined the class person yet.


We hadn't defined the method HelloWorld yet.
We did all this on the fly. In our development
environment assisted us with some auto completion,

it was able to create the class as well as


the method. So this is really a handy way

of programming. First of all, you define the


test. So this gives you an opportunity to

think about the property sign. And then you


define what you need, and you don't have to

actually even write it yourself. And when


you did everything correctly, you can simply

execute the test. And when it returns, okay,


and it screen, you will see that you did a

proper job. Okay, see, here, you'll see a


green bar, which means the test executed successfully.

So when testing we often speak of green or


red bar, because the green bar is such a good

signal that you understand your test passed


successfully, that people got used to just

speak of green and red bars. Okay, so we learned


some more stuff, for example, that this is

an annotation. And I told you, you don't need


to know more details about it yet. We will

go into details later. Besides on top of input


static, and also, I just want you for now

to know that something static exists, but


we will go into details later. Okay. I think

that's it. It's okay, if you don't understand


everything perfectly yet, I don't expect you

to. Um, so we'll go in more details later.


And we will repeat all this stuff. So it's

fine. I mean, the start is really tough. I


know that I don't expect you to be an expert

in Java yet. Um, this is just an introduction,


and you will grasp it soon. lesson four. Okay,

we're back in my ID E. Id is actually the


short form for integrated development environment.

And as this is much shorter, usually you just


say ID e. m, let's recap what we learned so

far. And the first one, you have the package.


And the second line, you might have import
statements, you don't necessarily need something
I didn't tell you so far is here we use name.

And we use the classes short name, because


actually, the classes real full name includes

always the package name, so that the name


is of the class is unique. So we could also

use its full name, including the package name,


and then we would not need to import the class.

But I mean, as you see, this is much more


readable, much shorter, so also much more

handy. So this is what you normally do. There's


only one exception, which is a bit more advanced.

So I will just shortly mention it. Sometimes


it rarely happens that you would have two

classes of the exact same short name

but have different packages. And so to define


which one you mean, then you would have to

use one with the full package name. Okay.


So next, we define the class. The class starts

with a curly opening brace and ends for the


curly closing brace. Um, we have here, we

say it's an instance variable actually. And


this is an instance method instance variable.

And instance methods could be, of course,


much more. But those together we call the

members of the class, because they belong


to the class. An instance is just like an

object. So of one class, you can create various


instances, like, one person could be Marcos,

another person could be, could have the name


of Peter. And you could have hundreds of hundreds

of class of objects, sorry. And each one of


these objects is an instance. And for the

instance variables, this means that each instance


has their own version of this variable, which

each might have a different value does not


need to. But it's like a duplicate version.

There's also another thing, which is called


a class variable. And a class method, which
we do when we add static to it, we can add
static here, as well as to the here. In this

case, now when we create different instances,


and we change the person name of one instance,

this means that all other instances will also


have the name change to the new value. This

is a bit more advanced and static. We should


talk about this in detail later. So I just

shortly, just to be complete, wanted to mention


it. For now, it's totally enough, if you know,

this is an instance variable, and this is


an instance method, okay. Besides that, I

would want to add a constructor, I think I


talked about constructors already.

Okay.

Opening and closing curly brace. This is what


we call a default constructor. It does not

have any parameter here, not any variable.


And so this is the default constructor. When

we want to create an object of type person


of class person, this constructor will be

called and everything that we would do in


here would also be executed. So this constructor

is actually used to initialize an object.


Because for example, let's do something else.

Now let's add a parameter, prison name. So


this now gets a bit more dynamic, more interesting,

because we could try to set the inner person


name to the given person name. Now, you see

something is wrong. Variable person name is


assigned to itself. Well, of course, how should

our ID or Java know? What do you mean? Here,


we need something to differentiate to tell

Java, what we want is we want to set this


instance variable to the value of the parameter

person name. One thing we can do to fix that,


we could just rename the variable to see it

works. Now we can automatically automatically


resolve the problem. But usually you don't
want that I mean, person name is better name,
of course. And now what we have to do, we

have to add this to one of them. And as we


want to set the value of person name to the

instance variable person name, we add this


dot person name. And so Java knows that we

mean this one here. And now, when someone


calls the constructor to create an object

of type person, it'll also have to add the


person's name. And then the person named darts

directly gets set at the time the object is


created. Okay, one more thing that you should

know is now that we have created our own constructor


that has the parameter person name, this means

this class does not does not have a default


constructor, an empty constructor like I showed

you before this one has gone. Java will automatically


created when there is no constructor defined

by us. But as soon as we have defined one,


General will not do that. Now if you remember

our test from the last version, we use the


constructor without any parameter. So this

will later on fail, but I want to show you


so I will let it as it is. Okay, so, um, remember

we had that method here HelloWorld, I told


you that in the first program in every programming

language has like a running gag, you return


hello world. Hello World is actually a string.

And here we say the method should return a


string. Now, I want to do some more advanced

on, I would like to have a method, I can give


a parameter of string. And then I want to

say hello, the person's name. Um, okay. And


as you also might remember, usually we start

with a test. So let's write a test for what


I'm planning. Okay, so how do we write the

test? So we have to first of all at the end


here, and then say test. This is what we call

it a notation. Much more. We don't know yet.


And you don't need to know for the moment.

I mean, this is all confusing. So relax. I'll


repeat everything various times, you will

understand that very soon. For now, let's


just write the test. So I say should we turn

Marcos.

Okay, because this is what I want the method


to do. Okay, now I have the opening and closing

brackets for the method. Okay, so we need


to create an object of type person. Last time

I called it, Marcos. This time, I want to


show you how we can use any name we want.

So it's called person, new person. So with


that new person, and the regular brackets,

I call the constructor. And this is like a


method that is being initially executed at

the time when the object is created in our


memory, and see something is read here. Because

I told you the default constructor is gone.


So if we want to do that, we have to go back

to our class. And we have to add the default


constructor again. We can add it at any place,

put it here. Okay, and now this is empty,


and it'll work. But having an empty method

or an empty constructor might be confusing


for a colleague. So usually what we do in

this case, we leave a comment. To mention


we haven't forgotten anything. We have done

this on purpose. So let's see how do we do


a comment actually.

So I say empty. On purpose, default constructor.


So what I have here is a multi line comment.

There's also also a single line comment, which


you do just like this single line, comment.

But I really recommend you should prefer the


multi line comment for various reasons. I

will go in detail about comments in a later


session. So for now, this is all I want to

show you. Okay, so we have fixed the test.


Yes, the red thing is gone. Great. We have

created an object of type person, let me copy


this to show you one thing. You can actually

create various objects one after the other.


But now, we already have one object that we

called person. So this will not work. So we


would have to give this for example, person

two. And so like this, we could continue.


We could create any number of objects, just

so that you see. We have one class of type


person. And we have two objects created calling

the default constructor. And so we have two


objects when this is executed later on. I

will delete this again. I mean, this was just


a short demonstration. Because we should remember

what we want to achieve actually is we want


the method to return Marcos. Well, actually

I was wrong. I want to say hello, Marcos.


Okay, so now let's assert again. assert equals,

I want Hello, Marcos. And I want to say person


dot Hello. And I want to give it here, when

we use a variable here, we call it an argument.


This is just to make it more confusing, and

people use this interchangeably. But to be


correct here, it's called an argument. But

it's all about variables. So we add a string.


And I add markers. Okay, and see something

is missing our ID, he tells us something right


here, we need to call him to finish this.

So I want on the object of person we created


in the line before, I want to call a method

Hello. And you see it's red. And it also our


Id even already tells us cannot resolve method

Hello. It doesn't exist. But we are programming


in a test driven style. And so we will have

to create a method right now. Okay, I'm actually,


with some magic, I can automatically make

my array he created for us. Well, there are


different IDs, and I will speak about it specifically
later on. So for now, I just did this to speed
up it up. Just believe me. I mean, you. I'm

sure you could create that by yourself. Now


and he did something it said return now about

now this is something special. I don't want


to talk now. I'll tell you later. Okay. Sorry,

I don't want to confuse you. But I also don't


want to tell you too much. So one after the

other. And now, I would add well Marcus's


a bit. Let's say name. Name, because it could

be any name, not necessarily has to be Marcos,


we could add any name we want. And what I

want is I want to add name to Hello. What


we say here we want to concatenate hello and

name. And something is missing. Oh, it doesn't


like it. What is missing is a plus. This is

how you concatenate two strings together.


So a new bigger string is created. And you

can do this any number of time. But for now,


I mean, all we wanted to say is Hello, and

the given name. So this should be fine. Actually,


there's a little back hidden, which you will

see very soon. Which I did on purpose, because


I want our test to fail.

Let's execute it. Ah, so you see expected


Hello, Marcos. But actual Hello, Marcus. So

there's a space missing. So see, this is one


reason why tests are really handy to help

you to think about the stuff you code. But


also when you do introduce a back an arrow,

then you will directly spot it and you're


able to fix it before it goes on production

and destroy something. And yeah, this can


be really expensive. So let's fix this. Let's

go down to our method. And here was a space


missing. Let's add it. We go back to the test.

executed again. And now the bar is green.


It's works. Oh, that's great. Okay. Um, yeah,

I think that's it for now. Lesson five. So


now, I would like to talk about modifiers
first of all about visibility modifiers. Actually,
we already talked about them a bit. One visibility

modifier is private. Another one is public.


So public, I think I already said this class

is visible or usable. From all other classes


in all other packages. This class now resides

on the package comm Mako speelde. java course


lesson two. So here, for example, name is

in lesson three. So if we would go in the


code of the name class, it could easily use

person as long as it's public. A private class,


we can try that. No, it says modifier private

not allowed here. And of course how That makes


sense. I mean, a class that's not usable anywhere.

But just in this class. This doesn't make


sense. But actually, there is one more option,

we can leave the modifier away. And this will


give us the default modifier. This is also

why it's called default modifier, also package


level modifier, because now, person can only

be used from other classes within this package.


And we can do the same for the variables,

the constructors, we can even have a private


constructor, we could have that public, we

could have that method private. And this one


default. And we can even call, let's use this

one. Let's call HelloWorld. From this method


here, all this is working. And this actually

even makes sense. Because especially when


your methods are growing, I personally would

say not more than three or 10 lines. Then


to break things up, you can split a long method

into smaller private methods, and then calling


the private method. Like, I mean, here, we

have only two methods. So to make things up,


you can call one method three times. But of

course, I could define further methods. We


don't have this now. And then you can call

any number of methods later on. Okay, so to


recap, visibility modifiers, we learned so

far is public, private, and default or package


level. Besides there are other visibility

modifiers, one, for example, is protected.


But we don't need this at the moment. So you

should be perfectly coming alone, along with


just public, private and default. So for now,

let's just concentrate on these few. Let me


fix the class shortly. Because very soon,

we are going to need it in our test. And I


don't want to adjust the test, I want to have

the code as it was before. Okay, because now


I want to show you a new concept. I have this

idea. I have prepared the test should return


number of persons. Let me create a few objects

of type person, one person, person to

person,

we could also use the other constructor, but


then I would have to create an object of name,

as this at the moment is just too much work


for me, I'm not doing it. And I can also give

it a different name, like my person, just


to show you, we can have any name for the

variables. So what this means is when the


test will be created here, after this line

is executed, which is just after the column,


we will have one object and memory two objects

in memory. And after this line three objects


in memory. So what I want now I want to test

on a number of objects. Now I should have


three objects created. And I want to create

a method that tells me exactly that. Just


dynamically, my person thought number of persons.

Okay, still read, remember, we'll create it.


And today Ah, int appeared. Because I mean

three is a number. And a number in Java is


an integer, or he In short, an int an int

this actually a primitive. And the default


of this is zero. So this is why my ID he put
zero here. So it's not red anymore. We can
have a first run. But this will not work of

course, because it statically returns zero


we expect three. So this is not what we want.

Well of course we could say three statically.


So, now this should work. It's a bit cheating,

of course, greenbar Tada. But, I mean, I want


this to dynamically work. So why not only

have two persons, I want this to be two. And


well, of course, I have to rename a variable.

Let's copy it. And now when I execute it,


of course, this is not going to work expected

to, but it's still three. So my first approach


the static one, always returning three. Nice

gag, but yeah, not what we need. So what we


need is, at the specific time, when each object

is created, we need to count each object that


is created. So what would be the place where

the object is created, there is one thing,


similar to a method that is called and this

is, you might guess it, the constructor, we


used the default constructor for creation.

So we would have to do something in here.


Now, I want to invent a variable, an instance

variable, I also call it or let's call it


person counter, person counter equals two.

And now I say person counter, because I want


the value it had before. And then I want to

add one to the last value of person counter


to have the new value dynamic. So on the left

side, is the new value. On the right side


is still the value from the prior calculation.

And I add one to it. Now, this is a lot of


code again. And this incrementation by one

is used so often, that they invented short


form for that, which is plus plus. So with

plus plus, we say take the current value of


person counter incremented by one and save

it again into the value of person counter,


it's still red, because we still have to create

it. Let's do that. Make it private, of course,


it's an int. I call the person counter and

column. Because I don't have to say zero,


I could also say equals to zero. But the default

for end is zero anyway, so what we usually


do is, we just put it here as is. So the idea

would be it starts with zero. The first time


this constructor is called, it's incremented

by one, and so on. So that my method now should


not statically returns three, but person counter

instead. Okay, let's try that. Execute the


method. Still not working it returned one.

It didn't return zero. It didn't return three


it returned one. How is that? We didn't say

one anywhere. Maybe you guessed it already.


So we started with zero, we incremented by

one. Now I told you something in the prior


session, which is this constructor is part

of the instance. So each object has their


own constructor has their own method. So this

is called for each of the objects. So in the


end, both objects would have the counters

set to one. So what we need is more like a


global counter. That is not on the instance

level. But we say on the class level, because


for all the objects of type person, there's

only one class person and this we achieve


with a modifier called static. Okay. However,

as a recommendation because this will help


you in the future, I won't go on details Why

just believe me. As we have the variable of


types of static, you should also have the

method of type static, it would work also


without that, it just better believe me. Okay,

so now let's execute it. And this work Great.


Let's try another thing. Let's add this time

for

free
for for an exit executed and it works, I said
actually person to why not saying person one.

And it works? Well as you see this might be


confusing I mean which variable to decide

on. And also there is a recommendation. Actually


what Java does is Java sees that number of

persons as a static method, it sees that you


have an instance variable off type person.

And as this is a static method, it doesn't


call the method on the object. Because as

this method is static, it's not part of the


object anymore. This is like moving it out

of the object. This method now is part of


the class. So Java does some magic here, is

trying to be smart and is smart, and calls


the right method of the class. So what we're

doing here is working because Java knows how


to do it properly, but it's not so nice. What

is better is darkly saying person, so that


everyone knows you're not going to any specific

instance, we're just calling a static static


method. On the person class, let's execute

that again. And it's working. Thank you. So


in lesson six of this Java course, I'm going

to talk about the tools which I'm using. So


first of all, let's start with this computer.

It's an apple MacBook Pro. This ID that I'm


using here is IntelliJ IDEA, which actually

at the moment is my favorite ID. Before I


was using many, many years, Eclipse clips

is open source is also very popular at the


moment, especially with companies because

it's open source and free. However, I think


intelligence here is really getting better

and better every year. So I really like it


and recommended. And they're not paying me

for saying that. But I mean, this is your


personal preference, and every person is different.

So I would say just try it out yourself. There's


also NetBeans. NetBeans is also very popular,

and it's also for free. I'll just in a second,


I'll show you where to get them. But let's

have a closer look at my tests before. So


in the tests, might have seen it already.

I'm using j unit, which is a testing framework.


framework means it's like a tool set. It's

a set of tools to set of classes. And it's


open source. So it's free to use. And I mean,

writing such a framework, it's not really


hard work. But why doing it if it's already

done. So this makes it really easy to start


with testing. J unit also is only one of a

few testing frameworks. The second one I would


tell you about is test and G, I think they're

pretty much the same. And really depends on


the company that you work in some use j unit,

some use testing G or any other framework,


I think between j unit and test ng g there

knows not so much big differences. So it doesn't


really matter. I just decided to use j unit

in here. IntelliJ IDEA actually supports both


of them out of the box. So you can easily

try them. Um, I'm not going in much more details,


by the way. I mean, this is a Java tutorial.

So I focus really on Java. Just to be complete,


I wanted to mention what I'm using here. But

I do this in less than six because at the


beginning, I think learning a new language

is already quite difficult. So I wanted to


focus on Java, but not that you puzzled. What

the heck is that here? What are you doing?


I wanted to mention this is J unit. And there

is lots of documentation on the internet.


Yeah, so you can read a lot about it. Okay,

so maybe we just go to the browser now. and


have a look. So first of all, I told you about

intelli j idea for you pops up.

So you can download, I would first of all,


go with the free edition, and then see if

you like it or not. Besides, of course, there's


Eclipse. This one is open source anyway. And

then you can choose your operating system,


and 32 or 64 bit, whatever you need. Last

but not least NetBeans. Just press the download


button, choose your language, and operating

system. And then also j unit, let's have a


look on that. In most It is these days, you

won't have to install it, because it would


come pre installed anyway. But just for the

record, I mean, this also has lots of documentation.


So yeah, he you can download the most current

version. Let's check documentation. Here.


It also talks about Maven, which, by the way,

also using so this way, you can define in


Maven that you want to use the current version

for 12 of j unit, which I actually did, because


I'm also using Maven, which we're going to

in a second. But after j unit, let's also


have a look on tests and G

test ng g on this page just provides the false


for Eclipse. But as I told you in IntelliJ

IDEA, it's included anyway. And I checked


for NetBeans. I mean, I'm not so familiar

with NetBeans, I have to admit that beans,


but I saw there is a plugin, which you can

download and install. So probably works just


as well. Now let's talk a bit about Maven.

Maven, there's what's called a build management


tool. So as the name implies, it manages your

build. Now, what's a build? Well, when you


program your programming consists of hundreds

of classes, and then you would want to release


them on production or send them to a client.

And then of course, you would not want to


send each file separately. So the so you would

usually do a package a single file out of


all the tasks together. And in former times,
and say in prehistoric times, this was done
manually. And this is really not a funny job.

So people very soon started to program, some


little scripts to make this task easier. The

first tool that I know of is probably make


it's a Unix tool. And often make they came

up with and and Maven again is the successor


of Maven of m sorry. And Maven currently exists

in version three. Besides Maven, there's also


Gradle and other build tools, I'm using Maven,

here you see it find that I'm using j unit


412. And also the find that my source encoding

is UTF eight, because what this bill two also


can do for you. I mean, it can do so many

things is environment specific settings. So


that I tell that my source encoding is UTF

eight, I can do it here. And so much more.


So also about Maven, you can visit the website,

Maven. There, you can download it. They also


have a free book, which is really a great

book. You can download all the files, even


the sources that you would need. And also

check Maven book. I really recommend that.


As far as I remember. It's available as HTML.

And also there should be a PDF somewhere.


All this is just too long. Anyway, I know

there is also a PDF available which you can


download. And so you can read all about Maven

Last but not least, let's also talk about


bit about text editors. Because I think in

at least one of the lessons I did so far,


I told you, you should start not with an ID.

But you should start with a text editor instead,


well, there are two that I would recommend,

first of all testbed for Windows, I really


like it using Windows. for Mac, it's unfortunately

not available. In this, you can write your


code, then you would save it. And then assuming

you have already downloaded the Java JDK,


which I have also not talked about, because
I assume I should be easy, but maybe we could
first, shortly go there. So for the JDK, so

that you can download your code, you can just


go here, say download, by the way that was

NetBeans, if it was soiled, and you can choose


your operating system and download it. I assume

you have already done that. And so when you


have installed a text editor, or like text

pad, or sublime, you're on. Mac, I'm using


sublime, which is also a great editor. Download

button. It's also available for Windows and


Linux. So using this text editor, here, I've

loaded the class person that we saw before.


I mean, it helps you a bit like see, I click

on person's name, it highlights the variable


person name and all forms, but it would not

so heavily assist you, like you might have


seen when I was in my ID, which for the beginning

is actually good, I think. Because when your


ID is too smart, then you don't have to use

your brain cells too much. I mean, after some


time, when you have coded too much, this is

really welcome. But for the beginning, I really


recommend to use your brain cells and so that

you get used and familiar with all these keywords,


public class, private static, should really

get familiar with that. And so for the beginning,


just use a text editor, then you can also

go on the console and called Java arc and


compile the class. Also, this is one show

you because in this course really I only focus


on the theory of Java. So yes, I think that's

it really short introduction of the tools


that I'm using.

If you have any questions, send me an email


as always, um, yeah. Lesson seven. So now

let's start with the topic of this video,


which is conditional statements, and of course,

conditional statements, and Boolean. So a


Boolean is a new data type. This one is actually

a primitive and it can have two values, Boolean,


true or false. And this is all there is to

it. So conditional statements, I mean, there


is a condition and it can hold true or not.

And that is something is executed or not.


I think, already from the wording, it makes

sense, and you might easily understand it.


But what exactly is a Boolean? Why is it called

Boolean? I mean, this is a bit weird, I think,


well, at least this is what I found. So I

just looked it up on the internet. Here on


Wikipedia, we have Boolean algebra, and I'm

really not a big fan of mathematics. So let's


go over this really fast. The only thing that

matters to me is Boolean algebra was introduced


by George Boole in his first book, blah, blah,

blah whatsoever. So it turns out that the


Boolean is called all the end because of this

guy here. Um, I leave this as your homework,


read everything about George Boole and Boolean

algebra, of course, this is again a big topic


by itself. We have folk focusing again on

Java, I just wanted to help you that you get


a feeling why Boolean is called a Boolean.

So this thing here is really helpful when


we want to say if something happens or something

exists, some condition, then only execute


a specific area of code. And then you can

also say else if this condition does not hold


true execute something else. So this is really

the if statement is probably the most important


statement, not only in Java probably in all

programming languages, at least the ones I


know of, because it allows us to, like really

have a different execution flow each time.


For example, we could say, I mean, B is a

bit boring. Let's call this Monday. And let's


add all the raining. I was raining. Let's
also have Monday. Okay, so in this little
example, it's Monday, and it's raining. And

nobody could say if it's Monday, and percent


twice,

raining.

So what these two M percent mean is, and so


this tells Java to check on this boolean value,

check if it's true, and only if the first


boolean value. Or he could also be a function,

like, is it Monday, which would have to return


a Boolean. And if it does, only then Java

would execute, go here. And check if this


is also true. Which also could of course,

be a function if Is it raining or whatever,


right. And if both here are true, then this

block here, starting with the curly braces,


is going to be executed. Now. I mean, I don't

want to implement the functions. So let's


make this Monday again. And simply raining.

Just to keep it simple, and then drink beer.


Because rain. I mean, what else can you do?

Um, but now let's make this more easy to drink


beer. I'm from Munich, so I'm really a beer

lover. So on Mac, I mean, as depends which


platform you use. On Mac, you press just out

and seven, twice. This is called the pipe


symbol. And the pipe symbol symbolizes or,

um, yeah, I know this is a bit weird. This,


you just have to know by heart that this means

or, again, as before with the two ampersands.


When you repeat it twice, it's called the

short circuit operator, which means if the


first condition is already not true, for the

end, at least, then it's not going to execute


the rest. So whenever In a statement, it sees

that a condition will cannot hold true anymore.


It will stop at the beginning and they will

not execute the rest, which is very handy.


Because I mean, if before we had a method
here, is it raining. Now imagine this method
takes like two hours to execute, we could

really save that time if we already see. This


is only true if both are true. So this is

why you use the ampersand twice. And the pipe


symbol wise, this is I would say the default.

So I want to even spend time to talk about


the other alternative. But now this is so

much nicer. If I have an orange here, if it's


Monday, or if it's raining, I drink a beer.

So this really increases my chance my chance


to get a beer. So I personally liked the statement

so much more. I'm just kidding. Um, so this


is the difference. Or, and, and, and of course

you can further combine that led so I don't


know what to do. Let's say raining and let's

say Tuesday and sunny. So we have to introduce


these Boolean variables first. So Tuesday.

Well, if it's Monday, it can't be Tuesday.


So we will say false here. And Boolean, if

it's raining, it can't be sunny. So sunny


will be false. But of course, let's change

this. Now it's not Monday. It's Tuesday. So


this will be true. And I misspelled that sunny.

Okay, now they're not red anymore. So now


what do we have here? Monday is false. So

if Monday is raining, but it's not Monday


at the moment. So this is the whole thing

here is not true. But here we have an or true


Tuesday, this is true, Sunny is still false.

So this is also false, which means the whole


if statement is false. And we cannot drink

a beer. But let's make this true. And now


it's Tuesday. And it's sunny, and we can drink

a beer Ray. Of course, I mean, when it gets


more complicated, I'd recommend you to introduce

more brackets to really tell Java first execute


this. And the result when you have it, then

only execute the next statement. I mean, if


you go more in more detail on the algebraic
logic, you will see there are preferences.
And they're really rules on that. But if you

don't know them, and if you always just add


the brackets, you're on the safe side to show

what you want. Okay, now, let's make this


not so complicated. Because let's introduce

something, something else. And this else is


the else statement. Because if it's not money,

we can do something else. And this is the


new keyword that I'm introducing the else.

statement. So here, we can say drink, milk.


might also be nice. Okay, so, only on Monday,

we drink beer. And on all other days, we drink


milk. So that means we have to drink a lot

of milk. So if you I mean, milk is really


healthy. So I recommend you to drink milk

like this. It's much better. But of course,


let's introduce some more variation. If no

sorry, else if, um, as you introduce a new


day, let's say Friday. So we have to introduce

Friday. At the moment, it's Tuesday, Tuesday.


So we'll change that in a moment. Make this

false. So else a Friday.

Sorry.

Drink water. Okay, so what do we have now?


And I mean, you can format this in any way,

but usually, you formatted like this, too,


so that you can see this all this whole construct

belongs together? Because it starts with if


money. And if this is not true. Java has to

check else is it Friday? If so, then call


this function. And in all other cases, we

still drink milk. So, okay, and you can have


any number of L's if statements here.

Else if I don't know some other condition,


we could just say sunny. Um, if it's sunny,

um, what should we do? go swimming, go swimming.


Yeah, we can do anything here. Okay, so you
can have any number of L's if statements.
And you can have just one l statement, of

course, but you don't have to, I mean, this


is not obligatory. You can also leave it away.

You just you cannot have AIDS if by itself


because else what I mean, there has to be

the whole statement has to start with some


Eve. I'm okay. I think this pretty much is

enough for if else if and else. Now let's


do some more cool stuff. Let me Remove all

that. Because normally, you evaluate some


condition. And then when the condition is

evaluated, this returns a Boolean. Under the,


under the covers, I would say, for example,

you could say in E equals to four. And then


we could say end. j equals to three, omit

that. Okay, so we have two primitive data


types of the end, which are introduced in

a form of video. And then I can compare those


values. I can say, I mean, of course, as well

as with the Boolean is it's obvious. But I


mean, in a big program, it's not so easy.

Normally, one function calls the other, and


he would like have the user typing in nature.

And then you don't know if the user typed


in four, three, some in this is a really stupid

example. I think we know that four is bigger


than three. But let's assume that we don't

know. And then I could say, if i greater than


j, then do something. Else. Do something else.

I mean, here, it's again, you can say ELLs,


if you could say if j greater than I, what

else can we say, oh, if i equal to j, which


at the moment, of course does not hold true.

This, by the way, you see there are two equal


signs. The reason is this equal sign we use

here when we assign the value of four to i,


or j, so we can't use that again. Instead,

in Java, here use two equal symbols to express


I want to have a Boolean check. And what you
also can do so so you see the result of this
will be a boolean value, you can assign that

boolean value are equal to a boolean variable.


And this is actually quite often very smart.

I mean, here, it's very easy to understand.


But sometimes you have way more complex terms.

And then if you give it a name, your code


will be much more easy to read, because now

you can say are equal. Okay. And then there


is also greater or equal, smaller or equal.

And then also unequal, which I will usually


I'm typing like this, but it's actually the

same. So not equal, you can say with the exclamation


mark equal, or with greater, smaller, like

this, it's both the same thing.

I really prefer that one. I think it's more


readable. Because this is like, exclamation

mark, really easy to read. And with this,


you can also whatever condition you have,

if this no holds true, when you put the exclamation


mark in front of it, that is false. If this

before was holes. Now it's true. Thank you


can even Yes, you can, you can add any number,

exclamation marks, and every time the value


is inverted. So from to false than true again,

and false again, and so on. I mean, this is


not really readable. So I wouldn't do it.

Just to be complete. I wanted to mention this


as possible. Okay, on. I think this pretty

much wraps it up. We talked about Boolean.


This is a condition. If it's true, we execute

code that is in here. You see it can also


be empty. I mean, it doesn't really make sense.

I mean, I would really recommend you to write


something, execute some method. You can also

of course, you don't have to have an method


in here, while again, I would recommend it

because it might be much more readable. But


in here, you can also do crazy stuff like
i equals to eight, for example. J equals 299.
So you see, now we have actually some code

or plus class, the increment operator that


I talked about, I think it was in less than

five. So if j with three before, when this


is executed will be four, or minus minus,

it was three before it will be two. Okay,


so you can have 30 Booleans. And here, what

you cannot do is compare a Boolean to another


data type like int, amin, this wouldn't really

make sense what you can do, but, and this


really, a lot of beginners do like to compare

a boolean value let's make this Monday again.


Monday. True. And now you could say, if Monday

equals to true, what does this mean? I mean,


this means if true, equals to true. Of course,

this works. And if this was false, if false


equals to true, false does not equal to true.

So the whole thing is false. But I mean, this


is one comparison too much. To say, if Monday,

this is enough. Yeah. But really, comparisons


like this false or true. I really see very

often in code. So if you see that, you're


free to refactor the code, and just shorten

it. If it's true, then just say, if Monday,


if it was, if Monday false use just say, if

not Monday. So, see, this is not. Okay. Lesson


eight, I would like to introduce you to loops.

This is really exciting, because it's a very


cool feature. It allows you to execute a repetitive

task much faster than any human could do.


So this really makes our programming very

powerful. So it's very important to know how


to program loops. So there are certain different

types of loops. The first one is a for loop


for because it says like, for a number of

times, execute something. So this is why for


and then sorry, this writing here will be

a bit cryptic. I'm sorry. The reason is because


this loop is really also a very old loop.

That was also introduced before Java, actually,


I think it's, for example, is part of C and

c++, which are much older than Java, actually.


So and when they invented Java, they just

took over the same style. So this is why it's


a bit cryptic. So

we have three sections here. Let me first


of all, type it and then explain. So this

the three sections that this first loop usually


has, which means First of all, introduce an

int, and assign it a value of zero. calling


this variable II, I sorry, is like the default,

because I just for integer because the guys


that invented programming, are sometimes also

mathematics, mathematicians. So yeah, they


really like short variables like AI. And it's

so it's so common. I also used AI, but you


could also call it like culture. It just that

people would expect you to call it AI. In


this type of loop. It's mostly always called

AI or just why are some some variables short,


just one letter. Okay, anyway. So this is

our counter variable that defines how many


times we want to execute a certain statement.

Our statement that we want to execute is actually


that Create a person object. And we want to

do this four times. In programming languages,


again, mathematicians, they're to blame. They

don't start with one, but they start with


zero. So if we want to execute it four times,

we have to make sure that we stay that I stay


smaller than four, because from zero to three,

this is four times. And each time when we


are finished at the end of the loop, I is

incremented by one, see, this is the plus


plus. So afterwards, it's incremented by one,

and then the next round, it will be one, one


is smaller than four. next one will be two,
two is smaller than four, three is smaller
than four, and four is not smaller than four.

So for the fifth time, the loop will be exited.


And so afterwards, the court will be here,

the cursor kind of, and we will not execute


it a fifth time. So I copied this into the

for loop.

And then this should make sure that four persons


on the fly are created. Actually, because

this variable is defined within the block,


we cannot access the person object anymore

in here, I think I showed you this, see it's


red. This is about the visibility, what we

could do is we could put the definition of


the variable up here. This way, we can still

access person one, but actually only the last


one because the variable person will always

be overwritten by the next one. I mean, for


this little test here, this is okay. Because

all we want is we want to calculate the number


of times the constructor was called. So this

works, as well as we could also define person


in here doesn't make a difference. In our

case, because this is a static method. We


talked about this in the earlier lesson. So

now, let's try that code. And it's green.


Now let's try it to put the time here. This

darkness does not work. Because see we expected


for but actually, there was 10 times the person

constructor was called because this is 10


a year. So this is how the first loop The

for loop. The regular for loop usually looks


to define an end, you give it a one letter

name like I, you assign it zero, and then


you compare it to some max value. In this

case, 10. Before we head for so that the test


is green again, you always have to separate

these blocks with a colon. And then you increment


i by one. You can also do any other statement
in here. Like you could say, I equals i plus
two. Which will then let's see. So I'll assume

something. See now we only created two persons,


because each time it was incremented by two,

which means the number of times that we were


going through the loop was only half the number

of course. And if we add four or even I don't


know 10 we will probably only executed once.

Let's try that. Yeah, see actual one. Okay,


so usually you could put any statement here,

but the default is to just increment a counter


variable by one. So, release. Try to stay

with the default and do it like This, I could


even further tell you crazy stuff. Like you

don't even have to do all this can have this


empty. This now would be an infinitive loop,

you can try this at home, because this will,


like probably crash your PC because it will

create lots of objects.

Um,

but it is valid. Okay. But this is how it


should usually look. So anyway, let's go to

the second loop, which is the while loop,


while some condition holds true, execute.

And each of these loops have their specific


reason to be used. I mean, actually, in theory,

you could use always just the one loop like


this loop or that loop, it just that when

you want to count something, I mean, this


really is helpful. Because it does all everything

at once, if you want to do exactly the same


code, we have to do it like this int i equals

to zero. Well, I smaller than four. And then


you have to say, at the end, I plus plus.

So this is exactly the same. And you see,


it's not so nice and short anymore. So this

while loop, you would usually do one, for


example, you have some condition that gets

dynamically calculated, like we had the function


here should drink beer. So if you had some

function here, like should drink beer. This


is when you would use a while loop. I mean,

I have not defined those variables here. But


I hope you get the idea. If you have some

function that is always calculated, you will


use the while loop. And then in here. You

could also create person, and you don't have


to do this now. Because we assume that this

method sometimes would return false. And when


returns false, this loop would be exited.

Okay, but let's go back because actually want


to run it once. And there is a bracket missing.

Because I promise you we can do exactly the


same thing. So let's try that. Okay, well,

this probably will not hold true anymore,


because then we have done it eight times.

So let me remove that code. Okay. Let's check.


Seems Okay. Let's see what j unit says. Okay,

seems like this is okay. So it's the same


one. And then last but not least, there's

also another loop, which is called This is


the newest loop because it was introduced

as far as I remember, with Java five, this


is the most simple and the coolest loop. However

I'm sorry I cannot show you this one. Because


for this I need to introduce you to arrays

and collection which I will do in one of the


next lessons. So for now just know there is

another loop the coolest one actually. But


yeah, so this was a very short introduction

to two different loops. Well actually yeah,


I could also show you the while loop you can

also do it kind of let's say backwards. So


you can say do while some condition um the

regular while and the for loop I showed you


that very common bows, but this one you will

hardly ever see because Again, it's a bit


more difficult to understand. What it does
is it executes this statement the first time,
sorry, without even checking a condition.

So the condition is checked only afterwards.


Of course, we also need to increment.

Okay.

So what we do here is we assert that number


of persons equals to four, well, no, this

is, this won't work, we have to sort it afterwards,


sorry. So now we create the first person without

even knowing how many times we have created,


then we increment i. And at the end, we check

that I is smaller than four. Let's try this


and remove that.

See, this also works. Um, this depends on


the logic that you need. Sometimes you may

use that. But actually, all the three different


loops I showed you, they are like equivalent,

you can do everything with each of those loops.


So it's just the different style. And this

depends on what you want to express what's


easier for you to use. This you will get used

when you're like, did a few months of programming,


and you use each of them, you will get the

hang of it. What's like usable in which situation.


Lesson nine, I would like to introduce you

to arrays. Arrays are also a very cool feature


of many programming languages. And they also

appear in Java. I kind of unofficially introduced


them already in the last video, where I mainly

talked about loops. And we stopped when I


said there is one more loop the for each loop

that is specifically designed for arrays and


collections. So today I'm going to introduce

you to areas at least. And so we can also


see the for each loop. And so an array is

really like container, a box, or let's say


a list. So an array isn't is also an object

is a data construct that can hold a number


of primitive data types or objects. And as
I already said, box, so far person, the way
we define it is with these were brackets,

which symbolizes something like a box, I think,


which is easy to remember, because we will

put our persons kind of in in here we could


think and because this container will hold

a number of persons, I will call this variable


persons. Okay, now I say new person. But now

there comes something new again. I don't use


the regular brackets, or again use the square

brackets. This does not call the person constructor.


This would be done like this, and should not

be working yet there's already a thread on


the line. So I'm not calling any constructor

here. This is a specific syntax that says


Create me an array of type person that can

hold a number of persons. And we have to now


give the number which is four. That was still

a red underline now it's gone. So now Java


knows we want an array of type person that

can hold four persons same thing we can do


with it. And by the way, on a Mac, you have

to press out five and six for the square brackets.


So in that same way is equals to new end,

which is also you know in this primitive but


now I say new ends because I'm not creating

again, I'm not creating an end, I'm creating


an object, an end airy object. Okay. And you

can also see that it's an object, because


when I put it here, and I'll put down the

button, I see a number of methods that I can


call. And we are this is actually not a method,

this is an attribute, which I can directly


access. So if you remember, I think you I

said you should have your attributes private,


this is accessible, it's not private. So this

actually violates that rule. And yeah, so


this is also a very old construct, and shows

us one place where Java itself violates the


rules of good object oriented design, but
we just have to live with it anyway. So what
this does, and we will use it very soon as

it gives us the number of

like the the length of the array than the


like, in this case for, okay, if this is three

year, why intz dot length should return three.


And in a minute, you will see what we use

it for, let's remove the end. Because I want


to continue with a person's I want to feel

this error. And the way this is done, again,


we need to break it we need a lot of times

is I say zero here, oh, I said person, of


course this is wrong, we don't have a person,

we have only this one object, persons. And


the type is person airy. So it's not a person,

it's a person airy object. Okay, and here


we can say new capslock. person. What this

does is it creates a new person object in


memory, and puts a reference to this person,

which is like a remote control a way to access


the person into the array at position zero,

which is the first position. Let's copy and


paste that four times. Three, four. So position

one, position two, position three. Okay. If


I would say position four, what you don't

have, I would again, get an error, which we'll


talk about in detail when I introduce exceptions,

which is again, a new big topic. Oh, okay.


So, and when you have done that, what you

can also do is, you can do crazy stuff like


at position three, put the object that is

in the person's array, at position, whatever,


zero or one or whatever. Right, because whenever

you write on every ad position, as it contains


a person, it's exactly the same as if you

would say, person, my person equals to a new


person. So now I created a person. And this

object was assigned to this variable to this


reference variable. And can also do it like
this. So now, this variable can access that
object, as well as all there's title. Persons

at position three, can also access the same


object. So we have like two references to

like remote controls to this one object. Yeah,


and you can do also the opposite. You can

say, my person equals to I don't know something


Let's take two persons at position two, which

means the object that is at this position,


the reference to it will be assigned to the

reference variable, my person. So this, my


person object now

should still be here, if I'm not wrong, I


mean, this really gets confusing. So, I mean,

I'm just explaining this so that you get the


hang of it. But in reality, don't make it

too complex, because you see, the more complex


the more box packs you could introduce. Okay,

so I hope you get the hang of it. Um, one


more thing I might mention. Of course, no

one forces you to, to really define to set


an object at each position. Now, when I left

out position one, this position is empty.


So what does that mean? What we say is at

position one, there is now because knowledge


the word like for nothing. So there is nothing,

there is no reference. If we access it, we


get an exception, because Java will not know

what to do. Okay. So that much about now,


which we could also specifically do, by the

way, we could also now it, it's called, the


wrong button. Sorry. Yeah, so now you can

also write, so this is like, put nothing here.


Or, here, that would mean that the beginning,

you have the new person object at position


two, later on, you kind of throw the reference

away. And if no reference exists to an object


anymore. In Java, there is something called

a garbage collector, I will talk specifically


about the garbage collector very soon, in

a specific lesson only about the garbage collector.


So this one is smart, and we'll throw away

that object, we'll clean up the memory. For


us, this is really a cool feature of Java.

In other languages like c++, this doesn't


exist. And so you have to take care of cleaning

up the memory by yourself, which is really


not fun. So this is really one of the coolest

features of Java. But anyway, I guess I'm


going too far, let's make this more simple

again. Because what I actually want to do


is now I want to take the for loop, and combine

that with the arrays and introduce the for


each loop. But let's start easy, let's first

of all, go to the regular for loop, take that


put it here. And now we have let's remove

all that all we have is an object of person


array called persons. And we have this for

loop that may create for whatever in this


case persons. And so we will use that dynamically,

so because I will change while we go through


loop, we'll start with zero will be 123. So,

we can say persons at position I this is really


a cool thing now, because this means this

one line Let me clean this up. So we create


each time an object of type person and we

put it into the array dynamically add position


I. So this will on the fly fill the whole

array with persons. And what we can also do


is in a different loop but also just in the

same loop. We can access this object by saying


persons at position I and call some method

on it like hello world that we created in


an earlier lesson.

Um, okay, I think I have not introduced you


how to print something on the console. But

maybe I should not do this now, because I


guess I feel it gets confusing with all this
stuff with Aries, but would be handy now to
show you that this can print all the name

of something for each person. But maybe I


will do this in a later lesson. Okay, so just

believe me, if we would print that, we could


like print, hello, and then a person name

for each person. Okay, this is already nice,


but it gets nicer with a new loop for each

loop. And this is not so much different from


the regular for loop. It was introduced only

in Java five. And this works like that. person,


person, and then colon and then persons. So

what this does is it automatically under the


hood, it does everything that this for int

it does. And now we can also access person


dot HelloWorld. Of course, this requires because

now we are using it. So this requires that


this has already run? Um, let me think. Yeah,

so this is only for like reading it. I'm fulfilling


it. Now fulfilling it, I wouldn't use it.

Because you have to specifically say what


you want to do. Because if this is empty,

this would also be empty. Okay, so but we


can call person HelloWorld on it, and see

how much nicer This is really condensed. So


this is the for each loop. And the for each

loop is like besides areas, there's also other


constructs, other container types, which I'll

also soon introduce, like collections really


a cool topic, because they're even more powerful

than just arrays. And so this for each loop


also works with these collections, whatever

that is. And it does whatever is required.


And it also does it in a very smart way. So

it's really smart to use that for each loop,


not only because it's more condensed, but

also because it's a performance and proper


way of doing it. Because Java will assist

you in doing it. Okay, so I think this pretty


much wraps it Oh, no, there is I have I have
a not sorry. I didn't know Have I told you.
I think I promised and then I didn't do it.

Person start length. This attribute which


is not private, I think is public. Yes, should

be public. This gives us dynamically the four.


So I mean, here, we know that it's four. But

just imagine what can also be yours, you have


a method, which just gets a parameter. And

you don't know its size. So you couldn't say


four. And so this just dynamically takes the

lengths that you need. And as you see in this


loop, we don't even need it because this is

dynamically calculated by Java for you. Which


of course also that's the person that links

in the background. At least this is what I


assume. Okay, lesson 10. I would like to introduce

you to enums. enums and Java represent an


enum eration. So they enumerate something

they were introduced in Java five. Now, I


want to further extend my explanation about

arrays because there is one more cool thing


and it also makes it easier for us.

We can actually even on the fly out five,


aisle six, well this is autocompleted id he

already PR Since two equals two, and now I


do something new, I say curly brace, this

is alt eight and nine on my Mac, by the way,


and see, there is no red marking anymore.

This actually also works. So what does that


mean? This actually is a shortened form. And

this says there should be an array. And we


don't have to say, a specific size, because

the size is automatically calculated, because


the brackets are empty. This means empty size,

that would be the same as saying zero, which,


of course, doesn't make much sense. But just

technically, it's possible. So and we cannot


feel this array. So and we don't have to set

the size, this gets calculated automatically.


So I'm just copying. I can also put your mouth

if I want to, I can also create a new object.


My let's call it my personal Sorry, I can

also just to show you what's possible define


a variable of type person and then assign

now to it or talked about now, which is like


nothing and put it here. So this actually

is the same like that. And I mean, I want


you to also see this, what this does is it

does not or what is not is, it does not like


combine this array and that array. Instead,

it says what you have at position zero of


this array, which in our case, is this person

object. Take the reference to add and the


reference, copy it here, which means this

position as well as later on, persons, zero.


So later on, after we have defined the array,

if we say, person to zero, that will be exactly


the same as persons zero. Because they both

point to this object in memory. All this is


a bit complicated, I'm sorry, I hope you can

follow me. And I will do a specific tutorial


only on memory management and show you how

things look in the memory. For now, I just


hope you can follow if not, it's not so important.

I mean, we're talking here about areas and


what I want you to understand is like this

is an array and this is a way of defining


the array and the specifics about the memory

Don't worry, we can go in more detail later.


And you will you will understand this very

soon I'm sure let's do the same trick again


just with a different position. You can actually

even do it twice or any number of times can


take another one or it doesn't matter let's

put this or we can also remove them now put


it here. So yeah, you can do what and you

can also do it on the fly you can say new


person. Now there is no a little difference
which is this object that defined here.

It sits somewhere in the memory and might


error a person's to has a reference to it

outside of my array there is no one who has


a reference to it, which we can change after

we have defined it. We could also say I have


not to count 0123456 I hope I have counted

correctly if not imagined I had counted correctly.


Okay, so I said six. So at position six. We

cannot copy this reference and I can say my


let's call it secret person. Let's call it

just VIP. So my VIP, now I have a reference


to it outside of the airy. So I created it

dirty on the fly in this line together with


the definition of this array. And later on,

just for the sake of it, I assigned it a variable,


which we then also can use and work on it

like hello world, which you can also do is,


say, person two at position six dot HelloWorld.

So you can really work with the areas at specific


positions, just as if you had a variable,

it's exactly the same thing, even though it


looks a bit awkward. But yeah, you get used

to it. Okay, anyway, I think this is a very


handy short definition. Because see how much

shorter This is here we find just for persons


and area for persons. And this was actually

five lines. Now in just one line, we have


defined an area of six positions, and we have

filled it, and this is all in one line. And


I think it's still readable. I mean, readability

is the most important thing. So it's not about


making something short. It's okay to make

it short, if it keeps being readable, or if


it's even more readable. That is okay. Okay.

And I might also already introducing new stuff,


I might also introduce you to final final

is another variable modifier. We already talked


about public and private and static, not final,
something new final says are like locked in
this variable, I don't want to anyone to poke

around with that variable. So if I later after


saying final, say this, Java will say Oh,

no cannot assign a value to a final variable


person to. So this is like a protection. As

you see, I have to say final. So this is one


more keyword. And this is one key more keyword

to read. This is one more keyword to write.


And so I would only do it if it makes sense

for a reason. And if you have code that is


just like here, two lines. I mean, while doing

that, I would assume you know what you do,


and you wouldn't like put this to now if you

don't want to just one line later. Where this


does make sense is if you have something like

some constant values, some status values,


for example, you could have a process a program

that operates on some values. And then you


want to remember the state that your processes

in Okay, let me give you an example. So for


this, we will again define an array, but we

would do it in the class on the class level,


and we would not do it for the objects, but

for all objects of the class. I mean, and


this, of course, is static. So static, we

talked about this already means we have just


one of this type for all the objects and no

final. So static and final, they're really


close friends, they are used together very

often. And all that say string

because I want to have a string. But actually


I want to have a string array. And I said

we said the braces right after it so that


we see it's not a string. It's a string array

and I call it my state values equals and then


the curly braces again. And now I can say

like pending, processing and processed. I


could of course sorry, brackets missing. Add
many more. Just for now. I have a short example.
So this is what we could do. Something is

wrong here. Yes, comma. Okay. And this means


now, and I've also, oh, I did something and

didn't explain you why I did that. So far,


all the variables that we defined, we had

in lowercase letters here, use the uppercase


letters, and the underscore. This is also,

again, a best practice, because like, we would


use this static final, somewhere down here

in the code. And you see, now the definition


is gone, we don't see it anymore. And so that

a programmer working in here and knows what


you're working on here is static final. So

I don't want you to touch it, I just want


you to read it. There, therefore, we use the

capital letters, and we separate them with


the underscores so we don't use the camel

case. And then we could, again, of course,


iterate through these values.

For

so let's do the for each loop, say, stream,


nice date, or just stayed. And then the curly

braces again, we could say, if we're talking


about if state has a certain volume, will

actually we can't on a stream, say equals,


this is not going to work properly. Because

the equals is working on on on primitive values


like int, and it's comparing the value that

is directly in the variable. Oh, no, sorry,


I'm going really complicated. Um, I don't

know if I, if I'm making it too complicated.


But now that I already started, I might as

well continue what we have to say for if we


want to compare two strings is equals. And

so we can compare that to some other value.


So we can do it, state equals and then a string,

some other value. So this is some that equals


is a method that is directly given to us from
the string class that we haven't written,
but we're using it from Java. And the says,

compare this string to some other something,


blah, blah, blah. Okay, if they're both the

same, we could do something. And then we could


do this a number of times for each value.

So we had, as far as I remember, something


like pending.

And

processing. And, of course, uppercase and


lowercase make a difference here. And I think

it was processed, but I mean, this is just


an example. So it doesn't really matter that

much. So, and then we could do some some something,


colo method. And here we would call a second

method and the third method and so on. Okay,


but actually, this is a lot of code. So there

is a faster way of doing that. And this is


the switch statement that are also promised

to talk about. And second. This string here


is also not so nice, because you could change

it any time. You could say in here, state


equals to love. And, of course with just a

few lines. I'm sure no one would ever do that


or hope. But he mentioned we only have always

see a very short examples. We could have like


a very complicated code, hundreds, if not

1000s of lines and we could like call other


methods For what is two other classes, and

then if someone in some other class, like


changes your value, you might not notice.

And you don't want that. You want actually


to have the value final. But this with final

doesn't work, because final only protects


the variable. It does not protect the value

in here, which you can change any time. And


for this, we have the email. The enum allows

us to define an enumeration. Oh, okay, oh,


let me just remove that. Or we can keep it
for the time being. But let's jump over I
have prepared here class will actually it

will be our enum and it will not be a class.


Okay, so far have just said package. For less

than 10, I have set less than 10. And now,


like you know it with the class, the class

we would say public class, logging level,

and

races. But this time we're not doing a class,


we're doing something a bit smaller. And this

is the enum. And now this is obligatory, you


have to start with the status definition.

And it's not a string. So we don't need the


double codes that we would have for the string.

Now this is really a value and enumeration


value, which we define as our email. So we

like we like program our own type. And we


already program the allowed values pending,

had processing. I think we had processed.


Yeah, and then we end

here.

And now we have defined an email. And we can


use that. Let's go back to our test. Let's

say logging level logging level, or let's


call it

my

state equals to logging level pending. So


this is a lot looking like static. And this

is already how it came. Because now we can


use these static values, we can also iterate

over them. But we cannot change this. I mean,


we cannot. Of course we can change it. But

we can only change it to the allowed level


allowed statuses that we have defined beforehand.

We can set pending, processed and processing,


the order is different but still the same.

It can only have one of the three values.


We could not say here. something crazy, because
it's not a string, we can only use the values
that we have defined here. And this is really

helpful and makes also our code more readable.


Now we can again, iterate through this enum.

In this case, it's a bit more complicated


actually, because we have to call a method,

which is called values. This method will give


us something like an array of all the allowed

values in here, pending processing processed.


And then, of course, there's not a string

anymore. We say let me also remove that. And


then we can do the same. Now, it's okay to

say equals, see this works. Of course, it


does not make sense. I mean, a string will

never be equal to an enum, but it's perfectly


fine. You may compare any object to another

object. Of course it makes more sense to say


equals dot for example, pending and then here,

processing and prose So


let's put processing.

Here.

Let's put processed. Okay? Um, but this is


not so readable. And we don't need equals

here. This is so cool. Actually, for an enum,


we can do the comparison, just with the double

equals, again, this does work. Because yada


yada, yada. Java DOES MAGIC under the hood.

So for now, just believe me it's working.


Because this is not an object, this is a static

value. Okay. Let's just remove this. Okay.


Now, you see, I think it already got so much

more readable and shorter. That However, there's


still a shorter form, which is the switch

statement. However, we will not do this today.


We'll do this in the next tutorial, the switch

statement, because I think otherwise, it's


just too much for one tutorial. Now we talked

about arrays repeated the for each loop. Yeah,


and I introduced the enum, which has here
this values method. Actually, there's much
more an enum can do. Maybe I should show you

this one. We can also add these brackets here.


Let me do this for a moment. And now we can

put values in here. So what is this going


to be? I'm adding a constructor, which must

be private. Let me check if it may be default,


but I think not. Well, let's just try it seems

to be working so far, but I'm sure it may


not be public, yet. This is not working. So

default, visibility seems to be okay. Even


though I think it's a bit awkward. And now

see this. It says the end cannot be applied


to this constructor. Because so far the constructor

is empty. Because what happens is, this is


calling the constructor. So let's put in here,

and now it's working. So having the constructor


here, you might also see I was kind of lying

to you, of course this is an object. But it's


just that for specific reasons, I don't want

to go in detail, we can still do the comparison


with the double equals here. Okay, anyway,

so we have a constructor. And let's now assign


the eye to some other variable. Of course,

you see, this doesn't make sense, assigning


eye to eye and we have already had that. This

thought I know, of course, I have to define


it. And make let's make this private. So now

it's working. I don't like it, I want this


private, this is just what he would do. Okay.

And then I mean, this, this depends what this


means could be some code of some form. So

let's have a method that returns public code.


And this was returned. I. So this enormous,

really powerful, is allows us in dismissing


to have methods to return something. But it

has these static values that we can iterate


over and that we can only choose from. You

could also think of a traffic like light with


like red, yellow, and green. You can also
of course have more values here any number.

I'm actually you don't have to have the enum


in its own file. You could directly on the

fly define it in line in a class, I would


just not recommend you to do saw, I mean,

forever, you're all there is an exception


and find out these exceptions for yourself.

But in 99% of the cases, you would be better


off having it in your own class. So yeah,

there's much, much more actually that you


can do with an enum. But I think we already

this tutorials already a bit long. And I think


I want you to digest this for now. We can

further extend this anytime, of course. So


that's the name. With its constructor and

a public method returning the I, you can also


have more parameters in here like a string.

But if you're if one of them has it, and all


of them have to have it, and every parameter

appearing here has to appear in the constructor


string, some string or let's just say s. You

may use it but you don't have to use it. But


usually, of course, you would use it as equals

s. And then something.

Yeah. Okay.

So I think that's enough for now. And the


next tutorial, I'm pretty sure I'm going to

show you the switch statement. Because this


is really cool for using for iterating over

these enum values, then the code gets much


shorter. I am going to talk about the switch

statement, which is another conditional statement.


Very similar to the if statement. However,

first of all, let's recap what I showed you


in the last episode. Actually, in the last

one, I covered a lot of ground, I think, I


hope this wasn't too fast for you. So let's

shortly recap. First of all, I showed you


this new way of defining an array. So like

the traditional, let's call it, the traditional


one was this one, where you just said, person,

square brackets, persons equals to new person


have four chairs with the size of four. So

this can hold four elements starting at zero.


Well, this needs a lot of lines. And this

actually is the short form just with the curly


braces opening and closing. And with a comma

separated list, you can define an array. And


my recommendation is end with a comma at the

end, so that you can easily extend the array


at a later time. Also, I introduced a new

modifier for variables, a final modifier,


the final modifier kind of protects a variable

for us. So what it does is when in a later


line, I try to assign something new. Like

let's use this area on top here, this is not


going to work cannot assign a value to final

variable persons to also we can try to assign


now, which is like emptying the variable will

also not work. This is nice ish. However,


I personally prefer to not use it locally

in a method. But instead to use it for static


final variables that are used read only and

are defined at the top of the class usually


like this here. I hadn't said any modifier.

So this at the moment is default visibility.


Usually I would prefer, like having it private.

And if you need other classes accessing it,


I mean, this is supposed to be read only.

So it would be okayish have this public. However,


even better. If you really want to focus on

clean code like I do. You could provide a


public method returning the string array.

I don't know some name. Let's call it states.


And in here, first of all, let me finish this

we could copy this out Because with a copy


if someone else, because the final, what it
does protect is as I set the variable, what
it does not protect as the content. So it's

safer if return a copy of the array. And there's


actually a helping Claus, which provides of

Java, Java util, which provides some static


methods and really have a look, see, we are

going to use the copy. But there's also many,


many more methods like here for doing a binary

search and so on. This is really a big toolbox


of methods that you can use, play around with

them. And I might show some of them at a later


time. For now let's use the copy off. And

then we take the array. And we have to state


the size, which again, we take dynamically,

array dot length, yeah, we also talked about


this. But this is dynamically returning the

length of the array, which in this case is


three, because the array has three elements.

So this is really a nice way of

generating clean code and returning this array.


Also, I told you, it's all in capital letters

and using the underscore and not written in


camel case, because this symbolizes that is

a static final. So in short, you just talk


of a static final, because this is how you

write it. Okay. Let's go back to the bottom.


I'm sorry, so not much about the array. I

also very shortly talked about equals, because


I had to, because for two strings, like ABC.

And you if you want to compare them, you cannot


do so with the double equals. This is not

going to work, even if it's the same. Because


the problem is that this comparison does not

compare objects. And this is an object, instead,


it compares the reference variable. So equals

does work for int three, and then you can


say three equals I, because the three is actually

in here. But if you have a string, let's make


it null for now. In here is not the object
or now in here is the reference, which is
something you can think of something like

a number also will be saved in here. And when


you compare with the equals the two equal

signs, then you compare this variable, which


means you kind of compare if it's exactly

the same. So what will be true is if you would


say my string equal equal my string, but this

usually is not what you want to say. And so


when you compare two strings, you have to

say equals talking about equals usually in


one sentence, you should always also talk

about the hashCode method. This is already


a very advanced topic. So let me keep this

very short for now. It just that if you create


a new class, like I created the class person,

it's often a good idea all depends, but you


might want to implement the equals method

in your person object so that you can compare


two persons. But if you do, so, you also have

to implement the hashCode method. What the


hashCode method is and all the details I will

explain at a later time. Okay, so that much


about the string comparison. Oh, one more

thing. I made this now because I also wanted


to make a point. What I see very often is

people that would write equals like this,


my string dot equals and then a static value.

This is not so nice, because as you see this


Might be now. And then this throws an error.

And of course, we don't like arrows. So instead,


always put a value in the front, which will

never be now, like this string here. I mean,


this is ACB, as a roll down, it will never

be now. So ACB equals now, we'll just return


false. But now equals ACB will always throw

an error. Okay. So let's stop here. Then,


actually, the biggest part of the last lesson,

we talked about enums, which I introduced,


I created this enum here logging level, let's
go to the class. So public enum logging level,
I do find, actually, the name is a bit awkward.

Because it's not a logging level, I was thinking


of something like info, warning, and error.

But then I decided we haven't talked about


logging either. So I

instead took pending processing process. So


this would more be more like a status. But

I don't know, let's leave the name for now


is just a stupid example. So this is the IEM

that are introduced, which is a bit similar


to a class, but has some limitations, but

also has some features a class does not have.


So it allows us to define these static on,

let's call them labels that we can act upon


in our code. So we can say if something is

pending, to this or that, so it's not only


more readable, it's also more safe. enon was

introduced was Java five. And before that,


people would have taken numeric values, like

if something is equal to not to zero, or one.


But then already people started to calculate

these values, this really gets nasty and problematic.


And I'm not showing you this because I want

you to do it in the proper way. And that is


using an enum. So this is really a cool feature.

You can you don't have to also introduce a


constructor, if you want to have extra values

for each enum value. And you can provide methods


that would return these values, or do whatever

you want, which are also like to make the


code more readable, is I often provide I mean,

not always. Whenever your code and you design


your code, always think decisions through

don't make a decision just because this is


never smart. So if for whatever reason, then

the code you work on, for example, the pending


value, and you need to ask is it pending,

that it might be nice to add this method is


pending.

And then you can say return this, which is


the minimum and not only the minimum, but

the current value of the enum equals equals


pending. So if in the code, you have an enum

let's do this modern level, still I call it


stage or status equals logging level, not

take processing. And then I could say if stayed


Dodd is pending, which now would be false.

Some code would have to be executed. But what


I want you to know is only add such a method

if you really need it. So it would not be


wise to always by default, provide a method

for each of these values.

People usually get lazy and when they see


something is working, they tend to just overuse

stuff and they just like I might be I might


need this. So let's just ask Method just because

no, never do that. Never add a method just


because always think think it through, I mean,

code lives. And you can always change your


code later. And you always can add a method

later. So only edit when you need it. Let's


say no, we don't need it. So we will also

remove it. Okay, I think this pretty much


rounds it up. For enums. Actually, they allow

much more crazy stuff, like each value could


have their own method implementations. I hardly

ever use it. So let's not show this for now.


I think this is pretty much what you need,

usually. And now, let's finally actually go


to the topic of this lesson, which is the

switch statement. So I think I already a bit


introduced it. In the last lesson, I said,

we want to shorten this here. So the switch


statement is also a conditional statement.

And that's pretty much exactly the same, like


these ifs here, just in a shortened form.

Okay, I mean, don't think about the exact


meaning here. This is just pseudocode. To

explain you something. Okay, this time, I


will not use a for loop, I will directly operate

on this state here. And then we can instead


of saying if we can say switch, so we are

operating on that value here. And then, instead


of if we're saying case, so if it's the case

that the state has this or that volume, case


pending. So this is the same as saying, If

equals pending. If you just have one, then


if it's of course shorter. But the switch

statement is usually used when you iterate


through all or most of them, because you have

this extra of saying switch, but then the


more states you have, the easier or shorter

it will get processing case process. Now I


mentioned we will have 100 different ones.

Let's format this. Now what happens is, I


haven't put any method here, and I have not

put a break statement here. So actually, what


would happen here, now let's put the same

method call, I mean, I have not implemented


the method, just the method. Imagine this

was a method. So for all these three different


states, while there is a common reason, we

would call this method. If imagine we use


a switch statement within a private method,

you could also like return a value. So this


depends, the difference with a return is when

you return something from a method, of course,


you also leave the method, while I'm pointing

this out is because normally usually, what


you want is you want to do something and it

might not even return something like printing


something on the console. And you would call

one method. And in here, you would call a


second method or do a second something calculation

or so. And here a third one. Now it gets problematic


if you forget the break, because what then
happens is a fall through this will be cold,
as well as that will be cold. So this is really

a big source of bugs. Very, very dangerous.


So in this case, never forget the break. And

if sometimes you'll want to have them together


because you want all the three of them for

example or to to call a certain method it's


recommended to leave a comment false through

so that you tell the next program I know what


happens and I did this on purpose.

Okay.

So that much about follow through. And you


don't have to set all possible values. You

can also leave One out, if nothing is found,


in this case, we will just leave the switch

statement, and we'll just not do anything.


What you can also do is you always have the

possibility to adding a default, which will


be called if none of the other case statements

apply. And then people sometimes say, I don't


know, call default method. Well, he, I really

want to warn you. And of course, again, we


had fall through would have to say, break.

This is not so wise. The problem is, I mean,


code lives. And who stops the next colleague

from extending your enum adding, for example,


an error state here for some text, your colleague

would just do this would not know there is


this switch statement. And now, you implemented

the switch statement, you didn't think of


the error case. And the error case might need

a specific behavior. But now you would also


call this method for this new error flag.

So usually, we don't want that. So what I


recommend you for the default statement, either

you don't use it, or even better use it. But


here, you would throw an error. He say, I'm

not doing this now, because I haven't talked


about exceptions yet. We will do at a later
time. But this is the place where you would
have like an exceptional case. And the good

thing about this is when someone extends your


income, and someone forgets to extend also,

one or more switch statements, you will see


this, I mean, you might say Oh, but then my

program crashes. And this is so nasty. Well,


of course it is. But there is a rule in good

design. And this is called fail early, it's


always better to have a high severe back on

production even. And to have to fix this within


let's say, seconds or hours than to have a

high severe bug. And no one notices it. Because


if it would not throw an error, it might calculate

something in a wrong way. But a client might


notice this, let's say three months later,

and then the problem will be so so much bigger.


So when programming, sometimes you just have

to be brave. I also see people that try to


prevent arrows and like return something,

for example, return now. So this is actually


just, instead of accepting I have done something

wrong. And let's fix it. This is just like


putting the problem to the future and making

it bigger. So I want you to be brave and throw


exceptions and handle them then this is always

better. I mean, I'm not saying you should


program buggy code. Of course, we should try

and concentrate. But sometimes bad things


happen. And then it's always better to fail

early. And so you you notice the problem and


you can fix it. This is always better than

hidden bucks. Okay. I hope you got my point.

Okay,

so also here. Well, if you have an exception,


you don't need to break because an exception

always leaves the block. But what is important


to always have a break, or, like here, we

don't have to break, leave a comment for through


to tell the next programmer, I know what I'm

doing, I want this and Tommy about warnings.


One more thing. don't overuse switch. as well.

don't overuse the if statements, these conditional


statements, you'll see how much the code grows

also in combination with for loops and see


how many levels This adds to the code. You

have to understand this switch. And then there


is different case statements or default. And

then inside of the case statement, there might


be a method called and so on. So this really

complicates the code. Same as with the if


statement. You have to See what is the condition

for me to enter this blog, ha, then this method


is called, you might click to the method,

you might want to check here. So this all


makes it more complicated. And actually, this

is also like a, let's call it a relic from


the past. This is what we call procedural

code. Because it's like a procedure, it's


like really, this makes you thinking like

a machine, like a machine would switch a state.


What's a case this dude that case this do

that. But humans usually don't, they don't


think like this. And the cool thing about

object oriented programming is that the object


oriented programming is very close to how

humans think. And this allows you to like


talk to business guys. And this really makes

your code nice. And switch is not object oriented.


There are some cases, corner cases where you,

it might just be easy and fast to use it,


but don't over use it. Really, I mean, there

are people that would have maybe hundreds


of lines in here, this is just crazy, really

hard to read. This is also why I had here


method, this is not yet perfect, but still

better than just having huge switch statements.


There are techniques, for example, just shortly,
you could have an object representing the
pending state, and an object representing

the process state and so on. So they are at


once techniques of how to prevent a switch

statement. And it always depends, like, what's


better? for very small switch statements?

It might be okay. Just remember, they are


a bit like evil and should not be overused.

Okay, I hope I have added enough warnings


of switch. And if statements. This is also

one reason why I'm only introducing it now.


Because I really want you to become a object

oriented programmer. I will further continue


talking about the switch statement. So I told

you that it's used to iterate over the different


values of enums enums, which are also told

you were introduced with Java five, um, before


that, the switch statement also existed, but

you had to emulate enums. And the way this


was done was by using int values. Um, this

is not so optimal. And this is also why enums


were introduced, because they're more typesafe.

And I would also not recommend you to show


to us ins in the switch statement. I think

I already said that in the last episode. I


even didn't want to show you but now I realized

I think I should still show you. Because you


will see it sooner or later. And so that you

can understand code of others, I will show


you, but just try to avoid it. Um, okay, anyway,

with that warning, I'll show you. And now


let's give it some name. Um, I call it my

state.

And now I give it some number 42. I mean,


this is just an example. And could mean whatever.

And this is already your problem. 42. What


does it mean? Does it mean pending? Does it

mean processed? How do we know? Well, to make


it a bit better, they then introduce static
final values, which I'll do right now also.
So let's go to the top and on the class level.

Let's introduce now this is a method. Let's


do it here. Private static, final, let's call

it processed, processed. Forgot to give it


the type of the primitive type int and this

is the 42. And we could also have pending


so this is like a trick. But you see this

is also where a normal use case From. So this


is also why in enums, we usually use the capital

letters. Okay, because it's a constant value


that will not be changed. So now I will give

this the name of pending cross cutting, let's


call this processing and processed. Now, of

course, we need different values, that could


be a 40, then this could be a 41. And this

would be a 42. And now I can copy that, go


back down. And then I can say, my state oops,

equals pending. And pending now, I think it


was 41. And then I can now switch on the end.

And now this is funny before depending was


of the logging level. But Java is smart enough

to realize, now we're not iterating on the


enum anymore, but on the int and s, we also

have processed there, as we have named it,


it still works. Of course, I mean, just to

show you, this is just because we named the


variable the variable. So if we processing

is not used, called is something then of course,


we will have to use this something below here,

because now you see pending as red, because


cannot resolve symbol pending. Because we're

not on the interim anymore. We only int something,


the problem is that my status an end. So no

one guarantees us that only these three values


that we want to use are used. anyone at any

time could say my state equals to 300. And


then it will not be something it will not

be processed, it will end up in the default.


See. And this is also a reason why here you
should not have regular code, but throw an
exception instead. Which we'll talk about

very soon, I hope. Okay, so anyway, this is


what you can do with an int. And since since

Java seven, I mean, at the time I'm doing


this video we are, we have Java eight. So

when they introduce Java seven, you now can


also use strings on my string, give it a name,

called also my string. Okay, not used yet.


and copy it. And now we can also switch on

strings. Of course, something doesn't work


because it's not a string, it's an int. So

now, I can of course start to use. Well, for


example, the empty string or a blank string.

I can use, again, something in lowercase letters.


And of course, here also I can do a column

labels, which then of course, are private,


static, final string. And now I call it I

don't know. I haven't used pending because


here of change it to something.

And I will call this pending. But it could


also be any anything any string 42 Yeah, whatever.

So of course, using that label, I'm only using


one now I think you got the point on too far.

Okay, so now, that label I can also use pending


in here. Um, you might remember from the last

session I talked about the fall through, which


is you don't have a brief statement here.

So if it's this case statement will be the


same one as that statement, which will both

then call this method and then break is called,


which will leave the switch statement. So

the court will continue online 122. The default


is at the end. It could also by the way, be

anywhere else. For example at the top which


would not be also a full Through. So if it's

not pending or something, or pending is, I


don't even know anymore what we put there,

I think it was 42. So, in this case, all the


threes different cases would call a method,

which he or we could have some other method.


As always, I'm not going to implement the

method. And then we could say break so that


for the default, just this method would be

called. And then we would end up here, leaving


the statement and ending in Wait, where's,

see, if I put my cursor at the beginning of


the switch statement of the curly brace, I

don't really see it ends up here. Because


if you have a method, and this is also a reason

why you should keep your methods very short.


You see, the method seems to go until line

141. And this method now got so big, that


it's really hard to see where it starts and

where it ends. So yeah, I can't say it often


enough, keep your methods short, I would really

keep them at one to 10 lines at most. I'm,


I'm really happy. If I'm able to keep them

at one to three lines. Some say I'm really


on my might be too strict on that. But you

will very soon see the fruits of your methods


are, the easier it is to understand them.

And also, the easier it will be to reuse them.


Yeah. Okay. But now back to the topic of the

switch statement. So you can use it with strings.


As of Java seven, you can use it with enums,

like I showed you in the last episode, you


can use it with ins and any other number types.

So far, I've only showed you int. I'm actually


there are others. I'm not sure if I should

really talk about the others, because they're


hardly ever used. They've just the range of

the number ranges just a bit smaller. In 99%


of the cases you would use it because I mean,

it doesn't really matter these days. how large


the ranges. So it is always fine. I mean,

not but maybe I still show you. For example,


this could be a bite. But now this is already
not working anymore. Why is it because I have
changed it on the string. Let's fix that.

So the bite here. This is just smaller than


the end. For example, if you put 3000 here,

it says this is incompatible, because it's


an int because it's too small. Um, yeah, but

the three works. But I really don't want to


go further in details. If you're interested,

you can also read this on the internet. Because


all you really need encode in 99% of the cases

is the end. So okay, I think this pretty much


rounds up the switch statement.

So you can use it with a string and an int


Oh, there's one data type, which I might show

you. That's also interesting. And this is


a car. A car is a string of a length of one,

while it's not a string, but it's very similar.


So it uses these single quotes instead of

the double quotes. So if I'm using the double


quotes, it's automatically a string. And this

doesn't work anymore. Here it says incompatible


types required car found string with a single

quotes, it's a car. So it's a character of


length one one single character. Of course,

it could also be a or b. But it cannot be


longer than one character. Because then it's

not a character anymore. Too many characters


in character literal. Okay, so we can also

iterate over characters. This sometimes might


be interesting. if you for example, parsing

a string or what is parsing it's have a string


five string equals something. And now you

can take each single character, because a


string is actually a combination of several

characters. And then you can iterate over


each character. And then you can switch over

this. Um, yeah. This you might need at a later


time. So I've also introduced car now and

told you there are other number types. I would


like to introduce you to logging. Well, actually,
what is logging?

Hmm.

Well, first of all, let's tell you what my


idea is. I have prepared this little test

here. I have prepared a little class car service.


I wanted to process this string, BMW, or Beamer.

And in the class, this class so far is empty.


My idea is I want to be notified in some way,

like a print out on the console into a file,


that database or maybe even an email or something.

So I want to be notified in some way I want


to monitor if someone calls this method, so

that I, like later on, can go through all


the course and can see if something happened.

For example, if my system was hacked, I could


go through a file and see what time what happened.

And then yeah, analyze it. So that's the idea.


And the way this is done, is by logging. So

actually, logging for me this word was a bit


weird. So I looked it up. Wikipedia is your

friend. So let's do this. So logging is called


logging for a ship's logbook. A logbook? Is

this thing here, you know, of ancient times


when the captain in his cabin was making plans,

and was writing down at what time he was at


which place and what speed the ship was going

in that direction. So this is a logbook. So


this is already like monitoring the state

of the ship. And but still I was asking, why


is the logbook called logbook. While this

article here have a read just very fast going


through it says it. The term originally referred

to a book for recording readings from the


ship lock. So what is a chip lock, let's click

and ship block, also called common lock shaped


lock or just lock is a navigation tool for

marinas used to estimate the speed of a vessel


through water. Interesting, so there's also
an image. So this thing here is the shape
lock from the end of the ship. And here's

even a picture they were throwing out the


ship luck and in equal distances they were

not in this line in this long line and the


faster the boat goes the faster Of course,

this chip block is taken away. And by measuring


the time they could measure the speed and

this was done given by knots. So this is still


why speed of a ship is given in knots even

today. So here it says ship log and associated


kit, the real of lock line is clearly seen.

So it seems I don't know this, but I just


guess it that it's called lock, because this

really looks like a lock, like, like a three


strong because it's this huge block. So I

would guess that this is why it's called lock.


So, this is why the ship lock is called ship

lock. And this is why the act of doing like


writing something into the lock is called

logging. And as a programmer, you can think


of yourself of like the captain of the code.

And as such when you want to write on events


that happen while your program is running,

you are logging and this is what we are going


to do today. So how is logging done in 2015

and 15 Well, currently you would use SL for


J. This is a framework for logging. I mean,

of course, you could write your own logging.


But this is a lot of work to make it

work properly. And this has been done already


for you. You can just use this framework.

Well, actually, this is only for Sade, well,


FSH is a design pattern that we haven't talked

about. So two, we could say it like, allows


you to use here is how it's used. you import

the code, Ork SL for j logger and logger factory.


And then, within your code, you say logger,

logger, logger, factory, get logger. give


it the name of the class. And you can use
it with different implementation of logging.
Because for many, many years, the most prominent

logging framework was log for J. Well, this


has changed. At the moment, you should probably

better use lockback because it's a more powerful,


and it's author is I don't can't pronounce

it properly. But I try shakey Goku, and this


is the same guy that actually implemented

love for J. So he continued with lockback,


because he wanted to make logging even better.

So today, therefore, we use SL for j in combination


with lockback. Because using this sl for j

visade. will allow us at a later time, if


there is a new logging framework introduced

that is even better than lockback, we can


easily each switch to the new framework without

having to change the code. Because the code


doesn't use the code of lock bag. It uses

SL for J. So how is this done? Let's jump


into the code. Okay, so first of all, I told

you, I'm using Maven for the configuration


of the dependencies. So here I've configured

to use the dependency org. So for j, and lockback,


classic. This is actually the implementation

of SL for J. And this is the core code of


lockback. So you need these three dependencies

to get logging in your code. Okay. And then


you should also have in source main resources,

our file called lockback, dot XML. Here, you


can define different things. Well, first of

all, you can say, how should you lock where


should you lock, in my case, I say, with giving

this class console appender, that will result


that my code is locked to the console directly.

There are also other appenders, or other implementations


for logging. So we can also look to the file

to the database, to email. And if there's


something you want to have locked to that

doesn't exist. You can also implement your


own implementation, like I don't know, maybe

like logging into Twitter in some way, if


that makes sense to you. Okay, and this is

the pattern, how, when a message is written,


in this case, to the console, it should look

like so the patterns has, I mean, you have


to read the documentation for details, but

it's like, give me the time when this event


occurred, the threat the logging level, because

the logging level is like a mechanism. It's


like a grouping mechanism. You can have different

levels of logging. This is like a signal of


the severity of the problem. Because debug

is probably for debugging purposes, use that


sparsely.

Then there is a logging level info and error.


So error you would use if there is an error

in your code, info for general information,


and debug, just for you know, some debug information.

But this really should be used partly because


for debugging. You can also use a debugger,

like in your ID, or we haven't talked about


debuggers either. But yeah, just for now.

Now there are different levels. So, in your


code, you can then say, I want to lock this

on level debug. And here I have defined the


package name. And I say here, this, when I'm

when there's some logging of a class that


is of this package, then I want to log it,

if it's debug, I could to also put your error,


that would mean only if it's an error, log

it. Or I could put here info, that would mean


only login, if it's info. info, of course,

also, it would include arrows, because this


is like more. So debug includes all includes

debug, info and error, but error would only


log messages that are locked on level error.

So you see, this is really makes it more flexible.


And you can even have here different loggers
for different packages. So we could also copy
this and, like have here a different package

like Java course two, and so on. And we could


then have this on the one on debug and the

other one on error. So this is really flexible


and can be changed. And here, this is the

root level. So like, generally lock on info


level just for this package. Log on debug

level, this is what it means. Okay, this was


only very short. There's much more information,

of course, on the internet. But first of all,


maybe a week go to our test. And we add the

login details here into car service, I put


it. So first of all, I need to import a few.

Like we saw just before in the documentation


here you see my ID, he already helps me SL

for j because I said we want to import only


SL for j and SL for j by itselves. knows that

it should be used, I should use lockback because


it will find the dependency of log back classic.

This one here. So SL for j is really smart.


So we don't have to tell it. Okay, so we say

SL for j lager and we say import org SL for


j.no. Just one dot logger factory. Okay, a

factory, by the way, is another design pattern.


At a later time, I will also do probably a

course, only on design patterns. design patterns


are like best practices on how you should

program code. And when you know what a factory


is, you will directly know what this thing

he does. Okay, more about design patterns


at a later time. Anyway, this is what we have

to do. And now in our class, we would probably


say private final lager. Let's call it log,

because it's all log. And then we say logger


factory. Get logger. So what this factory

does like a factory. This is why it's called


a factory. It gives us a logger. And we don't

know how is it created on the fly is a longer


reused, this is a smart thing and does all
the necessary work for us. Now, we should
still give it the name of this class. Because

this will be used car service class. That


sorry, in our log back XML XML file which

is in source main resources. As I showed you,


I mean, here we have a package, but we can

even extend that and lock only for specific


classes.

So this is the test and this is the service.


Okay, so this is how you generally find a

logger. Now, in here, you can now use it log.


Well actually, it's not static. I might just

as well have this in lowercase log dot and


in former times, like With log for j, some

of you might know it, you would usually say


like this is debug enabled. If it's debug

enabled, only then log something, log dot


debug. And now I could say, processing, car

plus input. So the input given in our case,


BMW, this will create a string, and then this

will be concatenated. together. And all this


will be locked, if the debug level isn't able,

at the time when the code runs, which at the


moment, as far as I remember, it is. So we

can activate and deactivate this. The reason


why we need this line, I mean, we could also

do it without just like this. But this is


not so good. I mean, in case of a string,

it's not so bad. I mean, all that would happen


is this string, and that string would be put

together. But you mentioned the string could


be really of in almost infinitive lengths.

So Java in the background for you, this concatenation


might take a lot of time, especially if we

have some very big object here, that might


internally consists of other objects, and

so on. So this creation of a string, as stupid


as this might sound can take a lot of time.

And, of course, I mean, here, we just have


a very stupid small program with just one

debug line. But of course, you would log maybe


not on debug, but on info or something, or

error, maybe a lot of stuff in your application.


And like, you could think of 1000s users concurrently

calling this method. And then if this only


takes, like, I don't know, 200 milliseconds,

200 milliseconds might not seem a lot of time.


But if this is done 1000s of times, then this

can really consume a lot of performance of


your server or PC. And so we would only like

to concatenate the string, prepare the string


for logging, if this will actually be logged,

because if we say log info, but then the logging


framework finds out, well, this does not have

to be locked, it would have to throw away


all the strings that were concatenated. So

we had done this without any need. And so


this we would want to prevent. And this is

why in lock for j, you would do it like is


debug enable debug. Or you can also say is

info enabled is error enabled, and so on,


is info enabled. Now it's locked for j and

SL for j However, there's actually even a


smarter way. Because you see, this was three

lines of code. And this is you can put here,


these curly braces. And then you don't have

to say plus, but you say comma. So within


the framework, the framework decides, well,

the user in this case, this would be us wants


to log on debug, first of all check is debug

enabled for this class. And if so, only then


take this input converted to a string if it's

not a string already, and only then concatenate


this string with this string. So this is really

a smart thing now. Okay, so another enough


of talking. Let's try this out. Okay, let's

check. We have the input given from the process


method. And we want to say processing car,
and then in our test,

we put here BMW or Beemer. Okay, so let's


also recheck our configuration file, log back

XML. We said comarca spiele. java course,


level is debug and the root level is info.

So if we no log on debug, within this package,


and comarca spiele Java course this is the

package. This means we should log it. Okay,


let's run the test.

Okay, so something happened. Process finished


with exit code zero. And here you see

at this time, which is now on level debug


from this class from this package car service,

we wrote processing car column BMW. So this


was logged. Okay. Now, let's try to deactivate

it. Let's say we only want to log on error


level for this package. Let's execute it again.

Run. Process finished. On top, this is all


information from lockback. When it gets configured?

Well, you see there is no BMW locked. Okay,


let's change that. We could say the root level

is debug. And we could say or, let's have


this on, let's have this on debug. And now

let's change the package. For example, Java


course two. Well, we're not in Java course

too. But we are in the package called Marco


spiele Java course, which means we should

log on the root level, which is debug. So


I would expect the test to log again. Let's

try it run. And there you see it already.


debug, call marks will Java course card service,

processing car BMW. So this seems to be working.


Okay. And here, again, you see the pattern.

This is what's compared. Here, we have the


minus that we have set here, minus and then

the message, and then this n, I think this


is for new line, so that when there's the

next lowing a new line will be attached. Okay.


And this is the console appender. So this
is the console that we can see here, in our
ID, if you would run this from the console

with like, for example, a terminal here, you


would only see it within the terminal. Okay.

So let's maybe go back to the documentation,


and check this a bit more. Okay, so here,

you see, and you should really use read it.


Now, I'm just really fast going through it,

you can read it typical usage pattern for


this is pretty much what we did. And here

with the curly braces, we locked on debug.


Well, we could also change maybe, after reading

the documentation, let's also log on Arrow


and info that you see this also works. And

here, it's also explained what I showed you


binding with a logging framework at deployment

time. So it says here lockback Classic, you


need this. If you want lockback as the logging

framework, which we used. Yeah, so really


have a look here and read this. And here you

see the dependencies, this is what we did.


You can also here you see you can use it with

lock for J. But lockback, as I showed you


is like the successor for for j and there

is also documentation of lockback which should


also have a look, by the way again. So the

author is chechi Goku, and others. Yeah, so


see they they worked on these frameworks for

12 years. I mean, you wouldn't want to work


for 12 years and there are at least these

three guys. So this is a lot of work and brain


power that has gone in that logging framework,

which you can use just by configuring it in


your code. Okay. Yeah, and you see we have

also done it import org. So for j logger,


and logger factory, here they made it static

which is also fine.

And here they log on info level. Okay. And


here's the configuration file. This I have
also showed you Okay, and there are also other
appenders I think I have put them here. Let's

see, oh, there's also the explanation you


can do it with logger is debug enabled, like

I showed you, or you see better alternative


with the curly braces. Because this is I mean,

basically, it's the same thing. But this is


three lines. And this like clutters your code

easily. And this is only one line. So it's


nicer. Because logging, I mean, it's important

that you want to focus on the domain, on the


business that you work in. And logging should

just not be in the way of your business. The


business is important thing. And logging is

important. Yes. But it's like not as important


as the business. So really have a look and

go through all the documentation. It really


explains this really nicely. Okay. So now,

I promised you, and then we should finish


already. We can also log on different levels,

like you can see error. Well, as, as far as


I remember, we're still on debug level. And

error is included within debug, because debug


is the finest logging level. So this should

also look just here, I would expect to see


not debug but error. So that we know, well,

we would use this in case an error occurred.


So that we can differentiate how important

some logging event is. Now you see an error.


So we would write, oh, some error occurred?

Well, in our case, this is not an error. So


we should also not log in on error. What else

can we use? Let's see, we should also able


to log this on worn for a warning. So you

would use a warning for something very close


to an error. But where no one has to manually

interfere, then you could use one logging


level. And info you would use for example,

when your server starts when your program


starts up, just so that the user of the program
knows everything is fine. And like here, this
is an info level. So we are informed lockback

is just starting up. Okay. And here you see


now we have one level processing car BMW.

So now that we're using one level, let's put


the root level to error. And now the package

that we're not using as well as the root level


are both on error. And it's printed to standard

out, which is this appender the console appender


which is this console here. Okay, and now,

I would not expect to see any logging. And


you see, just the info from doc back at the

logging is gone. Which again, we can change.


If we say here worn or let's change this back.

Here also we can say worn. So now we should


see the one locked again. Yeah, there it is.

Okay, well, as I Oh, I think I promised you


to show you the appenders and I have not.

So let's finally go back to Firefox. And see


I had it somewhere here found? employee No,

this is not yet. But it's somewhere appenders.


There, this is easy. Chapter four appenders

is really a good read. So I'm really fast


going over it. So outputstream appender, console.

appender. This one we used. File append Not


this one is of course very important to write

into a file and go through it read it. So


there you can set the encoding and all these

parameters. And there are some really cool


appenders like rolling file appender Well,

that means that new files are created when


like the file is has a certain size or like

for every day we could have a new file. This


is important for servers because otherwise

if we're always writing into the same file,


this very soon can reach

tons of gigabytes. Yeah. And therefore on


production for a server you very often use

a rolling file appender so that thing is really


important. Somewhere there should also be

ODP appender that is supposed to To log into


a database directly, really cool thing. And

this is really very easy to be configured.


Where is it, it was down somewhere. Somewhere,

somewhere somewhere, maybe I've already missed


it, there is an SMTP appender, I would assume

from the name that is used for logging, sending


an email when there is a lock event. And somewhere,

that was also the DB appender. I know it is


SMTP appender, blah, blah, blah, blah, ebf.

There it is. So this allows you to directly


write into a database, and you see all these

databases are supported. So this is really


great stuff, and so on, I mean, this page

still goes on. So there are really a lot of


appenders out of the box that you can use.

And as I said, you can always extend it and


write your own appender, which allows you

to lock to any other source. So that pretty


much rounds up logging. I would like to show

you the main method of Java. The main method,


as the name implies, is the method that is

used to start a program initially. However,


as this course, is done in test driven style,

or TDD In short, so far, we actually never


used it. Because we start programming by writing

a test. And so far, we use the test to execute


our code. Well, actually, as you might have

guessed, at some time, when you're done with


development, you would want to run the program.

And for this, you will need a class that has


a main method. So how does this main method

look? Well, it's not so different from any


other method. It is a public method, so that

it can be started from outside of the class.


It is a static method. Because we want to

run the method without having an instance


without having an object of car selector.
Because the class car selector in this case
here is only the like executer the, like the

frame that we use to start our program. And


therefore, I mean, we also only need, we don't

need further instances of this class. And


this is why the method is static has to be

static by definition. The method is void because


it doesn't return anything. And the name must

be made. So that it can be found by Java.


By the way, I might notice shortly, I always

say noticed by Java. Well, actually, what


I mean is noticed by the compiler, because

the compiler will compile the program to bring


it into an executable form. Well, compiler

is a big topic, there are huge books, if not


even libraries about compilers that you can

so you could even study compilers. So I tried


to prevent to keep you away from that topic.

But maybe, if I keep talking about Java, executing


something, I maybe should now say compiler,

and at a later time, I might do a dedicated


session on my bit of compiler details. So

that you will know more about compilers. So


anyway.

Okay, so back to the public static void Main


method. Now we add the brackets, but actually,

they have to contain something, because when


we start our main method, we want to be able

to give it arguments that the program might


need to run and this is obligatory. So these

are arguments that come as input as strings,


but as there can be a number of strings. This

is an area here. So square brackets, and all


the name of the string array. You can use

any name, people usually would set here arcs.


This is what you would see in documentation

I usually prefer arguments, because this is


more readable. Okay. And then of course, as

always, for our method, you would have the


curly braces, the opening and the closing
curly brace. Um, yeah. And that's already
it for the main method. Now, let's leave it

empty for a moment. And now when you compile


this class here, on the console using a terminal,

you can execute this Java class. And it will


then call this main method automatically.

So this is the place where you like set up


your whole program. In the last episode, I

created a car service. So we can use this


in here, car service car service. But I mean,

technically, it also works to run just the


empty main method, it will just not do anything.

So let me directly say new car service, no


title car service.

Okay.

And then you can call the method, car service


dot process. Yeah, remember, and this requires

an input. By the way, just to show you what


is possible in Java. You can also do all this

on the fly, you can say new car service thought


process, the only difference is that, you

will then just call the method, and you will


not have any variable to access the core service.

If you don't need it, that might be fine.


Well, the only thing missing now is a string.

And I mean, we could use any string here,


like PVC. But I mean, to make it a bit more

interesting, we could no, take the string


array. And as as this as this is an array.

Of course, we need a for each loop, which


are also introduced already. So let's say

string argument for one, colon arguments.


So this is iterating through our array, that

will be given to us. When the program runs


at runtime, opening curly brace again, closing

curly brace.

Okay.

That was formatting it. Okay, and now I can


take that argument. And so dynamically call

the process method, dynamically creating an


object. While this is always creating a new

object. So I mean, I wanted to show you that


this is possible. But of course, it would

probably be smarter to just create one object


and then put a reference on this object. So

this would be from the performance perspective,


probably faster. But it's really hard to talk

about performance. Because the compiler these


days is really smart. It might, it often recognizes

stuff. And when before a while it compiles


it can optimize your code. So talking about

performance is a topic by itself. And you


would usually test for performance just by

saying this will be fast or slow. You can


hardly do but again, performance. Yeah, I

could also do a course only on performance


really a big topic. Um, yeah. So now I created

an instance of car service. And in the main


method, I have this for each loop. And then

for each argument that is given to our main


method when the program is run, we call the

car service. Now let's execute this. Because


now we can run this without actually a test.

Well, I mean, in this episode, I want to show


you the main method. But I mean, what I said

still holds true, you should always start


programming with writing a test. But anyway,

see, now I have a run car, see, like the domain.


And I can execute the main method directly.

Here. This shows me the console directly in


my ID. Well, it seems like there's nothing

printed. This could either be because in the


class, remember, we had the logging, the logging

could be deactivated, but so far, I remember


it's still active. It should log on worn at

the moment. Well, the reason this doesn't


work. Anything is a different reason. And
the reason is, well, we didn't give our program
any arguments. So I mean, this is running,

this is not throwing any exceptions. By the


way, we will talk about exceptions very soon.

But it's empty. So the for loop will actually


not be executed at all.

When the program is run, so we will directly


jump to line nine or 10, just after it so

the program will directly exit. But we can


change this easily using our ID, I can click

on Run, and I say Edit configurations. And


here, I can configure how my main class see

this also contains always the full package


name. So how this is run, I can give it some

program arguments. So on the console, that


would be car selector, and then whitespace,

and then the program arguments. So let me


put here a few car names. BMW, or shi. C,

Mercedes. Yeah. And then Okay. And then let


me run the main method again. And now you

see, we have three warning loggings processing


car BMW processing card pushy, and processing

commerce. seeders. Yeah. So that's the main


method.

Um,

one more thing just really slightly mentioned.


What is also possible and not many people

know is you can do this. Now what does that


mean? And see, all the code is still working.

This thing with the three dots here is called


a foul arcs. Like a variable argument parameter,

which means when this is defined like this,


the code, the method that would call our main

method, while in this case, it's directly


started by the virtual machine itself. This

would have the ability to directly put in


strings that will be converted automatically

by the compiler to an array. So this is very


close to an array, but it's like just more
convenient for whoever calls that method.

Just so that you have seen this would also


be possible. The question is, does it make

sense because, well, Normally, you would not


call the main method directly.

So if you don't call the main method directly,


it doesn't make a difference. But of course,

you can write a test and you can call the


method directly. And in this case, it would

make a difference because you could directly


call the method which just one string? Yeah,

but let me talk about Fox arguments at a later


time. Okay, so let's re add. Let's make this

an array again.

Okay.

So now, string array arguments. Okay. So that


much about the main method, now, maybe a bit

of background knowledge for you. So I don't


know if my Java course is actually the first

Java course you ever listened to? I guess


in most cases, you would probably already

have heard another course or read the book


about Java. And in this case, you might not

directly understand why didn't talk about


the main methods so far. I mean, this is Episode

14 already. So let me give you the reason


for this. Because I really decided to do so

specifically. Because this is really a main


a main decision for me. Okay, so the reason

is, first of all, I think, in the very first


lesson, when you have never heard about Java,

and its keywords, it's hard to directly be


confronted with public static, void. This

is just the name of the method would be okay,


but public static void, and then even an array.

All all this stuff for a very first lesson


in Java is a bit much I think. Now in our

episode 14, you should by now know what public


means What static means what what means. And
we have also talked about arrays. So I hope
that by now, you can easily follow my explanations,

and you understand what all this means. Okay?


And then second, also, this is a static method.

And I told you, I think various times, Java


is an object oriented language, where you

usually focus on creating objects, but static,


this method is not object oriented. There's

just one version of this method. I mean, of


course, it might make sense. But, yeah, as

you should try to avoid static, wherever possible,


I think showing you a static method in the

very first Java lesson might lead you to the


wrong conclusions. Yeah. And then also, next

reason is, um, even though, I mean, the main


method is, on the one hand, very important,

because you use it to actually execute your


program to actually get your program running.

For any program at hand, you would have only


one main method. And usually programs would

consists of hundreds, if not 1000s, of classes.


And just one main method. And last but not

least, I mean, this counts for Java, se. But


if you like program a server application,

what you usually do is you don't re implement


all the server code. But you would like use,

for example, an open source server implemented


in Java, for example, Tomcat, and such a server,

I mean, has already been implemented for you.


And so you use that as like an infrastructure,

even though it's software. And so the Java


code you write will run within that Java software

infrastructure. And therefore, when you program


code for server, you usually don't write even

a main method at all. So, for example, in


my case, I mean, I have programmed in Java

for pretty much 14 years now. But I have maybe,


I don't know, 10 times 20 times, well, definitely

less than 100 times I have programmed a main


method, while I have programmed really 1000s

of classes, I'm sure. So the main method is


not so important. And, yeah, so we started

with writing a test anyway. So you are also


able to run your code, at least for testing

without the main method. Of course, I mean,


the tests. For example, let's look at this

one. This one is based on the framework j


unit. And j unit by itself is a Java program.

So j unit does have a main method. Of course


it does. But you don't see it. All you see

is the test methods that we write. And his


test method, they like plug into the whole

j unit mechanism, bet so we don't have to


write the main method. I mean, this is why

just using a framework, like j unit is so


handy, because it saves us from writing our

own main method. Yeah, and I promise you,


you can actually even execute even the main

method as if it was a regular method. Now


here you see I have prepared that he is an

array of string arguments, BMW and Porsche.


So this static method is called with the given

arguments as execute the test. And yeah, you


see, this works just as well processing car

BMW processing car pushy.

And,

as one last thing, maybe you'll see I could


change the signature of the method. Like I

could say the method returns some end. In


this case, just as an example 42 I could even

not make it static anymore. I can change it


in any way. This is okay as it's a Java method,

it just will not be recognized as a regular


main method. So this will will not allow us

to execute it as a Java program, but our test


can still execute it as it was before. I mean,

now this is returning something. So we don't


use the return value, but we could in return
use equals to Yeah. So you see, it's really,
we're calling the main method returning something.

And we can still call it from the test. But


if we want this to be really a main method

that will allow us to start a program, then


the signature must look like this. Okay, so

I think that's pretty much all I can tell


you about the main method, I'm really happy

that we were finally able to have a look at


the main methods. So now, with the 14 episodes

that I've done so far, I think this course


now really has gone quite far, by now you

should really know quite a lot about Java,


and should be able to write your own programs

by now, I will, of course, add a few more


things. But By now, you should really be able

to write your own small programs. I would


like to talk about Exception Handling in Java.

So first of all, let's have a look at some


theory, and some background information about

exception handling. And then later on, we


will as always, directly jump into my ID.

And I'll show you how to do Exception Handling


in practice. Okay, so as you see, this is

the Wikipedia article about exception handling.


So first of all, let's have a short look at

the definition. So here this article says


exception handling is the process of responding

to the occurrence during computation of exceptions,


and animals or exceptional conditions requiring

special processing. Okay, let's stop here.


Let's digest that. So, um, I think what is

very important is two things. First of all,


it is about exceptional conditions. Because

in my opinion, this is something that many


programmers get wrong. I mean, an exception

is called an exception, because it should


handle exceptional conditions. So the question

really is what is an exceptional condition.


While in my opinion, an exceptional condition

is something that really, as the name implies,


only happens exceptionally which means only

really rarely, only in very specific situations.


And those situations are an animal's soul.

So for example, programming errors, you when


your program, you introduce the buck, you

forgot to like you have an array, and you


have one field that is empty. And I talked

about that means it has a field that is set


to now. And then when you try to access this

field, that, for example, can throw a so called


null pointer exception. Well, that would be

really an exceptional case, which you wouldn't


have guessed it would happen. And yeah, that

would be one reason for an exception. So exception


handling is really the, as it says here process

of responding to the occurrence of exceptions.


So something exceptional happens. And then

we need

a way to react on that to handle that. Some


special processing, which is not the normal

program flow. But the cool thing about Yeah,


this also sent here, often changing the normal

flow of program execution. because ideally,


we want like a central place that handles

the exceptions. And so we want to leave the


normal program flow and we want to just specifically

take care of this exceptional case. Okay.


And here continues, it is provided by specialized

programming languages, which gives us a hint,


it is not provided by all programming languages.

Well, let's have a look at the history which


will tell us. Yeah, software Exception Handling

developed in Lisp in the 1960s and 1970s.


Well, I think the first programming language

was invented by Conrad Sousa in, like 1943,


or something. So you see, it took a while

until they finally came up with the idea of


exception handling, that something like this

is really necessary. And, well, maybe a bit


more about the history and Java, because again,

with Java, there was some something new introduced,


and that is checked exceptions. Before all

exceptions were unchecked, which means any


line of code can throw any kind of exception.

And there is no mechanism that forces you


to handle it, if you don't handle it. That,

for example, causes the program to stop. And


well, therefore, as soon as exceptions were

like introduced, many times nasty things happened.


And so when they invented Java in like 1995,

or something, they thought, well, maybe we


should do this a bit better. And well, first

of all, let's have a look. Check the exceptions


here. The designers of Java device checked

exceptions, which are a special set of exceptions

here.

Okay, and to make it short, so what's the


difference about checked exceptions, he is

also already an example and i o exception,


which happens when there is a problem with

an IO operation input output operation. The


difference with checked exceptions in Java

is they must be declared explicitly in the


method signature, or be handled. If you don't

do that, you will directly get a compile time


error, which means you're not able to even

compile your program. I looked at actually


up I think it's here it's quite interesting.

Like how it came with the checked exceptions.


The Java programming language introduces the

concept of checked exceptions, checked exceptions


must be handled in a method, or the method

must declare the exception in our throws clause.


Now it continues, I think here it's even more

interesting. According to Anvil wrath, who


was there at the beginning, the credit for
the Java exception scheme should mostly go
to Jim Waldo. And then they go on. And here

after some consideration, Java was retooled


to have checked exceptions, only those exceptions

for which there was no recovery, or reflect


application errors would be unchecked, and

the world was safe again. Well, so they thought.


Now, in the meantime, it's 2015, which just

like 20 years later, and it turns out, that


was not so smart. Because the problem is,

and this is also why stated at the beginning,


maybe we should go back to the very top. Exception

handling is the process of blah, blah, blah,


blah, blah, blah, blah, exceptional conditions.

And this is the important part. Because they


had the idea to have still unchecked exceptions

for something like programmer arrows for something


that is, as the name implies, exceptional,

and to have the checked exceptions for everything


else. But now I ask, why have checked exceptions

for these cases that can be handled? Why not?


If you if you can handle a specific situation,

why not that instead validating that situation?


And not at all throwing an exception? And

also, and now maybe we should already jump


into the ad because I guess it goes too far.

on too much theory. Let's directly jump into


the code. So yeah, so here you see An email

that I've written car stayed with a different


states driving, waiting and parking. I've

written this public static from method that


converts a string to a car state using a switch

statement. I told you, in a previous episode,


that since Java seven, it's possible to use

a switch inside air to use a string inside


a switch. And I want you not to do it. This

still applies. But in this case, I assume


that we are getting input from the console.

And input from the user coming from the console


cannot be an enum must be a string. So this

is all I mean, for every rule, there is an


exception. So this is an exception to the

rule, which is here, we do have a switch,


switching on a string. But now here, we have

the default case. And I also told you, I wouldn't,


I will only throw exceptions and the default

case, so that it cannot happen, that someone


adds a new state. And this new state would

then be handled by the default case without


anyone noticing, to have the fail early principle.

And so I told you to throw an exception, but


I didn't show you yet. While we can do this

now, and this is quite easy. You can just


say throw new exception, because an exception

in Java is just an A class. Like almost any


other class, while it has some specific

methods and stuff, but at least it's an it's


a class and we create, we can create objects

from it. Now, you know, you already see a


checked exception and action. And you see

how the compiler already wants me unhandled


exception. java. lang exception. So this is

also the package java. lang exception. And,


yeah, this is the number one checked exception.

Don't ask me why it's called exception. If


it's actually a checked exception, something

like a checked exception. I mean, the name


was not used within Java Lang. So you just

have to know that this exception is a checked


exception. And on top, the default, unchecked

exception is an is a runtime exception. This


sorry, also not my fault. This also you have

to know I mean, runtime makes sense, because


something that goes wrong at runtime. And

so you would normally use a runtime exception


for things where you don't know how to handle

them directly. And the idea was, as I said


before, to have checked exceptions, for cases
where you know how to deal with them. But
as I said, if you know how to deal with them,

why not dealing with them without throwing


an exception beforehand, using validation?

But anyway, let's continue. So how can we


fix that compile time error? One reason is,

at exception to method signature, let's use


our ID to help us and here it adds throws

exception. Now you see the compile time error


is gone. Nothing is read anymore, it seems

like we fixed the problem. So we told the


Java compiler, we know there is a checked

exception. We just don't care. The color should


take care of it. And now I have this car service

class here. And I made it to use the static


from method that I implemented. And you see

now this class has the problem. Okay, again,


let's do the same thing. Add exception to

method signature. Okay. And I guess you know,


where this leads to. Now we are the main method.

And again, we have the same problem. Well,


we can notate This is all the wrong stuff.

Seems like we're on the wrong line. But yeah,


I can no here appears add exception to method

signature. Okay. Well, sorry, I'm just lazy.


I could of course have written that myself.

But whenever you write something, you have


the chance of introducing a typo like this.

So whenever possible, I prefer to have my


ID he helped me and to have code written automatically

by the ID that can save From introducing bugs


with typos for example. Okay, so now this

will be, like fixed. But now the question


is, what did it help us, we have here throws

exception, we have here throws exception,


and we have here throws exception. So three

times we had to add this throws exception.


And only because Java tells us this is a checked

exception. But besides, we didn't handle it,


which means what will happen when I execute
the code, and the default case is chosen,
the exception will be thrown, it will be Bob,

it will bubble up to the top to the main method.


And as the main method doesn't handle it,

the program will stop. And we will see the


exception stack trace. Yeah, same thing we

could do, for example, with a runtime exception,


throw new runtime exception. Also in in both

cases, you can and you should add some meaningful


message that tells us why the exception happened.

So let's say on state, and concatenate that


with a given state. Oh, okay. So now, I can

still keep it. But I don't have to. It's not


obligatory anymore, because this is not a

checked exception anymore.

Same here, I can remove all these. And this.


So now I have exactly the same code. The only

differences I mean, I'm not handling the exception,


that my method signature doesn't get any longer.

Because he mentioned again, I'm always bringing


this example, you have a huge program of hundreds

of classes. And as soon as one method has


that throws exception, this is really contagious,

which means another method, sooner or later,


we'll use the method that says throws exception,

will then also have to say throws exception,


this method again will be used. And sooner

or later, you will have that throws exception


in each and every method. And then it doesn't

help us at all. It just makes the code more


wordy, let's say. And yeah, it's not really

meaningful. So anyway, let's first of all


provoke that exception that we see how such

as exception stacktrace looks like for this


to happen. I have to call the main method.

And I have to give it some some argument that


we don't know yet. Okay, let's go here run.

I think I have prepared something already.


Edit configuration. And yeah, flying parking,
driving, driving ABCD E, F, G, because also,
I wanted to show you, I mean, I've introduced

the main method only in the prior episode.


So here we have some valid states, as well

as some invalid states. Also in lowercase


letters, it will should be invalid. And as

we're iterating through the arguments and


a for each loop, we should see. Well, let's

just let's just do it. actually still have


to run it. And let's have a look what happens.

Okay, so you see, the exception happened.


I'm on state flying. So I would assume the

reason is that this happened for the very


first time the first argument was already

flying. So this is our program stopped. This


is the reason because it's not handled. Now,

we could also handle it to show you what's


the difference. Now the question is where

to handle such an exception? Well, always


as early as possible, like at the class that

can do something about the exception. In our


case, um, I just defined that. In the case

that I get a wrong argument from from when


the program is called as an argument. I want

this to be printed to the console, so that


the user knows which means I mean, I wanted

to be printed here, which means the first


place where I can handle this exception is

only here on the very top. And so there is


this new construct, I say, Troy, which is

like telling the compiler, I know something


evil can happen. And I just want to try it.

But now I can say catch. And I can catch this


runtime exception. Usually, I mean, I don't

like really short variable names, because


they're not readable. But in the case of an

exception, because an exception log is always


very, very short. The default is to call the

exception for with E, for exception. And I


think here, this exception is okay. Because

we don't want too much with the exception,


and the block will be so small that everyone

knows the E is for the exception. Okay, so


curly braces. And now we can do various things.

First of all, we could say e dot print stack


trace.

Well, this is actually exactly what we have


here. This is the stack trace, the stack,

you can think of as a list of all the methods


that were called in reverse order. So here

you see main process from can also jump there.


I mean, this is not, this doesn't hold true

anymore, because I've no edits code. But at


the time, we executed this code, and the exception

was thrown. This told us exactly in each class,


where the exception happened while he is still

true. And he also, but in my car selector,


I have adjusted the code, by the way about

this. The fact that I've adjusted the code,


also, when you sometimes have a stack trace,

and you need to analyze where it came from,


this is really often happening, that the code

that is running on production is older than


the code that you develop on, because of course

development continues. And then you can only


find out the exact place where the exception

happened, if you keep the exact same code


that you have running on production. Yeah,

but this only really, I don't want to go into


more details. Um, this would be a topic on

its own, again, about revision control. And


this is really a huge topic. But yeah, just

that, you know, the stack trace is really


helpful if and only if you have exactly the

same code that was implemented at the time


this code was running. I mean, that they're

both in sync. Okay, so print sectors here


wouldn't make sense, because in this case,
it's just the default anyway. But this can
be used. And it's often used to lock for example,

in I don't know, was it Episode 13? I think


I talked about logging. And so when you want

to log an exception, you can do it like this.


This is usually how you do it. Well, I haven't

got the log class here. And I don't want to


do log error or log one you will say and this

depends error only when there is something


that has to be done. For example, a database

that has to be restarted. In other cases,


probably one is also okay. Okay, message is

the string that I added into the constructor


of the exception

here.

And I have removed the stack trace, because


this is actually done inside of the log object,

which I want to add. Now. If you want to know


more about logging, have a look at my episode

13 where I explain logging in detail. Okay,


so logging is one thing we can do. But in

this case, I say I don't want to log it, I


want to directly printed on the console. I

think also in the episode about logging, I


want you not to do it always to prefer logging.

But in this case, let's assume we have just


a very small program only be used to run something

from the console. And in this case, it can


be okay to just say system error dot Clinton.

Which I also wanted to show you once print


ln For new line, and here, then I can say

dot get message. Or I can also say e dot print


stack trace, which doesn't make sense, because

we already have that. So to alter the behavior,


let's do this. Okay, let's run it again. Now,

you see something else. You see the program


hasn't stopped. But instead we see unknown

state flying Unknown, Unknown state driving


an unknown state abcdefg. Yeah, so all the
invalid states were printed out. Without we
don't even see the exception anymore. And

it's red, because I use system error Clinton,


I could also use out print on because this

is a special channel, only for errors. And


this is printing in general. See, now it's

white. But really, I still warn you don't


overuse system out or system error print on.

Because Yeah, you can't configure it like


you can configure logging. So in 99% of the

cases, using a logger is better. Anyway. So


let's have a look at the code now and think

is this really nice. Now, we have a for loop,


we have a try, we have a catch. Um, you see

a lot of different hierarchies and a lot of


different levels that we have to understand.

And this is something I really don't like,


this makes the code quite complicated. Okay,

so this is something you should try to prevent.


And, anyway, I can also, alternatively show

you, we could do exactly the same.

If this was throwing an exception. The only


difference is that if we're not handling it,

we have to add the signature

throws throws. So yeah. Maybe also, I should


now show you the alternative. If If we don't

want to add the method signature, the exception


signature, we can directly in here, say catch

and then handle it. And then I mean, handling


an exception does not necessarily always mean

you have to print it, I mean, printing, it


doesn't really solve the exception, it might

be even better to really have a method that


does something about the exception, and which

I call no handle the exception. The only problem


with that is, and I'm not implementing the

method now. And this is what I said before,


I'm the case that you're really able to do

something about the exception, which in this


case, I mean, what could we do, if the user

typed in something wrong? There's not much


we can do? Well, there is one thing, we could

for example, ask the user to type in to fix


the state he typed in. But this we couldn't

handle here. So again, if we want to, like


ask the user to do something about it, I would

instead validate

the state. So let's remove all that. Let's


for the time being I add the runtime exception,

but I will change it very soon, because now


instead, I want a validation at it. And this

can be done in the following way. I remove


all that trycatch instead, I say Valley date

argument and now I can implement that method.


Create method validate my ad he helps me again.

I'm

now well actually I want to say is valid with


a Boolean returned. Okay. Now, you see this

is also interesting, by the way about the


main method because this method is static.

Also, this Method automatically esthetic.


So because when this method is static, a static

method cannot call a method that is not static,


because an instance method can only be called

when there is an instance. But for the main


method, we won't create any instance, of course

selector. So for this reason this is static,


and it's private, because we don't need to

call it from outside, only the main method


will call it. Now how can we validate it?

Well, for example, we could use a method directly


provided to us from the enum class, and that

is value of this is not implemented by us.


But it's implemented, like automatically,

when they implemented when they invented the


enum and Java, this is one method that you

get for free. So this will directly try to


convert your string to an enum. So here I
can say car stayed. Cars date. So this actually
does exactly the same thing. Like our switch

did. So actually, we won't need it anymore.


Very soon. The difference to the method that

I implemented is or bill, I did it actually


also like this, when the conversion doesn't

work, this will throw a runtime exception,


I think, an in because they have different

types of runtime exceptions. And I think it


will be an illegal argument exception to tell

us the argument that you are giving that you


are giving to me, sorry, is invalid. But still,

it's a runtime exception. So and because this


will throw an exception, we have to add the

try catch block here, because we want to handle


this. Try catch. And then I say runtime exception

he or I hope I'm right. I can directly say


in valid on

invalid

human exemption, there it is. I think that


should be the one if not, we will see it because

the exception will not be caught. Okay, and


then here, we can just return false without

logging anything.

Now,

let's see, this is the wrong one, because


we can't catch an exception that is never

thrown. So invalid. Let's see what the lead


catch. Now this is not what I want. Maybe

it's an invalid state exception. Yeah, this


works. So see, this is also how you see this

value off may throw an invalid state exception


if the argument given is unknown, in case

of, for example, flying driving ABC. Okay.

And

to be honest,

um,
I think this is also not optimal, that we
only have this value off method, I think it

would be much, much nicer if the IEM base


class will directly provide is valid method

just returning true and false. But again,


seems like the inventors of Java doesn't didn't

listen to my opinion, crap, just making a


stupid joke.

So for this reason, we do have the exception,


but we are able to convert it. So because

we converting it directly. The exception doesn't


be doesn't pollute our whole system, let's

say like this. And we can now say here, return


true. Which we could also put at the end of

the method. This is exactly the same. Yeah.


So wherever you have it. So and this is also

the jump. I mean, imagine you could have lots


of other code like system out print owns and

just print something. So you could have many,


many more lines. That would do lots of stuff.

Let's just copy and paste that to show you


many more lines. We could even reassign car

state to something else. Let's just say now.


So what happens if This line of code doesn't

work out, because the argument is unknown,


for example, flying. When the code is executed,

the execution will jump from here, directly


into the catch. So this is leaving the normal

program flow, the normal program flow would


go from line 2122 2324 25, and so on. But

here we're jumping from line 21. To line 28.


Yeah, and this is helpful, because, for example,

imagine we have done this several times, for


examples here. And there, even maybe in sub

methods, then we have just one catch, that


would handle all these different places where

an invalid state exception could happen. That's


the idea of exception handling. Okay, just

to give you some more details, actually, I


don't even need that. So I would remove it.

We're only like, abusing that volume of method


to have the information. Is that valid or

not? Okay, and now I can react on that. I


can say if not valid, or I can say only, like,

only process it if it's valid. Yeah, maybe


let's do this. Because you saw already hold

the invalid states are printed. Now let's


do something else. Let's only process valid

arguments. The question, of course, is, does


that make sense? Now we wouldn't even realize

we have a problem in our code. So maybe we


should also say else. Print that we have problem.

system error dot print. ln M. invalid. argument


given? Or let's say ignoring, ignoring invalid

argument. So this, by the way, whenever you


log, I think I'm not repeating myself, because

I already talked about logging, but I can't


say it often enough. Always add as many arguments

as possible, so that whoever is responsible


for a problem knows why this happens. Otherwise,

yeah, it's really hard to understand why something


doesn't work out. Oh, no, we still have an

illegal argument exception. How is that? I


don't know. And this is interesting, because

we can now check. Like, this is what I told


you. It's in car state. There's, ah, we still

have the from it seems like we call it somewhere.


But no, I'm wrong. Because the session line

five, so this is not yet. Car state. Illegal


Aha, this is why See, I was wrong. This is

the invalid state exception. And what is actually


thrown by Java is the illegal argument exception.

So see, this is actually what happens most


that we see it. No, no constant flying. So

this is what Java gives us. It throws an exception.


And this now we will catch. Okay, let's retry.

See, this is how everyone introduces sparks.


And this is why we need tests. Today, I'm
not doing a test because I just want to show
you exceptions. But

yeah. We do need tests. Tests are very important.


Okay, now it works. See, ignoring invalid

argument flying ignoring new argument driving,


ignoring invalid argument abcdefg. And the

valid argument was processed. It just didn't


lock just didn't do anything. Which of course

we can change. Here we could say system out


print. ln, again, this thing here is evil.

Only use it in very rare situations. Yeah.


I can say bellet. Stayed. Car stayed. executed

again. Yeah, so you see three invalid states


and two valid states. Okay. So of course,

I mean, this was just an issue. Sample Normally,


you would have some method doing something

about the state

further,

do something with the car state. I mean, I'm


just making this up, because all I want to

explain you is exception handling, but I hope


you get the idea. So anyway, there's one more

thing. And then actually, I would like to,


like, shortly recap the important points of

exception handling. And the missing thing


now is, oh, by the way, let's remove the from,

because I showed you, we don't actually even


need this anymore. Okay. Because what you

can also do is finally, finally, this is very


important, not in our case, now, I'm just

making some something up. Finally, as the


name implies, this is done. Finally, at the

end, no matter even exception happened or


not, this block will always be called. And

this is important. When you have resources,


when you have input output operations, or

in short I O, which you have, if you communicate


with a database, if you read something from

a file from your hard disk, Yeah, something


like this. Because when you like read something,

especially from external systems, who can


tell you that the external system is actually

available, or like the hard disk could fail.


And so with i o operations, there's always

nasty stuff that can happen. But there's one


important thing, which is, for AI operations,

you need resources. And so you have to close


them. In any case, otherwise, you really could

have a problem with more and more resources


lost. So yeah, this is a big topic, I can't

explain it in like a second. But all I want


to tell you for now, this finally is very

important when you deal with IO operations


that might fail. And in this case, you can

close these resources and close resource for


now I'm just giving you my resource, this

stupid method. You can implement that yourself.


But also they are very cool. Helping utility

classes found on the internet, open source.


Like for example, I Oh, utils. Oh, it already

find something. But this is not the one I


mean, the one I know of is for example, I

think from Apache, and they will have something


like close thing silently or so close resource.

And then this will do all the nasty stuff


for you. Okay, I'm stopping here, what is

important is, and this I want to show you


just by printing something system out, print,

ln.

And I will throw the exception again. Which


means what you can also do is you don't even

have to catch it. This also works try and


darkly finally. Okay, formatted the code.

So, now with the invalid argument, our program


will be stopped, execution will be stopped.

But in any case, let's say I am still running.


And I can also show you this line will not

be printed after exception. Well, it might


be that this runs once if the first argument

is a valid one. Because with the string airy,


we never know for sure the order is not guaranteed.

But so that you see, I would whatever happens


for this vote for every time we call is valid.

This will always be printed. So let's see


what happens. Okay, oh, something's still

wrong. Not Found. Yeah, because we have removed


the from Yeah, sure. Um,

so let's for now remove that. We at the moment,


don't need it. And see, this is again, the

reason why we need tests.

I'm really doing some nasty hacking at the


moment. Okay, and you see, I'm still running

And then the exception comes. So this is what


happens when the exception happens. We didn't

catch it. So we see the stack trace instead.


But I'm still running is printed before that.

And this is the place where we can do some


cleanup operations, like closing resources.

But you could do anything in here, basically.


Same thing, if we catch it, catch is a runtime

exception, runtime exception, because it's


also a runtime exception. We should talk about

inheritance very soon. So that I can go in


more details why that is. So now what is wrong?

Yeah, we need the closing curly brace, and


one less of this. So now we can say, oh, maybe

I just have I will also show you print stack


trace. So this should actually do the same.

And now I will say, system out. print on.

Hello, again.

So you get an idea. In finally block.

Oh, okay.

Oh, no, something weird happened. And this


is for all the invalid states flying driving.

The stack trace was printed. And it's red.


Because, yeah, it's the print stack trace.
So it's printed on system error. Okay. And
you see, this is the illegal argument exception,

the first one, the second one, and so on.


And you see at the end, hello again. Which

comes after the whole stack trace. Yeah. And


you'll also see this line will not be printed

off to exception. Because it seems like I


mean, we had different arguments in here.

So for the valid ones, this line was printed.


And you see also, I mean, now I'm really having

a hard time knowing why this happened. So


again, I violated my own rule. I didn't add

the argument. So here I can say, our arguement.


I say valid argument. Yeah, because if it's

after the value of if this is printed, it


means the exception did not happen. Now, let's

call this again. And let me also remove the


stack trace for now to make it a bit more

readable for us. And let's run the main method


again. Okay, see now it's more readable. So

what do we have here? Hello again. So the


runtime exception happened. And, again, I

did not add the argument. In this case, I


can also say get message, which gets us the

message of the exception. I'm not sure if


our illegal argument exception has a message.

But we'll try this.

Yeah, see, this is the message Hello again.


And the message is no II non constant car

marktspiegel car stayed flying. So now you


see he can understand the problem so much

better. And after this we under finally block


then comes the valid argument parking. In

this case, we're also ending in the finally


block. Then comes a second valid argument.

Also in the finally block. Here again comes


in invalid state

thriving,
but we're also in the finally block. And the
last invalid state also in the final block.

So the finally block is always executed all


K. I think this pretty much rounds up everything

I wanted to tell you about Exception Handling


today. Now because this was quite a lot. Let's

go Shortly through the most important gotchas,


okay, so, in Java, there are runtime exceptions,

which are unchecked exceptions, unchecked


means they are not enforced by the compiler

to be handled, you can just throw them, and


also Java will throw them for you. For example,

a very famous or infamous exception is the


null pointer exception, you should never throw

that yourself, Java will throw that for you,


if you try to access something that is at

the moment now, just now for the exception


is probably the most famous exception, because

when it happens, you will not be very happy.


Okay? So unchecked exceptions, or runtime

exceptions. And they can happen at any line,


because any line can also be null. And they

don't have to be handled in code. If they're


not, then in the worst case, the program will

stop, like we saw before, because the exception


will bubble up all to the top. And if it's

not handled in here, the program will stop.


And it will by default, print the stack trace.

Then Java was the first and actually also


the last programming language that introduced

checked exceptions. Checked exceptions are


exceptions, that are enforced by the compiler,

that you do something about them, or you add


a throws with the exception name. In your

method signature. There are various checked


exceptions. One of the most famous ones is

probably the i o exception. That will be C,


it's in Java i o package. This one will be

thrown if you have any problems with i o operations,


which is again a topic on its own. Okay, um,
and I said Java was also the last programming
language that introduced checked exceptions.

So this really shows us indicates us that


checked exceptions were not so smart. Because

you see, all they help us in the end, is they


add noise to the method signature. And the

case that to use them for cases that you can


handle them. Well, I say, if you can handle

them, why not taking care of the problem beforehand,


for example, by using validation, validating

the case, the given argument, and then handling


that without actually even throwing an exception.

And then maybe last but not least, for every


rule, there's always an exception, we saw

that. I've removed it, unfortunately, yeah,


let me go back. We saw that with the switch

on the string were set in a prior episode.


Don't do that, while I did it here. And, um,

we also saw saw that

here,

where I use the value of method of enum, which


throws an exception, and I said, Well, we're

trying to validate it. So if we are validating


as we don't need the exception, it just that

we can't do anything about it how the method


was written by the inventors of Java, so we

just have to live with that sometimes an exception


is thrown where we will just validate it.

But what we can do is we can catch the exception


and then return true or false, for example,

so we can convert the exception into a valid


return value. Also, there is a hack. If you

have a library, like an old library that will


still throw a checked exception, like an IO

exception. What you can always do is you can


wrap we say wrap a checked exception into

our runtime exception. And this is like this.


Let's create more ioexception Let's create
an ioexception shortly. So see, you can also
just create them like any other object. And

now on that exception while it cannot be called


IE because we already have that I can now

say throw new runtime exception and okay.


Give it the IO exception. And this is why

we wrap it. Because we put this exception


into the constructor of runtime exception,

which means this is the wrapper, it wraps


around the other exception. And now our compiler

will be fine. Because we're not throwing an


IO exception anymore. We're throwing a runtime

exception. Well, this is a nasty hack. But


I think it's still better than having checked

exceptions all over your code. And yeah, I'm


going to talk about interfaces in Java. Well,

interfaces are probably the most powerful


feature of object oriented languages. Well,

before I continue, first of all, some organizational


stuff. So this is divided into three parts.

Part One, I will first of all, talk about


the definition, what does actually the word

interface mean? And tell you a bit about the


history. Like how were interfaces introduced

into Java. I'll make this part as short as


I can not to put you to sleep. And then second,

we'll jump into my ID, he will do a short


coding session, and I'll show you how to practically

use interfaces in Java. And then last but


not least, I'll do a short discussion about

the pros and cons of interfaces from a clean


coder perspective. Okay, so let's start to

jump into the topic interface. So what does


interface actually mean? So I've opened up

the dictionary page. And the definition is


an interface is the point of interconnection

between entities. And interfaces do not only


exist in programming, but also in all other

kinds of areas, for example, in chemistry


and physics, and there is defined as a thin
layer or boundary between different substances.
And I think this perfectly also applies to

interfaces in object oriented languages and


Java. Because it's really a very thin layer,

you will see, there is not much code needed


to define an interface. And it also forms

a boundary. When I say boundary, I think of


something like the Chinese wall, which was

a big protection from the hordes that were


invading from the north.

And this is also what an interface is, it


can protect a class from other classes, but

more of this later, okay. And then maybe we


should also look at the object oriented point

of view. So in object oriented programming,


it's a piece of code, defining a set of operations

that other code must implement.

So yes,

all this holds true for interfaces in Java.


But now, enough of the definition. Let's have

a look at the history. For this, I actually


had to do some research on the internet. Finally,

I found this page here from Oracle, where


Oracle says the concept of an interface in

the Java language was borrowed from the Objective


C concept of a protocol. Well, pretty much

everyone says are things that Java was actually


the first language introducing interfaces.

Well, actually, Oracle itself says that this


is not true. It was birthed from Objective

C. I find this quite interesting. Objective


C. I thought we should also have a look on

Objective C, then. So I found this page here


saying, Brad Cox and Tom love created the

Objective C programming language in the early


1980s. So actually much older than Java. Java,

was released as far as I know, in 1995. So


15 years later, in an effort to get people
to write cleaner, more modular and clearly
Separated code. Yeah, that sounds actually

quite good. Now, what is interesting is here,


this paragraph also says, into interfaces

were introduced to Java to enhance Java's


single inheritance model. So whatever single

inheritance model means

they didn't say

they had introduced the interfaces to get


more cleaner, more modular, and clearly separated

code. There is a different reason. Well, I


haven't told you what inheritance means yet.

And this for a reason. Because, um, well,


Java was released in 1995, said before, and

now we have 2015 20 years later, actually,


in the meantime, the especially the clean

code community does not believe so much in


inheritance anymore. Because, of course, inheritance

has a lot of advantages. But also many disadvantages


about this, I'll tell you, and one of the

next episodes when I'm going to talk about


inheritance in Java. But anyway, so when Java

was introduced, Java is the successor of c++


we could say. And c++ still had a model using

multiple inheritance. So multiple inheritance


is even more complicated than single inheritance.

And here they write. multiple inheritance


created too many problems for programmers,

as well as compiler writers, because it's


actually not so easy to implement multiple

inheritance in into a compiler. So it seems,


because they did not support multiple inheritance,

they added interfaces to Java s, like replacement


for multiple inheritance, to like, fix that

Java did not support multiple inheritance.


And this is quite funny. And let me say it

in different words, I would say, it seems


like the really powerful feature of interfaces

was introduced into Java by kind of accident,


because they said before, they didn't think

about cleaner, more modular, clearly separated


code, but mostly just to have a way of having

something similar to multiple inheritance.


Okay, let's stop here, and jump directly into

my ID. Cuz I felt you were already feet been


falling asleep. Um, so here, this is my car.

So it was test that I've used in earlier episodes.


Also, I've added this should demonstrate interfaces

method, as the name implies, just for demonstration


purposes, I'm still using the car service

that I've implemented, also in one of the


earlier episodes, and I've added a drive method

to it. So the idea is to have a service class.


And when I call the drive method, that this

should, like start the engines of several


cars, and make them drive. So for this, in

my car service, I have now a method drive.


It creates First of all, three different cars.

I mean, this is just an example you mentioned,


were hundreds of cars. And now I call the

drive method on each of these cars.

Okay, actually,

all these classes are in the same package.


This is why I don't have to import any class.

But imagine each class would be in a different


package. We would have to import each class

separately like BMW and Porsche GE and mercy


is and so on. So what we say here is actually

this car service at the moment is really Deeply


coupled to these car classes, this is something

that we don't want more about this later.


And also, you see, we need a lot of code to

make all the cars drive. And this is something


that we want to improve with using interfaces.

Now what, again, what is an interface? Well,


an interface is also like an abstract type

definition, what this type should be able


to do. In our case, we have an I mean, I'm
already saying it three different cars. And
all these cars can drive and you see it already,

I have three different drive methods. I mean,


the way they hold how they are driving might

be different because of course, a BMW has


a different engine than a pushy, and again,

a different engine than ms cedars. But they


have some certain specifics, like, for example,

they would all have four wheels, and they


can all drive which we can make something

like a contract off. So in this way, let us


introduce an interface and I've prepared something

here, car dot java. So far, we only have the


package declaration, we have to extend that.

So let's start. Let's start as if we would


write a class. So let's say public class car.

And then opening and closing curly brace,


and now public void drive.

Okay.

And then in here, we could do something. Well,


the problem is if we do it like this, this

is not going to work, because then all the


different types will have to drive the same

way. But this is not what we want. For example,


He in pushy, I have implemented already the

drive method. I mean, this is just a stupid


example. I still want you hardly ever to use

system out print line. But here for our example,


I just wanted to show you that each method

is implemented in a different way. Here it


says masseter striving there it says Porsche

driving, the BMW actually even has three different


methods. These ones we will actually use at

a later time. And it also has the drive method,


which says BMW driving. Okay.

So now,

maybe before,

I'm going to
continue with doing the interface, we could
also try to execute the code as it is. Let's

do this. Now, just so that you see the code


should be running by now already. So it says

BMW driving Porsche driving Mercedes driving.


So what I want to achieve is exactly the same

just using interfaces with less and more readable


code. By the way, exit code zero means everything

is fine. If there is a problem, an exception


thrown, it would be exit code one. Okay. So

back to what at the moment is still a class.


Now there is a very easy way to make this

an interface. And this is I say interface.


But now it seems there is still a problem.

It says interface methods cannot have a body,


or what is the body, the body is this part

here in blue. So the body is actually the


method implementation. method also has a method

signature. This on top here is called the


method signature, public void, and the name

of the method is drive. Okay. Sorry. So it


seems like it cannot have a body. How is that?

Well, I guess even makes sense. Because we


said we just want to have a definition, like

a contract. But we don't want to actually


implement it. The implementation will be done

by the specific implementations by BMW by


Porsche and by my seniors. And we have already

done the implementations. So let me remove


the body. Now there's still something wrong

and you see it. Here it even says it It wants


now, the semi column because the semicolon

now says, I'm finished. I'm done. This is


all I want to say. So now we have an abstract

definition of a method that other classes


may implement. And when they implement the

interface car, we can also say they play the


role of a car. Because actually a class can

implement more than one interface. A class


can implement any number of interfaces. And

remember, before I spoke about multiple inheritance,


well, multiple is, this is why it's similar,

because it also allows to have,

like,

multiple implementations in a way, but more


of this later. So a class can also implement

multiple interfaces. Okay. And when I click


here, you also see modifier public is redundant.

Why is it redundant? because by definition,


all methods that we define in an interface

must be public, they are always public. So


even if I remove it, well, if you still remember,

the episode I did on the visibility modifiers,


you might now think, Well, now that there

is no modifier defined, it must be of default,


or package level visibility, no, it is still

a public visibility, because it always a method


is always have public visibility. Another

modifier that is implicitly here is abstract,


can put it abstract just means what we have

here, that the method is not implemented,


and that it just consists of the method signature,

and that the body is left away, and that we


have to semicolon here. So also, this is redundant,

we can and we should remove it. Always define


your methods without public and without abstract,

you should just know that implicitly, they're


there. Okay. And then there's one more thing

you can do in an interface. Um, but I warn


you not to do it. This is actually an anti

pattern. But still just to be complete. I


let me show you. And this is you can add public

static, final. So you can add constants, for


example, Max, Max speed. I don't know 320.

And however, you shouldn't do so. And when


you think about it, I guess you will easily

find out why. Because for example, the BMW


might only do a max speed of 240. Porsche
Yeah, maybe a Porsche can maybe do 320, but
maybe also even more than Mercedes, I don't

know. So this is actually not part of this


should not be part of the interface, because

this is an implementation detail. And such


an implementation detail should be hidden

within the class, or even better. In an email


about this, let me also shortly show you a

little page I found on the web. And this is


here it is on the page of sonar. Well, actually,

it's called sonar cube sonar cube is really


a very cool tool. It's actually one of my

favorite tools for static code quality analysis.


I'm pretty sure very soon, I'll do an episode

on sonar cube alone. For now, let me keep


this as short as possible, because we still

want to talk about interfaces. But in this


sonar cube, it's actually a rule that checks

that you don't use constants in an interface.


Here it says console should not be defined

in an interface. And there was also or there


is also very smart, cool guy, Joshua blah,

the author of Effective Java, which is, by


the way, also a must read, I have a link to

that book on my blog, on Marcus minus bo.com,


where you can directly buy it from MSN. So

if you have the time, you can also read all


this, but I think I already explained the

important parts. Here, we can also look at


it. So noncomplying code is to define the

variables directly in the interface. And you


see here they even didn't say public static

final because this is again, every variable


you define, is implicitly a constant. So you

don't even have to say public Static final.


But this is not good. Anyway, the much better

solution is to use an enum we have talked


about enums already. So I won't go in more

detail here. Another possibility, which I


would not recommend, you can also have something

called constant classes, which you make final.

And then in the class, you have the public


static final constants. This is possible,

but it's always better to have small enums.


Because usually what happens is in these constant

classes, they would grow. And they would grow


and have contain all kinds of different constants.

While this only contains the constants of


this status here. And also, I mean, talked

about this when I talked about enums is type


safe. Well, here, you could change any number.

Okay, so anyway, so now back to our code.


So, here, you already see it's redundant.

All this is redundant, and should be removed.


But this should also be removed. As I said

before, because it's an implementation detail,


this is not part of our contract. Because

the car should just define what needs to get


done, what behavior class implementing that

behavior has, like it should drive, but the


way how it's how it drives, if it drives fast

or slow. This is part of the class and not


part of the interface. This is really important

when you want to do clean coding. Okay. So


now let us implement, use the interface. So

now, when I say implements car, when you you


can now use BMW as a car. And when you do

so, BMW plays the role of being a car. And


as I said before, you can also implement several

interfaces, which we're going to do very soon.


But first of all, let me finish this quarshie

implements car. And Marie cetus implements


car. Well, the compiler was directly happy,

I hadn't got to do anything, or implements


car. Because the work I've done beforehand,

implementing the method will normally let


me know that this just to be faster in my

here, code example. You won't do it like this,


you define a class, you say it implements

an interface. And then you see I already have


a problem with the compiler, which tells me

I have to implement the abstract method, Dr.


Okay, and then you do this. And the compiler

is happy. It has to be exactly like defined


in the interface. You cannot, for example,

say int as a return value, because this is


not how it was defined in the interface. Okay,

now, let me also show you, oh, there's still


a problem with car. It seems there's the curly

brace missing, somehow. Okay, it seems like


I probably deleted too much. Okay, see how

small is is well, actually, by the way, I'm


an interface should have at least one method.

While this is also not true, there are even


something called market interfaces that don't

even contain a single method. This is a specialty,


which I'm not going to go in detail now. But

usually they would have at most, at least


one method, and maybe even many more methods.

But again, I want to warn you, I see often


interfaces with 10s of hundreds of methods.

And sometimes it's just too much. It's better


to have many, many interfaces and to have

your classes implement several interfaces


at once, so that you can decide what role

your class is going to play. And lo let's


implement more interfaces in here. I've already

prepared again, adding these methods, because


I have also what interfaces one interface

is the lockable interface, which I defined.


The idea for such an interface is

for example, you want to do logging, you want


to do you want to lock several different objects,

could have cars, persons whatsoever, everything


can be lockable. And I defined that in order

to be likable. Such a class must implement


a method called message, which I then later
in my learning framework can call. Because
I know that whenever I have a class that implements

luggable, it will then have a message method


that I can call and it returns me a string

that should be used for logging purposes.


Then also, well took me a while to come up

with examples, because what other roles could


a car play, I said, it could also be a property.

And such a property would have an owner, for


example, the owner of the BMW I made myself

I mean, I want to have a BMW, how cool is


that. And one more interface, I said, I just

came up with the idea, we could also have


a role of being an asset, an asset would have

a value. And so my BMW also has a value. So


I cannot easily say, implements luggable.

Think this one I have not implemented yet.


And I still have to do No, not twice implement

car, comma luggable, comma, asset, comma property,


the order doesn't matter. But now you see,

I've implemented already the value method


and the owner method, the message method,

I still have to implement. And as I said before,


the order is not controlled, so I can put

it in any order message.

And, yeah,

here, we just return something

on the car.

Okay, now, I have a class implementing 1234


different interfaces. OK, now let's use my

classes implementing the interfaces. For this,


we go back into my car service, what I can

already do is now my variable my reference


variable is at the moment of type BMW, the

class so my BMW can do everything that a BMW


can do, which at the moment is drive message

owner value, these are methods that we inherit,


see, there is inheritance already, from the
object class more of this very soon, but these
were the classes that we have directly implemented

in the BMW class, so I can use all of them.


Or let me show you a message, we can use them.

Now, what I can also do is, now that I've


implemented the car interface, I can say my

I create an object of type in W, but I put


a reference on it of type car. And now, this

will change the behavior. Now, I can just


call drive on it, because now my BMW just

plays the role of a car I can also say luggable


and then I will not be able to drive the car

because in the context of logging, I don't


care about driving all I care is about login

and for logging, I would need such a message


okay.

So,

now, let me make all these cars and this is


also something you should do I mean, the object

is the object, but the variable when you have


an interface, always try to like reference

with the with an interface to the object.


Because this way, you can more easily exchanged

your code like imagine the BMW would come


as an argument to the method. Now, at the

moment we have these three cars, imagine at


a later time someone in when so very cool

Marquess car, then when the when the method


is operating on the car interface type, this

method will work even with new classes introduced


without even knowing them at the time, we

wrote our car service. So whenever possible,


use the interface type. Okay. So now, I want

to have a for each loop. And for this, let


me put All these cars into a car array. We've

also already talked about array called as


cars equals two. And now the short definition

I can even do it on the fly. Make it even


more shorter. You W, you're pushy.
You're more serious.

Okay.

Hello, on this array, I can now easily iterate.


And I can now say car dot drive. And, or as

said before, each car will drive differently.


But this will be handled by the object. Now

our car service does not know any specific


implementation anymore. This is the coupling,

decoupling the code is not coupled so much


to the specific implementations, my car service,

all that it uses, all that it knows is now


the car interface. Okay, and with these few

lines, I iterate over all the cars and I drive


them. Let's execute this code to and have

a look if it works. Yeah, see, this is exactly


the same as before, my BMW is driving or a

Porsche he is driving and marmet cetus is


driving. Now let's also have a look at the

car reference. As you see, we can only execute


drive on it. That is defined by the car interface.

And we do have a BMW as the first element


in our area. But this headline 10, we don't

know. All we know is we have an area of cars.


Okay, so we cannot call any BMW specific method.

In here. I can also not say BMW, because this


is not competitive compatible. We need a car.

And we don't need to be in w because this


array is of type car. Okay, so let me fix

that.

Okay.

So

I think this pretty much wraps up my explanation


of interfaces in Java. A really cool feature.

And now let's have a discussion about the


pros and cons about the advantages and disadvantages

of interfaces in Java. Well, first of all,


let's start with the disadvantages. And actually,

I can tell you, there are not so many. Well,


you see, for every interface that are introduced,

I have to type down this code. And, of course,


this is here, not much, it could be of course,

much more. So, and each class that wants to


use an interface has to implement this interface.

So there is some added complexity. Also in


my car service, I'm using now the car interface.

And whenever you introduce complexity, this


complexity must be justified. So if it makes

sense, if it helps us with something, for


example, here, I'm not able to easily iterate

over all the cars. And you mentioned there


could be many, many, many, many more. But

my for loop would just be the same. So this


would be for example, a justification. But

my car service at the moment does not implement


an interface. Well actually, this is kind

of an exception to the rule. Most services


should implement an interface. Very often

this makes sense, because it's specifically


for testing so that you can exchange the concrete

implementation just here. In my example, it


does not make sense because I just want to

explain you interfaces and I want to have


it really short and neat and not too complicated.

And I know I will only have this one class


here for demonstration purposes. So why Would

I implement an interface here? So at the moment,


I don't see a reason to make my car service

implemented interface. Sometimes, of course,


there are corner cases, we're not sure. My

personal point of view there is, if I know


that for the next months, I'm not going to

need the interface. My probably leave it away.


Because code, I mean, it lives you are allowed,

you can change it, you can refactor your code.


So if at a later time you, it turns out you

need to interface then edit at a later time.


Just don't do arbitrary decisions. There are
people that like they love interfaces. And
for this reason, they do something I would

call interface readers, like an illness, blindly


adding an interface implementing an interface

always just because, and I think this is not


too smart. And then really, interfaces can

be a disadvantage, because they just make


everything more complex. But now, this is

already pretty much it. To the advantages,


so the advantages, I think a few ones are

already mentioned, while explaining the interface.


Probably one of the most important ones is

that it decouples your code, as I explained


before, like now, the car service only uses

the cotton Well, no, I was actually like,


sorry, of course, as it is implemented at

the moment, we still say new BMW new Porsche


new messages. So of course, at the moment,

it would still be coupled. But normally, of


course, he would also not do it like this,

what he would usually do is you forward an


array that is already filled, only then. Now,

our core service is not coupled to the specific


implementations. So it really allows to decouple

your code much better than without interfaces.


And this decoupling also helps with other

things, for example, team cooperation. Imagine


you have a big team of 10 2030 developers,

and you have a big project that you have to


work on for weeks or months.

And then you would probably form smaller sub


teams. And then each sub team would work on

a specific area. For example, one team in


our example here, could work on the car service,

while there would be another team implementing


different car types. Now the problem is, the

car service is then or might be dependent


on specific car implementations to test it.

And on the other hand, the team that implements


the different car types might need a car service
for testing, and for integrating their code
with the other code. So it's like, each team

is dependent on the other team. And so each


team blocks the other team. So nothing can

be finished. And interfaces can be a solution


to the problem. Because when you introduce

an interface here, for example, in this case


for the car service, then the team implementing

the different cars would just do a very stupid


dummy implementation, something similar like

I did here, where you don't have real code,


or just something where you see it's working.

And then the other team can independently


also work on their code. And also add dummy

implementations where needed. And only when


both are finished, they can be brought together.

So interfaces really help in team cooperation.


And then next advantage is interfaces really

include increase your flexibility, because


as you see, as I have changed it now we have

the cars array as a parameter to our drive


method. So actually at runtime, in this case,

in our test method, we have this drive method.


So now at runtime, I could have something

some condition if it's sunny, just making


this up. Then I want to drive in my Porsche.

And so I create a pushy here, so I would say


car car And then I would say if sunny car

equals to new Porsche else if it's not Sunny,


well, I hope I had so many cars, then I would

say I take the BMW instead. Because it's better


for rainy weather. Knew, of course, and now

I don't want to make an error, let me change


the method. And I don't implement sunny nose.

So I just say true here, just to have it simple.


So in this case, Now, of course, you wouldn't

be cold. And in my drive method to make this


work, make this a car to have it simple. And

I would call drive. So now at runtime, we


will decide what kind of car this is. So this

really adds a lot of power to our code.

So

it might be a pushy, and it might be a BMW


that is given to the Dr. method. Really cool

feature.

Okay,

I guess there are many, many more advantages


of interfaces. Let me know if you have more

to add. But I think this is enough for the


moment so that you get an idea of what interfaces

are. And all the advantages interfaces have.


Just also, again, the warning don't fall into

our interface, serious illness. This will


also be not wise. But I think this pretty

much wraps it up. I'm going to talk about


inheritance in Java. inheritance is actually

a very powerful feature of object oriented


languages. Similar to interfaces, inheritance

allows to handle a group of similar objects


in a uniform way. On top of that, however,

it also allows to prevent code duplication,


by inheriting the members of a class from

a parent class to its child classes. I'm the


members of a class in case you don't remember,

are the instance variables, and the instance


methods. So everything that is not static.

Okay, well, I guess that sounds very promising.


The problem is, I think inheritance is just

a bit too powerful actually. Well, if used


incorrectly, inheritance, can severely damage

your code. So really take here and use inheritance


sparsely. I mean, there are definitely justified

cases to use inheritance. But whenever in


doubt, I would not use it. Okay. And also,

it actually requires some experience to know


when to use inheritance, and when to avoid

it. To give you a real world example, I'm


at the moment I'm working on a project of

about maybe 15,000 lines of code. And there.


I used inheritance, maybe once. Yeah. So there

are alternatives to using inheritance. I'm


about this. We will talk at the later time.

Yeah. Well,

let's stop here for a moment. Because now


the introduction is almost over. You see me

in the button right corner talking to you


all very soon disappear, because I'll jump

into the code. And I'll show you how to implement


and use inheritance. Before that one personal

request. I'm doing this videos for you. So


that you can learn Java, I hope they useful

to you. If so, I would be very happy if you


could give me your thumbs up in the bottom

right corner of this video. And remember,


you can also subscribe to my YouTube channel.

Okay, well enough of advertisement Now, let's


really do a coding session and jump into the

code. Okay, so here you see I have prepared


this CEU test class for you. We are actually

not really testing something now. This is


just for demonstration purposes, any arbitrary

example. Um, this example is actually taken


from the book, headfirst Java, from Kathy

Sierra, she is really my favorite author of


any Java related book, highly recommended

to read

this and any other offer books. In case you


want to know, you can find a link

to her books on my blog on market minus b.com.


I have a must read section there, you can

find her books. Okay. Now back to the code.


So I have here the SU class. So the idea is,

we have here an area of animals, similar to


the area of cars I had in the last episode,

where I introduced you to interfaces, and


I had a car every with BMW and Mercedes and
a pushy, now we have an animal array with
a dog, a gorilla,

and a line and a tiger. So you should already


see interfaces and inheritance in Java. When

you use them, here, it looks quite similar.


And this, by the way, is called polymorphism.

You might have heard that.

And the idea of polymorphism is that on the


left side, you have a variable a reference

variable of this super type a parent class

animal. But Polly Morphe. I mean, this also


works with interfaces. So the idea is just

that you have an interface or a super or parent


class.

And on the right side, an animal can be a


dog, a gorilla, a line, a tiger, anything,

so different things can be assigned to the


left variable. Because the polymorphism means

like, many sides solve can have different


implementations on the right side. And they

will all be handled uniformly here, I have


prepared this feed animals method. Let's maybe

jump here. Okay, so you see I've prepared


this for each loop, everything that is read,

we still have to implement, I have only prepared


it. So we're iterating through my array, we

still have to implement the eat method. And


we still have to implement the H method. Now,

again, totally stupid, arbitrary example.


But just to have something to show you. And

to have variation. My idea was, I mean, totally


arbitrary. Really, this depends on the design

of your code that like because code is always


like a model of the real world. And so it

totally depends on the example that you're


working on. Well, in my example, I just defined

that I said, Well, every animal, a dog, a


gorilla, a line, Tiger, they all eat in a
different way. Because for example, a gorilla
would probably eat, I don't know what it eats

grass, or leaves or something will align.


I don't know. It's some kind of meat. So therefore,

my idea was to have an implementation, a concrete


implementation of the eat method in each different

animal subtype. And further, my idea was to


have this H method. Well, every animal can

be of a different age. But the calculation


Well, normally, you wouldn't probably calculate

the age. But I mean, this is just my stupid


example, I made it a method. So the calculation

would be the same for every animal. So my


idea is to have this as a concrete method,

an animal and have this as an abstract method,


because this is something here, where interfaces

are different. Sorry, yeah, but interfaces


are different to inheritance. In interfaces,

you only have abstract methods. And because


you have only abstract methods, the abstract

keyword is not needed. But here we can enhance


inheritance, we can mix it, maybe I should

already jump now to the animal class. So an


animal class this is still just a stupid simple

class totally empty. So you can use inheritance


with just a simple class. And now let's implement

two methods concrete

methods, public void, eat Later on, I'll make


this abstract. But for now, I wanted concrete.

public void. Ah, oh, okay. So now maybe we


should also do something in the method. And

again, avoid system or print boom, just, if


you're like me doing an example, showing something.

This is the exception polluter rules and it's


okayish to use system or printable, but avoided

in real code. Okay, so I say, animal is eating.


Well, this is not what we want. So it's just

step one, I said every animal is eating in


its own way. And here is say, h is cold. collated.
Okay, it's here the dots to just for fun.
So now, see, this class looks totally like

a regular class, you have seen so many times


before. Now, I go to the dog class, and I

want the dog to be an animal. Well, if this


would be an interface, I would say implements

you remember, but it's not it's a class and


we extend the class and therefore the keyword

is extends really, totally easy. Okay, so


we say extends animal. And all this is already

using inheritance. Now it's looks like as


if the dog class was empty. But in fact, we

can already use these two methods in dog Okay,


let's continue doing this for all the other

subtypes

gorilla

extends animal line extends animal. These


by the way are two interfaces, I also want

to show you and I might just as well do it


now, we can mix using interfaces and using

extending classes using inheritance we can


mix them the question is should we first say

extends or first implements, well, there is


a rule it must be that we say extends first

and then implements because in Java, we have


single inheritance. So, we can only extend

a single class, but we can implement any number


of interfaces, and therefore, this is a comma

separated list. And therefore, to make it


a bit easier, it's at the end. So, we say

implements and I can say this interface lockable


and comma printable. So, an interface plays

a role. So Aline can play the role of being


a lovable, when like, he mentioned, the code

is running on production at a certain time


where we want to lock the line or we want

to print it and therefore we can implement


this interface. Again, this is pulley Morphe

that align can be a luggable Okay, so, you


see there is something red, because now we

have a lot of methods that we have to implement.


First of all, from the animal, I mean, the

order is arbitrary. We can also start with


a printable. So there was a public void. Um,

was it print I hope method. And then there


was a public void I think message for luggable.

This might have Yeah, you see, so the rule


is, when we implement an interface method

as well as when we, when we implement an abstract


method from animal, the signature, the method

signature must be exactly the same. We can't


say what year because the interface said it

must be a string, return something just for


our little example. Okay, and in here, I say

system dot out.

Print.

ln

printing,

okay, get the idea.

So, now, there is still the eat method missing.


No, actually, it's not because we made it

concrete. So we don't have to implement the


method I'm already a bit too fast.

So see the red is gone. Everything so far


seems okay. But there's still a problem and

Sue test. Let's check this are the tiger,


we still have to do the tiger extends because

the tiger was not an animal yet. Maybe we


should look at this again. I mean, this is

interesting. So see, all those classes are


all already extending the

animal. And so these are already animals,


but the tiger is not yet required, we need

an animal with found is a tiger. Okay, so


let's make this also an animal. Now it's an

animal, and now it's working, the red is gone.


Okay, but we still haven't done what we want
it. Because I said I want this method abstract.

Now, you probably remember from when I explained


interfaces, an abstract method does not have

this method body, the implementation, but


just the method signature, this here on the

top,

the method signature. So let's remove the


body. And we have to say abstract in the interface

we didn't have to, because in interface, all


the methods are,

by definition abstract. But here I mean, how


would Java Nope, there's a concrete method.

And this one is supposed to be abstract. So


therefore, in inheritance, we have to explicitly

set abstract. But now there is a difference.


Because if one method is abstract, the whole

class has to be abstract.

Now,

what does this mean? Because actually, this


changes a bit of the behavior. And this, again,

depends on your personal design of the program


that you're writing. An abstract class cannot

be instantiated. Now, we cannot say the compiler


will not allow us We can't say new animal.

An abstract class is like just the contract,


just the protocol. Pretty much the same as

an interface is just the raw definition. But


we cannot create instances from an abstract

class, we can only do so from concrete classes.


But concrete classes cannot have abstract

methods. So this is something that you have


to clearly think of. And also amin, I said,

another warning, I said that this can be used


to prevent code publication. Now you might

think, well, cool, I just create some tool


class. And this has any method that I'm like

needed anytime for example, age. And then


I can say animal extends tool. Because even
the inheritance can have several layers. So
even though talk says extends animal animal,

again, could extend some class. So now we


could say, extend some to class haven't implemented

that. But I hope you get the idea. Well, even


though you can do so you should not do so.

Because the rule is you have to apply and


is a test. Also, this is from

the book of Kathy Sierra had first Java. They


you say an animal is a tool? No, it's not.

So because it's not a tool, we don't say tool.


Because otherwise, this can really get nasty.

And so you shouldn't do that as a recommendation.


But really a strong recommendation. Okay.

So yeah, it still has to be made abstract


because of this abstract method here and we

have to remove new animal as I said, doesn't


work. Okay, not everything read has gone.

Now,

let's go into our classes again. See, now


there is a problem. Now that this method is

abstract, we also forced to implement it.


So we have to say, public void, eat. And we

have to implement this method. And again,


stupid examples system called print ln dog

is eating dot dot dot Okay, So gorilla is


eating in a different way. It's, I don't know,

grass or something reuleaux is eating leaves.


Um, next one line, the line is eating something

again, and the tiger is eating something.


So in this case, they all implement the eat

method in their own unique way. So in reality,


you wouldn't, of course have your system out

print on but some specific, Tiger related


logic that only fits for tiger. And this is

why we have it here. And all the logic that


fits for all animals you put here. And this

by the way, I mean, on the one hand, this


is handy. But to me, this is really a double
double sided sword. I mean, this is handy
and can help. But on the other hand, it also

is really complex. Because when you're in


a class like Sue, how do you know which animal

implements eat, and which animal just inherits


the eat method, same for the H method,

because we could of course, again mix that.


And we can also override a method. So for

example, ah, this one is implemented. But


we could say, gorilla is implementing the

age by itself are not something. So this is


like, how you could define an exception to

the rule. You could say, well, my gorilla


does not use the H method. But instead, the

H method is replaced by exactly this method.

And the way this is done is, the signature


must be this method signature here must be

pretty much looking the same. You can't like


change the return value or the parameter

values.

Well, you see, you can, but it's just not


using inheritance. Now, this is also why it's

not yellow, but gray. Um, this is called overloading


a method. overloading a method means you implement

a method that has the same name as another


method. But it's just something completely

different. So this has nothing to do with


inheritance. If you want to inherit the method

and override me override it, it has to have


the same signature. Okay, there is one exception.

And for this, I have to introduce a new visibility


modifier. I think shortly, I talked about

it in an earlier episode, but I didn't really


explain you what it means. And this is protected.

Now what means protected? protected, means


it's visible, on the one hand, similar to

default, or package level visibility, and


the whole package. So now we can use the H
method. In Su. See, this is not read. It also
means it's visible in any class that extends

animal. In our case, now, we have all the


classes in the same package. But he mentioned

we had a car sitting, extend animal, I mean,


of course, we should not this would be stupid.

But just technically not from a design perspective.


We could then use the H method, because it's

protected. So the visibility is to any class


that inherits from animal on top, any class

that is in the same package. And this again,


makes it complex. Do you see how much I have

to explain? so that you understand, and this


is why I would avoid using it. So I just want

you to passively know when someone else uses


it. But I would really avoid it. But so protected

visibility is less visible than public. And


what I am allowed to do is I can increase

the visibility in a child class. So where


was I? Here? So I'm allowed you see it works.

I can say public void. Now this is still not


inherited. Nowadays, it's yellow again. So

I can say public And now I can also say protected,


which at the moment is the same visibility

as in parent class animal. But I'm not allowed


to say private, this will give me a compiler

error, attempting to assign weaker access


privileges. It was protected. So you're allowed

to make it public, but not less than protected.


The idea behind that is, I mean, an abstract

method defines a contract a protocol. Exactly.


Like with interfaces, by saying extends animal,

you promise any other class in the Java universe?


I am an animal, and you have a method that

is public. And you can call it. And me. You


mentioned the crazy stuff that would happen.

If there is one class that just does not fulfill


this contract. So this is why it's not working,

it has to have the same visibility. Oh, okay.


Then also, I mean, I said, we inherit the
members of a class. And I said, the members
of the class are the instance methods. These

are the instance methods, and the instance


variables. So you can also have here a protected,

I'm in H. And this will also be inherited.


We can now say, directly access is in here.

I mean, this is the H method. Maybe I should


now here have a public void. h method instead

of the eat method.

Okay.

And now I can say this dot age, or just age?


Or a statement? Yeah, of course not. It's

not finished

45. So this would now we'll set the age to


45. Or just age because here, we don't need

this. Because we know what we mean.

Um,

even though this is possible, we inherit the


age field, I would not make use of it. Well,

first of all, because I don't like protected


as I said, and second, because I think this

kind of violates the capsulation because the


animals should be the only one working on

its internal variables. Okay. So avoid protected


and avoid like, making the variables the members

the the instance members visible. If we have


a static method, public static, something.

Well, I have to implement it. Of course, this


can be used static void. For example, by saying

animal dot something can also be used now.


From Zoo or wherever. So we could say, animal

dot something. Yeah, you see, it's also formed


formatted differently. So we don't really

see this as a static method.

But this will not be inherited. So you cannot,


like override this or so. And the gorilla

class again, you can say animal dot something


will actually you can even say and this is
a bit weird. Gorilla dot something. But this

is not inheritance. It's just Java is a bit


smart. Here. The compiler is a bit smart.

It knows gorilla is an animal. So it realizes


this is an animal and then it takes the static

method.

But this is still not inheritance. Oh, K.


Let me remove that. I hope I haven't confused

you too much with that static.

Just remember, we only inheriting the members


of the clause. The instance methods and the

instance variables. All Okay. Well, I think


this is pretty much it. Maybe I should execute

it again. And now we see dog is eating. He


is calculated. Gorilla is eating gorilla is

implementing the H by itself. This was I was


overwriting the H method in gorilla, and only

in gorilla lion is eating, he has calculated


Tigers eating ages calculated. So inheritance

really is a complex beast. And in conclusion,


use it sparsely. Only use it when you can

say, when you can apply the is a test. A dog


is an animal, a gorilla is an animal, a lion

is an animal, a tiger is an animal, a tool


is not an animal. So you will not say tool

extends animal never. Um, if you're just looking


for something to like, not copy and paste,

to not duplicate code, you can do something


else, put your code into its own object, a

tool object. And then always you can use composition.


You could say, for example, a tiger has, I

don't know, um, has a leg. If that makes sense


or not, I don't know. So leg, leg.

And then you if you have a method, for example,


walk, you can say leg dot walk. And if you

have another animal that also needs up it


called eat still. So this would be walk. So
now if you have another animal that should
also use the lecture also use this method,

you can also make it to have

this member. And this by the way can and also


should be an interface. So that really makes

it much more flexible actually, even than


inheritance. Because using an interface, you

can exchange the behavior at runtime. This


is something I showed you in the last episode

talking about interfaces, where I said you


could have some condition, if I don't know,

Sunday.

He was

this implementation and otherwise the other


implementation. I mean, this is just not real

code. Just very fast. Else. I just hope you


get the idea. I could say if Sunday, like

equals to my fast leg, legs, you know.

And

the other days, I'm not so fast. I say used


to slow lag. And then after the instantiation

I would say like dot walk.

Okay,

so of course I mean this if else again introduces


some complexity. So whenever you design something,

there's always pros and cons, you have to


think, what do I really need? But so you can

use this, just to give you one example to


not use inheritance and still not duplicate

your code. Oh, okay. Let me remove that. Don't


want it to be read. Wanted to be working.

Okay, now, let's maybe recap before I finished


this video. So we talked about inheritance.

We talked about polymorphism. I showed you


you can use composition. And there's also

actually design principle it's called favor


composition over inheritance. As I showed
you you can mix using inheritance with was
that one of these classes? Yeah. With interfaces,

I showed you can implement several interfaces,


you can only extend one class. So I cannot

say it already. When I do the calmer Something


is wrong. So I cannot say this animal to this

doesn't work. Just believe me for now. Or


I mean, yeah, this is also a class, which

is implemented. Yeah. So you see class cannot


extend multiple classes. This works in C plus

class. And it's even more nasty than Single


inheritance. This causes something called

the deadly diamond of death. But I will not


continue. This is too, too much for now you

can google this deadly diamond of death. Because


Java doesn't support multiple inheritance.

I'm going to talk about the method finalize


of the class object. The class object is the

root of the class hierarchy. Every class in


the whole Java universe inherits the methods

of this class. So this is what makes those


methods here, very important. Which is probably

also the reason why those methods are very


often used in Java developer job interview

questions. So one way or the other, I hope


I have now raised your attention. Also, you

should now that this episode, as well as the


following ones talking about all those methods

are based on the really great book, Effective


Java second edition from Joshua block. I think

I mentioned it already earlier. Now I have


to say it again, buy this book read it. Even

better would be if you read it twice. It's


full of condensed information. Advanced Java

developer must know my episode is supposed


to give you an introduction to the topic.

But for more detailed information, it's necessary


that you read this book. Okay. So let's already

start talking about the finalize method. The


finalize method is actually a hook method.
What is a hook method? a hook method is a
method that, um, there is an empty implementation

provided in the class object. And the idea


is that when you want this method to be used,

he would provide an implementation in your


own class, by inheriting by overwriting sorry,

by overwriting this method. And then this


method will be called by the JVM. But before

I go in more details, the one the most important


takeaway from this episode is, this method

is flawed. So the best you can probably do,


generally speaking, is not overriding this

method. So not using it because it has its


flaws, will, in this episode, see? Why. I

mean, there are some few valid users, at least


according to Joshua blog.

I can tell you, I'm developing in Java since


2001. So quite a few years already, I have

never ever overwritten this method. So today


is probably the first time to demonstrate

you what it is what it does. Okay. So maybe


we should already jump into the into the code,

because it might be easier to understand for


you, or maybe before we read here, this description.

So the finalize method is called by the garbage


collector of an object, when garbage collection

terminate determines that there are no more


references to the object. So again, next question

was probably what is the garbage collector?


Well, the garbage collector is really a very

cool thing of the Java language. Other languages


such as c++, don't have it. As the name implies,

it collects the garbage what's the garbage


the garbage is or objects that you created,

worked on them. And after some time, the process


will be finished, at least on certain objects,

he will not need them anymore. And so it helps


to free up those memory resources. So that

you hopefully never run into out of memory


exception. And this is all done behind the

cover as synchronously by the garbage collector


for you. But here is already the problem of

the finalize method. Because I said it's,


it's called just before the garbage collector

runs. The problem is the garbage collector


is running as synchronously so you can't influence

when or if the garbage collector is running.


It is like its own smart beast. And you have

no influence to tell it that it should run.


You can only give it recommendations. But

you have no guarantee that the garbage collector


will ever run. And so you also have no guarantee

that the finalized method will ever run. Yeah,


and what would you usually do in the finalize

method, the idea was, you will also clean


up stuff, they're just not memory related

resources, but not memory real related resources.


For example, if you have a connection to some

i o resource, like a database or a file, those


are also system resources. And all resources

are limited. So if you don't want to get in


trouble, and if you don't want that your system

totally, totally freezes. You have to, again,


free up resources when you don't need them

anymore. So the idea was to do that in a finalized


method. Now the flaw is, you don't have a

guarantee that runs. And this already says


it's not working as intended. Okay. Besides,

Joshua Bloch also gives other reasons. For


example, He somehow measured that creating

an object and destroying it, again, is 430


times slower when you have an finalizer method

implemented. So again, don't use it. And now


let's jump into the ID and look at it in more

detail from a practical point of view. Okay.


Also, just before, in the API documentation,

you might have seen, this method is actually


protected. Here. Again, we can see it protected
void finalize, I mean, this Java API is just
written into the source code. Here, you can

see the source code of object dot java. So


you see, it's also just a regular Java class.

And you'll also see this method is empty.


This is what I said, it's a hook method. The

idea is that you override the method and that


you provide code that is executed for cleaning

up non memory resources.

And Java, try to prevent that you directly


call the finalize method, because as I said,

the idea is that you don't call it but that


the JVM calls it for you. So this is why this

method is actually protected. Protected is


quite hard to understand. One way you can

use a method that is protected is if you are


in the same package. So let's check this class

isn't a package Java Lang. So I thought being


nasty, I can just as well create a class in

this package. And this is what I did here,


test Java. In package Java Lang. You see,

everything seems fine. I don't have any exception


from the compiler. So now, let's try to call

this method. And you see, this dot finalize,


seems to be working. I mean, this is not working,

because this is a static method. So we would


actually need a non static method. Or I could

also say, new object. Well, there is an exception,


because it can throw a throwable as we see

here at the bottom. I'm not going to handle


this now, because I only wanted to show you

from a theoretical point of view, this is


possible. There's just one problem. Let me

now surrounded with a try catch to get the


compiler happy. So see, this would be now

directly calling finalize, from a class that


is in package Java Lang. So I'm within my

public static void Main method. So I execute


it. Bam, I get an exception, security exception.
It's prohibited. I cannot use Java Lang as
a package name. So this is not working. Okay,

I just thought I should show you. I think


this is quite interesting. Now, let's close

this again. And let's complete remove this


method. Okay, so what you should also know

I mean, I said object is the root class, but


it's also a concrete class, you can create

objects of the class object. What I don't


like here is that the word object is used

twice, because the class is called object.


That's a bit confusing. So anyway, you see,

you can call all those methods. But here within


the class car selector, we cannot call the

finalize method. Okay. So for this, I have


here, this portion class, that's also close

the object class. And now let's override the


finalize method, public void finalize, without

any parameter. So to override a method, it


is very important that you do it exactly.

Like in the superclass, the only difference


is, and this is allowed, I don't make it protected

anymore, I can make it public. Because public


is more visible than protected. This is fine.

Okay. And now, the idea would be that in here,


I do clean up my resources. Let's imagine

I had some i, o reader, i, o reader, reader,


Peter, I'm not going to implement this, just

so that you get the idea. So the idea was


that within here, he would like for example,

close those resources for this, usually I


already use provide a closed method. Now there

are several problems for one, I said, you


don't have a guarantee that this method is

ever called. This is totally in control by


the JVM, and you can not influence that it's

running out of your control, it's running


as synchronously. And therefore, it doesn't

really serve our purpose. Second flaw is,


if within here, we have an exception that
is not caught,

the

process here will be stopped. And our objects


will remain in some weird, let's say zombie

state. Yeah. Okay, so the question is, what's


the alternative than to using the finalize

method, the alternative would be, if you have


a class that you will use that uses resources

that you want to be closed before it's cleaned


up, you could provide, like I told you here,

the reader would do. You could and you should


provide some closed method. And then in here,

you do clean up i o resources. I'm going to


implement this now. And then make this compilable

in car selector. Let's imagine this was a


client of using Porsche. When we have Porsche,

Porsche, a new Porsche you use a try Finally,


we talked about Exception Handling array.

And I think, there in this episode, I told


you also, you can say try catch and finally,

but you can also use the finally without a


catch. Now, if we need a catch or not, this

is a different discussion. What is important


is that at the end, you have finally because

the finally the cool thing about the Finally,


even when there is an exception happening,

it will always be executed. Because this was


our problem, we need to make sure that the

non memory resources get cleaned up. Okay,


so try finally. And then in here, we could

say Porsche e dot close to clean up the resources.


This is how you probably do it in Java. Okay.

Also, shortly, let me show you what I think


is interesting. Let's go back what I had before

and the finalize method. What I also want


you to know is I mean, I said we overriding

the method from the class object which is


empty. And there's actually an annotation
that is quite helpful here. And this is the
annotation, the override annotation. See,

when I put the ad, there is override. So about


annotations. We have haven't talked a lot

yet. So let me explain that. In short, this


is actually some meta information for your

compiler, that you say, Well, my intent here


is I want to override some method. If this

has a different name, some other name. Here,


you see, you get an exception method does

not override any method from its superclass.


Now, you might not understand what this helps

us. So let's, again, call it finalize. Now


the thing is, you only override a method if

the signature is the same as in the superclass.


Now, if I add the parameter here, this is

not overriding anymore, but overloading the


method, because it's just a method that has

the same name. But as it has a different parameter,


it has a parameter string, and not no parameter.

This is not overriding anymore. And now we


get a compile error. So you will directly

notice. So this helps us to have the problem


directly at compile time while we're still

in our ID. And we will not because otherwise


it could happen, you think you have implemented

a method while you have not. And then you're


still using the superclass method. And this

you will only see when your code runs on production.


This is why whenever you override something

at this override, annotation. Okay. So I think


this is pretty much it, talking about the

finalize method. In short, again, generally


speaking, don't use it. Instead, to free up

non memory resources use a try Finally, I'm


going to talk about a method clone of the

class object,

a class object I said before, is the superclass


of all the objects in the Java universe. And
this is why you can use the method clone in
all your objects. Now, the question is, should

you Really? And the short answer is, you should


not at least generally speaking, and this

is similar to the finalize method that we


talked about in the last episode, which is,

again, the reason why I'm talking about clone


today, because in this aspect, they're both

quite similar. Okay, but before going in more


details, maybe first of all should clarify

what actually does the clone method do. And


clone as the name implies, it creates an identical

copy of the object that you call clone on.


So what it does not do is, if you have an

object, you can always assign it a second


or third, how many references ever you want.

The problem is with references, that when


you work on this reference, all other references

will have will be influenced by your changes.


And sometimes this is not what you need, you

want an independent copy. And for this reason,


you could use the clone method. However, there

are actually better alternatives, which I'll


tell you later. But now enough of talking

Anyway, let's jump into my ad and look at


the code. Okay, so, here you see my Porsche

test, you might remember the pushy and the


other cars from my earlier episodes. Before

I show you the nasty stuff, I wanted to show


you one case, where actually I think using

clone is actually good. And this is here I


have prepared an array of strings 123 and

here, I mean array is also an object. So it


also has the clone method and for the string

for the array, it was already implemented


the way it should be. So you can and you should

clone your array. So I can say string copied


array equals to array dot clone. And then

I can assert not same, which means this check


checks. Now, if we just have a reference.
In this case, it would be the same

airy

and copied airy. Which, to show you that their


friends I can also call, assert same and use

twice the same reference. So this should be


true. They should with not also be true. So

there are two different instances.

You see, it finished with a green bar, this


is what we want to see. So it seems error

and error compared to itself, it's both the


same reference, they're both referring to

the same object. But the copy is not the same


reference, it's not the same object, it is

a new object. And now, I mean, I want to make


this short. But I want to show you at least

system out, print ln. And then, you know,


this is not I just want to show you the first

element and then I just hope you believe me,


or you can do it at home can print out the

whole elements in in an in a loop. Now I'm


just showing you the first element of my copy,

and you see it's one. So the other ones are


also or unlike just as well. Otherwise, you're

telling me copied error. This way, you also


learn how you can print out the whole array.

And this is now I can print odd STR and this


will then in the loop and a for each loop,

print out all the strings

for us.

So I hope this is working now. 123 C, out.


Okay. So for now this should be enough. This

was just a very short demonstration of a good


case of clone. Actually, I found on the internet

and very interesting article Actually, it's


a newsletter article from Dr. Heinz Cabot's,

he's really a very cool guy. I love his newsletters.


And he actually made a test and found out
that clone for very small areas might be a
bit shorter, f slower. However, for large

arrays, it's actually faster than any other


method. Well, I can't go in more detail, we

don't have the time. And this is also very,


very advanced already. And we're still on

beginner level, approaching more advanced.


So anyway, let's continue with our portion.

And this is now really test driven style programming.


Because I start with an empty test. The code

is not finished, we start with writing a test


to test Well, first of all we read, and then

we are working our way to get the test screen.


Okay. So I say Porsche Porsche equals to new

Porsche, actually, this is something you can't


know. Before doing this episode, I have extended

adjusted my class a bit. I mean, you might


remember the Porsche from my last episodes,

because it was empty. Initially, there was


no attributes, no instance members. So this

I had to change because I want to show you


something that we copy. So I added a string.

And I said, it's the owner, the name of the


owner. And well, which name should I choose?

Because I always wanted to own a Porsche.


I thought I might just as well make me the

owner of the Porsche. And because you probably


also want to own a Porsche. I thought I should

make you the owner of our copy of our clone.


Because I will not give you my pushy, but

I might just as well copy mine and then give


you this copy. Well, in real world, this is

pretty much impossible. However, here in Java,


See how easy that is? Only problem we have

is I don't know your name. So for this example,


I just assume your name is Peter. So I say

Peters for xi equals to new pushy. But this


is not what we wanted to do. Right? We wanted

to clone. Yeah, because this is no easy. I


can just say Peter, and then you have your
pushy but this is not the original idea. So
let's remove that. And now let's say Porsche

dot clone. And interesting enough, really,


I mean, we can see what happens behind the

covers, because this is done really, by the


JVM. And we don't care too much, as long as

it works. But there is never a constructor


actually cold. So this is really internally

copied from the memory. It's just see, we


still have this read something is still wrong.

I mean, I said, we start with a not working


test. So it says clone has Protected Access

and Java Lang object. And this is something


we have to fix. So the method that says the

method is already there. The problem is, it's


not visible to us, because it is protected.

Protected would be visible in the same package.


The class object is in the package, Java,

Lang, as I showed you last time. But here


we are in a different package. Also, my Porsche

test does not inherit anything from Porsche.


Because this is from Porsche, so I can't use

clone in here. Okay, but what I can and what


I will do, I can override the original clone

method. But still, I want the code the implementation


of the class object. But let's already jump

into the Porsche class. So I will override


it, public, Porsche, because I wanted to return

a Porsche to me,

clone.

And then you might still remember from my


last episode, we can and we should put the

override here to have a check from the compiler


side, that we actually did everything correctly.

Now, let me format that. Okay. And you see,


there's nothing red. So it seems like so far,

everything is fine. We'll actually went into


one interesting thing is the original implementation
says object, because in object, what could
you return, you don't know. The object that

the method always is exactly copying whatever


object there is. And in our case, we have

a Porsche. So the so it is also fine to directly


make this return pushy. But now we have an

empty implementation. And we have to return


a Porsche. Or we could say return new Porsche.

But again, this would not be a clone. So this


would, our test would fail in this case. So

this is not what we can do. So we have to


say super, super means. I want to call a method

from superclass in this case object. And you


will see already here I see clone is actually

the first method, because my ID is already


smart, it knows the name of this method is

clone. So it assumes I want to call super


clone. Okay, so and then I want to return

it. So all we did so far is we override the


method. And then again, we said, well, actually,

I don't really want to override it. All I


want is I want to use the method of class

object. So all we did so far is we made the


visibility public so that we're able to use

it this is all we did so far. But now, you


see there is still a problem unhandled exception

Java Lang clone, not supported exception.


And this is already in my opinion, a flaw

because, like, why does this Now throw a clone


not supported exception, if we do support

clone. So, anyway, this is how it is. And


now we have to fix that the way we fixed that

is we say try, because there is an exception


that could happen. And we will catch the exception.

Catch. And there my ID Egan helps me clear


not supported exception.

I usually give it the name here. Okay, now,


what should we do here? Some people say return

now. Because we have to return something.


This is just the signature forces us
to return something. But this is not so nice.
I mean, actually, we assume this is hopefully

never happening. But if it for whatever reason


is happening, we really want to see that it

is a problem. So in this case, and I kind


of copied that from Josh block. Because again,

my episode here about clone is based on his


book, Effective Java second edition. And it

was exactly the same with a finalized episode.


So I can only give you a short introduction

to the topic. Um, Josh block in his book,


he has like, I think eight pages only on the

clone method. You should really buy the book


and read it. So for this, you can go to macros

minus bu.com, click on mastery, it's, and


there you will find the book and you can buy

it directly. Yeah, also all the books in the


must read section. I mean, I have picked the

name for a reason. Those are really books.


I want you to read them all. They're really

classics, the best of the best best Java books


you could find, in my opinion, at least. So

if you trust me by that book and read it,


okay, anyway, so what he did and what I will

do the same, as he said, throw new assertion


error. Because if this happens, this is not

even an exception. Is this really an error?


We really have a big problem here. If we get

this clone, not supported exception. Okay,


so this year now seems fine. But there's still

something wrong. And this is it says I'm calling


super dot clone. And as I told you, this is

the method from object, an object returns


an object, at least from the signature of

the method. But we are smarter we know actually,


it's safe to say pushy, because this object,

I mean, the super type is object. But the


subtype is a Porsche. So we do an explicit

cast, and we cast it to Porsche. This is safe


here. Yeah, if it was not safe, it would throw

a class not support F. Class cast exception.


Sorry. But in this case, believe me, we'll

see. It'll it should work. Okay, well, are


we done? It looks like we were. Well, actually,

as I said, this method is flawed. So we are


not done, we still have to do some more thing.

But this I want to see. I mean, my idea was


to implement the method I did that. So now

let's go back to our test, you see, everything


is? Well, I can't say green, but the red stuff

has gone. So I can execute the test. But I


haven't asserted anything yet. So the first

assert that I want to do is I want to assert


not same. This is just a shorter, Handy form

of saying not equal. So it won't be the same


if we say pushy, not equal to Porsche Peters

pushy, because the idea is that when my clone


word that I have a new object. And because

it's good to have a method that already from


the method name tells us what it does, I use

this one. And I compare not pushy to Peters


pushy. So my first test is just asserting

that this reference here is not referencing


this Porsche here now. But something else,

this isn't our first test all I want to achieve.


Okay, so I execute the test.

And bomb.

You see the assertion error? I said, Well,


everything will be saved law when it's not.

And this is why tests are so great. Yes. And


now we can see what happened. And think about

why did this happen? Okay, so by jumping here,


see, line 28. I see this happened. Problem

is here in this case, without further knowledge,


it would really be hard to know why this happened.

So here, sorry, I have to help a bit. Thing


is, I mean, I told you this method is flawed.

It's not enough to use the power of inheritance


here. On top you have to use, you have to

implement an interface here. So we are already


implementing car. But for interfaces, I told

you in the episode about interfaces, we can


implement several interfaces. So here I have

now to implement the cloneable interface from


Java Lang also. Now, funnily enough implementing

the interface, normally, I would expect that


I would have to implement some method. Well,

in this case, it's different. We don't have


to implement anything. And this is a specific

case, this interface we call a market interface.


So this interface is actually empty. There's

nothing in there. It just tells the JVM. I'm


implementing cloneable. So you can call cloneable

here, it's a clone here it works. And this


is a bit awkward, because normally when you

implement an interface, you would on the Reference


Now, like I can now say that I implement cloneable,

I can also make this a cloneable. So that


my pietras portion now plays the role of being

a cloneable. The problem is, this doesn't


help me anything. I don't have the method

cloneable. Here, all I have is the other methods


of the class object, which we're not using

now. So because I can also say car, I mean,


I'm implementing, also the car interface.

And then I can call the methods of car, which


is drive, plus all the methods of class object.

Okay, well about macros interface. That's


also another topic. This is a design pattern.

haven't talked much about design patterns


yet. Marker interface really has good users.

So a marker interface, generally speaking


is not bad. It just here in this case, it's

a bit weird that you have to implement a market


interface and then on top, you have to override

the method. Okay, so I make this portion again.


But now, and now the same as already, again,
working because otherwise you could not compare
different things. Let's try it again. And

see, now we have the green bar process finished


with exit code. So my first assumption is

correct. Peters pushy is not the same instance,


as pushy. Okay. So now I want to see who is

the owner at the moment of Peters, Porsche,


Peters, Porsche, Dodd, s string. And this

is why before I prepared this method, because


it returns Porsche II off plus the owner's

name, because at the moment, we don't have


another way of seeing the content of owner's

name. So I wrote this method to see who is


owning it at the moment. Okay. And my expectation

when we're finished is that the name would


be Peter. So I would say it should return

partially off, Peter. So let's write a test


for this. assert, equals, first, the expectation,

you also see it expected. So I'm expecting


it to say pushy off Peter. Okay. And then

comma. And I put here pushy, Dodd as string,


which is calling the method. So I expect the

method to return portion of pizza later on.


I mean, there's also again, a method called

equals. In an later episode, I'll talk about


this and we will have a better way of comparing

that for now. I'm using the S ring method,


because we haven't talked about the equals

method yet. So there's still something missing.

Okay. I can remove that. So let me also execute


this test now. And it should be read. Yeah,

oh, there's an error. I have missed a semicolon.


Again, sorry. Yeah, comparison failure. Expected

portion of Peter bar is still mine. Now this


is even cooler for me. Now I have actually

two portions. But okay, I said you get one.


So let's change that. And for this, I will

now change the owner. So I will sell on my


second car. Okay, and I will sell it to Peter.
Which means I mean, I just made this method
up before I assign the owner's name the new

owner. Okay. Also, by the way, I mean, here


I'm using string to have this as simple as

possible for our example. Usually, I would


prefer to have this proper object also, like,

name, for example, and I also already have


that here. But in this fast example, I use

string. But more object oriented would be


if you have name as an object there. Okay,

so I sell it to Peter. And now I expect the


test to be green. Let's try it again. Okay,

it's green,

it worked.

But now I have a fear. What if now my pushy


would not be mine anymore. So on top, I want

to assert that the The original pushy is still


mine portion of macros to the original portion.

K, which also worked. And this tells us now


starting from my pushy macros, I called the

clone method, it created a new object in memory.


And this new object was assigned to the reference

Peters Porsche he inserted that they're not


the same object to different objects. And

then I changed the second object. And I gave


it the owner of Peter. So and I asserted that

now, the owner's name is Peter, by comparing


the string. And second, I asserted that what

I was working on the second object, the copy


was not influencing my policy. So this is

like proving that our clone operation did


work. But now let's look at the code. What

we needed to do for this, I had to say implement


cloneable, I had to override the clone method,

I had to call the super clone method, I had


to catch the clone, not supported exception.

This is a lot of lines for only this. And


actually, there's more to it. Because actually,

what this does is it creates only a shallow


copy, and not a deep copy. Now, again, this

is a more advanced topic. So I try to keep


this as short as possible. What's the difference

between a shallow copy and a deep copy? Okay,


well, a deep copy for this, I have prepared

here a more complex object BMW. And here I'm


using actually the object name. And I'm even

using a second object color. And let's make


this a bit bigger. So you see more, a deep

copy would mean that not only BMW is copied,


but also all the objects inside of BMW are

copied. So that they are also independent,


that they're not referencing the same object.

But a shallow copy will here, only copy the


reference. And the object for name, as well

as the object for color will still be the


same objects for shallow copy. Sometimes this

is okay. And sometimes it's not, it really


depends on your implementation. However, in

short, if you're using clone want to make


a deep copy, you will also have to call clone

on the internal objects, and this here, I


have prepared. So here, I'm calling clone

actually, three times. Now, one more problem


of the clone method is what I'm actually doing

here is, first of all, I cloned BMW, and then


on this attribute, and this one, which is

already fully functional, I assign a new value,


which only works if this is not final. So

it turns out not to in order to make a deep


copy, it only works if your internals are

not final, and sometimes you want them to


be final. So this is really a limitation of

the clone method. And also, I mean, how complicated


it is, is not so nice. Okay. Um, and for this,

there are alternatives I told you. I've written


here a lot of code. I have written this code

so I could show you what to think. Yeah, I


would want to make this episode not as long,
because I noticed many of you are only watching
like the first minutes. So 95% will already

be asleep anyway. So let's keep this short.


So in short, let me show you alternatives

to using the clone method. There are two alternatives.


The first alternative is using so called copy

constructor, and this is this thing here.


The copy constructor has one parameter, and

this is the same object. And then you see


here, I say new name, on owner's name, new

color on BMW dot color. So I'm taking the


internals and I'm creating new objects on

it.

And so in the end, I will have a new object


that has the same values as the original object.

This is One alternative. The other alternative


would be, and this is actually my preferred

one to use a so called static factory method.

And this is this here, it's a static method.


So you can directly say BMW as the class name

dot new instance, you can give it the BMW


object you want to copy. So in this case,

probably Marquess BMW. And then you You see,


I again, call the constructor, new BMW. But

here, this is a more complex object. So I


have to recursively we call this recursively.

Because again, I say new instance. And he


also new instance. And I have to again, call

those methods to also cop copy the owner's


name, because now I'm actually doing a deep

copy, I could have also just assigned the


values, this would be a shallow copy, but

it's safer to have deep copies. Okay, so And


for this, we can also have a short look into

name and color. Because there again, I do


the same thing. Here I have my new instance

method. So this is taking a parameter of name,


and then says new name, first name, dot last

name. Now, first name and last name are both


strings. And strings are also objects. So

why do I not need to copy down? Okay, now


it gets more and more complicated, I'm sorry,

um, thing is a string as an object, but it's


actually an immutable object. And immutable

means whenever you change the object, like


you assign, instead, first name, Marcos, you

say, Peter, you will not influence the other


reference. But instead, whoever said make

this, Peter will get a new object. So this


was really helpful. And for string, this is

done for you. Actually, you can do this for


your own objects too. And in order to achieve

this, you just have the limitation that you


don't offer any method to the client that

allows the client to change the values in


here. But instead, you will always for any

change, return a new instance. And then you


have an immutable. For this, I have also here

an immutable test. Because there's another


class that actually does it, which is big

integer. Big integer is similar to an int,


that we already looked on it just a bit better.

First of all, because it can work on ends


of, well, at least theoretically, any length

until your memory is full. And there you have


operations to add and subtract, for example.

Now, when you say one, add one, this is returning


a new object to but the original object will

not be influenced by this operation, you can


also subtract, but everything that you call,

every method that you call will never influence


will never change how the object looks. So

it's created once with the constructor, this


will like assign one to it. But after this,

you can never ever changed it again, which


is very helpful. In many cases, it's really

a good design principle to use immutables


whenever possible. Um, yeah, and it's also
very good to use multiples when you do code
multi, multi threading. We haven't talked

about multi threading yet, we will at a later


time. But there immutables are also very helpful,

they will make everything more easy. So, maybe


you take one more thing with you from this

episode. And this is favor immutables try


to design your objects your classes in a way

that they are not mutable, that they cannot


be changed after they were created. Or came

here at the same thing with string. Maybe


I can show you so I call so assigned twice

Hello, which in memory is actually the same


object. But when later on here, I Say hi.

This will influence the string one, and not


influence a string to let's execute this shortly.

So you see, like the speaker so we can see


Bo's bigger even. Okay. So now I see the first

string here printed Hi, the second string


printed Hello. And so they're not equal, the

first one has high, and the second one has


Hello. And if I remove this, this is why I

had commented it out. Let's execute it again.


Of course, now they both have Hello. So that's

the difference. And this is one example of


an immutable strings are, by definition immutable.

Maybe we could also call this here. So I print


out any n 01. And two. And also, I assert

to do a few things. So the input value of


one is one, the input value of two is two,

and the end value of zero is zero. Well, I'm


operating on these objects, they will always

return a new object, return a new object,


they will not influence the original object,

this is an immutable, this is something that


you should try always to achieve our K, let's

go back to Chrome. Let's recap. So in order


to properly use clown, you have to first of

all, override the clone method so that it


is public. Second, you don't have to, but
it's recommended. Use not object here, but
use the type of the class that you're in,

then you will have to do an explicit cast


to the class here. Catch the claw not supported

exception, thrown your assertion error, which


will show you in case you forgot to implement

cloneable, which you will also have to do.


However, what this is going to achieve, it

will create a shallow clone for you. Which


means if there are objects that are not immutables,

and you then operate on those objects, this


can break another object, because still you're

not totally independent, you're only potentially


independent, you're only on the first level

independent. But if here you have name, this


will only copy the reference and the object

here would still be the same. If you also


want to achieve this, you have to implement

a more complex clone method, you have to also


call clone on the internal objects and then

assign the new clone values to your internal


attributes, which will only work if they are

not final. So this already limits the way


you can implement your code. See if this is

not working now. So and this is one of the


one of the many, sorry, one of the many reasons

why you should not use clone, other than to


clone an array. And I showed you two alternatives.

One is use a static factory method. I call


the new instance. Same like Josh block in

Effective Java that you should buy. And here,


I call the constructor. And again, recursively.

I call again, a factory method on name. And


again, a factory method on color, which even

creates a deep copy. Or I can do the same


thing with a constructor. But you see this

is actually shorter. So this is why I would


prefer to use the factory method. But it both

works. Okay, so here, I call twice a new constructor,


I create a new name object, and I create a

new color object. Okay, and then in name,


we can also look. You see, I do the same thing.

And this now is strings and I said strings.


Now we don't have to call clone because a

string is immutable. So you have to do this


recursively until you reach either an immutable

object or a primitive. If this were again,


like first name object, we would have to continue

with cloning, or copying, like calling the


constructor until you reach either a string,

or a primitive value or another immutable


object. See here also implemented clone.

And then we can also look at color one last


time. For all of them, I have done the three

different implementations here with a static


new instance method, here with a clone method.

And last but not least, here with a copy constructor,


it receives a color object, and then it retrieves

the string from the original object, which


is a string, which we don't have to clone

any further. I'm actually going to talk a


bit about various smaller topics. We're still

on track, talking about the class object,


and all its methods. The last two methods

I need to tell you about are hashCode. And


equals. Actually, they're one of the most

important methods in Java, I think. However,


hashCode and equals are a bit more complicated

to explain. So before I can tackle them, I


decided to push an episode in between to straighten

things up. And to talk a bit about the missing


pieces in this episode. Okay, so let's start.

As you see, I have prepared this demo test


class for you. Actually, we're not really

testing something today. This is really only


to use to demonstrate those few small missing

things. So let's do one by one. And the first


thing is, I want to talk about static imports.
You might remember, I think I talked about
static imports, in the first three episodes,

and I kind of promised you to later on give


you more details about it. The problem at

this time was we hadn't talked about static.


Well, in the meantime, we have, I just didn't

have any better opportunity to talk about


it. And I felt a bit guilty. So I think now,

I should really finally tell you what exactly


is a static import, how you can use it, and

what it helps you. So actually, we used it


all the time. And you might have seen it.

Here on top, I have this import static org


j unit assert dot star, it's just grayed out

because at the moment, I'm not using it. This


is also set here unused import statement.

Now you can see it. And you can also see here,
the regular import or j unit test sub question

is, what's the difference between the two


of them? So this one imports the code of the

whole test class? Well, this one here, a static


import just focuses on all the static methods.

Because in j unit, you know, when we want


to test, we always use these assert methods.

assert equals assert true.

Let's do that now. Like assert. True, you


see, it already helps me true. I mean, when

true is always true. There's a stupid, but


I just want you to see the method. And the

thing is, this is only not working because


I have this here assert and seeing, it's not

great anymore, it turns white, because now


it's in use. So let's actually have a look

at this class, I can jump there, you see even


it says it extends object will no wonder all

the classes extend object anyway. So here


you see, I see the decompiled code. This is

what my ID he can also do to show me the code.


This is very helpful, so you understand better
what happens behind the cover. So you Here
you see a lot of static methods. So this class

actually like groups them and makes them usable


to me. And as you might know, from static

when I talked about static, the way you would


use a static method would be normally you

say class name, dot assert true. Now you can


either use the full fledged class name, which

is org dot j unit dot assert, and then assert


true or if you don't want to use the package,

you would import the class and then you can


just say assert dot assert true. Of course,

there are also other methods, you can have


a look on those, by yourself. actually quite

complicated ones like you can even compare


areas, and so on and so forth, not equals

equals, with message without is equals, and


so on. Well, we have used some of them. So

this means I can also say, assert dot assert


true. But now you see this is not working,

because I have not normally imported the assert


class. So if I would want to do this, I would

have to say org, J unit dot assert, and then


import it like this. Now you see it's not

used anymore, because now I'm not statically


importing it, but regularly, and I'm using

the class name to use the method. But I mean,


when they introduced it, I think this was

with Java five. The reason to introduce this


where it was to just make these statements

shorter, because you don't always want to


write assert dot all the time.

Okay,

and you could also do it as said before, without


any import, this would even be more longer

than you could go without the import. Now,


they are not see, but there it is working.

That's the difference, because now I don't


do any import. Let's put it back. And then
we can go with or without. And if you wanted
like this and the shortest form, you need

the static import and not the regular import.


So that is a static import. And the dot star

means just input all the static members or


members, static is not members, all the static

functions and also the static variables of


the class. So if you have variables you want

to import that are static. This also works


with the star operator here. But you can also

say you import only specific functions or


attributes. So this is up to you. Okay, so

that's all I can tell you about static imports,


I think sometimes they're helpful. More often,

it actually happens, then you would think


that you would import several methods or attributes

that are the same in different classes. If


you have that it's exactly the same, like

I told you about the imports, you can only


import one method name once by using a static

import. If you're not have a second class


that has the same method, you will then have

to use the full fledged, or at least a class


name so that the JVM, the compiler knows,

in this case, I want the assert true method


from this class. And in the other case, I

want the assert true from another class. Okay,


so you can't I mean, there must be a way that

the compiler understands what you're trying


to do. If I only import this statically once,

I mean, then it's just obvious the assert


true is part of the assault class here. Oh,

okay. So that much about static imports. The


next small thing I want to talk about, let's

open this up is default values for different


data types. I think this is quite important.

And also interesting. Because I see many people


that would have here, member variables defined.

And then they would say something like, here,


or for cards, different weight. Like for the
Boolean, they would say false. Or for the
object, they would say novel. And you don't

have to do that. Because now for object, as


well as false for a Boolean is the default.

So this is in my eyes, this is just clutter,


you write code that you don't have to. I mean,

for every rule, there's always an exception.


For example, if this is very important that

this is set to false. And this is really a


specific case and you want to give a message

with it. It might make sense to sometimes


right here explicitly false. But then it also

maybe you should name your variable a bit


different so that it says why this is important.

And because my Boolean now I mean, this might


be the problem. It doesn't say why this is

always false. Okay, so And now let's have


a look at all the different defaults. But

when I say default, this really only applies


for these member variables up here. If you

for example, have a local variable Like Boolean,


B, you can't do that, if I'm not trying to

use it, this is not going to work. If b, this


will give me a problem variable b might not

have been initialized, but it does work with


the Boolean up here. This is going to work,

see, and now it will count as false. So the


if would not be executed the branch. Okay,

but now enough of talking, blah, blah, blah.


You might already be asleep, so wake up. Okay,

so let's make this a bit bigger, so we can


see it properly. Okay. Now, so you see, by

default value, short default value, those


are all zero.

Actually, there are many number types that


we haven't talked about. And this is also

what I'm just going to introduce right now.


Because we totally focused on end, because

this is actually the one that is most times


used. But as you see here, there are also

others. I think I shortly once showed you


bite, and I also showed you one's car. Um,

but there are also others. In my opinion,


this is just the smaller data types, we will

see the ranges very soon are only here because


I think like this or similar, they existed

in other programming languages before Java,


like maybe c c++. In my opinion, this is a

The reason is probably because like something


like 30 years ago, the memory was so expensive.

And that was really the memory space was so


limited, like you would have a memory of,

I don't know, a few kilobytes. Now with gigabytes


of RAM, this is totally a different issue.

So the space end users actually a bit more


bytes. But the space is really not relevant

these days, in 99, and probably 99.9% of the


cases are always use int. So wide and short,

in my personal opinion on something like deprecated.


I mean, this is not true, actually, because

I'm sure someone can tell me there is a specific


case where you would need them. It just that

on average, generally speaking, you should


be fine with an int. And we will look at actually

the sizes of these types in a second. So yeah,


that long is actually bigger, can save longer

numbers than end. This sometimes might be


needed, but also not so often really, I think,

now float and double, as the name implies,


at least for float, they're both floating

numbers. And double, I think the name comes


because it's like double the space or something,

then that of a float. Actually, also these


I hardly use, because first of all, I personally

did not worry too much with these kinds of


floating point calculations. And second, in

case I did, for example, calculating on money


that you would need that. But they are they
are quite problematic, actually, because they
don't calculate properly on the scent, it

can happen that when you have something like


two euro 20 multiplied by, I don't know, divided

by a number of people that in the end, you


lose or you gain a cent. And like in India,

in the financial industry, this is just not


okay. So therefore float and double can't

use be used there. The reason I can't perfectly


tell you but I think it has to do with internally

these numbers of course stored in a binary


format, you know, a computer only knows zero

and one. And then when, from this format,


it's transferred to our decimal format. For

those floating point numbers, then there are


rounding issues. And therefore, when you really

need to have a correct floating point result,


there are various other solutions. One is

to store the number without the floating point,


for example, as a long or end or alternatively

even as a string. And then you do your calculation,


and when it's finished. You insert the floating

point visually at the place in the UI where


it's needed. Which is also dependent on like

local settings, like numbers are formatted


differently in different languages. So therefore,

this is usually the way you would go, at least


definitely in the credit card or in any financial

industry. Okay, so anyway, float and double


are both floating point numbers. What is interesting,

by the way, is like, when you have a constant


value,

like 34 43.31, this here, I mean, this is


a value of constant value. And if I just write

this down like it is at the moment, this is


now by definition automatically a double.

If I want to have this as a float, I have


to say, the capital a lowercase F, at the

end, which makes it up float. So, if I have


like float my float node equals to this, or
he really have to say f at the end, because
if you leave it, I would get a problem, because

it says it found a double, but float is required.


And the same applies actually for int, short

bite, there is just the other way around,


because there is the default. And when you

want to use a short short as equals to 43.


This just works implicitly because Java sees

the space is fitting. And then it will just


implicitly convert the end because this is

really an end to a short. Ever. Let's try


the same thing with a long, long for d3. This

also works because now you try to store the


smaller thing, the end into a long, which

should always fit. Okay. So what else, so


we have object, the default value is now as

I said before, Boolean, the default value


is false. Car. Now this is interesting, it

depends on if you safe if you display this


as a car as it is. And then this is I think

it's called the null character. And I think


this is just nothing or maybe space here you

see there is something it just can't be displayed


by my UI. I mean, here, if I try there's nothing

blue. But here when I go over it, it's displayed


as blue because there is actually something

it just not visible. And I can convert this


character, the default character to an end.

And then it's a zero. Okay? Now, so these


were the default values of the different number

data types as primitives. Okay, and now, as


the next topic, I also want to tell you never

told you so far, all these number types, they


in parallel also exist as objects. Let's have

a look, and then see and discuss why that


is. Okay, so you would have bide my, this

is used already on top. So let's call, let's


just call it b

equals to bite dot value of now, this is a


static method method, which can and should

be used to convert convert, sorry,

a byte primitive to a byte object. You can


also say new byte. But this is just not recommended

because this might use more space. So, I don't


want to go in details because then I could

talk forever for performance optimization.


But this is just creating always a new object,

while the other one might reuse an existing


object of the same value. So, this usually

is good enough. Okay, there's also other methods,


static methods like pars. The difference is,

this works not on a string as far as I know,


let's try to Yes. And let's go into the function

See, I can Also see it here. And this converts


it not to the object, but again to the primitive.

This is the value of it converts it to abide.


He even you can give the radix, like the radix

of 10, or eight or 16, or whatever. This usually,


well, I never really needed. But there are

a lot of lot of functions. What is also interesting


is that these objects, they all extend the

abstract type number, abstract class, we talked


about inheritance already. So you're here

you can see all these different functions


that each of those number types have to implement.

So each of them, you can convert to an int,


long float, double as the primitive value.

The green stuff is, by the way, the Java API


documentation that you can also read online,

short. So this, all these types automatically


will have. Okay, so back. Now, besides offering

these cool methods, that might be helpful.


There is also another reason why these exists

as objects. The reason is, I think, mainly


because there is something called collections

that we will talk about very soon. I think


I even mentioned it shortly, it's something

similar to an array, it's like an array on


steroids. It's just a container that you can

throw in objects. And that's really it, you


can only throw in objects. And so you could

not throw in any primitive. And therefore,


this is also called a wrapper type, because

this object then will wrap around this primitive


type, and can be wrapped and unwrapped. Which

by the way, in the past, when working with


primitives and collections was needed. So

before putting it into the collection, you


would have converted your primitive data type,

like the CMI byte, input, the object would


then have, let's just say collection, let's

just say add, I mean, in reality, it looks


a bit different. But just so that you get

an abstract idea, you would have added this


thing here. And later on, when you wanted

to retrieve it again, you could then say,


wide dot, get the byte value. And then again,

there were people saying all this is just


too much work. And so I think also, with Java

five, there was an auto conversion introduced,


that now Java can work with a primitive and

an object, and will automatically behind the


covers convert a primitive to an object and

an object to a primitive, whatever is needed


by a certain function. Now, this is heavily

in used by almost every developer, I really


don't like it, and I really activate in my

ID, that I get displayed these conversions.


Because for one, this could even be an issue

with performance, because I see functions


that would like convert from a primitive to

an object, and to a primitive and so on back


and forth several times, which is just stupid.

Second, for a primitive, you have the default


value of a zero, that is safe, that will never

throw a null pointer exception. Ever for an


object. When it's not initialized, like here,
the value will be now and then when you on
an object call, b dot byte value, this will

actually throw a null pointer exception. The


problem is you don't see it, because it'll

be automatically be inserted by the compiler


for you. You only see it at runtime and then

you get a nullpointerexception. So really


be careful with these automatic conversions.

I personally hardly ever use them.

Okay, but so, so that you know of each of


these primitive number types There is also

the same type as an object. The names are


pretty much always the same, like there's

a short object. For int, it is integer. So


there's an integer. For long it's long. For

float is float and double, it's double. And


also Boolean exists as an object. Which by

the way, also has static Boolean object values.


So you can even say Boolean be laughter Remove

the bite. Because this is also B, Boolean


b equals to true, or equals to false. But

now this is an object. I can also show, you


know, the automatic conversion works. Even

though this is an object, the aesthetic value


here, can even jump there you see public static,

final Boolean false equals to new Boolean


false. So the cool thing when you use this

is there's only one object that is always


reused, and you don't always say new Boolean,

to save some space. Okay. And now you see,


I can assign this object to the primitive

type, because internally, the compiler will


do this for you, you just don't see it. Okay,

so that's, I think, all I can tell you about


the different number types and their object

variants. Now let's have a look at their ranges.


I said for example, byte In short, they have

smaller ranges. But enough of talking, I think


the best is I just show you. So execute the
test. And we see, let me scroll this down.
I think this makes it easier. Because then

we can see the test and the code in parallel.


Okay, so here, I used the system print long.

Remember, don't use it avoided. Just try test,


it doesn't really matter. I just shortly wanted

to show you the results. Otherwise, in productive


code prefer logging, because it's more flexible

and would probably lead generally speaking


to more performance, okay, but enough. So

here you see. So there are signed types and


unsigned types. Signed means you see, there

is a minus, so it goes from minus 128 to plus


127. Interesting is, this is not 128. But

127. While he is 128. This actually is for


all the sign types. The reason is, the JVM

in your memory of your computer will actually


need this one number to store the information

if it's a minus or a plus. And this is why


they had to take one number away. And they

just decided that minus has one, one more


number than Plus, I mean, they could have

also done it the other way. But this is how


it's done in Java. Okay, so you see, this

is only for very small numbers. 120 minus


128, two plus one and 27 short is already

much bigger. It can store 32,000 something


plus and minus again, one less here on the

right side in again is much bigger. I think


this is like 2 billion or so long, again is

much bigger. I don't even know how long this


number is. Um, yeah, usually you should be

fine with int can in some rare cases you need


a long Yeah, actually, sometimes I needed

a long Okay. And then there's his float floating


point number with the exponent minus and plus

and the double see here even is much bigger


324 to 308 minus plus and the car this one

is unsigned. So, this is why there is no minus


which is also why the size here is 65,000
something is the double size down to the short
because the short has the same space, but

it needs to have it in a signed form with


a minus and a plus. So this is why here we

can store zero to 665,000

Okay, and car as you have seen before, usually


is used not to store numbers, but characters.

But if you convert it to an end, you can also


use it to store numbers unsigned from zero

to 65,000 something okay. I think this is


actually interesting to see all these ranges.

Okay, so these were the ranges let's go to


the next. And so, in order to be able by the

way to show you see here I converted this


two intz and also our This is also interesting

you see here I used actually the object, the


objects and the These are static values, which

gives me the min and max value. This is really


handy. When you need those ranges, you can

just use them out of the box and say min value
max value, because I wouldn't know them. Yeah,

directly, I can just look them up. And Java


will tell me then, okay, let's close this

now. And go to our next test. Because now,


what I want to show you is actually, you can

also save your numbers, not only on the base


10, but also on the base to base eight, and

base 16. So now it depends. I don't know,


if you had this already in school or university,

I'm assuming you had, they should be really


easy for you to understand that, for example,

with the base two, you would store you would


display a number would be displayed differently,

then with the base 10. If you never heard


of this, then don't don't mind this really

is not so important. I think I never needed


to display the number in one of these formats,

decimal was always fine to me. I mean, this


is also the way the value will be stored here
on the left side is always the same, no matter
which bass you use. So this might just be

used, because you are in a certain domain


and a certain business area where you need,

for example, the hex. And so you would, for


example, have documentation that speaks of

a hex value. And so you could have the same


value as you have them in the documentation

here in your code, which would make it easier


possibly to look at the code. However, this

has nothing to do with how they're stored.


I mean, they're still stored on your computer

in your memory. And your computer can always


only store them as zeros and ones. So internally,

no matter what format, you use them internally,


they're saved always in the same format. And

by default, they're also when I print them


out, which I'll show you in a sec, they will

also always be printed out on the base of


10 just like a regular number like you know

them. So this is only a displaying issue in


the code. If you want to display them in the

binary format, you need specific formatting


options. This will be an episode on its own.

So I will not go in detail on this. Now. Also,


I think this is not needed in many cases.

What is also interesting, by the way, I mean,


the space two was introduced with Java seven

only. So this only recently got added. Speaking


as of 2015, before, you had only the option

to store, base 10, base eight and base 16.


Now the Edit base two besides to make this

stuff more readable. I mean, especially with


base two, you will get these long strings

here of zeros and ones. So that you could


easily read this. And also for something like

credit card numbers, you can add these underscores


actually as many as ever you want.

You're just not allowed to do it at the beginning


of the string and at the end of the string.

But I mean, I don't see how this would make


any sense, because this wouldn't help to read

it. So this is why you put them here in between,


you can also add more like here. Now the question

is, is that more readable? In this case? Of


course not. But I think it can be quite helpful,

especially for something like credit card


numbers for long numbers that you can read

them more easily, like on the phone talking


to a colleague, and you want to read out the

number nine you can talk about the blogs makes


it easier. But these underscores again, this

is just the displaying issue in the code.


The way they are stored is exactly the same

like before. So now let's execute the test.


So I mean, so that this gets printed out,

and we can have a look at it. Okay, so here


you see the first one ob this just indicates

I'm storing the number in binary. The number


is given in a binary format. So this is just

the zero. You can use the capital and a lowercase


it's supposed to same. So this one is an apple

On this long thing here, so ob four is binary


format, and undo redo Do you do all this,

you can use your calculator and calculate


it. And in the end, you will see this is this

number in decimal format.

Or K.

By the way, of course, just shortly, binary


format means you can't, for example, use a

three, this will give you an error, integer


number two large, because now we are in binary

format, indicated by the B and zero here with


the base eight, and scroll down. It, it started

with a zero only. So zero and seven means


this is a seven now, but 010 is actually the

eight in the on the base of eight. As I said,


if you know it from like school or university,
you will understand what I'm talking about.
If not, doesn't matter. Not important. Yeah,

you will hardly ever need it. Let's have a


look at it. So as I said, this is the seven,

this is the eight. And this is some large


number. So these underscores are not displayed

in here. This is just to help so that it's


more readable in the code. And the base 16

hex code is started with zero and x. And then


the zero is 01. The F, you know in Latin,

no, I think our numbers are not Latin, their


Arabic numbers. And these Arabic numbers,

they are based on the base 10. So nine is


the last number. And when you want to say

10 you need one zero, while on the hex, you


don't have any more Arabic numbers. So therefore

they used ABCDE, F for 10 to 16. So the F


is actually the 16. Let's execute this. Well,

I was lying to you. It's the 15 in this case,


because we start with the zero. No, yeah,

it's the 15. Because the 16 again, would be


one zero. Okay, yeah. can get really easy,

confusing. Sorry. So anyway,

I mean,

I think it's not so important. It's just interesting


to show off. I mean, like in a job interview,

I think you really should know, Java inside


out. And so I think you should know that this

is possible. The question if you personally


will use it, because you personally in your

project will need it. I don't know, depends,


maybe you need it. But if you need it, it's

here to be used. Okay. So now, I think really


did an in depth view on all these small topics.

And I think this is really now a good base


to talk about hashCode and equals. Going to

talk about the two methods equals, and hashCode.


This tutorial actually concludes my presentation
of all the methods of the Java Lang object
class, equals and hashCode both follow a contract

that ties them closely together, which is


also why I'm talking about both methods in

just one episode. Knowing all the details


about these two methods, will make you a better

programmer today. So get yourself some popcorn,


and listen carefully. So let's start with

the equals method. What does it do? What's


it actually useful for? the equals method

is used to compare two objects for equality,


similar to the equals operator, which is used

for primitive values. But before I'm going


into much more detail, let's first jump into

my ID and see this in action. Now in my ID,


let's first of all, see, what do we need the

equals method for anyway, because so far,


we happily used the equal equal operator,

and this was working. Let's see this again,


with two primitive values, I equals four,

and J equals four. So now I assert, with the


equals operator that they're both equal. And

we get the green bar. Old tests passed, everything


is fine. So i equals to J. Now let's do the

same thing with strings. Here we have a constant


value of Hello, and another constant value

Hello. And each has assigned to its own string,


reference variable. Now, we all Want to compare

these two strings with the equal operator?


Let's try this. And Ted Ah, this is also working.

And I told you a string is an object. So as


this is working, it seems we don't need the

equals method at all. Well, with a string,


it's a bit tricky, actually. Because with

a string, there is some optimization going


on in the background for constant values,

because for this constant value, there's actually


only one and both variables, they both point

to the same object in memory. The variable


is stored in a memory area called stack, the
object is stored in a memory area called heap.
And there's only one, but things get quite

differently. As soon as I add a new string


variable, and always say, string hello, three

is only age. And then I say at runtime, hello,


three equals two, hello, three, plus, concatenate

ello to it, which will be Hello, at runtime.


And just to be sure, let's also print this

that we can see there is really Hello. In


the variable, hello, three. And then let's

assert, hello, one, equal operator Hello,


three. And this is not working, we get the

red bar, nasty, nasty. So now they're not


equal. But here you can see it printed out

Hello. So from our expectation it should have


been equal. So this is something really tricky

with string.

And ensured you should not use equal operator


on objects, also not on strings. Instead,

for strings, there is the equals method. Let's


try this. Hello, one equals Hello, three.

This works, it seems like using that method,


they're both equal. Now, let's have a look

actually at the method. Here we are clustering.


And there is a method equals operating on

an object. It says things like if this equals


to the object given return true. So if it's

the same reference, if it's the same object,


this is actually a performance optimization.

Now it checks that the object is actually


a string. This is achieved by the instance

of operator so that we can safely cast the


object to a string. And so that we can compare

both strings. Interesting thing about instance,


of By the way, which not many people, many

developers know, or at least not all, yet.


This also includes a check for now, if an

object is now this will never be a string


will never be true and will return false.
So anyway, without going into further details,
there's this while loop. And this compares

character by character of both strings. And


only if they're completely equal, it will

return true. So this is how equals was implemented


in the class string. But actually, I told

you, the equals method is a method from the


class object. And yes, it is. Well, it turns

out string is also a subclass of object and


the string class overrode the equals method

here. So then it works on strings as expected.


Okay. So it seems like for strings we can

happily use equals, so that we know that a


string like hello one and hello three is equal.

Now, how are things with classes that we implement


ourselves? Like here I have created a class

car with owner Marcos. It is a Porsche and


it is it has the color silver So it seems

like it has both instances have exactly the


same attributes. So I would expect them to

be the same car. Now let's first of all, try


it with the equal operator, like before. And

this is false. It's not working test failed.


Well, of course, because we have two different

instances here. Let's try the positive case.


portion one, equal operator, my Porsche one

again, comparing it to itself. So yes, this


is working, of course. But it seems like for

to be able to compare Porsche one and Porsche


to we again need to use the equals method.

Let's do this now. For sheet one. Oh, let's


first of all, I want to push it to here. But

let's also do this, my portion one equals


my portion one,

I would expect that to be true. And yes, it


is true. My Porsche one, so it is equal to

itself. Now, let's compare my Porsche one


to my Porsche e two. And let's see if this

works. Huh,
it's not working. We have the nasty red bar.
This was so nicely working with a string,

why is it not working with our car? Let's


jump to this method again. And you see, we're

in the class object. Because in our car class,


we have not overwritten the equals method.

So what happens is, the original method of


the class object is used. And as you can see

here, internally, what happens is, we compare


this which is the object itself, in this case,

my pushy one, we compare it using the equal


operator to the object that is coming into

the method, which was pushy to. And this compares


only the reference variables and not the objects.

So this is false, because we have two different


reference variables.

What by the way, is also possible. To make


this true again, we could assign my portion

to the reference variable of my portion one,


which would mean this object is somewhere

in memory, no variable is assigned to it.


And there is this one object

here in this line, and both variables, point


to it. Let's try this. And see if this works.

Because now actually, we only compare the


same object with each other. Like here. This

compares the reference variables, which now


have the same value. So this would be working.

But this is not what we want. So let's remove


that we really want to compare both objects.

We want to compare this one with that one.


Okay, so let's have a look at the class car.

This is a small class I wrote. And it just


has a constructor and these attributes for

now. And there is no equals method overwritten.


So this is what we have to do. Public Boolean

equals now, I want to compare a car car. No,


this you cannot do in the class object. There

is object. So we have to say object here.


And then later on, we have to cast it to a

car, like we saw on the class string.

And then it's always good to add the override


annotation so that we make sure we have properly

overwritten the method. Now, I mean, this


is not a true implementation. I always return

false, just to see that when I'm in my car


test, not jump there. See, it jumps to me.

I overridden method. Now, of course, when


this always returns false, this will also

not work. So we will have to implement it.


But actually implementing such an equals method

is not so easy. And we need some more theory


for this before we can continue. So let's

first of all, jump back to my slides. Before


we are able to implement the equals method,

we need to come up with a proper design first.


Actually, many developers just skip the design

phase, and simply click on autogenerate. But


this may lead to severe bugs, or at least

two sub optimal performance. Let me show you


how you can properly do it. First of all,

you have to define what it is in your specific


program that makes two car instances equal

or unequal. In your program, are two cars


equal when they have the same manufacturer,

maybe when they have the same manufacturer


in color, or the same engine, the same number

of wheels, the same top speed, the same vehicle


identification number, or when In short, based

on a knowledge of the business you are working


in, you have to decide which fields are identifying,

and which fields are redundant, and not helpful


for the equal comparison. Besides for improved

performance, you need to define in which order


you want to compare the attributes. Are there

any fields that have a high chance to be unequal?


Are there fields that may be compared faster

than others? To implement a meaningful equals


method, you must first analyze all these aspects

in great detail. Let's go through this process.


With my example. I would assume that the car's

top speed relates to the type of engine and


some form. So that seems to be a redundant

field, that will not be helpful for the equals


implementation. So let's just remove it. Let's

just say the number of wheels is always for


in our specific example. So number of wheels

would also not help us to differentiate the


car. What about the VIN?

Well,

this again depends on the type of program


you want to create. For a public authority

like the police, this one is probably the


only proper way of identification. But what

about a program used by the manufacturer itself.


While the car is still being built, and not

sold yet, I would assume the witness of less


importance. But I personally wouldn't know

that in detail. This is what you will have


to clarify with the business people of your

company or your department. Based on their


knowledge, you have to select which attributes

to compare in which order. In my artificial


example here, I'm the developer as well as

the business analyst. So for my example, I


just arbitrarily define that two cars with

different wind numbers can be seen as equal.


Therefore, I will not include this field in

my equals comparison later on. Now, before


you think that's it, I'm sorry, there's actually

some more theory to cover. In the introduction,


I already told you that there is a contract

of equals and hashCode we have to fulfill.


First of all, there are five conditions, our

equals implementation has to comply with,


believe me, it looks much more scary than

it actually is. Let's go through each of them


slowly. reflexivity. An object must be equal

to itself, so that when I call my old car


equals my old car, it returns true. I think

this makes sense and should be easy to understand.


symmetry to objects must agree whether or

not they are equal. If my old car equals some


other car, then some other car equals my old

car must also return true This sounds obvious


and very simple, when in fact, it is not such

a simple condition when it comes to inheritance.


If you have a car class and a BMW class, which

is extending the car class, it could happen


that your BMW is equal to a car. But the same

car is not equal to the BMW is every BMW is


a car. But not every car is a BMW. So you

see, the symmetry rule can actually lead to


some nasty problems. There are quite a few

interesting articles online discussing potential


symmetry issues of the equals method. cover

each contract condition with a dedicated unit


test to make sure your class is fully compliant

with a contract. Our next condition is transitivity.


If one object is equal to our second, and

a second is equal to a third, then the first


must be equal to the third again. This rule

sounds much more complicated than it actually


is. If object A is equal to object B, and

object b is equal to object C, they should


all be equal to each other so that C is also

equal to a consistency. If two objects are


equal, they must remain equal for all time,

unless one of them is changed. So when you


repeatedly compare the same two objects with

a equals method, it should always return the


same result. In other words, calling the equals

method should not alter the object in any


way. The last rule model returns false is

what Josh Bloch calls nonlocality. When knowledge


is given as a parameter to any equals method,
they should always return false and never
throw a null pointer exception. So now, you

know quite a bit about the equals method.


But what is the hashCode method actually useful

for? For processing similar objects are usually


put into a collection. Such a collection in

Java is like a more powerful array, or an


array on steroids, as I often call it.

Besides other things, it allows you to look


up objects not only based on their index position,

but also based on their specific values. This


is where the equals method comes into play.

To speed up this lookup process, the Java


creators added specific hash based containers

that will use the hash value as a grouping


mechanism to reduce the number of equal comparisons

needed. In the optimal case, each object that


is considered unequal by the equal method

will also return a different hash code. This


hash code is used to group the objects in

so called buckets. Now, in this optimal case,


you will be able to find each object simply

by a lookup based on its hash value. However,


there may also be something called hash collisions,

where two unequal objects will share the same


hash code, in which case they end up in the

same bucket. Now, if I'm looking for that


scar, I have to look up the correct bucket

based on the hash code minus 391. That car


will return. However, as there is a hash collision,

I will on top have to do an equals comparison


on a list of two cars in this case, illegal

but inadmissible bad performing hash code


implementation could statically returned 42

for all objects. In this case, however, the


whole hashCode logic would not help at all.

In the end, you would have to do an equals


comparison on the entire list of cars just

as if the hashing logic had never existed.


Okay. Now that I have talked about the general
idea of the hashCode method, I have to further
tell you about the contract that the hashCode

method has to fulfill. The first condition


that has to be fulfilled by the hashCode method

is for any two objects return same hash codes


when equals returns true. To achieve this,

use the same idea Define attributes for both


methods in the same order. Don't worry too

much. Now, if you don't fully understand what


I mean. As soon as I'm finished introducing

you to the hashCode contract, I will jump


back in my ID and show you a practical example.

When hashCode is invoked more than once on


the same object, it must consistently return

the same int value as long as the object is


not changed. This role is similar to the equals

consistency rule, I introduced to before both


equals and hashCode methods must return consistent

results. To fulfill this contract, you should


override hashCode whenever you override equals,

and vice versa. Also, when you add or remove


attributes from your class, you will most

probably also have to adjust your equals and


hashCode methods. Last but not least, aim

to return different hash codes when equals


returns false. This is not a hard and fast

rule, but it will improve the performance


of your program by minimizing the number of

hash collisions. to the extreme, the hash


code contract would allow to statically return

42 for all objects, as Josh block states in


his book Effective Java, however, this could

result in quadratic rather than linear execution


time, and therefore, could be the difference

between working and not working. Actually,


the hashCode method is a rather complicated

beast, I couldn't practically fit in all the


details without risking that you would fall

asleep. Therefore, I have done a follow up


tutorial, that will give you an in depth view

on the hashCode method, which you will need


to understand to become an expert in Java

programming. Below this video, there's a link,


you can click to watch my follow up tutorial

for the hashCode method. For now, that's all


the theory, you need to be able to implement

your own hashCode and equals methods. to round


up this topic, let's jump back into my ID

to show you some practical examples of hashCode


and equals methods. So back to my ID II, you

can see I've implemented both equals, and


hashCode based on the fields manufacturer,

engine, and color, also here and hashCode,


manufacturer, engine, and color. So I've implemented

them based on the decisions I made during


the simulated design phase that I did during

the theory session. So the car clause has


fields like Vehicle Identification Number,

Manufacturer, engine, color, and number of


wheels. But in the design phase, I decided

that number of wheels and Vehicle Identification


Number are not helpful for the way I want

to compare a car. Of course, this is totally


arbitrary. So this is not how you would do

it. I really can't stress that enough. In


your case, in reality, you have to talk to

the business people and find out what is important


and what is not. Also totally arbitrary is

the order that I've chosen. I just thought


about it. And I thought that while there are

millions, or however many colors that for


usually for cars, there are not so many colors.

I think most cars are either black or white,


silver, blue, red. A few might even be green,

or yellow. But that's probably it. So I thought


they there are probably more different manufacturers,

and also more different engines. And I want


the equals method. If I compare two objects
which are not equal, I want to leave the method
as early as possible, because the earlier

I leave the method, the faster the entire


code will run. If two instances are equal,

then usually it has to go till the very end.


So in this case, it doesn't make a difference.

But it does make a difference if it's not


equal. If we can leave the method here. So

for perform performance optimization I have


chosen this order

on.

So this is what I would also ask you to do,


think about a good order to improve the performance.

And if the performance is important, then


you should test it, because you never know

for sure until you test for the performance.


What is important that the order is the same

hashCode and equals. And now, we should also


talk about all this stuff here on top. This

mostly is also a performance optimization,


at least here, this equals object. So, if

I compare the object to itself, I want to


directly return true, because then the reference

variable references the same object in memory.


And so I directly know it's the same object,

I don't have to compare all these things.


So, this is why I have this here. If you have

a specific case, where you know that you will


never ever compare an object to itself, you

might even leave this if a way. Yeah, this


is the this depends. Generally, this is done,

because such a check doesn't also cost a lot,


then this object equals null return false

is actually very important here. This is the


last rule that we have to fulfill that when

an object that we compare is now that we always


return false, which is also important because

otherwise object dot get class would throw


a null pointer exception that this cannot
happen, because now we are already, we have
already left the equals method with false.

Okay. And then the third, if check compares


both classes. So that we make sure that the

object that is coming in to all equals method


is also a car. So that we're not comparing

bikes and cars, for example, or cars and apples


or whatever, right? Because otherwise, also,

this explicit cast to car would also throw


a class cast exception. But now that we have

made sure that they both have the car class,


we can safely caused the object to a car.

And now I think this is quite interesting.


Because now I can easily say manufacturer

equals other dot manufacturer. This field


here is private. But because we are here in

car, even though that this is another instance,


but it's also an instance of car, I can directly

access this private field. So I don't have


to use any method, I can directly access the

field. This works and makes the code I think,


much more readable and shorter. So if it's

not equal, then I can directly leave the method


and say return false. I do this with all the

fields. And if I'm here, that I'm sure that


all the three fields are equal. So I do not

compare number of wheels as well as we equal


identification number, because as I said,

about them, I don't care because number of


wheels, in my specific example would always

be four. So would be the same anyway. And


we equal identification number, that might

be two different cars. But just like, if I'm


only interested in the price of a car, for

example, or the look, then I wouldn't care


that actually, they are physically two different

cars. I would just say well, this is a BMW


with I don't know, that kind of engine and

Lou. So for me, this is the same car. Period.


Yeah. Okay, so that much for the equals method.
Now the hashCode method. This is actually
very complicated, I'm sorry, and it's so complicated

that I've decided to do a follow up tutorial,


as said before, which I really recommend you

to watch. There is a link below this video,


you can click to watch the follow up. So he

only in short about the hashCode method. The


31 year is a prime number and a prime number

he is multiplied with always the result. So


this continues to take the hash code of a

field, which will return some in number

will edit, starting with one, and then multiply


it with 31. And this for each attribute. The

reason is this is an optimization to have


less collisions, because I told you about

the collisions, that this can decrease the


performance. As you see, I'm actually not

really doing something here, I'm just calling


recursively hashCode for each class. And this

is why now we should jump in the other classes,


at least, I can show you all the classes,

but I've chosen engine here in this case,


to see how it's actually hashCode implemented

in one example. So let's jump to engine. Okay,


so the equals method is pretty much the same,

or at least similar. Then in car, the only


difference is here, I added something that

I called optional field, because I defined


that this optional field could also be now.

So therefore, my check here for equals has


to be a bit more complicated. Because I have

to save it's now then I check if the other


field is also now, if it's not now, then this

field is now the other is not so it's not


equal. And if it's not now, then I can compare

both fields. So I'm doing all this again to


prevent another pointer exception. In the

other case, when I don't check for now, my


assumption is that, well, this is a primitive
field, so it can't be null anyway, but for
car, my assumption was that a car always needs

a manufacturer, engine and a color. So my


assumption is, those fields will never be

now, if someone would introduce a bug. And


would forget to set these fields then, of

course, this could produce a nullpointerexception.


But checking for something that is exceptional.

This is what I call rocket code. Because it's


like extra safe code, this is just cluttering

your code, you have to have certain assumptions,


like saying mighty sign for bits that these

fields, these fields can never be now. And


so I trust on that. Otherwise, well, the program

will crash, okay, we have to fix it. But then


the problem is already fixed. And the code

stays clean. And this is important, because


your code should be really readable and maintainable.

Okay, so only four fields where you know,


they can be null at these extra null checks.

Okay. So that much for the equals method,


everything else here should be the same as

in car. Now for the hashCode method. Here,


you see there is some more stuff going on.

Because here, I cannot forward to a hash code


method. But instead, I have here a primitive

long. And for that, because the primitive


fields there, you actually have to calculate

some hash code. And this is a long, and so


we want to like convert a long to an int.

A long has that has like 64 bits, while an


int has only 32 bits. So you want to like

make the long to half its size, and you want


to make it in a way that will result in the

least possible number of collisions. And therefore,


this weird line here. This here does it. This

is actually based on again, Josh blocks book


Effective Java there, he explains it. One,

actually, he doesn't explain it too much.


If you want an in depth explanation again,

watch my follow up tutorial about hash code


there, I can explain you. Now here only insured.

This is a shift by 32 bits. And then this


is an X or Y you again, come like let's say

combine this field. And last but not least,


you do an exquisite cast from long to end

where you throw away Half of the long, but


this whole thing can't explain you in like

one minute, you have to watch really the extended


tutorial. But this is really a very performant

good way to create an end hash code from alarm.


This is the standard default way of how this

is done today.

And the second field here is a string as it


can be now, I need this extra knowledge check.

And I'm not sure if I have shown you this


before. This is like in if it's just shorter,

because otherwise the code would even be longer.


So you have to read it as is optional field

now. If true, then return zero, else return


optional field dot hashCode. So this again

calls the hashCode method of string. This


I showed you in the beginning of this episode,

where the code was like in a while loop, going


over each character of the string, and then

calculating an int value for the string. So


as this is already done for us, we can simply

call the hashCode method. Okay. So, again,


you also see, I have, in this case, two fields.

And in this case, I decided to use both to


differentiate if an engine is equal or not.

And so as I use type an optional field and


equals, again, I use type an optional field

and hashCode in the same order and same fields.


Okay, last but not least, some class now this

is this doesn't mean anything, this is really


totally abstract, I just wanted to it very

short, show you all the different primitive


types they are plus the string object. So

that you see like how the different cases


of equals and hashCode could be calculated.

So let's first of all look at hash code. So


this with long we have already seen, same

one here, float, well float has the same size


32 bits like an end. And then there is a native

function, which will convert the float to


an int to be used for the hashCode. Double

A has the same length as a long. So this is


done in two steps. First of all, it's converted,

again, with a native function too long. A


native function is a function that is not

implemented in Java, but in machine dependent


code. So I can't show you. But again, for

details, watch my follow up tutorial. But


anyway, so long we take and again, we do this

weird line here to convert it to an end. Next


one Boolean. Here again, this weird stuff

here. If it's true, question mark, then 1231.


And if it's not true, then take this number.

All this stuff is really technical might be


a bit hard for you to understand. This is

just really important for performance optimization


to have the least number of collisions. Um,

car is just taken as it is because it can


be handled like a number. For string again,

we call this hashCode method. And for the


other fields, everything that is as big as

an end or smaller than an end, that's relatively


easy because you can just take the value as

it is because a byte will always fit into


an end short will always fit into an end.

And an end of course, should also fit into


an end our K so I know this was really rough

really short. I'm just not enough time to


go in more details. But exactly For this reason,

I have done the follow up tutorial you can


watch. I hope then it will be more easy to
understand. Now last but not least, let's
have a look also at equals. So I think for

the primitive values here, it's pretty easy


because you don't have to use equals If you

can just use the not equal operator.

So if it's if the bytes are not equal, just


looking at the variables without any objects

involved, false is returned. And also see


this is the order I've chosen, I start with

the smallest possible values, because here


checking them is probably faster than doing

all this crazy stuff down here. And this is


why I've chosen the order. All K, with a short

end, long, this is all easy. With float, it's


a bit more difficult, we have to convert it

first to an end, that will has to be converted


to a long, um, Boolean is, again, easy. Well,

actually, if this was a real whoops, if this


was a real implementation, I would have done

it differently, I would have put it to the


top. So this order is also based to explain

you the different types. So in reality, I


would ask you to really think about the order

based on what the business tells you what


is easy to differentiate. And like, then also

you have to think, like, from the performance,


what takes longer to calculate. Um, of course,

it depends if you really need the performance.


And if you do, then always test performance,

because you might think something is fast.


But when you tested, it turns out, it's not

as fast as he would have thought, okay, because


what I'm telling you here is just a rule of

thumb, but I might be totally wrong in a specific


case. So this is also what I'm doing, if I

need a certain performance, I test for it.


In all other cases, I just do how I feel like

it. Or I just use my gut feeling to sort the


values, as I think could be fitting out. Okay,
so I hope you liked this episode about hashCode.
And equals I'm sorry that this is all so complicated

and so long. I just wanted to put in everything


possible, because this is really such an important

topic that he should really understand in


detail. Of course, there is way more actually.

So I would also ask you go to my blog, www


dot Marquess minor spiel.com. I will put up

some links to some extended articles on the


topic on and also you might consider buying

Effective Java from Drush blog, he also talks


about it quite extensively. So

here

I will give you a high level introduction


to the Java collections framework. Unfortunately,

there are several overloaded uses of the word


collection. Let me clarify the various meanings

up front. The different use cases are a collection


without any it relevance as a compilation

or group of things. Second, the Java collections


framework, a library of different interfaces

and classes. Third, a collection as a data


structure. Think of a box or container that

can hold a group of objects, like an array,


for example. For us, the Java collections

interface, one of the two main interfaces


of the Java collections framework, and fifths,

Java util collections, or utility class that


will help you to modify or operate on Java

collections. This episode is based on chapter


11 of the OCA OCP study guide. The book is

packed with knowledge. As a great fan of the


author is Kathy Sierra and Bert Bates. I recommend

you to read this book, even when you don't


plan to get a certified programmer. So what

is the Java collections framework? from a


high level perspective? First of all, it's

more like a library a toolbox of generic interfaces


and classes. This toolbox contains Various
collection interfaces and classes that serve
as a more powerful object oriented alternative

to arrays, collection related utility interfaces


and classes that assist you in using the collections.

I'm going to describe both parts in detail


now. On the next slides, you will see the

interface and class hierarchy for collections.


Unlike arrays, all collections can dynamically

grow or shrink in size. Except before a collection


can hold a group of objects, a map can store

pairs of objects that have some kind of relation,


which ties them together, named key and value.

A value

does not have a specific position in this


map, but can be retrieved with the key it

is related to relax if you don't get it now.


We will look at it in more detail later on.

So here you see the hierarchy of classes and


interfaces, extending or implementing the

collections interface. Just try to remember


some of the names listed here. This is just

an overview so far. As you can see, the collection


interface sits on top of a number of sub interfaces

and implementing classes. A collection can


hold a group of objects, the collection interface

is extended by the interface of set list and


queue. A set is defined as a group of unique

objects. What is considered as unique is defined


by the equals method of the object type the

set holds. So in other words, a set cannot


hold to equal objects. A list is defined as

a sequence of objects. So unlike a set, a


list can contain duplicate entries. Besides

a list keeps its elements in the order, they


were inserted into the list. A queue has two

sides, entries are added to the end and removed


from the top of the queue. This is often described

as first in first out, which is pretty much


like a waiting line in real life works. The
first person queueing up will also be the
first person leaving the queue. Now let's

have a closer look at the interfaces and classes


that extend or implement the set interface.

Hash set linked hash set and three set are


all implementing the set interface. Hash set

is the default implementation that is used


in the majority of cases. Linked hash set

is like a mix of a hash set and the list as


it does not allow duplicate entries like a

set. But it returns its elements in the order


in which they were inserted. Like your list

would do. Chrisette will constantly keep all


its elements in sorted order. But keep in

mind, there is no free lunch. So every edit


feature comes at a certain Cost Of course.

After looking at the classes implementing


the set interface, let's also have a look

at the two extending interfaces we haven't


talked about yet. As the name implies, sorted

set is a set that is constantly sorted. The


navigate will set interface was added which

Java six, it allows to navigate through the


sorted list. For example, it provides methods

to retrieve the next element greater or smaller


than a given element of the set. Next, let's

have a closer look at the classes that implement


the list interface. Every list is the default

implementation of the list interface. Like


any list implementation, it does allow duplicate

elements and it does allow to iterate the


list in the order of insertion. As it is based

on arrays, it is very fast to iterate and


read from an every list. But adding or removing

an element at a random position is very slow,


as this will require to rebuild the underlying

array structure. vector is a class that exists


since JDK one which is even before the collection

framework, which was added with Java two.


In short, its performance is sub optimal.
So So please never use it. Use ArrayList or
linked list instead. So let's directly remove

it and forget about it. The next list implementation


is linked list. As the name implies, its implementation

is based on a linked list, which makes it


easy to add or remove elements at any position

in the list. Last but not least, let's have


a look at the classes implementing the queue

interface. We already talked about link list,


as it also implements the list interface.

However, the fact that it's based on a double


linked list makes it quite easy to

also implement the queue interface. linked


list is the default queue implementation.

priority queue is a queue implementation that


keeps its elements automatically ordered.

It has similar functionality like a tree set,


but it does allow duplicate entries. Now let's

look at the map interface. This interface


has no relation to the collection interface.

A collection operates on one entity, while


a map operates on two entities. A unique key,

for example, a vehicle identification number,


and an object that is related to this key

for example, a car object with the help of


the key you can retrieve the object it relates

to. The interface map is the root of a lot


of interfaces and classes, which we'll look

at now. The class hash table was the first


collection in Java JDK one that was based

on a data structure hash table. So the Java


creators called a hash table. Unfortunately,

this makes it a bit hard to differentiate


between the two. Like vector the class is

deprecated, because of its sub optimal performance,


so let's also remove it and forget about it.

Instead, use one of the other classes that


implement the map interface. hashmap is the

default implementation that you should use


in the majority of cases. A map usually does

not make any guarantees on how it internally


stores its elements. An exception to this

rule is linked hash map, which allows to iterate


the map in the order of insertion. Last but

not least, tree map is a constantly sorted


map. Now let's look at the interfaces that

extend the map interface. As the name implies,


the interface sorted map extends the map interface

and defines the contract of a constantly sorted


map. navigable map again extends the sorted

map interface, and adds methods to navigate


through the map. This allows you to retrieve

all entries smaller or bigger than a given


entry, for example. Actually, there are many

similarities between the map and the set hierarchy.


The reason is that the set implementations

are actually internally backed by a map implementation.


Last but not least, you might have noticed

the Java collection classes often contain


the data structure there are based on in their

name. To choose the best collection for a


given situation, you have to compare the specific

characteristics of data structures like array,


linked list, hash table or tree first. In

short, there is no single best option. Each


one has its very own advantages and disadvantages.

I promise to talk about this very exciting


topic in a later episode. So stay tuned. This

overview of the collection and map classes


that only show you a part of the whole story.

In a later episode, I will introduce you to


the concurrent containers of the Java collections

framework. generics is a topic at least as


big as the Java collections framework. In

the context of this episode, I will therefore


only explain you the bare minimum you need

to understand the collections framework. It's


okay if you have a lot of open questions after
my brief overview. Give both of us some time.
I promise to explain everything one after

the other I would recommend you to subscribe


to my YouTube channel to be informed as soon

as I upload the next episodes of the Java


collections framework. Now fasten your seat

belts. Here, it's going to be a bumpy ride,


I promise. You see this weird stuff in angular

brackets. Just relax. Actually, it's much


easier than you might think. And the first

line, you see I have defined a list variable


my list. And with a string parameter in ANGEL

brackets, I tell the compiler that my main


list reference variable is supposed to be

used only with strings.

Then I create an object of type ArrayList.


And again, I tell the compiler that this object

is only supposed to be used with strings,


and the compiler will ensure that no one ever

tries to put anything else than a string into


my list. In other words, this is what makes

the container type safe. Also, note that I


use the interface list for the variable and

not ArrayList. This makes your code more flexible.


Only at one place you create the object, but

at various places in your code, he will use


it. When you use list instead of error list

for the reference variable. You could later


replace the error list by a linked list, for

example. And all

you had to adjust was this one line of code.


In case you don't really need to specific

methods of a list,

you could also use the collection interface


instead. Always use the least specific interface

for the reference variable. Oh, by the way,


I'm sure you notice the integer 100 that I

use as a constructor argument. This I have


added for performance optimization. As said
before, the collection classes can dynamically
grow and shrink in size. However, aerialist

and all hash table based collections are internally


operating on arrays. When an array based collection

grows in size, it will internally on the fly,


create a larger array and transfer all contents

from the old to the new array. This of course


takes some extra time. What on hardware is

so fast, that is usually should not be a problem.


But on the other side, if you already know

the exact, or at least the approximate size


of your error based collection, this is usually

better than trusting on the collections default


size. In the next episodes, I will look at

the data structures that the Java collections


are based on, which will help you to better

understand performance considerations like


this one. However, to me, taking care of such

small little details, makes the difference


between a developer and a software craftsman.

So I wanted to let you know as early as possible.


Okay, enough, blah, blah, blah.

Let's get back to the topic of generics. Now


in the second line, you see how a hashmap

is instantiated accordingly. As said before,


a map is basically a relation of one identifying

key to one value element. Both these elements


can be of different types. Like you in my

example, I use Vin, the vehicle identification


number as the key and the car object as the

value. This has to be added as a comma separated


list in ANGEL brackets. And the compiler again

will check that this holds true. If you create


the instance reference variable and the object,

both in one line, you can also leave the second


pair of angel brackets empty, as it can be

inferred from the generic type of the reference


variable. This was introduced with Java seven

and is called the diamond operator. Because


the empty Angel brackets in a way, look like

a diamond. Actually, I'm sorry. That's not


the whole story. There are two parts. And

what I just showed you. This was actually


part two, the usage or invocation of a generic

class when you lock in the contract parameter


to be used. But this is only possible if the

method, the interface or the class was defined


to be used in a generic way beforehand. Here

you see a generically defined interface. In


the first line, the interface is defined as

an interface operating on two separate generic


types that have to be specified at a later

time. However, when these types are locked


in, this will automatically also specify the

type, the types, interface methods we'll use.


So, if you see some weird one letter types

in one of the next slides, just remember it


means this is a method that can be used in

a generic way. Okay, now we are ready to look


at some additional utility interfaces of the

Java collections framework. They are implemented


by classes of the collections framework or

the JDK in general, but they can also be implemented


by your own classes, making use of the power

of the collections framework. Well, strictly


speaking, the interface Java Lang iterable

is not part of the framework. But more precisely,


it sits on top of it. It is the super interface

of Java util collection. So every class that


implements Java util collection, will also

implement the Java Lang iterable interface.


Okay, anyway, let's now look at each interface

in detail. an iterator is an object that acts


like a remote control to iterate through a

collection. Let's look at its methods. Boolean


has next returns true if the collection has

more elements. ie next returns the next element


in the iteration. And void remove removes
the last element returned by this iterator
from the underlying Collection. This interface

provides only one method, which will return


an iterator every collection that implements

this interface can be used on the for each


loop, which greatly simplifies the usage of

your homemade collection. In order to plug


in your collection into the for each loop,

you will have to execute two simple steps.


First create an iterator that is able to iterate

over your collection with methods like hasnext.


And next, as we saw on the last slide. Second,

you need to implement the iterable interface


by adding an iterator method that will return

an instance of this iterator implementing


the interface Java Lang comparable defines

a sort order for your entities. The interface


contains only one method you need to implement

which is int compared to if you want to define


a natural sort order for an entity class,

make it implement this interface. return a


negative integer if the object is less than

a given method argument, zero if the object


is equal to the given method argument, and

a positive integer if the object is greater


than the given method argument. What means

smaller or greater is for you to define. For


numbers, that would probably mean that one

is smaller than five, for example. But for


colors, This all depends on how you want to

sort your entities. When you put objects of


an entity that implements the comparable interface,

into a tree set or tree map, it will use your


compare to method to automatically sort all

elements you put into the collection. As you


can see, the Java collections framework has

been greatly designed for extension. It offers


a lot of possibilities to plug in your own

classes. This interface is very similar to


the comparable interface. It allows you to
define additional sorting orders like a reverse
ordering. So the sorting logic is not directly

implemented in your entity, but in an external


sorting strategy class that can optionally

be added to a collection or sorting method


to the Find an alternative sorting order for

your collection of entities. The rules of


the interface contract are pretty much the

same as for comparable. return a negative


integer if the first argument is less than

the second argument, zero if both arguments


are equal, and a positive integer if the first

argument is greater than the second. Last


but not least, let's look at the two utility

classes, collections and arrays, like a Swiss


Army knife. They provide static helper methods

that greatly enhance the general usefulness


of the collection classes. Java util collections

offers methods like sword shuffle, reverse


search, min or max. And Java util arrays operates

on areas and not on collections actually,


similar to the collections class, it allows

us to swap areas or to search through areas


for example, I'm going to take an in depth

look at ArrayList. And the second half, I'll


do a practical coding session. Okay, let's

get started. Error list is the default implementation


of the list interface. As with any implementation

of list, you can have duplicate elements in


your array list. And you can go from element

to element in the same order as the elements


were inserted. As it is based on Aries, aerialist

provides fast access, but inserting or removing


an element at a random position requires more

time, as this will require to reorganize the


list. fast access however, is crucial for

most applications, which is why ArrayList


is the most commonly used collection. to store

data that changes frequently. However, consider


using an alternative container, for example

linked list. I will talk about this as well


as other containers in the upcoming episodes

of my free Java video course. Okay, before


I continue, let me introduce you to two different

terms, which are important to understand in


context with error list, size and capacity.

Size is the number of elements the ArrayList


currently holds. For every element you add

to the list, the size will grow by one capacity


or ever, it's the number of elements the currently

underlying array can hold. The capacity of


the array list grows in intervals. The error

list starts with an initial capacity. Every


time you exceed the capacity of the array,

the ArrayList copies the data over to a new


array that is about 50% larger than the previous

one. Let's say you want to add 100 elements


to an aerialist have an initial capacity of

10. As the list grows, the system will create


six more areas

to take the place of the first. First one


area that can hold 15 elements, then one for

a maximum of 22 elements. Then areas with


a capacity of 3349 73 and finally 109 elements

to hold the growing list. These restructuring


arrangements can negatively impact performance,

you can instantly create an array of the correct


size to minimize these merging activities

by defining the correct capacity at creation


time. In case you don't know the final size

of the ArrayList at creation time, estimated


as close as possible. Choosing a too large

capacity however, can also negatively impact


performance. So choose this value carefully.

I advise you to always explicitly set the


capacity at creation time as a documents your

intentions. For most projects, you won't have


to worry about optimizing performance to too
powerful hardware. But this is no excuse for
sloppy design and poor implementation. Here

you can see a simplified extract of the class


aerialist. Keep in mind, the real class looks

a bit more complicated. This is just meant


to give you a more concrete idea of what the

class ArrayList looks like. As you can see,


error list is just a class anyone could have

written. Given enough time and knowledge,


there is no black magic, you can find the

actual source code online. However, don't


rely too much on internals that you spot them

the source code as they may change any time


if they're not defined in the Java language

specification. Default capacity is the initial


size of the array, when you don't specify

it as I recommended before element data is


the array used to store the elements of the

ArrayList in size is the number of elements


the ArrayList currently holds get add and

remove are some of the many functions ArrayList


provides, we will look at those methods now.

So, let me give you a short overview of the


methods of the ArrayList class. To make things

easy for you, I have broken up the overview


into methods belonging to the Java util collection

interface, and methods belonging to the Java


util list interface. When I talk about other

containers in later episodes, implementing


the list or the collection interface, I will

refer back to this episode. Instead of repeating


myself over and over again. Make sure you

are subscribed to my YouTube channel. So you


will be informed when I release episodes about

these classes also. Okay, so let's start with


the methods belonging to the Java util collection

interface. The contract of the collection


interface does not guarantee any particular

order, and therefore does not provide any


index or order related methods. So here you
can see the first set of methods that implement
the collection interface. So what I say about

these methods does not only apply to ArrayList,


but also to all classes that implement the

collection interface. The method Boolean ad


appends the element to the end of the collection

to the next empty cell of the underlying array.


Boolean at all appends all given elements

to the end of the collection. The stuff in


ANGEL brackets is related to generics. In

short, it ensures that no one can call such


a method with the wrong arguments. From now

relax. I will tell you more in my upcoming


episode about generics. Boolean remove removes

the first occurrence of the element you specify


from the collection. Boolean remove all removes

the given elements from the collection. The


iterator method returns an object usually

use an a loop to move from one element to


the next element of the collection. Step by

step you say I iterate over the collection.


Hence the name iterator. incise returns the

number of elements of the collection. Boolean


contains returns true if the collection contains

at least one instance of the element you specify.

Wide clear removes all elements from the collection.


Boolean is empty. This returns true if the

collection contains no elements. And to array


returns an array containing all of the elements

of the collection.

Alright, let's move on to the methods of the


Java util list interface. The methods are

similar in part to the methods we just looked


at, but they differ in that they require an

order on the elements of the list. So here


again, you should know that everything I say

about these methods does not only apply to


every list, but to all classes that implement
the list interface. This add method with an
index parameter. It's actually more like an

insert method. It allows you to insert an


element at any index position of the list.

Instead of just adding the element to the


end of the list. And the process the elements

of the underlying array will be shifted to


the right and migrated to a larger array if

necessary. The remove index method allows


to remove an element from any index position

of the Similar to the Add method we just looked


at, this might require to shift the remaining

elements of the underlying array to the left.


The get by index method returns an element

from any given position of the list. The index


off method takes an object and returns the

index of the first occurrence of the element


in the list, or minus one if the element is

not found. In last index of returns the index


of the last occurrence of the element in the

list, and SP four minus one if the element


is not found. List sub list returns a view

of the list starting with the position you


specify as from index and ending one possession

before the one you specify as to index. Last


but not least, the sword method sorts the

list following the order of the given comparator.


Alright, so let's end the lecture session,

time to move on to some practical coding.


So now I'm in my early and you can see I have

prepared a little test method. So we can do


some practical coding with ArrayList. I have

already created an instance of ArrayList.


And I've assigned it to a reference variable

of type collection. Now, this might be a bit


counterintuitive at first, because why is

that not ArrayList? Or at least list. While


there is a reason to it. And let me cite Robert

C. Martin, he says, a good architecture is


one that maximizes the number of decisions
not made, or the number of decisions D fared.
And this is such a situation, because by making

this collection,

I mean, you would create this instance for


a reason, of course, and you probably would

forward it to either other methods and or


other objects. So now, if you make this an

ArrayList, this will really limit all your


other objects, because they all only have

to work on an ArrayList. But now, the requirements


of your business, I mean, requirements, usually

they change very fast as you know. And if


they change, like for example, an ArrayList

can hold duplicate elements. But now there


might be a new requirement that tells you,

you cannot have duplicate elements, you have


to prevent that you have duplicate elements.

So you might want to use hash set here. Now,


if you use list or every list everywhere in

the code, it will be very tough to change


your mind, you will have to touch a lot of

code, which is very dangerous. But if this


is a collection, a collection can be so so

many things. And so it will be much easier


to change your mind. Because all you will

have to do is change the instantiation of


the object that is actually being used. So

if you can, like of course, this limits the


number of functions that you can use, because

the collection interface is less powerful


than the list or the error list interface.

But if you can, like if you only need the


methods of the collection interface, well

then do it like this. later on. We will switch


here to a list interface because I will also

show you methods that only appear in the list


interface. But we'll start with a reference

variable of type collection. And then you'll


also see the difference. Okay, what else can
you see in the single line? Besides you might
spot that have used generics in the angel

brackets, so we have created a collection


of type string. And here, you might spot the

so called diamond operator that was introduced


with Java seven. Well, because we do both

in one line, we do the object instantiation.


And we create the reference variable in one

line. The compiler directly sees this must


be a string. And this is why here we can use

the diamond operator. But we could also do


it the old way by typing here string. This

is just a bit shorter. Okay, and last but


not least, you should notice here I wrote

initial capacity, which is a constant, which


I have defined here as private final int,

initial capacity five. Now you might say well,


you could have also said just five I mean,

this is faster. Well, at first, it might seem


so but this is a so called magic number. And

this is evil, because it makes it so much


harder for the next developer to know what

this five actually means. Like not everyone


knows that an aerialist has an initial capacity.

But if you use the constant value here, you


document in the code your intentions. So this

is actually quite good. And I recommend you


to do it also. Okay, but now let's already

start using some methods. I mean, we're not


doing I'm not going to properly program something,

but we're just playing around with the methods,


so you get a better feeling of like what aerialist

is all about. And as this is now, a collection


reference very Oh, of course, you'll only

see all the methods of the collection interface.


And we'll start simple with ADD. Of course,

like one limitation that we have now is we


don't see any index based methods, which was

also the reason why before in my slides, I


divided the methods into methods that are

related to the collection interface, and methods


that are related to the list interface. Because

now I can also go back to the slides and compare,


because now we're doing the methods of the

collection interface. So this is a collection


of type string, so I can add a string. So

let's add B, capital B. Let's add some more.

later on, I'm also planning to sort the error


list, which aerialists allows. But right now,

with the collection reference variable, we


will not be able to sort it. But stay tuned.

I'll do it soon. Oh, okay. And I mean, even


though we have a reference variable of type

collection, still, the fact that we have an


ArrayList influences that we can have duplicate

elements. So let's do that. Maybe I should


also add one eight here. Okay, and now let's

count how many numbers elements I added 123456,


the initial capacity or ever is five. So that

means when you add the sixth element, internally,


within the execution of this method, the error

list will realize, well, the capacity is insufficient,


will then create a new array of a larger size,

and will then migrate all the existing data


to the new array. Before the next element,

the second he is added, which costs some extra


time. But really don't worry, I mean, in the

regular situation like this five, six elements,


the performance difference is altra altra.

Low. So never, I'm never worry, in such situations,


this should really be only, like only think

about this when it gets a problem. And usually,


this could get a problem if you have like

1000s or 10s of 1000s, if not a million of


elements. So it always depends on the amount

of elements, you have the amount of iterations


that you do. Okay. So and then we can also
print the error list as it is now, there are
two different ways ArrayList has also a two

string method. So I could directly say system,


out print ln elements. But I'm doing it a

bit more complicated, because I want to show


you how we actually iterate over the ArrayList.

And this is because every list, and every


collection implements the iterable interface,

which is used in this new for each loop. And


so we can iterate over the array list by saying

string string, and then column and then elements.


And what is required to iterate over this

list will be done here inside and you don't


see it. This is all done by the compiler for

us internally. In short, I can tell you, there


is an iterator method that I showed you showed

Before, which will then be used. You might


also check my last episode where I introduced

you to the iterable. And the iterator interface,


both will be used here. For now. I mean, it's

enough, if you see, you can use the ArrayList


and the for each loop. And now we can print

out each element separately, which of course


gives us a bit more flexibility. Like I could

print something else here also. Okay. So this


is called iteration going over the collection,

element by element. And I also want to show


you, let's comment this, oops, let's comment

this out. I also want to show you that which


is a feature of list, this order, how we added

the elements, AB AC E, will be also exactly


the same order as the elements are printed

out, which would be different if we had a


set. Okay, but enough of talking, let's already

execute it and see it in action.

Okay, so here you see a B, A, C, E, exactly


like we added that, which is a feature of

list. Okay, now that we added elements, we


could also remove some elements, which is
also just as easy we move. And now on the
collection interface, I can't remove by index.

But I can remove by stating the object that


I want to be removed, which by the way, internally

uses the equals method. If you don't know


about the equals method, I also have a video

about the equals method. So it goes over each


element and checks by using equals, which

is implemented in the string class. If there's


a is equal to one of those elements here,

and will then remove it. You might also notice


I have two A's. So now it's interesting to

know, like will the first a be removed will


the second AB removed of or both be removed?

And there is another tip I have for you. Like


if you have such questions, you can look for

a book for video tutorial, you can look in


the API and so on and so forth. But you will

never be as Sure. And probably also never


be as fast if you just write a simple test

like this. And you just try it out for yourself.


I mean, how pragmatic How cool is that? Because

the code doesn't lie. If you see it, he will


be sure that it behaves like you can see it.

So let's do this and check which element is


removed. And here you see B, A, C E. So the

first a is missing? So the answer is the first


element is removed, not all A's are removed.

Okay, so what else can we do? Let's check.


We can also ask for the size. Let's make this

a bit simpler now. To have it as short as


possible. So now we have 1234 elements. I'll

copy that copying some code that you will


reuse is just safer not to introduce any typo,

or K. And as long as you're just copying the


code and not duplicating the code, it's also

fine. So this supposed to give us the number


of elements. Let me document this out. So

we just see the number of elements. Let's


also do it directly after instantiation of

the object. So I expect here to see a zero,


no elements included. Or I mean this would

be another alternative possibility that this


would throw an exception if the list is empty.

So let's check that execute the test was actually


not really a test. I'm just experimenting

but here. So you see it return zero and the


first line and then four. So this is the size

method. You can even ask, Are you empty? Which


should probably here say Yes, true. And here

probably false. And there is true and false.


Okay. So let's now switch Over to the list

interface. And let's also play a bit around


with that. You see, I have not a reference

variable of type list. And I can use all the


methods exactly like I used them before, because

the list interface

extends the collection interface. So it includes


all the methods that the collection interface

has. But on top of that, we now have more


methods

than just the methods of the collection interface.


For example, I can insert an element by giving

an index position. So I could for example,


say, at index position zero, at me, I don't

know T and S at index position two. And then


let's use the simple fast print odd method.

Let's remove this because it'll format the


list in a one liner. But let me just show

you what I mean. Okay, we still have the true


we can also remove this. Okay, but for now

it's fine. So we have T, because we added


that at index position zero, which means this

will be inserted where a was before. Before


I added that at index zero, this was the index

zero. So this, put it to where a was before


and then shifted everything else to the right.

And this is why now this is nice to see it


like this in one line. Because you see, this

is all shifted to the right, which when I


remove an element, the opposite happens. Like

if I remove the s, everything will be shifted


to the left. But let's see this later. Okay,

and we added the S at index two. So now this


is index 01 and two, which again shifted the

rest to the right. Okay, so let's also remove


something, let's do this here. Let's say I

remove index. And now let's see, I remove


index one, which is which should be the B.

Okay. And there, it seems I am wrong because


the a is still there. And the B is still there.

Let us see. Well, of course, because it's


a bit confusing. As I added the T at index

position zero, a is now index position one,


and this one was removed. So removing by index

is always not so easy. Really, I have to tell


you these index based methods, I hardly ever

use them. Normally, you're fine, actually


with most of the methods of the collection

interface, which again tells you like, often


it's a good idea to use collection here. Okay,

so this actually inserts an element. Okay.


By the way, let's increment this a bit, just

for demonstration purposes. I mean, this is


not so flexible. I mean, really, as I said

in my slides, you should really think carefully


the number of elements that you need. Just

here, it's different because we're playing


around, because I want to show you the difference

again in the example between the capacity


and the size, because the size of the list

is the number of elements. Let's do this here,


and not the capacity, because my area with

a capacity of 100 the area will be 100 elements


big even though they're empty, but the size

however, will be much smaller. And here you


see the size is four and not 100. So there
is a difference. Okay. Now we can also ask
for the index of a certain element. Let's

do this here. Index off and there is also


last index off and also is empty. Yeah, this

we should also use. So index off. Let's use


the aim. Yeah. Which is maybe we should remove

that. to not make it too confusing to keep


the A where it is. So now index off gets you

the first index of an element. So I would


expect that to be zero now, let's see this.

And they receive zero. And we can also say


last index of, which should be the second

a.

Check that. And you might ask, Well, what


do I need the index for? All you can use that

to more flexible, like combine the methods


now that you have the index, you could also

say like, like, remove this index or so on,


I don't know, might be helpful. Okay, so now

I can also show you the clear method. And


the is empty method. I think the is empty

method we already saw. But now let's use rim

clear. This method is void, so I cannot cannot


print it. But I can put it here, clear, will

empty the list. And then we'll ask

is it empty now. And we can also print out


the list. An empty list, which is also interesting,

because this would be another question. Can


I print out an empty list? Or will this again

throw an exception maybe? Let's test it. And


you see yes, it is empty. And you can print

it. It's just the square brackets and there's


nothing in there. So this was an empty list.

Okay. So I think that's already it. A really


short introduction, some practical coding,

I really recommend you to do the same fire


up your ID or your text editor and play around

with the methods of earliest. I know there


are many, many more methods of course, it
just that in this video i don't have all the
time. So this is just meant to give you some

motivation to play around with it by yourself.


Okay, that's it for this episode. If you have

any questions, leave them as a comment below


this video. And please remember to give me

a thumbs up before you go. Thanks for watching,


and see you next time.

You might also like