Java Calculations
An assignment statement is used to store the result of a calculation in a variable. The format of an assignment statement is a variable name followed by an arithmetic expression followed by a semicolon, for example:
gross = net + tax; // Calculate value of expression on right of the = and assign it to variable on left
It is possible to write multiple assignments in a single statement, for example:
x = y = z = 0; // Initialise co-ordinates
For integer calculations, you can use the basic operators +, -, * and / (add, subtract, multiply and divide). The precedence is that multiplication and division are executed before any addition or subtraction operations. For example,
12 - 2*2 + 10/5 is equivalent to 12 - 4 + 2 which makes 10.
You can change this by using parentheses. For example,
(12 - 2)*(2 + 10)/5 is equivalent to 10 * 12 / 5 which makes 24.
You can nest parentheses, in which case the innermost is evaluated first.
Here is an example of a program which adds 2 integers together.
public class IntCalc
{
// The (String[] args) is used for accessing what is passed to the program from the command line
public static void main(String[] args) // static so it works even without an object
{
// Declare and initialise three variables
int x = 9;
int y = 18;
int tot = 0;
tot = x + y; // Calculate the total
System.out.println("Integer calculation program");
System.out.println("The total is " + tot); // Display the result
}
}
For details of how println() works, click here.
If your Java environment does not display the output long enough to see it, add the code included in the following example
import java.io.IOException; // For code that delays ending the program
public class IntCalc
{
public static void main(String[] args)
{
// Declare and initialize three variables
int x = 9;
int y = 18;
int tot = 0;
tot = x + y; // Calculate the total
System.out.println("Integer calculation program");
System.out.println("The total is " + tot); // Display the result
// Code to delay ending the program by waiting for you to press enter
try
{
System.in.read(); // Read some input from the keyboard
}
catch (IOException e) // Catch the input exception
{
return; // and just return
}
}
}
