Ralpharama Archive. The archive is almost 20 years old, this website is no longer maintained.

Home | New Writing | Old Writing | Cooking | Technical | Wine Making | Cocktails
   
 
Article

Ralpharama's Programming 101

Hits 4000 | Created 2008-01-14 | Modified 2008-01-14

A tutorial from 2003. It may still of interest, though a bit old: This tutorial may interest you if you satisfy the following criteria: You don't know anything about programming. You want to learn some Java. You think it would be fun to pass time writing inane little games. You want to write these little games to run in a browser window like Internet Explorer. Still with me? Good. I'm assuming no knowledge at all about anything, so, let's begin.

Introduction

This tutorial may interest you if you satisfy the following citeria:

×           You don’t know anything about programming.

×           You want to learn some Java.

×           You think it would be fun to pass time writing inane little games.

×           You want to write these little games to run in a browser window like Internet Explorer.

Still with me? Good. I’m assuming no knowledge at all about anything, so, let’s begin.

 

1. Java

It’s a pretty good bet to learn Java for a few reasons:

×           It’s very popular and is unlikely to go away in the near future.

×           The progams you write can run on almost any machine.

×           You can write programs to run on the internet in broswer windows.

×           The language is quite simple and also powerful enough to do a lot of nice things.

Now the tedious part – you will need to download from Sun or Microsoft the latest versions of the Java Development kit. These two links will get you going in the right direction:

×           (Link1)

×           (Link2)

The Development Kit, or SDK, or whatever else they are calling it at the moment consists of a lot of files that will fill up some of your Hard Drive, these files allow you to translate your programs into a format that will work in browsers etc, and also provide some documentation for you to stare at when you can’t get something to work. There’s more, but you don’t really need to know, or worry about it.

 

After you’ve downloaded the correct files for your computer and installed the thing, we’re ready to begin.

 

Note: Apple users – you may already have a Java compiler on your system – search for ‘javac’ and see.

2. First Steps

Okay, so where is Java? Good question. It will be tucked away somewhere difficult to find in all probability. What you need to be able to do is get to a command prompt - this will be a MS-DOS box on Microsoft machines, or a Unix box on some others. At the command line, which might look like this:

C:\WINDOWS>_

Type the following and press enter:

Javac

You should get some text like this:

Blah Blah, Visual J++ Compiler, etc.

If not, and the computer complains that it can’t find this file, try typing this instead:

Jvc

If this works, good. There is no difference, just a name. Remember which one works. This is the Compiler.

 

If Javac and Jvc fail to produce any results except error messages that the file is not found, then something has gone wrong, and you probably need to do something else to get this to work, such as put a line in your autoexec.bat file on a PC, or something similar. You will have to refer to your installation instructions that came with the download – it will be in there somewhere.

3. The Compiler

So now you can access your compiler, this is good. The way this works is:

×           You type in a program in a text editor.

×           You save it.

×           You then run the compiler on that file.

The compiler creates a new file, called a .class file, which can then be used on web pages, amongst other things.

 

I would suggest creating a new directory or folder, easy to get to, where we can put all our programing. Mine is going to be called ‘Java’ and it will be off the main C:\ directory on my PC.

 

Now, I bring up my MS-DOS box, get my C:\WINDOWS>_ prompt, and type:

Cd \java

The prompt changes to this:

C:\JAVA>_

 

This is all working? Good. You’ll need to have this up and running every time you want to program.

4. First Program

If you’re anything like me, you’ll want to get a program working right away, and then learn about it, rather than reading twenty pages of explaination before duing anything at all.

 

So, okay, in your best text editor (notepad will do), type the following in, exactly, and save the file in your Java directory called ‘hello.java’. Make sure you save the file as text, and not as, say, a Word document.

 

Don’t worry about what everything does, we’ll look at that later. Also, do type it in, don’t copy and paste it – it is good practise to get used to typing in the code, it sinks in better.

 

Before you start, a point to bear in mind is that Java is case-sensitive, that is, capital letters make a difference, so type it in exactly as you see it.

 

// hello.java

 

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

 

public class hello extends Applet implements Runnable

