Java Lesson 04 – Classes


A big part of learning how to program, is knowing how to use and create classes. So far we have already seen a couple of classes: System and Scanner. These are all classes included with java. Things that weren’t classes were int and double. Those are primitives.

Classes in general start with an Uppercase and each subsequent word is also capitalized, example: InputStreamReader. When you initialize a class you always use the new keyword: Scanner scanned = new Scanner(). Primitives on the other hand can be directly initilized: int i = 10;

Now let’s create our first class. Create a new project and call it Lesson 04. In the project right click the src folder -> New -> Class -> name it Animal (make sure public static void main(String[] args) is unchecked) -> press Finish. An should have been created now with the following code inside:

The keyword class is used to create a class and public means that it can be used by other classes, it’s publicly available. The name of the class is Animal and should be the same as your .java file. Everything between the {} will be part of your class. Something that you will also need to know is that all Class inherit the Class Object. This means that all classes are of the Object type.

Next just like the previous lessons create a Main class where you initialize our Animal class:

In this line the Animal horse = is where you create a new Object called horse with the class type Animal. With = new Animal(); you initialize your Animal Object called horse with the class Animal. So to initiate a new class the syntax is: <class type> <initialized object name> = new <class type>(); . What the round brackets are for at the end we will go over later.

When you run this it will print out something like: Animal@e53108, which is basically <class>@<hash>. The hash is used by the compiler and you will probably never have to do anything with that. This print out doesn’t really tell us enough. We want it to print out that its a horse, but so far our Animal class doesnt know its a horse yet.

So lets first create two functions: One to set the type of the Animal class and One to get the Type.

Lets first create the function that will set the type of our Animal.

Here we created a function called setType which takes one parameter that is of the type String.

Next create a function that will get the type from our Animal.

The getType doesnt need any parameters, but it does have a return type and it’s a of the type String. If a class doesnt have a return type it will be called void, like the setType function.The syntax to create function is basically: <plublic/private> <return type> <function name>(<parameters>){}

The getType function is probably also give you an error, because it has a return type defined but its not returning anything, we will fix that next.

To actually make the class remember it’s type we will need to create a class variable. At the top of you class (inside the {} ) place:

So if your Animal object doesnt have a type set, it’s default type is None. To make the setType function set the class variable instance add: this.type = type; to it. To make the getType return the type add return type; to it.

Result SelectShow

The this. in the setType is to reference the class variable. In  the setType function there are two variables with the type name, the one that is given when the function is called and the class variable. When you put your cursor on the type variable it should highlight where it’s being used. The keyword this is used to call the current instance of the object and call its variables or functions, it’s not always necessary to use, but to make the distinction between the class variable and the one given it is in our case.

Now to change what the Syste.out.println prints out we will need to override the toString function of the Object class which all class inherit. This function has a String as return type. In this String we are going to return our type.

Above this function you see @Override. This is an annotation. This annotation is used to tell the compiler is overriding a function that it inherited from another class. Basically this means that it will just throw an error if it’s trying to override a function that doesn’t exist yet. Try change the function name to tooString for example. It will give you an error, because that’s a function it doesn’t know. The same thing if you try to change the return type to something else.

Now when you run the following code in your Main class:

It should print out: Animal type= Horse and Animal type= None.


The assignment is to add a name and weight to the Animal. So create a setName and getName, the name is a string. Also create a setWeight and getWeight and weight is a double. Finally change the toString function to also display the name and weight of the animal. To test if everything is working create 10 animals with different values.


The examples and the solutions to the Assignment you can download here

Special note

A String is also a class, not a primitive, even though you don’t need to use new to initialize it. String is an odd one in this. Because String is a simple class and it’s used a lot, java added a way to optimize memory use. When you create two different strings with the same value, they will have the same reference in your memory. You can call new String as well to give a new reference, that is why when comparing Strings you should always use equals, which checks if the values are the same.


Java Lesson 03 – User input / Ifs

User input

Now that we had some of the basics lets do some ‘real’ programming. We’ll start with something simple: accepting user input. As with everything there are multiple ways of doing this. We’ll do it with the Scanner class. The Scanner class is a java class used to get user input lines in the console. The constructor of the Scanner class needs an InputStream. This means that to create a Scanner object an InputStream object is needed. In our case to ‘listen’ to what the user is typing we will use the This will give us the InputStream of the system, which is in the console.

Lets try that with an example. Create a new project called Lesson 03, create a Main class and copy in the following code:

When you copy this code in and press ctrl + s, to save, there will be a red line under Scanner meaning it has an error. This is because it doesnt recognize the class Scanner. To fix this we need to import it into our Main class. An easy way todo this is to stand with your cursor on the error and hit ctrl + 1 (or right click and press quick fix), this will bring up the quick fix menu. In this menu you should be able to choose to create your own Scanner class or to import the existing java.util.Scanner class. Choose to import and hit ctrl + s again to save. Now you shouldnt have any errors left. (I wont be telling you to save again, you need to save your code to run it and you need to save it for eclipse to compile and check if you have errors)

When you run this program it will say Firstname: and then pause. Now put your cursor in the console and type your first name. When you hit enter the program will continue and ask for your lastname. Fill it in and hit enter again and it will print out your full name.

As you might have guessed scanner.nextLine() will pause your program and wait for you input and when you have have typed something and have pressed enter it will put what you typed in the lastname String. How it does this I dont know. All I know is that it listens to the InputStream we gave in the Scanner constructor. Its kind of like using a tv. We know how to turn it on and we know how to change channels, but we dont know how it does this. Same goes with many java classes. You dont have to know how they do it, you only need to be able to work with them.

