Arithmetic Operators


Arithmetic Operators

🙋 Need help? Ask an expert now!

An arithmetic operator is a mathematical equation, similar to what we have seen in algebra, that takes integers and calculates them in a certain way. Java contains a set of basic common arithmetic operators that can be used to perform a number of different calculations. Take a look at the five operators we will examine.
package exlcode;

public class ArithmeticOperatorExample {

  public static int exampleVariableOne = 15;
  public static int exampleVariableTwo = 2;
  public static int exampleVariableFive = exampleVariableOne + exampleVariableTwo;
  public static int exampleVariableSix = exampleVariableOne - exampleVariableTwo;
  public static int exampleVariableSeven = exampleVariableOne * exampleVariableTwo;
  public static int exampleVariableEight = exampleVariableOne / exampleVariableTwo;
  public static int exampleVariableNine = exampleVariableOne % exampleVariableTwo;

  public static void main(String[] args) {
    // This will not print 7.5 because exampleVariableEight is an integer

Just as we learned in math class, Java honors the order in which mathematical operations should be performed. Division, multiplication, modulus (%), followed by any addition and subtraction. A minor difference between math principles and Java is if we are dividing two integers, the Java answer will also be an integer, not a number with a decimal point, following the same rule of truncation we discussed earlier. Let's look at an example: the Java result for 15/2 will be 7, not 7.5.

One new operator to you may be the modulus operator, whose function returns the remainder of dividing the first number by the second number.

Edit Me on GitHub!

Application Question

Given the fact that variable flightTime is larger that 60, which of the following can be used to replace /* missing code */ so that the flightTime can be displayed in hours and minutes?

public class TestClass()
  int flightTime = 130;
  int minutes = 0;
  int hours = 0;

  public static void main (String[] args)
    /* missing code */
    System.out.println("The flightTime is " + hours + " hours and " + minutes + " minutes long.");