# Connexions

You are here: Home » Content » AP Computer Science A, Clarification of the Java Subset » Language Features, Arithmetic Operators

### Lenses

What is a lens?

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

#### In these lenses

• Pythagoras

This collection is included inLens: Mika Kolu's Lens
By: Mika Kolu

Click the "Pythagoras" link to see all content selected in this lens.

Click the tag icon to display tags associated with this content.

### Recently Viewed

This feature requires Javascript to be enabled.

### Tags

(What is a tag?)

These tags come from the endorsement, affiliation, and other lenses that include this content.

Inside Collection (Course):

Course by: R.G. (Dick) Baldwin. E-mail the author

# Language Features, Arithmetic Operators

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: This lesson explains several of the pitfalls awaiting the unsuspecting Java programming student using the arithmetic operators.

## Preface

### General

This tutorial lesson is part of a series of lessons dedicated to the AP Computer Science A Exam .

The purpose of the series is to help you to better understand some of the material that you will find on the website that provides information for the exam.

For example, if you access the AP Computer Science Course Description and scroll down to Appendix A titled AP Computer Science Java Subset , you will find the following specification :

#### Note:

2. Arithmetic operators: +, -, *, /, % are part of the AP Java subset.

(Note: This is the wording that appeared on the website on March 1, 2011. It may change over time.)

May be clear to some, but not to others

While some students and their homeschool parents may know exactly what is meant by this text, others may not. Therefore, my objective will be to elaborate on and attempt to clarify such specifications from a technical viewpoint to help those students and their parents get a better understanding of where they need to concentrate their efforts.

In this lesson, I will provide program code that illustrates some of what the student is expected to know about the arithmetic operators.

### Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

### Supplemental material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com .

## Discussion and sample code

According to Sun's Summary of Operators website , the Java arithmetic operators are shown in Figure 1.

Figure 1: Arithmetic Operators.
Arithmetic Operators.
 + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator

Five arithmetic operators

If you compare Figure 1 with the specification , you will see that all of the arithmetic operators are included in the Java subset. Unlike the case for primitive variables discussed in an earlier lesson, none of the arithmetic operators are excluded from the subset. Therefore, the student is expected to understand how to use all of the arithmetic operators in order to successfully complete the exam.

As indicated in Figure 1 , the + operator is also used for string concatenation, but that is another topic for another lesson.

Are the operators as innocuous as they seem?

At first glance, you might ask why there is a need to elaborate on or to clarify this specification. After all, aren't the arithmetic operators completely innocuous? The fact is that the arithmetic operators may not be as innocuous as they seem. There are several pitfalls involving these operators that can trap the unsuspecting Java programming student.

The subtraction operator is rather innocuous

There is very little to say about the - operator. It performs numeric subtraction as indicated in Figure 1. It is hard to get into trouble doing numeric subtraction.

The other operators are not so innocuous

However, the addition, multiplication, division and remainder operators probably do deserve a little more scrutiny, particularly insofar as to how they behave for different types. (Note that the remainder operator is also known as the modulus operator.)

### Integer division

Let's begin with a question. Which of the following outputs, if any, is produced by the program shown in Listing 1 ?

• A. Compiler Error
• B. Runtime Error
• C. 33.666666
• D. 34
• E. 33

#### Listing 1: Integer division.

public class Division01{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
int myVar01 = 101;
int myVar02 = 3;
System.out.println(myVar01/myVar02);
}//end doWork()
}//end class definition

The first program

Since this the first program code that I have presented in this series of lessons, I will explain some aspects of the code before providing and explaining the answer to the question.

A violation of specification number 18

To begin with, this program, (and many of the other programs that I will present in this series of lessons) , violates specification number 18 in the course description . That specification reads partially as follows:

"18. Visibility: In the AP Java subset, all classes are public."

Overkill

While that probably is a worthwhile requirement in large-scale project development, it is overkill for the simple programs that I will present in this series of lessons. (Note that the class named Worker in Listing 1 is not declared public .)

If I were to declare the Worker class public , it would be necessary for me to put it in a separate disk file named Worker.java . That would complicate my disk management efforts with regard to this series of lessons, and would also complicate your efforts in those cases where you want to copy, compile, experiment with, and execute the code.

All class definitions in the same disk file

Therefore, in most cases, I will omit the public declaration for all classes other than the driver class that contains the main method. That will allow me to put all classes belonging to a single program in a single disk file, and to provide a listing of the program in a form that you can easily copy into your IDE.

Having copied the program into your Java IDE, you can save the source code in a single disk file. Having done that, you can compile and execute the program without having to create a separate disk file for each class definition in the program.

