More variables and arithmetic

Numeric variables

String variables are all very well, but what if we want to store numbers. Well, we could store them as strings, but then we wouldn't be able to perform arithemetic on them. For instance, the following program contains two numbers stored as variables:

import java.awt.*;
import java.applet.*;

public class show_concat extends Applet
 {
    public void init ()
     { String first_number = "34";
       String second_number = "106";
     }

    public void paint (Graphics g)
     { g.drawString(first_number + second_number,10,10);
     }
 }

However, instead of displaying the value 140 as you might expect, Java concatenates the two strings into one, 34106, and displays that. No, we need special types for holding numbers. Fortunately, there are quite a few to choose from:

Would you like to see an example of these? All right, then, you twisted my arm ...

import java.awt.*;
import java.applet.*;

public void class show_numeric_variables extends Applet
{
  public void init ()
  { int x = 34;
    double y = -400;
    float another_variable = 6.0223;
  }

  public void paint (Graphics g)
  { g.drawString("The value of x is ", 10, 10);
    g.drawString("" + x, 150, 10);
    g.drawString("The value of y is ", 10, 30);
    g.drawString("" + y, 150, 30);
    g.drawString("The value of another_variable is ", 10, 50);
    g.drawString("" + another_variable, 150, 50);
  }
}

(I'll explain the reason for including "" + later).

The variables have been declared using the declaration + assignment method that you saw in the previous section. The values of the variables can be displayed using g.drawString, just as the values of string variables can be. Note, again, that when you want the value of a numeric variable displayed, don't put any quotation marks round the variable name. For instance, if you replaced the second drawString instruction in the program above with

g.drawString("x", 150, 10);

then the program displays the letter x on the screen, rather than the value 34.

Displaying numbers

You are probably asking why I put those quotation marks in just before the variable name, i.e. "" + x rather than just x etc. The reason was that drawString requires its first argument to be a string rather than a number and the quotation marks "fool" it into accepting the numeric variable name as a string. The same would apply if you wanted to display a number:

g.drawString("" + 5608, 150, 10);

... although, in that case it would be easier simply to write:

g.drawString("5608", 150, 10);

But what about a statement like this?

g.drawString("Here is a simple sum:" + 3 + 4, 10, 10);

This contains two plus signs, and we want to know whether Java will interpret them as addition (3 + 4 = 7) or as string concatenation. In fact, if you include this line in a program, it produces the following output:

Here is a simple sum:34

It has not added the numbers together, but treated the three items as strings and joined them all together (concatenated them). To persuade it that the second plus sign means simple addition, enclose the sum within brackets:

g.drawString("Here is a simple sum:" + (3 + 4), 10, 10);

The extra brackets mean "Do the 3 + 4 first", then deal with that answer and the string that comes before it". The result will be as follows:

Here is a simple sum:7

which is probably what you were expecting.

Be careful of assignment

What's wrong with the following statement?

int value = 4.6;

Well, value is declared to be an integer, and yet we are trying to set it to a decimal value. The Java compiler will complain if you try to include a line like that in your program. It will produce some message talking about "incompatible assignment". On the other hand, an assignment like this is perfectly acceptable:

double q = 70;

This is because there is nothing to stop a double variable from holding a whole number. The compiler won't complain in any way. However, if you want to set a double or float variable to a number which happens to be a whole number, then it is more normal to put .0 on the end of the number to indicate that it is being assigned to a floating point variable:

double q = 70.0;

Variables can be assigned to other numbers at any point in the program, or to other variables, providing that they are suitable, of course:

public void init()
{ double height = 1.66;
  int x;
  x = 2;                 // This is perfectly legal
  // x now has the value 2
  x = height;            // This is not legal!
}

The same applies to string variables, of course:

public void init()
{ String greeting = "Bonjour";
  String foreign_word;
  int x = 2;
  foreign_word = greeting;      // No problem
  foreign_word = x;             // Definitely a problem!
  x = foreign_word;             // Also an illegal instruction!
}

Please note! Here's a warning about constant numbers assigned to float variables. in this case, you should put the letter f after the number itself. If you don't, then Java will assume that the constant is a double rather than a float. This is the correct way to assign a float variable:

float q = 2.3f;

... rather than this ...

float q = 2.3;

The only difference between them is a letter f.

Simple Arithmetic

Arithmetic can be done using variables, as shown in the following program. The symbol * and / are used for multiplication and division respectively.

import java.awt.*;
import java.applet.*;

public void class show_numeric_variables extends Applet
{
  public void init ()
  { double a, b;       // Note the variables have been
    a = 5.1;           // both declared on one line
    b = 2.9;
    double sum, diff, product, quot;
    sum = a + b;
    diff = a - b;
    product = a * b;   // Multiplies a and b
    quot = a / b;      // Divides a by b
  }

  public void paint (Graphics g)
  { String blurb = " of " + a + " and " + b + " is ";
    g.drawString("The sum" + blurb + sum, 10, 20);
    g.drawString("The difference" + blurb + diff, 10, 40);
    g.drawString("The product" + blurb + product, 10, 60);
    g.drawString("The quotient" + blurb + quot, 10, 80);
  }
}

There are several things new about this program. I thought I'd use it to kill quite a few birds with one stone:

Brackets

What value would the variable calc be set to here?

calc = 2 + 3 * 5;

If you said 25 (on the grounds that 2 + 3 = 5 and 5 x 5 = 25), then you would be wrong! In Java (as in mathematics), multiply and divide are both always done before add and subtract. This fact is technically called operator precedence. The first calculation is 3 x 5, then 2 is added to give the final answer of 27. The same thing applies if variables are included:

another_calc = 10 - temp1 / temp2 * temp3 + 90;

Firstly, temp1 is divided by temp2 and then the answer is multiplied by temp3. Then the result of those two calculations is subtracted from 10 and finally 90 is added. You'll notice that when Java has a multiply and a divide to deal with, then it does them in strict left-to-right order.

You can temporarily "promote" add and subtract to be done before multiply and divide by enclosing them within brackets. Brackets always mean "Do me first" regardless of operator precedence. If we alter the previous statement so that is as follows ...

another_calc = (10 - temp1) / temp2 * (temp3 + 90);

In this case, (10 - temp1) is calculated first, and the answer is divided by temp2. Then (temp3 + 90) is calculated, and the answer multiplied by the previous answer. That then gives the result which is assigned to the variable another_calc. There is no reason why you can't have various pairs of brackets, all "nested" within each other. Consider the following:

my_variable = 4*(3 - 2*(x + 5) + 6*(x + 7));

The brackets enclosing x + 5 and x + 7 are nested within the brackets after the 4*.

The modulo operator, %

There is a special operator (with the same priority as %) which gives the remainder when a division is performed. However, it can only be applied to int or long values (variables or numbers) as division of floating point numbers produces no remainder. This is how it works:

int answer = 40 % 7;
g.drawString(answer, 10, 10);  // Displays 5

int x = (first + 2) % 20;      // Remainder when (first+2) is divided by 20

If the brackets were missed out on the second calculation, then the first part of that calculation would be 2 % 20, which would produce the value 2, and then that would be added to the variable first. The answer is then assigned to the variable x.

Implicit conversions

You can do a certain amount of "mixing and matching" of variable types in expressions, providing you don't try to assign inappropriate values to variables. Consider the following:

float y = 3.4;
int z = 100;
double x;
x = 34 + y * z;

In this case, a float variable is being multipled by an int variable. In fact, the value of z is converted to a float before the calculation is carried out. Please note - the value of z does not change (it remains as 100, and z remains an int variable), but a floating point equivalent of z is created and lasts just long enough for the calculation to take place producing a floating point answer 340.0

The last part of the calculation involves an integer value 34 being added to 340.0. In this case, the value 34 is temporarily converted to the floating point equivalent 34.0 before being added to 340.0 to give 374.0. This floating point value is then converted to a double value before being stored in x.

Also note that if x had been declared to be of type int, then the program would not have compiled as the answer to the calculation is a floating point value and that can't be assigned to an int variable.

Java is pretty good at converting variables, but there is one situation where it doesn't, and that is "integer division" ....

Note carefully!

A warning about integer division

What do you think the following program will display on the screen?

import java.awt.*;
import java.applet.*;

public class little extends Applet
{ 
    public void paint (Graphics g)
    { double value = 10 / 3;
      g.drawString("" + value,50,50);
    }
}

If you said 3.33 or 3.33333 or something similar, then you are wrong. In fact, the figure produced is 3.0. What Java has done is assumed that because the two figures being divided are both integers, then the answer is to be an integer as well, and it is rounded down (always down, never up!) to 3.0. Even though the answer is being assigned to a floating point variable (of type double), the thing that Java takes notice of is the two numbers involved in the division itself.

If either of the two numbers involved were floating point numbers, then the division would be carried out properly. For instance, if the crucial line were changed to any one of the following ...

double value = 10.0 / 3;
double value = 10 / 3.0;
double value = 10.0 / 3.0;

... then the value displayed is 3.3333333333 as you might expect.


Go back
Top of the page
Main menu
Go on
Go back
Top of page
Main menu
Go on