{

// Declare Image to draw on

private Graphics paper;

private Image img;

 

// Declare The size of our screen

private int xsize;

private int ysize;

 

// Declare A thread

Thread proc;

 

public void init()

{

// Create images to draw on

xsize=250;

ysize=250;

img=createImage(xsize,ysize);

 

// Set Applet background and foreground

setBackground(Color.black);

setForeground(Color.white);

 

// Paper is a Graphics pointer to 'img'

paper=img.getGraphics();

 

// Draw a black rectangle over our 'paper'

paper.setColor(Color.black);

paper.fillRect(0, 0, xsize, ysize);

 

// Change the current colour to green

paper.setColor(Color.green);

}

 

// Calls to repaint and screen refreshes redraw image to screen

public void paint(Graphics g)

{

g.drawImage(img, 0, 0, this);

}

 

public void update(Graphics g)

{

paint(g);

}

 

public void start()

{

if (proc==null)

{

proc=new Thread(this);

proc.start();

}

}

public void stop()

{

if (proc!=null)

{

proc.stop();

proc=null;

}

}

 

public void run()

{

while (true)

{

try

{

proc.sleep(20);

}

catch (Exception e)

{

// Do Nothing

}

 

synchronized (this)

{

paper.drawString("Hello World",50,100);

repaint();

}

}

}

}

 

Okay, so you’ve typed this in and saved it your java folder, in a file called ‘hello.java’ – the name is actually important.

 

Now, go to your MS-DOS or UNIX box command line, and type this:

Javac hello

(Or Jvc hello, if that is what worked earlier). What should happen is that the compiler will think about things for a minute, and then create a new file in your Java folder called hello.class. Now, the .class file is the one that actually works.

 

Now wait, before you can run your new program, you have to do one more thing – display it in a browser window, like Internet Explorer.

 

To do this, go back into your text editor and create a new file. Type in the following:

 

<htmlL>

<head>

<title>Hello</title>

</head>

<body>

<applet code="hello.class" width=250 height=250></applet>

</body>

</html>

 

Save this file as ‘hello.html’ in the same ‘Java’ folder. In this Java folder you should now have the following files:

×           hello.java

×           hello.html

×           hello.class

 

Okay, now load the hello.html file in your internet broswer, say, Internet Explorer. You can either drag it into the window, or choose to open a local file from within the browser, or double click the hello.html file.

 

Now, the applet should load, and you’ll see a black box with the words ‘Hello World’ in the middle, in green.

 

Congratualations, you just created your first applet.

5. A word about programming

You can’t go on forever without having a little bit of theory, so here is the first bit, and hopefully not too painful.

 

A program is simply a set of instructions to complete a task. People have thought long and hard about the best way to describe actions that make up that task, and have come up with computer programing languages.

 

To make our life easier, I’m going to use an analogy of a group of friends building a house together on a plot of land. You are the supervisor of the project. Okay, imagine that your friends are incredibly stupid people and require explict instcutions on every step of every little tiny bit of house building. The instructions you give them to build the entire house can be thought of as a program.

 

Building a house sounds like a nightmare of complexity – so many things to do. So, you’ll need to break it down into easier to manage concepts. Remember that your friends are very stupid, so unless you tell them to stay until the house is completed, they will just wander off half way through the job, or, worse, keep on building once the job is finished. You have to tell them when to stop. So a good first rule for the house building program is one designed to keep your workers in place, building, until you no longer need them:

 

Build until the house is finished.

 

Pretty good. That will work. Now you just have to define build for them.

 

Simplisticly, we could say that building consists of laying bricks. So our new program looks like this:

 

Until the house is finished

Lay bricks

Otherwise,

Stop

 

Programs simply go through their instructions, line by line until they are told to stop. Each instruction will be carried out, and the next one read. In our housebuilding above, the stupid friends check the first line, is the house finished? And if it isn’t, then they will lay more bricks and go back to is the house finished? And so on, forever, or, until the house is finished. Once it is, they will see the instruction to Stop, at which point, they’ll all go home, probably.

 

A few questions raise themselves here, like, how will they know when the house is finished, given that they are so stupid? Well, we could add the following to our program:

 

Until the house is finished

Lay bricks

If we have four walls and a roof

The house is finished

Otherwise

It isn’t

Otherwise,

Stop

 

This makes some kind of sense. But it isn’t very easy to see the flow of the program. In programing languages, we group together ‘loops’ and ‘blocks’ using various methods. In Java, we group blocks together within curly brackets - { }

It is easier to see this visually:

 

Until the house is finished

{

Lay bricks

If we have four walls and a roof

The house is finished

Otherwise

It isn’t

}

Otherwise,

Stop

 

So we can see that if the house isn’t finished, we do everything in the { } after the check, that is, lay bricks, and check if we have four walls and a roof. When we reach the end of our curly bracket, we jump back up to the check at the top, because we have said there that we do this until the house in finished. So, we’ve made a loop.

 

