Arithmetic operations, conversions, and casts

 

Basic arithmetic operations

identifier = expression;

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo (remainder)

 

Addition, subtraction, and multiplication

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:

  1. 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.

  2. 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.

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

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.

public class App {
  public static void main(String[] args) {
    System.out.println(2.1/.7);
  }
}

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)

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.

2.2 % .7   results in   0.10000000000000031

This is obtained by subtracting .7 from 2.2 until the result is less than .7

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

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

Operator Operation
++ Increment (add one)
-- Decrement (subtract one)

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

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

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

  1. Which of the following will add one to the value of the numeric variable someNumber?  (choose four)

  1. someNumber += 1;

  2. otherNumber = someNumber + 1;

  3. someNumber = someNumber + 1;

  4. ++someNumber;

  5. someNumber++;

  1. 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++;

  1. x = 35, y = 5, z = 8

  2. x = 42, y = 5, z = 8

  3. x = 35, y = 6, z = 7

  4. x = 42, y = 6, z = 7

  5. x = 48, y = 5, z = 8

  1. 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
4
short a = 5;
byte b = 2;
short c = a - b;
System.out.println("The difference is " + c);
  1. the program will compile and run to display "The difference is 3"

  2. the program will compile and run to display "The difference is c"

  3. the program will compile but an error will occur at run time

  4. a compile error will occur at line 3

  5. a compile error will occur at line 4

  1. What data type and value will result from evaluating the following expression?

(5.0 - 20) % 7

  1. an int with the value -1

  2. a double with the value 1.0

  3. a double with the value -1.0

  4. a float with the value -0.1428571

  5. a float with the value -1.0