Program organization

As you can see from Listing 1 , this program contains two class definitions:

• Division01 , which is declared public .
• Worker , which is not declared public .

As explained above, all of the source code is contained in a single disk file named Division01.java .

The class named Division01 is what I will frequently refer to as the driver class. In particular, it contains the main method, where execution begins and ends in a Java application.

A simple main method

In accordance with specification 13 of the course description , the main method is very simple. In particular, the main method instantiates a new object of the class named Worker , and calls a method named doWork belonging to that object. All of the work in the program is performed by the method named doWork .

Back to the question...

Now let's get back to the question that was posed earlier . Which of the outputs listed above are produced by the program code in Listing 1 ?

Explanation

This program illustrates the integer truncation that results when the division operator is applied to operands of the integer types.

The result of simple long division

We all know that when we divide 101 by 3, the result is 33.666666 with the sixes extending out to the limit of our arithmetic accuracy. (Confirm it using your hand calculator.)

The result of rounding

If we round the quotient to the next closest integer, the result is 34.

Integer division does not round

However, when division is performed using operands of integer types in Java, the fractional part is simply discarded (not rounded) . The result is the whole number result without regard for the fractional part or the remainder. Thus, with integer division, 101/3 produces the integer value 33.

If either operand is a floating type...

If either operand is one of the floating types,

• the integer operand will be converted to the floating type,
• the quotient will be of the floating type, and
• the fractional part of the quotient will be preserved to some degree of accuracy

And the answer to the question is...

The code in Listing 1 displays 33 on the standard output device (typically the command-line screen) .

### Arithmetic overflow

Let's continue with another question. What output is produced by the program shown in Listing 2 ?

• A. Compiler Error
• B. Runtime Error
• C. 2147483649
• D. -2147483647

#### Listing 2: Arithmetic overflow.

public class Overflow01{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
//Integer.MAX_VALUE = 2147483647
int myVar01 = Integer.MAX_VALUE;
int myVar02 = 2;
System.out.println(myVar01 + myVar02);
}//end doWork()
}//end class definition

Explanation

This program illustrates a dangerous situation involving arithmetic using operands of integer types. This situation involves a condition commonly known as integer overflow or arithmetic overflow . This problem usually involves either the addition or multiplication of integer operands.

The good news

The good news about doing arithmetic using operands of integer types is that as long as the result is within the allowable value range for the wider of the integer types, the results are exact (floating arithmetic often produces results that are not exact) .

The bad news about doing arithmetic using operands of integer types is that when the result is not within the allowable value range for the wider of the integer types, the results are garbage, having no usable relationship to the correct result. (Floating arithmetic has a much higher probability of producing approximately correct results, even though the results may not be exact.)

For this specific case...

As you will see by the answer to this question given below, when a value of 2 (see Listing 2 ) was added to the largest positive value that can be stored in type int , the incorrect result was a very large negative value.

This result is simply not correct. (If you know how to do binary arithmetic, you can figure out how this happens, but that is a topic for another lesson on another day.)

No safety net in this case -- just garbage

Furthermore, there was no compiler error and no runtime error. The program simply produced an incorrect result with no warning.

You need to be especially careful when writing programs that perform arithmetic using operands of integer types. Otherwise, your programs may produce incorrect results without you even knowing that it is happening.

And the correct answer to the question is...

D. -2147483647

### Integer divide by zero

What output is produced by the program in Listing 3 ?

• A. Compiler Error
• B. Runtime Error
• C. Infinity
• D. 11

#### Listing 3: Integer divide by zero.

public class Division03{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
int myVar01 = 11;
int myVar02 = 0;
System.out.println(myVar01/myVar02);
}//end doWork()
}//end class definition

Dividing by zero

This program attempts to divide the int value of 11 by the int value of zero.

Integer division by zero is not allowed

This code produces the runtime error shown in Figure 2 , which terminates the program.

Two ways to deal with this kind of problem

One way is to test the right operand before each divide operation to ensure that it isn't equal to zero, and to take appropriate action if it is.

A second (probably preferred) way is to use exception handling and to surround the divide operation with a try block, followed by a catch block for the type java.lang.ArithmeticException . The code in the catch block can be designed to deal with the problem if it occurs. (Exception handling will be discussed in a future lesson.)

And the answer to the question is...

The code in Listing 3 produces the runtime error shown in Figure 2 .

Figure 2: Runtime error.
Runtime error.
 Exception in thread "main" java.lang.ArithmeticException: / by zero at Worker.doWork(Division03.java:13) at Division03.main(Division03.java:5)

