Virtual Core 5

Java Tutorial

Part I, Lesson 1, Scott's Version

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.  Java is used 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

In Java, the most often used idea is that of sending a message.  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 you push the power button on the TV remote control, you're sending a message to "Turn the TV on;" or when you step on the gas pedal in a car you're sending a message to "Speed up."

But what are you 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 you send a message to "Turn the TV on," you are sending that message to a particular "object" -- your television.  It's important to note, though, that not every object can make sense of every message -- what does it mean to tell your 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 actually be sending messages to 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.
 

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. The name of 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 called 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 name 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.  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, 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, 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 send a message, drawRect(), to an object, g, that meant "Draw a rectangle on the screen."  What parameters would be required in this case?  We certainly need to give the dimensions (the width and the height) of the rectangle.  We also need to tell g where on the screen to draw the rectangle.  So we need to provide four parameters:  the position on the screen of the upper left corner of the rectangle, and  the width and length 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 mesage 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);
In fact, the drawRect() message is a standard part of Java; it works exactly as we've used it in this example.  Let's see how to write a complete Java applet (our first) which will cause a rectangle to be drawn on the screen just like in this example.  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 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.


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.