If Statements

The programming we have done so far is pretty liniar. Most of the time you will want certain pieces of code only to execute when a certain comdition is met. (.lenght() gives the number of characters in a String)

Those are all the basic ifs. Now the firstname and lastname program we had and print out a message if they are shorter than 3 characters or longer than 16. Do this in 4 different ifs and try to use 4 different conditions.

Result SelectShow

Our current program has 4 ifs it will always check, which isnt really necessary. If firstname < 3 is true it will still check if firstname > 16 too. You can improve this with an if else construction.


Besides making it ask for lastname and firstname make it also ask for your adress, city and phonenumber. Also create an integer error that tracks how many things are filled in wrong. If there were no errors print out that everything was filled out succesfully.


The examples and the solutions to the Assignment you can download here

Java Lesson 02 – Numbers

Learning about numbers

In the previous lession you learned about the Object type String used to contain text. In this lession you will learn about the various object types that can hold numbers.

We will start with creating a new project. Calls this project Lesson 2. After that create a Main class again, just like in the previous lesson. If you forgot how to do that look it up in Lesson 1.

The most used types for numbers are Integer and Double. Lets start with Integers. An Integer is most often refered to as an int. Integers are always whole numbers with no decimals.

Try the following example:

As you can see in the example above an int can be converted to a double, but a double cant be converted to an int.

Basic Calculations

Lets start with some basic calculations answers are down below, but try solving them yourself first before looking at the answers.

Some basic math first. Remember it is * / before + –

Answers SelectShow

Next some calculations with round brackets. Calculations inside round brackets go first.

Answers SelectShow

When calculating with double and ints make sure to watch out what you are calculating with, because ints are whole numbers and always rounded downwards. Again, guess what the answer will be and figure out why that is.

Answers SelectShow

Now you might be wonder what the use of integers are and why not just use doubles for everything. For 1 integers take up less space in your memory and for al lot of calculations double just isnt necessary as you will see in coming Lessons. For now its just important that you know the difference between the two.


You have 3 numbers 8, 3, 2 you can choose yourself whether you use them as a double or integer. You can use each number only once and you need to use them all.

Try get the following results:1) 9.0
2) 3
3) 2
4) 12.0
5) 7
6) 1.0
7) 4
8) 5

Answers SelectShow


The examples and the solutions to the Assignment you can download here

Java Lesson 01 – String basics

Creating a new Project

note: everything about programming is case sensitive make sure to use the right case.

In eclipse at the top right click File -> New -> Java Project. You will now have a New Java Project wizard. Fill in the Project name: Lesson 1 and press finish. Is that it? What about the other options? Don’t worry about the other options for now. It’s all fine. You now have created your first project.

Ok so now you might be wondering thats nice and all, but what is it for? A project is the shell of your programm. Its the container of your class files. In it self it does nothing. Its mostly made to make your improve your workflow and keep things organized. Lets continue into making this project a runnable program.

Go into your Lesson 1 project and right click the src(source) folder -> New -> Class. This will open up a New Java Class wizard. Fill in the name: Main and put a tick infront of public static void main(String[] args). When you’ve done that press Finish.

Inside your src folder should now be a (default package) and inside that a For now you can ignore the (default package) we’ll go into packages later on you can ignore that for now. Open the and you should see:

Everything that starts with // or is inbetween /** and */ are comments, remove these for now. Now than lets starts simple and add to the main:

Ok let me explain this piece of code. String s = “Hello World!”; is how you define a variable. String is the variable type, s is the variable name and “Hello World!” is the variable value. And in java you have to end every line of code with a semicolon. Strings are used to store text in, values of a String variable have to be inbetween double quotes. The s is a variable name you can basically call it whatever you want as long as its not a known variable type, something like String String = “Hello World!” would give you errors also variable names have to start with a letter and may only contain letters, numbers or underscores, so no spaces or starting with numbers. There are more variable type, we’ll get into them later.

The System.out.println(); is javas way to print stuff to the console. In the above sample we will be printing the String s. Its not really something you need to understand, just know how to use it. Its mostly used to debug your code.

Now lets teach you how to run this. Before running your code you always need to save your code, use ctrl + s. You should save quite often, because after you save it recompiles internally and shows you if you have any errors. What happens if you run your code is that it compiles and runs your code. Eclipse does this all automatically for you.

There are multiple ways to run your code:

  • Right click -> Run As -> Java Application
  • Select the and hit the Green circle with an arrow inside in the eclipse toolbar
  • Select the and hit ctrl + F11
  • Select the and go to Run -> Run in the eclipse top menu bar.

After you’ve run it, your console log should dsiplay that is was <terminated> and there should be Hello World! in the log. Congratulations you have now created your first program.

Playing with strings

This bit is where you get to try out code yourself. What do you expect the results of the following pieces or code are? Be sure to try them out one by one.

Besides System.out.println there is also System.out.print which prints everything on the same line.

Read after trying out all the examples SelectShow


This assignement is optional. You can move on to the next Lesson if you want.

Assignment: Create me some ASCII Art. Before you ask me what ASCII Art is do some research yourself, it’s pretty easy to find out.

Warning: Try not to use a \ in your string it will give you errors. If you want a \ you will have to do a double \\. Ill explain why that happens some other time.


If you want my project with the Hello World and my ASCII Art download it here.

Unzip it somewhere on your pc, not in your workspace. In eclipse: File -> Import -> General -> Existing project into workspace -> Browse to where you stored the Project -> Tick copy into your workspace -> Press finish.

You can now delete where you stored the project.