Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Arithmetic Operators
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.
ArithmeticOperatorExample.java
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) {
System.out.println(exampleVariableFive);
System.out.println(exampleVariableSix);
System.out.println(exampleVariableSeven);
// This will not print 7.5 because exampleVariableEight is an integer
System.out.println(exampleVariableEight);
System.out.println(exampleVariableNine);
}
}
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.
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;
publicstaticvoidmain (String[] args)
{
/* missing code */
System.out.println("The flightTime is " + hours + " hours and " + minutes + " minutes long.");
}
}