### Floating divide by zero

What output is produced by the program shown in Listing 4 ?

• A. Compiler Error
• B. Runtime Error
• C. -Infinity
• D. 11

#### Listing 4: Floating divide by zero.

public class Division02{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
double myVar01 = -11;
double myVar02 = 0;
System.out.println(myVar01/myVar02);
}//end doWork()
}//end class definition

Floating divide by zero

The program in Listing 4 attempts to divide the double value of -11 by the double value of zero.

No runtime error with floating divide by zero

In the case of floating types, an attempt to divide by zero does not produce a runtime error. Rather, it returns a value that the println method interprets and displays as either Infinity or -Infinity .

What is the actual value?

The actual value returned by the division operation in this program is the value of a static final variable in the Double class named NEGATIVE_INFINITY . (There is also a value for POSITIVE_INFINITY .)

Is this a better approach?

As you learned earlier, if you attempt to divide by zero with integer arithmetic, an exception will be thrown. Is this a better approach than throwing an exception? I will let you be the judge of that. The important thing is that you know what will happen in both cases and be prepared to deal with the consequences.

In either case, you could test the right operand before the divide to ensure that it isn't equal to zero, and then take appropriate action if it is zero.

Cannot use exception handling in this case

For floating divide by zero, you cannot handle the problem by using try-catch because an error or exception won't be thrown. However, you can test the result following the divide to see if it is equal to either of the infinity values mentioned above . Note, however, that you will need to test against the constant values shown above and not against the output produced by the println method.

And the correct answer to the question is...

C. -Infinity

### Mixed-type arithmetic

What output is produced by the program shown in Listing 5 ?

• A. Compiler Error
• B. Runtime Error
• C. 4.294967294E9
• D. 4294967294

#### Listing 5: Mixed-type arithmetic.

public class Mixed01{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
//Integer.MAX_VALUE = 2147483647
int myIntVar = Integer.MAX_VALUE;
System.out.println(2.0 * myIntVar);
}//end doWork()
}//end class definition

This program illustrates the use of arithmetic operators with operands of different types.

Declare and initialize an int

The method named doWork declares a local variable of type int named myIntVar and initializes it with the largest positive value that can be stored in type int .

Evaluate an arithmetic expression

An arithmetic expression involving myIntVar is evaluated and the result is passed as a parameter to the println method where it is displayed on the computer screen.

Multiply by a literal double value

The arithmetic expression uses the multiplication operator (*) to multiply the integer value stored in myIntVar by 2.0 (this literal operand is type double by default) .

Automatic conversion to wider type

When arithmetic is performed using operands of different types, the type of the operand of the narrower type is automatically converted to the type of the operand of the wider type, and the arithmetic is performed on the basis of the wider type.

(By narrower and wider, we mean the width of the range of values that can be accommodated by the type in question.)

Result is of the wider type

The type of the result is the same as the wider type; double in this case.

In this case...

Because the left operand of the multiplication operation in Listing 5 is type double , the int value is converted to type double and the arithmetic is performed as type double . This produces a result of type double , causing the floating value 4.294967294E9 to be displayed on the computer screen.

C. 4.294967294E9

### Signed modulus operations

What output is produced by the program in Listing 6 ?

• A. Compiler Error
• B. Runtime Error
• C. 2
• D. -2

#### Listing 6: Signed modulus operations.

public class Modulus01{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
int myVar01 = -11;
int myVar02 = 3;
System.out.println(myVar01%myVar02);
}//end doWork()
}//end class definition

What is a modulus operation?

In elementary terms, we like to say that the modulus operation returns the remainder that results from a divide operation. In general terms, that is true.

Some interesting behavior

However, the modulus operation has some interesting behaviors that are illustrated in this and the next several questions. This program returns the modulus of -11 and 3, with -11 being the left operand.

What is the algebraic sign of the result?

Here is a rule:

The result of the modulus operation takes the sign of the left operand, regardless of the sign of the quotient and regardless of the sign of the right operand.

In this program, that produced a result of -2. Changing the sign of the right operand would not have changed the sign of the result.

Exercise care using the sign of the modulus result

Thus, you may need to exercise care as to how you interpret the sign of the result when you perform a modulus operation having a negative left operand.

D. -2

### Modulus with zero divisor

What output is produced by the program shown in Listing 7?

• A. Compiler Error
• B. Runtime Error
• C. 2
• D. 11

#### Listing 7: Modulus with zero divisor.

