This is the 1st HTML5 slant canvas

KIWY logo depicting a kiwi bird with a candle

k i w y

Need a light for your site?

This is the 2nd HTML5 slant canvas

Arithmetic Operators

The basic operators are: + , - , * , / , %
These do arithmetic as expected (addition, subtraction, etc). Division is a special case. For integers, the / operator gives the quotient of a division, and the % operator, called the modulus operator, gives the remainder.

  int remainder = 19 % 5;    // gives the result 4
  int quotient = 19 / 5;     // gives the result 3
This example illustrates the arithmetic operations in Java
public class Arithmetic
{
  public static void main(String[] args)
  {
    int x, y;
    System.out.print("Enter integer value for x: ");
    x = MyInput.readInt();
    System.out.print("Enter integer value for y: ");
    y = MyInput.readInt();

    // display arithmetic results
    System.out.println();
    System.out.println(x + " + " + y + " = " + (x + y));
    System.out.println(x + " - " + y + " = " + (x - y));
    System.out.println(x + " * " + y + " = " + (x * y));
    System.out.println(x + " / " + y + " = " + (x / y));
    System.out.println(x + " % " + y + " = " + (x % y));
    System.out.println();

    // now try it for doubles

    double a, b;
    System.out.print("Enter double (float) value for a: ");
    a = MyInput.readDouble();
    System.out.print("Enter double (float) value for b: ");
    b = MyInput.readDouble();

    // display arithmetic results
    System.out.println();
    System.out.println(a + " + " + b + " = " + (a + b));
    System.out.println(a + " - " + b + " = " + (a - b));
    System.out.println(a + " * " + b + " = " + (a * b));
    System.out.println(a + " / " + b + " = " + (a / b));
    System.out.println(a + " % " + b + " = " + (a % b));
    System.out.println();

  }
}

When doing an arithmetic operation on two operands of the same type, the result is also the same type.  What about operations on mixed numeric types?

  int x = 5; 
  float y = 3.6; 

If we do (x + y), what type will the result have?  In this case, a float. An arithmetic operation on two mixed types returns the larger type (where floating point types are always considered "larger" than integer types, as well). The result of (x + y) will be 8.6.