CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Java

Java Programming
Numeric variables
Arithmetic expressions

The basic operators for arithmetic expressions

Operator Name Description
+ Addition Adds two operands.
- Subtraction Subtracts the right operand from the left.
* Multiplication Multiplies the right and left operands.
/ Division Divides the right operand into the left. If both are integers, the result is an integer.

How to code arithmetic expressions

  • An arithmetic expression consists of one or more operands and arithmetic operators.
  • When an expression mixes int and double variables, Java automatically casts the int types to double types. To keep the decimal places, the variable that receives the result must be a double.

Statements that use simple arithmetic expressions

// integer arithmetic

int x = 14;
int y = 8;
int result1 = x + y; // result1 = 22
int result2 = x - y; // result2 = 6
int result3 = x * y; // result3 = 112
int result4 = x / y; // result4 = 1

// double arithmetic

double a = 8.5;
double b = 3.4;
double result5 = a + b; // result5 = 11.9
double result6 = a - b; // result6 = 5.1
double result7= a * b; // result7 = 28.9
double result8 = a / b; // result8 = 2.5

Statements that increment a counter variable

int invoiceCount = 0;
invoiceCount = invoiceCount + 1; // invoiceCount = 1
invoiceCount = invoiceCount + 1; // invoiceCount = 2

Statements that add amounts to a total

double invoiceAmount1 = 150.25;
double invoiceAmount2 = 100.75;
double invoiceTotal = 0.0;
invoiceTotal = invoiceTotal + invoiceAmount1; // invoiceTotal = 150.25
invoiceTotal = invoiceTotal + invoiceAmount2; // invoiceTotal = 251.00

Statements that mix int and double variables

int result9 = invoiceTotal / invoiceCount // result11 = 125
double result10 = invoiceTotal / invoiceCount // result12 = 125.50

Previous | Declare and initialize | Assignment statements | Arithmetic expressions | Next