Here is a fundamental programing concept: We build programs using checks, like if, and while. Let’s make our prorgram look more like a Java program:

 

while (the_house == not_finished)

{

layBricks();

if (number_of _walls == 4 && the_roof == yes)

{

the_house = finished;

}

else

{

the_house = not_finished;

}

}

else

{

end;

}

 

Okay, we’ve added a few things here, but it is starting to look like Java.

×           We’ve changed the until to be while, which is the word we use in Java.

×           We’ve put things that we check into normal brackets ( )

×           We’ve added an if (thing) – this checks the condition like a while, but does not loop. If the condition is true, then we do whatever is in the { } after it, and then just move on, not looping back to check it again.

×           We’ve used == to mean equals, or is ‘the same as’

×           We’ve added ; to the end of statements that aren’t checks.

×           We’ve changed Lay Bricks to layBricks(), the () means that this is a different bit of the program and we should go there, do what it says and then come back. We haven’t defined layBricks() yet, so this program would report problems.

×           We’ve used = to change a value, example, the_house = finished, changes the state of the house to be finished. It is important to understand that == is used for comparison purposed (is the same as?) and = is used to assign values (is made the same as).

×           We used && to mean ‘and’. Both the_number_of_walls must == 4, and the_roof must be == yes in order to do what follows this statement in the { }

 

Okay, we’ll change this into a proper java program, explain the changes and then get back to our working, real program.

 

boolean the_house;

int number_of_walls;

boolean the_roof;

 

the_house = false;

number_of_walls = 0;

the_roof = false;

 

while (the_house == false)

{

layBricks();

if (number_of _walls == 4 && the_roof == true)

{

the_house = true;

}

else

{

the_house = false;

}

}

else

{

end;

}

 

So what has changed?

×           We declare all the things we are going to check and use at the beginning, and tell the computer what kind of values they might hold – don’t worry too much about this now.

×           We give all our things (or variables, as they are things that vary during the program), initial values, like the_house is false (not finished), and the number_of_walls=0 (we have none) Remember, we use the single = to assign value.

×           We use ‘false’ and ‘true’ instead of ‘yes’ and ‘no’.

 

Happy? No? You should be fairly happy with the concepts introduced here before going on. The best way to learn is by doing, so from here on in, we’ll be explaining and using the working program to learn more.

6. Back to hello.java

The hello.java program should now contain some things that begin to look fmailiar – blocks of instructions surrounded by { }, if ( ) statements, = assignments, == checking for equality statements, etc.

 

Let’s start at the top and I’ll tell you what everything does. Some of the things here are complicated, and you don’t really need to understand them fully in order to go on – don’t worry too much, is what I mean.

 

// hello.java

 

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

 

Firstly, we use // s to add comments to our program. When the computer sees //, it ignores everything on the line afterwards. It is a good idea to put comments evrywhere, so you can see what is going on easily both now, and in six months when you are trying to re-use an old program.

So // hello.java could ust as easily be // My program called hello.java by Dave Cheese, or whatever.

 

Next three lines tell the computer that we will be referring to some pre-written things that came with Java within our program. You see, while it would be possible to write programs to handle mouse clicks, keyboard interations and graphics, it is probably better to use the ones already written for Java. More on this later, suffice to say that awt is a set of miscallenous things that are useful in Java, applet contains things used for working with applets, and event contains things like keyboard, mouse clicks etc.

 

public class hello extends Applet implements Runnable

