Basic arithmetic operations
Involve two "operands" that must be numeric primitive values (non-boolean). Because char data has a positive integer equivalent, it may be used in arithmetic operations.
Appear in expressions. The calculated result of the expression is often assigned to a variable according to the following general syntax:
identifier = expression;
Five arithmetic operations are part of the Java language. Other useful arithmetic operations, such as exponentiation and trigonometric functions, are provided as packaged code in the Math class and will be covered later.
Operator Operation + Addition - Subtraction * Multiplication / Division % Modulo (remainder)
Addition, subtraction, and multiplication
Act as you would expect. They calculate the sum, difference, and product of two numeric operands.
Example: This program reads two integer values from the user. It then displays the sum, difference, and product of the two numbers.
public class App {
public static void main(String[] args) {
// Variables for holding two integer values entered by the user
int x;
int y;
// Prompt for and read the two integer values
System.out.print("First integer: ");
x = Keyboard.readInt();
System.out.print("Second integer: ");
y = Keyboard.readInt();
// Display the sum, difference, and product of the two integers
System.out.println("\n\t" + x + " + " + y + " = " + (x + y));
System.out.println("\t" + x + " - " + y + " = " + (x - y));
System.out.println("\t" + x + " * " + y + " = " + (x * y));
}
}Notes:
This sample reads data from the keyboard, which isn't easy in Java. My custom Keyboard class makes it easier. For information on using the class, click here.
The prompt messages use the print() method instead of println(). They are virtually the same except that print() leaves the insert point at the end of the current line so that the user's entry will appear on the same line as the prompt.
Overflow or underflow will result in an erroneous value if the calculation is mathematically too large or too small to be properly stored in memory
Example: This program results in an overflow and displays an erroneous sum.
public class App {
public static void main(String[] args) {
// Two extremely large integer values
int x = 2000000000; // 2 billion.
int y = 1000000000; // 1 billion.
// Display an erroneous sum due to overflow
System.out.println("The erroneous sum is " + (x + y));
}
}
Division
When both operands are integers, the result is the integer quotient obtained by dividing the first operand (the dividend) by the second operand (the divisor)
The sign of the result is determined by the rules of algebra
When both operands are integers and the second operand is zero, a run time exception occurs
Example: The following program reads two integer values from the user and displays the result of dividing the first number by the second number. If the user enters 0 for the second number, a runtime exception will occur.
public class App {
public static void main(String[] args) {
// Variables for holding two integer values entered by the user
int x;
int y;
// Prompt for and read the two integer values
System.out.print("First integer (dividend): ");
x = Keyboard.readInt();
System.out.print("Second integer (divisor): ");
y = Keyboard.readInt();
// Calculate and display the integer quotient
System.out.println("\n\t" + x + " / " + y + " = " + (x / y));
}
}Note: When testing this code, be sure to try division by zero.
When either operand is floating-point, a floating-point value will result that is an approximation. For example, the following program will give you a result other than the expected "3.0"
public class App {
public static void main(String[] args) {
System.out.println(2.1/.7);
}
}
When either number is floating-point, division by zero is allowed. The result will be + infinity.
Example: This program reads two floating-point values from the user. It then displays the result of dividing the first number by the second number. If the user enters 0 for the second number, a result of + infinity will occur.
public class App {
public static void main(String[] args) {
// Variables for holding two floating-point values entered by the user
double x;
double y;
// Prompt for and read the two floating-point values
System.out.print("First floating-point number (dividend): ");
x = Keyboard.readDouble();
System.out.print("Second floating-point number (divisor): ");
y = Keyboard.readDouble();
// Calculate and display the result
System.out.println("\n\t" + x + " / " + y + " = " + (x / y));
}
}Note: When testing this code, be sure to try division by zero.
Modulo (remainder)
When both operands are integers, the result is the integer remainder obtained by dividing the first operand by the second operand.
The sign of the result is the same as the sign of the first operand.
When both operands are integers and the second operand is zero, a run time exception occurs
Example: This program reads two integer values from the user. It then displays the remainder that results from dividing the first number by the second number. If the user enters 0 for the second number, a runtime exception will occur.
public class App {
public static void main(String[] args) {
// Variables for holding two integer values entered by the user
int x;
int y;
// Prompt for and read the two integer values
System.out.print("First integer (dividend): ");
x = Keyboard.readInt();
System.out.print("Second integer (divisor): ");
y = Keyboard.readInt();
// Calculate and display the integer remainder
System.out.println("\n\t" + x + " modulo " + y + " = " + (x % y));
}
}Note: When testing this code, try different integer values with different signs. Also try a second operand of zero.
When either number is floating-point, the result is a floating-point approximation of the fractional value remaining after an integral number of subtractions. For example,
2.2 % .7 results in 0.10000000000000031
This is obtained by subtracting .7 from 2.2 until the result is less than .7
The sign of the result is the same as the sign of the first operand
When either number is floating-point, division by zero is allowed. The result will be NaN (meaning Not a Number).
Example: This program reads two floating-point values from the user. It then displays the remainder that results from dividing the first number by the second number.
public class App {
public static void main(String[] args) {
// Variables for holding two floating-point values entered by the user
double x;
double y;
// Prompt for and read the two floating-point values
System.out.print("First floating-point number (dividend): ");
x = Keyboard.readDouble();
System.out.print("Second floating-point number (divisor): ");
y = Keyboard.readDouble();
// Calculate and display the floating-point remainder
System.out.println("\n\t" + x + " modulo " + y + " = " + (x % y));
}
}Note: When testing this code, try different floating-point values with different signs. Also try a second operand of zero.
Arithmetic assignment operations
Combine arithmetic and assignment into a single operation to save coding time
All five basic arithmetic operations have a corresponding arithmetic assignment operator
Operator Operation += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulo (remainder) assignment Example: This program reads a percentage value from the user (such as 5.5) and converts to the correct decimal equivalent (such as 0.055) by using the division assignment operator.
public class App {
public static void main(String[] args) {
// Variable for holding a percentage entered by the user
double percent;
// Prompt for and read the percentage
System.out.print("Enter a percentage in n.nn format: ");
percent = Keyboard.readDouble();
// Convert it to its decimal equivalent and display the result
percent /= 100;
System.out.println("The decimal equivalent is " + percent);
}
}Note: The arithmetic assignment operators always result in the first operand (the one on the left) being modified.
Increment and decrement operations
Require only one operand. They are said to be "unary" operators.
Are the most efficient way to add or subtract one from a numeric variable
Operator Operation ++ Increment (add one) -- Decrement (subtract one)
Can be placed on the left or right of a numeric variable. On the left, the increment or decrement occurs before the expression is evaluated. On the right, the increment or decrement occurs after the expression has been evaluated.
Example: The following program reads two integer values from the user. It increments the first value and decrements the second.
public class App {
public static void main(String[] args) {
// Variables for holding two integer values to be entered by the user
int x;
int y;
// Prompt for and read the two values
System.out.print("Enter an integer to be incremented: ");
x = Keyboard.readInt();
System.out.print("Enter an integer to be decremented: ");
y = Keyboard.readInt();
// Perform the increment and decrement and display the results
x++;
System.out.println("The new values are " + x + " and " + --y);
}
}Note: It is best to use a stand-alone statement when using the ++ or -- operators. It makes your code easier to read.
Conversions
Are performed automatically when mixed numeric types appear within an expression. Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a "widening" conversion.
The order of conversion (from narrowest to widest) is as follows. Memorize this table!
byte | short char \
/
int | long | float | double
Example: This program to convert a fahrenheit temperature to celsius will NOT compile.
public class App {
public static void main(String[] args) {
// Variables for holding fahrenheit and celsius temperatures
double tempF;
float tempC;
// Prompt for and read the fahrenheit temperature
System.out.print("Enter the fahrenheit temperature (nn.n): ");
tempF = Keyboard.readDouble();
// Convert to celsius and display the result
tempC = 5 * (tempF - 32) / 9;
System.out.println("Celsius equivalent is " + tempC);
}
}Note: To fix the compile error in this code, tempC must be double or tempF must be float. Alternatively, the result of the expression can be "cast" as float (the next topic).
Casts
Are a programmer's way of telling the compiler to ignore possible loss of data or precision that might result from a conversion
Should be used with caution. Data loss is not to be taken lightly. The general syntax is
identifier = (data-type) expression;
Example: This is a corrected version of the previous program that uses a cast to prevent the compile error.
public class App {
public static void main(String[] args) {
// Variables for holding fahrenheit and celsius temperatures
double tempF;
float tempC;
// Prompt for and read the fahrenheit temperature
System.out.print("Enter the fahrenheit temperature (nn.n): ");
tempF = Keyboard.readDouble();
// Convert to celsius and display the result
tempC = (float) (5 * (tempF - 32) / 9);
System.out.println("Celsius equivalent is " + tempC);
}
}Note: The result of the entire expression is double but is cast as float in order to be assigned to the float variable. The additional set of parenthesis are coded around the entire expression to prevent only the integer literal 5 from being cast.
Some thoughts on arithmetic expressions
Arithmetic expressions can be large and complex with several variables, constants, and operators. The order in which operations are performed is the same as in mathematics (multiplication and division first, then addition and subtraction, working from left to right). To avoid confusion, good programmers keep their expressions as simple as possible and use parenthesis for clarity.
Review questions
Which of the following will add one to the value of the numeric variable someNumber? (choose four)
someNumber += 1;
otherNumber = someNumber + 1;
someNumber = someNumber + 1;
++someNumber;
someNumber++;
After execution of the code fragment below, what are the values of variables x, y, and z?
int x, y = 6, z = 7;
x = --y * z++;
x = 35, y = 5, z = 8
x = 42, y = 5, z = 8
x = 35, y = 6, z = 7
x = 42, y = 6, z = 7
x = 48, y = 5, z = 8
What will happen if an attempt is made to compile and execute the following code? You may assume the statements are within a valid main method of a valid application class and that the line numbers are for reference purposes only.
1
2
3
4short a = 5;
byte b = 2;
short c = a - b;
System.out.println("The difference is " + c);
the program will compile and run to display "The difference is 3"
the program will compile and run to display "The difference is c"
the program will compile but an error will occur at run time
a compile error will occur at line 3
a compile error will occur at line 4
What data type and value will result from evaluating the following expression?
(5.0 - 20) % 7
an int with the value -1
a double with the value 1.0
a double with the value -1.0
a float with the value -0.1428571
a float with the value -1.0