public class Modulus02{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
int myVar01 = -11;
int myVar02 = 0;
System.out.println(myVar01%myVar02);
}//end doWork()
}//end class definition

Integer modulus involves integer divide

The modulus operation with integer operands involves an integer divide. Therefore, it is subject to the same kind of problem as an ordinary integer divide when the right operand has a value of zero.

Program produces a runtime error

In this case, the program produced the runtime error shown in Figure 3 , which terminated the program.

Dealing with the problem

As with integer divide, you can either test the right operand for a zero value before performing the modulus operation, or you can deal with the problem after the fact using try-catch.

The code in Listing 7 produces the runtime error shown in Figure 3 .

Figure 3: Runtime error.
Runtime error.
 Exception in thread "main" java.lang.ArithmeticException: / by zero at Worker.doWork(Modulus02.java:13) at Modulus02.main(Modulus02.java:5)

### Modulus operator with floating types

What output is produced by the program shown in Listing 8 ?

• A. Compiler Error
• B. Runtime Error
• C. -0.010999999999999996
• D. 0.010999999999999996

#### Listing 8: Modulus operator with floating types.

public class Modulus03{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
double myVar01 = -0.11;
double myVar02 = 0.033;
System.out.println(myVar01%myVar02);
}//end doWork()
}//end class definition

Modulus operator can be used with floating types

In this case, the program returns the remainder that would be produced by dividing a double value of -0.11 by a double value of 0.033 and terminating the divide operation at the beginning of the fractional part of the quotient.

Say that again

Stated differently, the result of the modulus operation for floating types is the remainder that results after

• subtracting the right operand from the left operand an integral number of times, and
• terminating the repetitive subtraction process when the result of the subtraction is less than the right operand

(Did you know that division is nothing more than repetitive subtraction and multiplication is nothing more than repetitive addition?)

Modulus result is not exact

According to my hand calculator, taking into account the fact that the left operand is negative, this operation should produce a modulus result of -0.011. As you can see from the answer that follows, the result produced by the application of the modulus operation to floating types is not exact.

And the answer to the question is...

C. -0.010999999999999996

## A totally incorrect modulus result

What output is produced by the program shown in Listing 9 ?

• A. Compiler Error
• B. Runtime Error
• C. 0.0
• D. 1.5499999999999996

### Listing 9: A totally incorrect modulus result.

public class Modulus04{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
double myVar01 = 15.5;
double myVar02 = 1.55;
System.out.println(myVar01%myVar02);
}//end doWork()
}//end class definition

A totally incorrect result

Unfortunately, due to floating arithmetic inaccuracy, the modulus operation in this program produces an entirely incorrect result. The result should be 0.0, and that is the result produced by my hand calculator.

Terminates one step too early

However, this program terminates the repetitive subtraction process one step too early and produces an incorrect remainder.

Be careful

This program is included here to emphasize the need to be very careful how you interpret the result of performing modulus operations on floating operands.

And the answer to the question is...

D. 1.5499999999999996

### Not a Number

What output is produced by the program shown in Listing 10 ?

• A. Compiler Error
• B. Runtime Error
• C. Infinity
• D. NaN

#### Listing 10: Not a number (NaN).

public class Modulus05{
public static void main(String args[]){
new Worker().doWork();
}//end main()
}//end class definition

class Worker{
public void doWork(){
double myVar01 = 15.5;
double myVar02 = 0.0;
System.out.println(myVar01%myVar02);
}//end doWork()
}//end class definition

Floating modulus operation involves floating divide

Because the modulus operation for floating operands involves a floating divide, you might expect the result to be Infinity when the right operand value is 0.0.

Not true!

The modulus operation with floating operands and 0.0 as the right operand produces NaN , which stands for Not a Number .

What is the actual value of Not a Number ?

A symbolic constant that is accessible as Double.NaN specifies the value that is returned in this case. Be careful what you try to do with it. It has some peculiar behavior of its own.

D. NaN

## Run the programs

I encourage you to run the programs that I have presented in this lesson to confirm that you get the same results. Copy the code for each program into your IDE. Then compile and run each program. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

## Resources

I will publish a list containing links to resources in the following module and will update and add to the list as the remaining modules in this collection are published:

## Miscellaneous

This section contains a variety of miscellaneous materials.

### Note:

Housekeeping material
• Module name: Language Features, Arithmetic Operators
• File: Hs01006.htm
• Keywords:
• AP Computer Science
• Java subset
• homeschool

### Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF. I also want you to know that, I receive no income from the Connexions website even if you purchase the PDF version of the module.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX, and have no affiliation with the College Board .

-end-

## Content actions

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

#### Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

#### Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks