Nav-Bar 

April 1999 Tutorial


Java Zone Index Page Search the Java Zone Site Java Dictionary

View the Tutorials Archive

What is Java? Java syntax and general style guide How to get Java running
Links to relevant sites

Email me

General Programming Principles

The easiest way to think of a program is as a list of instructions, which are executed in order. Consider the following list of instructions:
 

  1. Get three numbers and label them a, b and c
  2. Take 'a' and multiply it by 'c' and multiply the result by 4
  3. Add 'b' squared to the result of that
  4. Square root the result
  5. Divide this by 2 multiplied by 'a'
  6. Label this result 'd'
  7. Print out to the screen the result of 'b' divided by 2 multiplied by 'a' add 'd'
  8. Print out to the screen the result of 'b' divided by 2 multiplied by 'a' minus 'd'
  9. End Program
This is in effect a program. It's meant to find the root of a quadratic equation although in its current form it may be ambiguous and misleading. Written in mathematical notation it wouldn't be ambiguous but it would still, in essence, be a program.

To write a computer program you need to know the "commands" your computer will understand. For example, if you want to print something to the screen, it would be worth knowing that the java command for doing this is 

     System.out.print("Message");

This will do as you expect. So a java program is a list of instructions, all carried out in order. There a commands to perform sums such as addition, multiplication etc., as well as commands for getting user input, drawing graphical interfaces, displaying pictures, and many other useful things.

Types of Data

One important aspect of programming is in using "variables". These are named pieces of memory that store particular data. For example, you might want to store an integer to use later. In Java, all you need for this is:

     int variableName;

This says that the variable called "variableName" will store an integer. Note that CAPITALISATION IS IMPORTANT. VariableName is different to variableName which is different to variablename.

Notice that we haven't said what the integer is. To actually define which integer "variableName" is to store, we just use the assignment operator which in java is the equals "=" sign. So:

     variableName = 10;

specifies that "variableName" now stores the value 10. We can later set it to a different value if we want to, in the same we did here. The following table shows the other types of data we can store using the above method:
 
 
int Stores an integer value between -2,147,483,648 and 2,147,438,647
byte Stores an integer value between -128 and 127
short Stores an integer value between -32,768 and 32,767
long Stores an integer value between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
float Stores a floating point (decimal) number with about 7 significant decimal digits
double Stores a floating point (decimal) number with about 15 significant decimal digits
boolean Can be set to true or false
String Stores a "word" or "many words in a sentence like this"

Remember that capitalisation is important. So to set up a particular datatype you use the commands:

     long longValue;
     longValue = 10000;
     byte byteValue = 90;

You'll notice that I've set the value of "byteValue" at the same time as creating it. You'll do this quite a lot when programming - mainly because it cuts down on typing and is more elegant. Sometimes you CAN'T do this though - ie. when you don't know what value it's going to store yet!

Notice that the 'String' type has a capital first letter where the others do not. This signifies it is in fact a CLASS (more on this later). In fact, the String type is quite special in Java. If you've programmed in C you may be surprised to find that the string can be set in the same way as the basic (numerical) types. That is:

     String name;
     name = "David";
     String surname = "Vivash";

This will do as you expect, ie. it specifies that "name" will store a String, then sets it to David, then it creates a String called surname that stores the String Vivash. Notice the double quotes around "David" and "Vivash". These are very important, and are different to the single quotes - ' '. For now all you need to know is that your String values need to be surrounded with double quotes.

Object-Oriented Programming

You might wonder why I'm talking about Object-Oriented programming already when I haven't even explained "normal" programming yet... I haven't even told you how to write a "Hello World" program in Java yet :) Well bear with me and I'll tell you.

The term "Object Oriented programming" may seem quite scary. In fact, it's just a certain way of programming - a way Java supports reasonably well. From it's name you might guess that it's something to do with programming with "Objects". And you'd be right to guess that. The main reason Object-Oriented scares people is because of the jargon used. I could probably dedicate an entire web site containing explanations on all of the jargon - and then another web site explaining all my definitions probably. Terms like "inheritance", "polymorphism" and "encapsulation" form the backbone of Object-Oriented programming languages, and can be a bit daunting to get hold of - but there's no reason you have to know their meanings to program in an Object-Oriented way.

