Prev NEXT

How Java Works

Variables

All programs use variables to hold pieces of data temporarily. For example, if at some point in a program you ask a user for a number, you will store it in a variable so that you can use it later.

Variables must be defined (or declared) in a program before you can use them, and you must give each variable a specific type. For example, you might declare one variable to have a type that allows it to hold numbers, and another variable to have a type that allows it to hold a person's name. (Because Java requires you to specifically define variables before you use them and state the type of value you plan to store in a variable, Java is called a strongly typed language. Certain languages don't have these requirements. In general, when creating large programs, strong typing tends to reduce the number of programming errors that you make.)

Advertisement

import java.awt.Graphics;
import java.awt.Color;

public class FirstApplet extends java.applet.Applet
{

    public void paint(Graphics g)
    {
        int width = 200;
        int height = 200;
        g.drawRect(0, 0, width, height);
        g.drawLine(0, 0, width, height);
        g.drawLine(width, 0, 0, height);
    }
}

In this program, we have declared two variables named width and height. We have declared their type to be int. An int variable can hold an integer (a whole number such as 1, 2, 3). We have initialized both variables to 200. We could just as easily have said:

        int width;
        width = 200;
        int height;
        height = 200;

The first form is simply a bit quicker to type.

The act of setting a variable to its first value is called initializing the variable. A common programming bug occurs when you forget to initialize a variable. To see that bug, try eliminating the initialization part of the code (the "= 200" part) and recompile the program to see what happens. What you will find is that the compiler complains about this problem. That's a very nice feature, by the way. It will save you lots of wasted time.

There are two types of variables in Java -- simple (primitive) variables and classes.

The int type is simple. The variable can hold a number. That is all that it can do. You declare an int , set it to a value and use it. Classes, on the other hand, can contain multiple parts and have methods that make them easier to use. A good example of a straightforward class is the Rectangle class, so let's start with it.

One of the limitations of the program we have been working on so far is the fact that it assumes the window is 200 by 200 pixels. What if we wanted to ask the window, "How big are you?," and then size our rectangle and diagonals to fit? If you go back and look on the documentation page for the Graphics class (java.awt.Graphics.html -- the file that lists all the available drawing functions), you will see that one of the functions is called getClipBounds. Click on this function name to see the full description. This function accepts no parameters but instead returns a value of type Rectangle. The rectangle it returns contains the width and height of the available drawing area. If you click on Rectangle in this documentation page you will be taken to the documentation page for the Rectangle class (java.awt.Graphics.html). Looking in the Variable Index section at the top of the page, you find that this class contains four variables named x, y, width and height, respectively. What we want to do, therefore, is get the clip boundary rectangle using getClipBounds and then extract the width and height from that rectangle and save the values in the width and height variables we created in the previous example, like this:

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Rectangle;

public class FirstApplet extends java.applet.Applet
{

    public void paint(Graphics g)
    {
        int width;
        int height;
        Rectangle r;

        r = g.getClipBounds();
        width = r.width - 1;
        height = r.height - 1;

        g.drawRect(0, 0, width, height);
        g.drawLine(0, 0, width, height);
        g.drawLine(width, 0, 0, height);
    }
}

When you run this example, what you will notice is that the rectangle and diagonals exactly fit the drawing area. Plus, when you change the size of the window, the rectangle and diagonals redraw themselves at the new size automatically. There are five new concepts introduced in this code, so let's look at them:

  1. First, because we are using the Rectangle class we need to import java.awt.Rectangle on the third line of the program.
  2. We have declared three variables in this program. Two (width and height) are of type int and one (r) is of type Rectangle.
  3. We used the getClipBounds function to get the size of the drawing area. It accepts no parameters so we passed it none ("()"), but it returns a Rectangle. We wrote the line, "r = g.getClipBounds();" to say, "Please place the returned rectangle into the variable r."
  4. The variable r, being of the class Rectangle, actually contains four variables -- x, y, width, and height (you learn these names by reading the documentation for the Rectangle class). To access them you use the "." (dot) operator. So the phrase "r.width" says, "Inside the variable r retrieve the value named width." That value is placed into our local variable called width. In the process, we subtracted 1. Try leaving the subtraction out and see what happens. Also try subtracting five instead and see what happens.
  5. Finally, we used width and height in the drawing functions.

One question commonly asked at this point is, "Did we really need to declare variables named width and height?" The answer is, "No." We could have typed r.width - 1 directly into the drawing function. Creating the variables simply makes things a little easier to read, and it's therefore a good habit to fall into.

Java supports several simple variable types. Here are three of the most common:

  • int - integer (whole number) values (1, 2, 3...)
  • float - decimal values (3.14159, for example)
  • char - character values (a, b, c...)

You can perform math operations on simple types. Java understands + (addition), - (subtraction), * (multiplication), / (division) and several others. Here's an example of how you might use these operations in a program. Let's say that you want to calculate the volume of a sphere with a diameter of 10 feet. The following code would handle it:

float diameter = 10;
float radius;
float volume;

radius = diameter / 2.0;
volume = 4.0 / 3.0 * 3.14159 * radius * radius * radius;

The first calculation says, "Divide the value in the variable named diameter by 2.0 and place the result in the variable named radius." You can see that the "=" sign here means, "Place the result from the calculation on the right into the variable named on the left."