{

 

Well, public means that this is something to that is visible and accessible to the outside world, and not private and secret. To use our housebuilding analogy, public would be working in the open air where people can watch all the things going on. People are even able to talk to one of your friends and use him on his own housebuilding project. If your house build was private, rather than public, you’d put up big black sheeting so no-one would be able to see in, and no-one would even be able to see, let alone talk to your friends inside.

 

Class is what we’re making – our program that runs in the applet is a class. It’s just a name used for a compiled program. Oh, and compiled is just a name for the program after it has been translated from English(ish) to Computer-Speak by the compiler (javac or jvc).

 

Hello is the name of our program, and the name of the file – they must match.

 

extends Applet means that we’re using the pre-written applet program that came with Java, and we’re adding to it. The prewritten program allows you to get your applet up and in a broswer window without too much trouble. Essentially, this means we make a copy of it and add to it. It would be like someone taking your house-building plans and using them, but using them to build an airport, rather than a house – they use the same methods, but change the design and general plan.

 

implements Runnable – you know the loop where we check over and over if the house is built and keep on doing things if not? Well, implementing ‘runnable’ allows us to do this. It is a another pre-written program that allows us to start a loop that starts up every 500 milliseconds, or whatever.

 

And lastly { this means that until we find the matching } at the end, everything following is part of our class file called hello.

 

Next, we declare our variables:

 

// Declare Image to draw on

private Graphics paper;

private Image img;

 

// Declare The size of our screen

private int xsize;

private int ysize;

 

// Declare A thread

Thread proc;

 

Just after the declaration of our class file, we declare all the variable we will be using. Variables are the things that we can check, assign to, add to, subtract from, etc. They come in different types, depending if they are going to be numbers (like number_of_walls), or yes-or-no states (like the_roof_is_on – true or false). Here are the ones we use:

×           Graphics paper: The name of the variable is ‘paper’, and it is of type ‘Graphics’. What this means is that we will be able to perform actions on this, like drawing shapes etc.

×           Image img: The name of the variable is ‘img’, and it is of type ‘Image’. A picture of a bird is an image, for example. In our case, we are going to perform actions on the paper, which will make changes to our ‘img’, which we will draw to the screen. It makes more sense later, come back to this.

×           int xsize: An integer – that is, number, called ‘xsize’. We’re going to use this to store the size of our screen width-wise.

×           int ysize: An integer – called ‘ysize’. We’re going to use this to store the size of our screen height-wise.

×           Thread proc: A ‘thread’ called proc. A Thread is a loop that starts up every so often until we tell it to stop. You’ll see how this works later.

×           Private this is the black-sheet effect – it means that other programs aren’t allowed to look at this variable – that it is only visible and useable inside my hello program. The alternative is public which can be useful for other reasons, which we’ll see later.

×           Note the use of ; at the end of lines.

 

Declaring variable is like gathering your house building friends and telling each one – you’re a carpenter, you’re a electrician, you’re a plumber, etc. They now know what they are, but not what to do, or where to begin. We need to give variables initial values before we can use them.

 

public void init()

{

// Create images to draw on

xsize=250;

ysize=250;

img=createImage(xsize,ysize);

 

When our applet is run in a browser window, the part of our program called init() is run first, and then the applet ends. All applets must have an init() part. In this we must do everything we need to do in order to get our applet going to run on the page.

 

×           public: This part of the program (or procedure) is accesible from the outside world – in the case to the browser that will be starting the applet – it must be able to see and run the init() procedure, so it must be public.

×           void: This means that this procedure does not return any kind of value back to whoever called it (the browser in this case) – don’t worry too much about this just now.

×           init() : The name of this procedure. The () signify a set of instructions that has a name.

×           { : Everything following, until we find the matching } is part of init() and will be executed by the browser.

 

Now, we give out variable initial values:

×           xsize=250; : Note the single =. We’re saying that we want the integer =type variable that we declared earlier to be set to a value of 250. Note again that everything that isn’t a check-statement, a {, or a }, or a procedure declaration has a ; after it.

×           ysize=250; : We’re saying that we want the integer =type variable that we declared earlier to be set to a value of 250.

×           We use xsize and ysize to hald the size of our screen. That is 250 pixels wide and 250 pixels high. You can see how much this is by looking at the applet window on the browser screen.

×           Exercise: Try changing the value of xsize and ysize to less than 250, save the file, re-compile it, and reload your page in the browser. What changes? Notice that in the hello.html file we also use values of 250. What happens if we change these? Do they have to be the same as we set in the hello.java program?

×           Img=createImage(xsize,ysize); : The variable ‘img’ is an image, if you recall. We’re asking the computer to create a new, blank image of the size we have just set. We could just as easily load an image from the computer here to use, say, of a forest. We’ll try this later. For now, we just make a blank canvas.

 

// Set Applet background and foreground

setBackground(Color.black);

setForeground(Color.white);

 

// Paper is a Graphics pointer to 'img'

paper=img.getGraphics();

 

×           setBackground(Color.black); : We paint a picture into the applet, so the normal background colour doesn’t concern us too much, but this is how you set it anyway. setBackground is a pre-written routine that we included earlier, (Color.black) is one of many pre-set colours we can use. There’s also Color.blue, Color.green, etc.




Make a Comment

Name
Comment


Antispam Code (always a number)

Enter Code Above
Submit

Note: All HTML will be removed except for bold and italics. Links will not display. Line breaks are added automatically. Use <pre>...</pre> for code.

Tags

This item has the following tags:
tech java programming guide help

Useful? Donate for hosting costs

All content copyright (c) Ralpharama