Virtual Core 5

Java Tutorial

I.1.S.C.S


Introduction

In class we briefly discussed HTML -- the "HyperText Markup Language", which is used to describe how information is organized in a web page.  This is a very powerful language, but it is only intended to deal with passive information:  information which sits on the page while you observe it.  If you spend just a few minutes browsing the web, though, you'll notice that the most eye-catching and compelling sites are those which are highly interactive -- that have "active content".  This is accomplished in a wide variety of ways; in this class we will explore one of the most powerful tools for doing this:  the programming language Java.

Java itself can be used in many many different situations, but we will focus our attention on web pages.  We useJava to produce applets (think of "miniature applications") which may be inserted a web page and activated by anyone who browses that page.  Here [not really, yet] is an example of a web page which contains a simple applet.

In this Java tutorial, you will be learning how to develop applets like this one.  We will start with some very basic Java ideas and gradually increase the complexity of what we can do until, finally, you will be able to design applets even more complicated than the one above.
 

Sending Messages

Sending a message is one of the most often used ideas in Java.  It's a very general idea, and therefore it's a very powerful idea.  What kind of messages are we talking about?  It's really limited only by imagination.  We can (and will) send messages like "Draw a rectangle on the screen," or "Tell me if this number is bigger than 0," or even "Open this web page."  Of course,  sending messages like this is something you do all the time:  when we push the power button on the TV remote control, we're sending a message to "Turn the TV on;" or when we step on the gas pedal in a car we're sending a message to "Speed up."

But what are we sending these messages to?  In Java, the answer is another general, powerful concept:  messages are sent to objects.  This, too, works a lot like the "real world":  when we send a message to "Turn the TV on," we are sending that message to a particular "object" -- our television.  It's important to note, though, that not every object can make sense of every message -- what does it mean to tell a television to "Speed up?"  That is, the type of an object determines what kinds of messages make sense to it.

Now, when we're writing computer programs, we won't be sending messages to actual televisions or cars.  But we might send messages to objects that are supposed to behave like, or simulate, objects in the "real world".  For example, if we were designing a video game to take place on a race course, we would very likely create Java objects that acted like (that is, responded to the same messages as) "real" cars.  Let's think about this a little more carefully. . . .

Imagine that someone has actually written a racing video game in Java.  When we start to play the game, the computer screen is filled with all kinds of things relating to the game -- perhaps a control panel, the track, cars on the track, spectators, obstacles, etc.  Now, where do we see the Java object that simulates a car?  Is it the image of a car?  No; that's just a drawing.  In fact, we can't actually "see" the Java object; the car object is a group of instructions that (somehow) controls everything about the car -- how it's drawn on the screen, how it interacts with your controls, how it responds to other car objects (say, if it crashes into one), etc.  Where do we see the program for the whole game?  Is it the colletion of images that fill the screen?  Again, no; the game itself is a group of computer instructions that control what appears on the screen and how the contents of the screen respond to each other and to the player.  The game will send messages to objects; for example, if you indicate with the controls that your car should turn left, the game might send a "turn left" message to the car object.

In fact, this idea can be (and is) used in many other computing contexts.  Consider using a word processor:  when you "open" a document using your favorite word processor, are you seeing your document?  No; you are merely seeing a group of pixels that represent your document.  Indeed, with many modern word procesors you can see many different "views" of your documents; e.g. "print preview", "page layout", "outline", etc.  None of these are your document, but they are all representations of your document.  And what you see is determined by the instructions in the word processor -- and in the document object.

Exercises

True or False:
  1. An object is just an image on a computer screen
  2. Any object will respond to any message
  3. Simulation is a kind of imitation of the real world
  4. It would be sensible to allow an object simulating a calculator to respond to "turn up the volume" messages

Java and Messages

So how do messages and objects work in Java?  We need three kinds of information in order to send a message in Java:
  1. A way to identify the object we're sending the message to
  2. The name of the message we want to send
  3. Any details (called parameters) about the message itself
