java

Java Lesson 05 – Inheritance

In this lesson we are going to continue with the classes from the last lesson. Do create a new project called Lesson 05.

Object instances

Look at the following code. What do you expect the System.out.println to print out? Now run the code. Where you wrong or correct? Why do you think that happened?

With the Animal b = a; you give b a reference to a, making both a and b point toward the same Object instance. So when you change a, b will also change.

Now look at the following code and try to guess what will happen again and try it out.

When a gets a new instance that doesnt mean b will also get a reference to that new instance. The b object will keep having the Miranda instnace that’s later renamed to Miranda.

Like I’ve said before all classes inherit the Object class this means any class can be cast to Object without any problems.

Inheritance

To make one class inherit another class you use the extends keyword. Now lets create a Horse class which inherits the Animal class. In this class also @Override the getType functions and directly return the correct type, so they dont have to be set anymore.

Now you should change the Animal class to an abstract class, because when you need Animal classes they should just create seperate classes for them.  You can also delete the setType function as that shouldnt be used anymore and change getType into a abstract function that should be overriden by classes that extend Animal. So far we used the toString() function to print out our animals, we are now going to create a print function in Animal instead.

An abstract function can not have any functionality so it doesn’t have curly brackets. Abstract can only be created in abstract classes and when a class inherits an abstract class it will be forced to create all abstract functions in that class otherwise it will give errors. Give it a try by creating a Cat class which extends the Animal class. Also give this class two new functions isClipped that returns a boolean and a setClipped which sets if the cat has been clipped. Also @Override the print function to print out whether or not the cat has been clipped.

Result SelectShow

Now if you create an instance of the Cat class and print it, it will show whether or not your cat has been clipped.

<h2>Assignment</h2>
Create two new functions in the Animal class called setAge and getAge. These functions will take an int. Also create an abstract function called getAverageAge with an int as return type. Next create some more animals and like the cat try and think of unique functions and variables to give them and override the getAverageAge and getType correctly in them.
<h2>Download</h2>
The examples and the solutions to the Assignment you can <a href=”https://dl.dropboxusercontent.com/u/3096920/tutorials/java/Lesson%2005.zip”>download here</a>

Java Lesson 04 – Classes

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 Animal.java 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.

Assignement

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.

Download

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.

 

Forge Lesson 02 – Creating a block

In lesson two we are going to add a block, which if right clicked will spawn a sheep. We will continue with the workspace from last time in which we created an item which spawns pigs. You can download the code at the end of the previous lesson

We will start with creating a new class named BlockSpawn in the noppes.tutorials package and make it extend the Block class.

Next we need to create a new BlockSpawn object and register the block in the GameRegistry in the Tutorial class init function.

Run minecraft and you will see the block in the tools creative tab. Again it will have no texture and no name.

You can give it a name like with the item by adding the following line to your en_US.lang

Now to fix the texture you will need to create a new package: assets.tutorial.textures.blocks and download the block texture or create your own and put it in the package. To point the block texture to the correct location call setTextureName with a string containing the modid:texturename

If you run minecraft again the name and the texture should display correctly.

Blocks have an onBlockActivated functions which is called when a player right clicks a block. To make the block spawn sheep we will need to overwrite that function.

Just like with the item we dont want it to spawn client side otherwise it will ghost. To give it a random color we use world.rand.nextInt(16) is for. That gives a random integer between 0 and 16 not including 16 itself.

Note: In 1.6 setBlockName used to be setUnlocalizedName and setBlockTextureName use to be setTextureName. Basically the same as with Item. I wouldn’t be surprised if mcp changes it back in the future.

Download the Code

 

Forge Lesson 01 – Creating an item

The first lesson will be to create a simple mod, which adds an item that can spawn pigs.

First start with creating a package for our mod (in eclipse right click the src/main/java folder -> new -> package). Call the package noppes.tutorials.  Inside this package create new class called Tutorials (right click the package -> new -> Class).

To the top of the Class add the annotation @Mod with the parameters modid=”tutorial”, name=”Tutorial”, version=”1″. Inside of the class create a new function called init, with the annotation @EventHandler which takes the paramater FMLPreInitializationEvent ev.

Your class should now look like:

Next create a new class called ItemWand which extends Item:

Inside your init function in the Tutorial class create a new ItemWand object with the integer 4000. Also call setUnlocalizedName with an unique item name and setCreativeTab with the value CreativeTabs.tabTools.

Next run minecraft, open a creative world and in the tools tab you will see your item. It will however not have a proper name and no proper texture. Lets fix that next.

First create two new packages: assets.tutorial.lang and assets.tutorial.textures.items in the src/java/resources folder. Next download the wand texture or create your own and put it in the items package. After that create a new file in the lang package called en_US.lang.

When you ran minecraft and checked the name of the item, it should have shown something like item.tutorialwand.name. The tutorialwand is the name we gave it in the setUnlocalizedName function earlier. Now open your en_US.lang with a text editor and add the line:

To point the items texture to the correct location call setTextureName with a string containing the modid:texturename

When you run minecraft again and check the tools tab, it should show the proper name and texture.

All thats left is to make the item spawn pigs. To do that add the next function to your ItemWand:

The onItemUse is called when a player clicks on the ground. Depending on what part of a block (top, bottom, sides) is clicked the face integer has a different value. When the top of a block is pressed the face value is 1, since we only want to spawn it when the top is pressed we return false if the top isnt pressed. The world.isRemote is to check if its called client or server side. You should only spawn new entities server side otherwise ghost entities will appear.

Side note: language files always go into the assets.<modid>. lang and item textures in the assets.<modid>.textures.items. Language files always need the en_US.lang, which is used by default if it cant find the selected minecraft language.

Download the Code

 

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 System.in. 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.

Assignment

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.

Download

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.

Assignment

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

Download

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 Main.java. For now you can ignore the (default package) we’ll go into packages later on you can ignore that for now. Open the Main.java 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 Main.java -> Run As -> Java Application
  • Select the Main.java and hit the Green circle with an arrow inside in the eclipse toolbar
  • Select the Main.java and hit ctrl + F11
  • Select the Main.java 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

Assignement

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.

Download

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.

 

Java Getting started

This getting started is windows specific, but Im sure if you google, you’ll be able to find out how to do this stuff on your OS (operating system). I wont completely be holding your hand with these tutorials. Im going to asume you know how to install things and how to unzip and stuff like that. If you dont, programming basically all about problem solving, you will have to learn how to solve your own problems, usually googling your problem helps a lot.

To get started with coding java, you need a couple of things first:

Installing JDK

JDK is short for Java Developers Kit and you will need to have this installed if you want to develop java. To download you have to go to the Oracle Download page and press download. That will bring you to a download selection page. There you have to tick Agree Lisence Agreement. If you are on a 64 bit pc be sure to download the x64 version. If you have a 32 bit pc or dont know what you have, download the x84 version.

Well I take you know how to install things so just run the exe you just download and install it. during installation you will probably be asked to install the JRE, this is the Java Runtime Environment. You most likely have this installed this already since that is whats needed to run java programs on your pc. Doesnt hurt to install it again though. At the time of writing this you will also asked to install JavaFX, feel free to skip this. If you want to know what it is use google.

So you have installed the JDK now, but you arent done yet. Now comes the tricky part making windows be able to use it. You have to let windows know where you intalled the JDK otherwise it wont be able to use it. You do this by adding the JDK bin location to your Windows Path. Now why this isnt done automatically when you install it I dont know. Anyway you have to go to your Environment Variables. Where these are located slightly variables per Windows. Ill explain it for Windows 7, but Im sure if you use google you’ll be able to find how its done for your windows.

Go to Control Panel -> System -> Advanced System Settings -> Enviroment Variables. That wasn’t so hard right? Now be careful these are settings your windows needs to run properly so no messing around. Now look at the System variables and find the path and double click it. This should look something like:

Now go the end of the Variable value and if there isnt a semicolon there add one. Now find out where your JDK installed. This is probably in your C:\Program Files\Java and go into your JDK and than bin folder and copy the path. At the time of writing this is C:\Program Files\Java\jdk1.7.0_05\bin. Now take that path and copy it after the semicolon you placed in the Path varuable value. Once again make sure you dont delete anything in it, this could mess up your windows. After doing this press ok.

Now you should have succesfully installed the JDK. You can test this by hitting your windowskey + r -> type in cmd and hit enter, a command promt should now pop up. Type in the command prompt: java and hit enter. If it gives you a bunch of text with explanations how to use it than its installed correctly. If it says ‘java’ is not recognized as an internal or external command, operable program or batch file. it didnt install correctly.

Installing Eclipse

Eclipse is a free IDE for java. An IDE is an Integrated Development Enviroment. Its basically a tool made to make programming easier. Ill be using eclipse for the upcoming tutorials. Ofcourse there are more IDEs for java or if you are really ‘hardcore’ you can ofcourse not use an IDE and just use notepad to code in. That is your own desision. Though if you are a starter I suggest you start with eclipse.

Go to the eclipse download page and download the standard eclipse. Reminder if you downloaded the 64 bit JDK you have to use the 64 bit eclipse and 32 if you got the 32 bit JDK. This will give you a zip file. Unzip the folder where you want. I ususally do it to my c:/ or c:/program files. Now go into the folder and run eclipse.exe. If it doesnt run you either installed the wrong version of eclipse or didnt install your jdk. Either way go to the eclipse forum to get help.

When you start eclipse it will ask what workspace you want to use. I for example have different workspaces for: school, work, private, testing etc. You can make as many workspaces as you want. For these tutorial workspaces I suggest you create a WorkspaceTutorials or something similar like that.

When you start ecplise it might get a welcome screen. Feel free to close it. Your start screen should look something like: