Java Advanced Placement Study Guide:  Assignment and Arithmetic Operators

Sample question:  What is the result of evaluating the expression: 15.5 % 1.55

Published January 7, 2002
By Richard G. Baldwin

Questions

File JavaAP004.htm


Welcome

This is the second lesson in a miniseries of tutorial lessons designed to help you learn the essential features of Java object-oriented programming as identified by The College Board.

Purpose

The purpose of this miniseries is to help you study for, and successfully complete, the Advanced Placement Examinations designed by the College Board.

Once you understand everything in this miniseries, plus the material in the lessons that I published earlier on Java Data Structures, you should understand the Java programming features that the College Board considers essential for the first two semesters of object-oriented programming education at the university level.

Hopefully, that will help you to take and successfully complete the Advanced Placement Examinations.

Approach

These lessons provide questions, answers, and explanations designed to help you to understand the subset of Java features covered by the Java Advanced Placement Examinations (as of October, 2001).

Please see the first lesson in the miniseries entitled Java Advanced Placement Study Guide: Introduction to the Lessons, Primitive Types, for additional background information.

Supplementary material

In addition to the material in these lessons, I recommend that you also study the other lessons in my extensive collection of online Java tutorials, which are designed from a more conventional textbook approach.  You will find those lessons published at Gamelan.com.  However, as of the date of this writing, Gamelan doesn't maintain a consolidated index of my Java tutorial lessons, and sometimes they are difficult to locate there.  You will find a consolidated index at Baldwin's Java Programming Tutorials.

What is Included?

Click here for a preview of the Java programming features covered by this lesson.



1.  What output is produced by the following program?
public class Ap010{
  public static void main(
                        String args[]){
    new Worker().doAsg();
  }//end main()
}//end class definition

class Worker{
  public void doAsg(){
    double myVar;
    myVar = 3.0;
    myVar += 4.0;
    System.out.println(myVar);
  }//end doAsg()
}//end class definition

Answer and Explanation

2.  What output is produced by the following program?

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

class Worker{
  public void doAsg(){
    double myDoubleVar;
    //Integer.MAX_VALUE = 2147483647
    int myIntVar = Integer.MAX_VALUE;
    myDoubleVar = myIntVar;
    System.out.println(myDoubleVar);
  }//end doAsg()
}//end class definition

Answer and Explanation

3.  What output is produced by the following program?

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

class Worker{
  public void doAsg(){
    //Integer.MAX_VALUE = 2147483647
    double myDoubleVar = 
                    Integer.MAX_VALUE;
    int myIntVar;
    myIntVar = myDoubleVar;
    System.out.println(myIntVar);
  }//end doAsg()
}//end class definition

Answer and Explanation

4.  What output is produced by the following program?

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

class Worker{
  public void doAsg(){
    //Integer.MAX_VALUE = 2147483647
    double myDoubleVar = 
                    Integer.MAX_VALUE;
    int myIntVar;
    myIntVar = (int)myDoubleVar;
    System.out.println(myIntVar);
  }//end doAsg()
}//end class definition

Answer and Explanation

5.  What output is produced by the following program?

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

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

Answer and Explanation

6.  What output is produced by the following program?

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

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

Answer and Explanation

7.  What output is produced by the following program?

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

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

Answer and Explanation

8.  What output is produced by the following program?

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

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

Answer and Explanation

9.  What output is produced by the following program?

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

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

Answer and Explanation

10.  What output is produced by the following program?

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

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

Answer and Explanation

11.  What output is produced by the following program?

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

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

Answer and Explanation

12.  What output is produced by the following program?

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

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

Answer and Explanation

13.  What output is produced by the following program?

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

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

Answer and Explanation

14.  What output is produced by the following program?

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

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

Answer and Explanation

15.  What output is produced by the following program?

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

class Worker{
  public void doMod(){
    int x = 11;
    int y = -3;
    System.out.println(
                      x/y + " " + x%y);
  }//end doMod()
}//end class definition

Answer and Explanation



Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com


What is Included?

According to the subset document,

Answers and Explanations

Answer 15

C.  -3 2

Back to Question 15

Explanation 15

String concatenation

This program uses String concatenation, which has not been previously discussed in this series of tutorial lessons.

In this case, the program executes both an integer divide operation and an integer modulus operation, using String concatenation to display both results on a single line of output.

Quotient = -3 with a remainder of 2

Thus, the displayed result is the integer quotient followed by the remainder.

What is String concatenation?

If either operand of the plus (+) operator is of type String, no attempt is made to perform arithmetic addition.  Rather, the other operand is converted to a String, and the two strings are concatenated.

A space character, " "

The string containing a space character (" ") in this expression appears as the right operand of one plus operator and as the left operand of the other plus operator.

If you already knew about String concatenation, you should have been able to figure out the correct answer to the question on the basis of the answers to earlier questions in this lesson.

Answer 14

D.  NaN

Back to Question 14

Explanation 14

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.

Answer 13

D.  1.5499999999999996

Back to Question 13

Explanation 13

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.

Answer 12

C.  -0.010999999999999996

Back to Question 12

Explanation 12

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 is the remainder that results after

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, the result produced by the application of the modulus operation to floating types is not exact.

Answer 11

B.  Runtime Error

Back to Question 11

Explanation 11

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 a runtime error that terminated the program.  The error produced by JDK 1.3 is as follows:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Worker.doMod(Ap020.java:14)
        at Ap020.main(Ap020.java:6)

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.

Answer 10

D.  -2

Back to Question 10

Explanation 10

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 with sign of modulus result

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

Answer 9

C.  Infinity

Back to Question 9

Explanation 9

Floating divide by zero

This program 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 Infinity.

What is the actual value?

The actual value returned by this program is provided by a static final variable in the Double class named POSITIVE_INFINITY.

(There is also a value for NEGATIVE_INFINITY, which is the value that would be returned if one of the operands were a negative value.)

Is this a better approach?

Is this a better approach than throwing an exception as is the case for integer divide by zero?

I will let you be the judge of that.

In either case, you can test the right operand before the divide to assure that it isn't equal to zero.

Cannot use exception handling in this case

For floating divide by zero, you cannot handle the problem by using try-catch.

However, you can test the result following the divide to see if it is equal to either of the infinity values mentioned above.

Answer 8

B.  Runtime Error

Back to Question 8

Explanation 8

Dividing by zero

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

Integer divide by zero is not allowed

This produces a runtime error and terminates the program.

The runtime error is as follows under JDK 1.3:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Worker.doMixed(Ap017.java:14)
        at Ap017.main(Ap017.java:6)
 

Two ways to deal with this sort of problem

One way is to test the right operand before each divide operation to assure 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 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 subsequent lesson.)

Answer 7

E.  33

Back to Question 7

Explanation 7

Integer truncation

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.

The result of rounding

If we round the result 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,

Answer 6

D.  -2147483647

Back to Question 6

Explanation 6

Danger, integer overflow ahead!

This program illustrates a very dangerous situation involving arithmetic using operands of integer types.  This situation involves a condition commonly known as integer overflow.

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

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 can see by the answer to this question, when a value of 2 was added to the largest positive value that can be stored in type int, the incorrect result was a very large negative value.

The result is simply incorrect.  (If you know how to do binary arithmetic, you can figure out how this happens, but that is not a topic for the AP exam.)

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.

Answer 5

C.  4.294967294E9

Back to Question 5

Explanation 5

Mixed-type arithmetic

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

Declare and initialize an int

The method named doMixed() 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 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.

Result is of the wider type

The type of the result is the same as the wider type.

In this case ...

In this case, because the left operand 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.

Answer 4

C.  2147483647

Back to Question 4

Explanation 4

Uses a cast operator

This program, named Ap013.java, differs from the earlier program named Ap012.java in one important respect.

This program uses a cast operator (shown in boldface) to force the compiler to allow a narrowing conversion in order to assign a double value to an int variable.

Here is the cast operator

The statement containing the cast operator is shown below for convenient viewing.
 
    myIntVar = (int)myDoubleVar;

Syntax of a cast operator

The cast operator consists of the name of a type contained in a pair of matching parentheses.

A unary operator

The cast operator always appears to the left of an expression whose type is being converted to the type specified by the cast operator.

Assuming responsibility for potential problems

When dealing with primitive types, the cast operator is used to notify the compiler that the programmer is willing to assume the risk of a possible loss of precision in a narrowing conversion.

No loss of precision here

In this case, there was no loss in precision, but that was only because the value stored in the double variable was within the allowable value range for an int.

In fact, it was the largest positive value that can be stored in the type int.  Had it been any larger, a loss of precision would have occurred.