For example, suppose we wanted to send a powerOn() message to an object identified by  MyTV (note that we don't need any details in this message).  In Java, we would accomplish this by the following statement:
MyTV.powerOn();
The identifier of the object comes first, followed a period, followed by the name of the message we're sending.  The parameters (if there are any) go in parentheses after the name of the message.  If there are many parameters they are given in a list separated by commas; each message has a fixed number of parameters it is allowed to receive.  Since there are no details in this case, there's nothing in the parentheses -- but the parentheses must be there every time you send a message.  The semi-colon tells Java that this is a complete "action", just like a period indicates the end of a complete sentence in English.
 

Exercise

Give a Java statement which sends a powerOff() message to MyTV.

Exercise

Suppose MyTV can also receive changeChannel() messages; this message requires one parameter: the number of the channel to change to.  Give a Java statement which sends a message to MyTV telling it to change to channel 7.

Exercise

Consider simulating the behavior of a soda vending machine.  Suppose we have an object identified by MySodaMachine which can receive two kinds of messages:
  1. dispenseProduct(), which requires one parameter:   the name of the soda to dispense, such as "Pepsi", or "Fresca"
  2. dispenseChange(), which requires one parameter: the amount of change to give, in cents
Give a Java statement which sends a message to MySodaMachine telling to give back 45 cents in change.

Exercise

Consider simulating the behavior of a calculator.  Suppose we have an object identified by MyCalculator which can receive four kinds of messages:
  1. add()
  2. subtract()
  3. multiply()
  4. divide()
Each message requires two parameters:  the two numbers that are being operated on (the operands).  Note that for subtraction and division, the order of the operands is important:  7 - 5 is different from 5 - 7.

Give a Java statement which sends a message to MyCalculator telling it to add 27 and 14.

Give a Java statement which sends a message to MyCalculator telling it to divide 56 by 7.


Towards a First Applet:  Drawing Simple Shapes

Suppose we wanted to draw a simple shape, such as a rectangle, on the screen.  What would we do?  Well, since we're just beginning in Java we have no idea about the specifics, but we can make some educated guesses.  Since this is Java, we could guess that we would need to send a message that somehow indicated that we wanted to draw a rectangle.  Now, we know that to send a message we need three pieces of information:  a way to identify the object this message is being sent to, the name of the message we're sending, and any parameters the message requires.

Let's think about the second piece of information first:  what message are we going to send?  Hopefully, there is some kind of object "out there" that knows how to draw rectangles and would understand such a message, but how do we know?  Off the top of our heads, we don't know.  But the Java languages comes with a large number of predefined object descriptions, and by consulting these we might be able to find what we need.  In fact, this is what professional Java programmers spend a lot of their time doing.  It turns out that objects of type Graphics can receive a message called drawRect() which will indeed cause a rectangle to be drawn on the screen.  We need to make sure that we have access to an object of this type; for the moment let's just assume that there is one, identifed by g.   Finally, we need to provide any parameters that drawRect() expects.  How do we know what drawRect() expects?  By again consulting the description of the Graphics class, which tells us that drawRect() expects 4 parameters:

  1. the distance of the rectangle's upper left corner from the left edge of the screen
  2. the distance of the rectangle's upper left corner from the top edge of the screen
  3. the width of the rectangle
 These values are given in units called pixels (picture elements); think of them as dots on the screen.  The number of dots on the screen varies (depending on your monitor, etc.), but it's common for screens to be at least 800 by 600 pixels.  So let's send a message to draw a rectangle that's 200 by 100 pixels, and let's say to draw it near the top left of the screen, 40 pixels over and 20 pixels down.
    g.drawRect(40,20,200,100);

    Exercise

    Give a Java statement which draws a rectangle with width 50 and height 200 with its upper left corner 100 pixels over to the right and 100 pixels down from the top.
     

    Exercise

    True or false:  the rectangle drawn by this statement
         
        g.drawRect(40,20,200,100);
         
    will appear to the left of the rectangle drawn by this statement
       
        g.drawRect(200,100,40,20);

    Exercise

    True or false:  the rectangle drawn by this statement
         
        g.drawRect(40,20,200,100);
         
    will be larger than the rectangle drawn by this statement
       
        g.drawRect(100,100,200,100);




Now, a drawRect() message by itself won't do anything; it needs to be incorporated into a complete Java applet first.    Here's the applet:
import java.awt.*;
import java.applet.*;

public class FirstApplet extends Applet {
    public void paint (Graphics g) {
        g.drawRect(40,20,200,100);
    }
}

There's our drawRect() statement in the 5th line of text, but what's all that other stuff for?  These other lines are necessary for telling Java that we're writing an applet, rather than some other sort of Java program.  The first two lines make sure that all the objects and messages we might need for writing an applet will be available to us (if we leave them out, "drawRect" won't make any sense!).  The third line tells Java that we are writing an applet (it "extends Applet"), and that the name of our applet is FirstApplet.  The fourth line says that what follows describes what the applet should draw (or "paint") on the screen; the applet will use the object identified by g to do the drawing; the word Graphics tells Java the type of g -- it can receive messages about drawing, but not, say, about adding and subtracting, or dispensing change, or turning on a television.  Notice that the entire applet is enclosed in {}, as is the entire paint section.  Never leave these out!
 

Exercise

Write a complete Java applet which draws a rectangle with width 50 and height 200 with its upper left corner 100 pixels over to the right and 100 pixels down from the top.
 

Exercise

Notice that these rectangles look "hollow"; they're just line drawings.  Objects with type Graphics can also receive fillRect() messages, which work exactly like drawRect() messages except that the rectangle that is drawn is filled in instead of hollow.

Write a complete Java applet which draws a filled rectangle with width 75 and height 30 with its upper left corner 150 pixels over to the right and 20 pixels down from the top.


Objects and Classes

We mentioned that the type of an object determines what kind of messages it can respond to - for example, a television object might respond to a "change channel" message, and a car object might respond to a "speed up" message. An applet may contain several objects of different types, or multiple objects of the same type.

In Java, the characterization of a type of object is called a description of a class of objects. The definition of a class determines the characteristics and behavior of objects of that class.

In the applet above, the phrase Graphics g tells us that the object g belongs to the class Graphics. The definition of the class Graphics is part of standard Java, and it specifies that objects of this class can respond to messages such as drawRect(), but not to messages like powerOff(). We will be using several predefined classes in the next few lessons.

Although we used cars and TVs as examples of objects, the Java language does not include a car class or a TV class. One of the things that makes Java so powerful is that programmers can define their own classes, so a programmer can define an appropriate class for the application he is working on. This is a very powerful part of Java that we will [or will not, as the case may be] get to later in the term.
 

Exercise

True or false:
  1. Graphics is name of a class of objects in Java
  2. Graphics is name of a message in Java
  3. Graphics identifies an object in Java
  4. Any class can by defined in Java
  5. Java only allows one object of a particular class



Drawing Several Shapes Together

Although the examples we've done so far have only involved sending one message at a time (for the sake of simplicity), Java allows us to write long sequences of statements as well -- if it didn't, our applets would never be very interesting.  For example, we could write an applet like this:
 
import java.awt.*;
import java.applet.*;

public class AnotherApplet extends Applet {
    public void paint (Graphics g) {
        g.drawRect(40,20,200,100);
        g.fillRect(80,80,150,100);
    }
}

This applet causes two rectangles to be drawn on the screen in different places, one hollow and one filled.
 

Exercise

Write a complete Java applet which draws two rectangles on the screen as follows:
  1. One must be hollow and one must be filled
  2. They must be the same size
  3. The hollow one must be to the left of the filled one
  4. They must be directly adjacent to each other (i.e. "touching" each other)
They can be any size you like, and be drawn anywhere on the screen, but you must determine how to fulfill the 4th rule.