Every program you write in Java is an object (or more strictly speaking a "class", but I'll explain this later). So what exactly is an "Object"? Well, if you look around yourself now you'll be able to see lots of objects. Around me now I see a coffee cup, a monitor, a keyboard, a carpet, a book, a door and lots of other things. Every object has certain properties associated to it - such as colour, size, age and other things. For example, my monitor has the following properties:
 

  • colour (ie. mine is a beige colour)
  • make (ie. manufacturer)
  • Serial number
  • Possible resolutions
  • on/off switch
  • Brightness
  • Contrast
  • Screen width
  • Screen height
  • Horizontal screen position
  • Vertical Screen position
You'll find that these properties are applicable to many different monitors. To store information on a monitor you might want to use the above set of properties. But as well as having certain properties, an object can also perform certain functions. For example, my monitor has buttons to adjust the brightness, and to change the screen width amongst others. These functions change some of the above properties - there is no other way for me to change the screen width without using the button on the monitor. There are other functions we can do with the monitor though - for example, how do I know who the manufacturer is? Well I can just look at it, and it says on the front. It's important that I can't physically change the manufacturer, I can only look find out who it is.

So we have some functions that can be used to change properties, and some that tell us what certain properties are.

This is what Object-Oriented programming is all about. It's about creating objects - which have certain properties, and then writing functions that can change these properties or just simply tell us what they are.

Classes - The Object cookbook

Still no actual programming eh? Well we'll get to that in a minute... I'm about to make an important distinction, so listen carefully. When you create a definition of an object - ie. what properties it's going to have and what functions there are going to be, this is called a "class". When you actually create an "instance" of this class, the thing you have created is an "object".  So the class is the blueprint, and the object is the created article. It's possible to create many objects all from the same class. So you could have lots of monitor "objects" all created from the monitor "class". They would all contain their own properties and have access to the functions.

The Java API (Application Programming Interface) has details of all of the classes that Java lets you use in its normal distribution. It's like a cookbook full of recipes. Every class is a recipe. When you make one of the recipes in the cookbook (or rather, when ou ask your mum to make you one of the recipes), it's like creating an object in Java. The recipe is the class, with the object being the created delicasy.

How to write an Class

This is the easy bit. Every program you write in Java is a class. Remember that when you compile your Java source code, a class file is created. Whether it is in fact a class in the sense of what has been described above is besides the point - a class is just a Java program. Look at the following:

    public class Monitor
    {
        int serialNumber = 0;
        int screenWidth = 0;
        int screenHeight = 0;
        int horizontalScreenPos = 0;
        int verticalScreenPos = 0;

        public void setScreenWidth(int width)
        { screenWidth = width; }

        public int getScreenWidth()
        { return screenWidth; }
    }

The above is a class. It's incomplete, but it would work, trust me. The first line asserts that we've created a class called "Monitor". The five lines following that create a few properties - such as the serialNumber and screenHeight. Notice that I've set them all to zero to begin with.
We then go on to define the functions of the class (referred to as "member functions" or "methods"). A function must have a name, a "return type" and an access restriction. You can also specify if the function should accept any inputs, or "arguments".

The first function above has the name "setScreenWidth", and has one argument - "int width". This just means that the variable called "width" will be an integer (we haven't set it to a value yet).
The first two words in the function definition are "public" and  "void". The "public" keyword just means that the function can be called by anyone who creates an object from this class. The "void" keyword means that the function doesn't have any output.

So we've defined a function that can be used by anyone who creates a Monitor object, which doesn't return any values but expects an integer to be sent to it as input.

Contrast this to the second function. This one is public also, so anyone can use it. Where the previous function had "void" though, this function has "int". So whilst the last function didn't return anything (ie. no output), this function returns an integer. Notice, however, that the brackets after the function name are empty. This means that no input is expected to this function. So where the first function expected an integer, this one expects nothing.

This class doesn't actually DO anything by itself though. Remember that a "class" is just a blueprint - a recipe. To actually USE these properties or functions we need to create an "instance" of the class - an Object. So now we'll actually write a program - one that uses this Monitor class.

    public class MonitorApplication
    {
        public static void main(String args[])
        {
            Monitor myMonitor;
            myMonitor = new Monitor();

            int wid1 = myMonitor.getScreenWidth();
            myMonitor.setScreenWidth(100);
            int wid2 = myMonitor.getScreenWidth();

            System.out.print("Initial screen width=");
            System.out.println( wid1 );

            System.out.print("Final screen width=");
            System.out.println( wid2 );
        }
    }

Okay, so this seems a little bit more complex. To get this program to work, you need to have a compiled the Monitor class first. To do this, just type in the source code given for the class "Monitor" and save it to a file called "Monitor.java"

Then go to a command line and type in "javac Monitor.java"

This will create the Monitor class for us, and we'll be free to use it as we have in the above program.

So let's analyse this program. The first line is obvious - it just states that this is a public class (remember that all Java programs are "classes"), and that its name is MonitorApplication. One thing I didn't mention before is that the class name must also be the name of the file it's saved in. So we'd have to save the above program to a file called "MonitorApplication.java".

To compile it you do the same as before, ie. "javac MonitorApplication.java" will compile the source code, then just type "java MonitorApplication" to run it.

Analysing the Class Code

You'll notice that the MonitorApplication "class" is pretty pathetic as classes go - I mean, there's no properties stored in it, and there's only one function (the function does create a few variables, as you can see, but these are only accessable inside the actual function). The function it does have is quite special though. The function definition is:

        public static void main(String args[])

Now, we've come across most of these keywords before. The first one, "public", we already know just says that the function is accessable to everyone. The second one's new though - "static". Don't worry about this for now. Just know that if a function is called "main" as this one is, you need the "static" keyword shoved in there.
We then move on to "void". This just mean that the function doesn't return anything. We saw a function that did return something in the "Monitor" class, and I'll talk about this a little later.
We can see that the function takes an input - a String with the name "args[]". You don't need to worry about this either at the moment. 

In fact, the definition of the "main" function, shown in the line above will always be the same in your programs - so as long as you copy it as it is above, you shouldn't go far wrong.

So why have we called it "main". Well, the "main" function is quite special in a class, because it means that the class can be "run" as a program. Remember that our Monitor class had only two functions and neither of these were "main" - this means it can't be run.

When a program is run each line is executed one ofter the other. However, any functions inside the program need to be explicitly "called". Look at the Monitor class again:
 
 
public class Monitor
{
Class definition
    int serialNumber = 0; set serialNumber to 0
    int screenWidth = 0; set screenWidth to 0
    int screenHeight = 0; set screenHeight to 0
    int horizontalScreenPos = 0; set horizontalScreenPos to 0
    int verticalScreenPos = 0; set verticalScreenPos to 0
    public void setScreenWidth(int width)
    { screenWidth = width; }
Function - skip past
    public int getScreenWidth()
    { return screenWidth; }
Function - skip past
} End class definition

So you see, going through these in order results in nothing being done. The Java interpreter will see that you've got no "main" method so won't bother trying to run the above program.
However - if there is a main method in your class it won't be skipped like the functions above are. The main method will be executed once the Java interpreter comes across it, and then each command will be executed in order inside of main. So whilst the above class doesn't have a main method can't be "run", our MonitorApplication program DOES have a main method. So when the interpreter reaches it, each line inside the main method is executed in order.

So lets have a look to see what MonitorApplication actually does:
 
public class MonitorApplication
{
Defines "MonitorApplication" as a class -
Remember Java programs are always classes
  public static void main(String args[])
  {
This function has the name "main" so its contents will be executed.
    Monitor myMonitor; Tells Java that the variable called "myMonitor" will be a "Monitor" object. It's like writing "int myInt" to tell Java that "myInt" will store an integer value.
    myMonitor = new Monitor(); Creates a Monitor object called myMonitor.
So myMonitor will have all the properties of a Monitor and we can use the functions we defined for Monitors.
    int wid1 = myMonitor.getScreenWidth(); Creates an integer called "wid1". It also calls one of the functions we defined for our Monitor class. If you remember, inside our Monitor class definition we had a function called getScreenWidth which expected no input but returned an integer as output. On this line here you can see how we "called" our getScreenWidth method - we first put the name of the Object (myMonitor), then put a dot, then put the name of the method we wanted to call. The empty brackets after the method name indicate that we are sending no input to the function. However, remember that our getScreenWidth method returned an integer as output. Because we have "int wid1=" on this line before the function is called it means that wid1 will take up the value that getScreenWidth returns.
    myMonitor.setScreenWidth(100); Here again you see how to call a method that's inside another class. We first put the name of the Object, then a dot, then the name of the method.
You'll notice that I keep saying to put the name of the "Object" rather than just the class name. Remember that the class name is "Monitor" but this is just a blueprint for Monitors - you can't physically use it. So we create an "instance" of the class called myMonitor which we CAN use.
So, our method this time doesn't return anything for output, but does expect an integer as input. So here we just send it the integer "100" as input.
    int wid2 = myMonitor.getScreenWidth(); This line is similar to the one before last. Again we use the format objectName.methodName() to invoke a method in another class. The output of this function is stored in the integer wid2 this time though. 
    System.out.print("Initial screen width="); Here we are using a similar syntax to what we've used before - objectName.methodName - here the Object is "System.out" and the method is print. The print method can take lots of different inputs which it then prints to the screen. Here we've given it a String as input.
    System.out.println( wid1 ); Here we use the System.out Object again, but we use the println method instead. The println method will go to a newline once it has done its printing, unlike the normal "print" method. You'll notice as input we've given an variable (wid1) - so we will print out hat value that wid1 currently stores.
    System.out.print("Final screen width="); This is just the same as the line before last.
    System.out.println( wid2 ); We now print out the value that wid2 is storing.
  } End of "main" method
} End of MonitorApplication class

So we seem to have done a lot of work to print out two lines of text, yeah? Well, okay, yes we have. But there's a lot of key concepts of Object Oriented programming demonstated above. I mean, even if you decide to give up now, at least you can say you've "done a bit" of Object Oriented programming now.

The good thing about Object Oriented programming is that it's not as scary or difficult as some people would have you believe. All we really did above was define how a Monitor Object should behave (in the Monitor class), then we just created one and used it in our MonitorApplication class. And this is all Object Oriented programming is about - defining, creating, and using "Objects". There are a few more things to it than that, but this is the general idea.

You may have noticed one odd thing about our MonitorApplication class - the "System.out" lines. These are Objects as I said, but we didn't explicitly create them like we did our myMonitor object. The reason for this is because they're automatically created for use when our program begins. There isn't really much you need to know about the "System.out" object at the moment, apart from knowing that you'll always be able to use it and two of the functions you can call from it are "print" and "println".

That's all Folks

Well, after possibly excessive use of pale shaded tables, this months tutorial is officially over. Have I gone too fast? Probably. Don't worry about writing you own classes just yet - if you can read and just about understand what I've done with my Monitor class you've done well. Remember that Java is an Object Oriented programming language, so if you want to program it well it's best to learn it in an Object Oriented way. Anyway, I'll leave you with this months exercises. Enjoy!

Exercises
 

  1. Look around yourself now. Pick an object you see at random. List on a piece of paper all the properties it has (like if it's red then list "color" as a property). Now list all the "functions" associated with it - what can it do? What can you do to it? Put a star next to all the functions that change a property.
  2. Write a "setScreenHeight" method for the Monitor class. Also, write a "getScreenHeight" method. These should be almost identical to the ScreenWidth methods so look at those if you're not sure.
  3. Add a "manufacturer" property to the Monitor class - it should appear with the other properties. Set it initially to "Unknown" but have methods for changing the manufacturer and for checking to see who it is.
  4. Write any other methods you think the Monitor class should have. Try and think of the inputs your methods require and whether the function should output a value.
  5. Hum a popular pop song with seven marshmallows in your mouth and see if anyone can guess it.


Download this months source code - Size 1.55 Kb

2-4-99