More on this later ...

I will have quite a bit more to say about the cast operator in subsequent lessons.  I will also have more to say about the use of the assignment operator in conjunction with the non-primitive types.

Answer 3

A.  Compiler Error

Back to Question 3

Explanation 3

Conversion from double to int is not automatic

This program attempts to assign a value of type double to a variable of type int.

Even though we know that the specific double value involved would fit in the int variable with no loss of precision, the conversion from double to int is not a widening conversion.

This is a narrowing conversion

In fact, it is a narrowing conversion because the allowable value range for an int is less than the allowable value range for a double.

The conversion is not allowed by the compiler

Therefore it is not allowed by the compiler.  The following compiler error occurs under JDK 1.3:

Ap012.java:16: possible loss of precision
found   : double
required: int
    myIntVar = myDoubleVar;

Answer 2

C.  2.147483647E9

Back to Question 2

Explanation 2

Declare a double

The method named doAsg() first declares a local variable of type double named myDoubleVar without providing an initial value.

Declare and initialize an int

Then it declares an int variable named myIntVar and initializes its value to the integer value 2147483647 (you learned about Integer.MAX_VALUE in an earlier lesson).

Assign the int to the double

Following this, the method assigns the int variable to the double variable.

An assignment compatible conversion

This is an assignment compatible conversion.  In particular, the integer value of 2147483647 is automatically converted to a double value and stored in the double variable.

The double representation of that value is what appears on the screen later when the value of myDoubleVar is displayed.

What is an assignment compatible conversion?

An assignment compatible conversion for the primitive types occurs when the required conversion is a widening conversion.

What is a widening conversion?

A widening conversion occurs when the allowable value range of the type of the left operand of the assignment operator is greater than the allowable value range of the right operand of the assignment operator.

A double is wider than an int

Since the allowable value range of type double is greater than the allowable value range of type int, assignment of an int value to a double variable is allowed, with conversion from int to double occurring automatically.

A safe conversion

It is also significant to note that there is no loss in precision when converting from an int to a double.

An unsafe but allowable conversion

However, a loss of precision may occur when an int is assigned to a float, or when a long is assigned to a double.

What would a float produce?

The value of 2.14748365E9 shown for selection D is what you would see for this program if you were to change the double variable to a float variable.  (Contrast this with 2147483647 to see the loss of precision.)

Widening is no guarantee that precision will be preserved

The fact that a type conversion is a widening conversion does not guarantee that there will be no loss of precision in the conversion.  It simply guarantees that the conversion will be allowed by the compiler.  In some cases, such as that shown above, an assignment compatible conversion can result in a loss of precision, so you always need to be aware of what you are doing.

Answer 1

E.  7.0

Back to Question 1

Explanation 1

Declare but don't initialize a double variable

The method named doAsg() begins by declaring a double variable named myVar without initializing it.

Use the simple assignment operator

The simple assignment operator (=) is then used to assign the double value 3.0 to the variable.  Following the execution of that statement, the variable contains the value 3.0.

Use the arithmetic/assignment operator

The next statement uses the combined arithmetic/assignment operator (+=) to add the value 4.0 to the value of 3.0 previously assigned to the variable.  The following two statements are functionally equivalent:

myVar += 4.0;
myVar = myVar + 4.0;

Two statements are equivalent

This program contains the first statement listed above.  If you were to replace the first statement with the second statement, the result would be the same.

In this case, either statement would add the value 4.0 to the value of 3.0 that was previously assigned to the variable named myVar, producing the sum of 7.0.  Then it would assign the sum of 7.0 back to the variable.  When the contents of the variable are then displayed, the result is that 7.0 appears on the computer screen.

No particular benefit

To the knowledge of this author, there is no particular benefit to using the combined arithmetic/assignment notation other than to reduce the amount of typing required to produce the source code.

Four similar operators in the subset

In addition to the += operator, there are four other similar operators, which, according to the subset document,

"are part of the AP Java subset although they are used simply as a shorthand and will not be used in the adjustment part of a for loop."
The set of five

The complete set of five combined arithmetic/assignment operators is as follows:

In all five cases, you can construct a functionally equivalent arithmetic and assignment statement in the same way that I constructed the functionally equivalent statement for += above.

This is not all

Note that the Java language provides some additional operators having similar syntax that are not included in the above list, and are not part of the AP Java subset.



Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-