Increments

In Java, there are compound assignments. Examples of compund assignment operators are +=, -+, *=, /=, etc.

There are two forms of the ++ and -- operators in Java. The prefix form increments (or decrements) the variable before its value is used in the rest of the expression; the postfix form increments (or decrements) it afterwards.

i++ is a shortcut for i = i + 1. Same with i --. You can use the longer one, but it looks bad and it's a waste of time.

Bad example of using ++: code while(i <= n) { sum += i++; //This won't work. Don't use ++ or -- in expressions. } code Good example of using ++: code while(i <= n) { sum += i; //Like this, use ++ and -- only in separate statements. i ++; }

code The increment operator must be applied to a variable. The following is incorrect:

int x = 15; int result;

result = (x * 3 + 2)++ ; // Wrong! //


 * __Practice Quiz__**

1.)What is the most common operation performed by a program? a. adding int. one to an int. variable b. floating porint division c. object construction d. Internet access

2.)What is the meaning of variable++ ? a. add one to the variable b. add one to the variable after its current value has been used c. Add one to the variable before using its value. d. Double the value in the variable.

3.) What does it print? code int value = 0; int count = 1;

value = count++ ;

System.out.println("value: "+ value " + count: " + count );

code a. value: 0 count: 0 b.value: 0 count: 1 c. value: 1 count: 1 d. value: 1 count: 2

4.) Are the auto-increment and auto-decrement operators (++ and -- ) an essential part of the Java language?

a.No---any program that uses them could be written without them. b.No---they are not fundamental, but some programs could not be written without them. c.Yes---some programs can't be written unless these operators are available d.Yes---because adding or subtracting one can't be done without them.

5.) Fill in the blank so that wages// is divided by two. code wages ____________ 2 ;

code a. *= b. -= c.=/ d. /=

6.) What does the following program output ? code int a = 0; int b = 10;

a = --b ;

System.out.println("a: " + a + " b: " + b ); code a. a:9 b:11 b. a:10 b: 9 c. a: 9 b: 9 d. a: 0 b: 9

7.) Inspect the following code and what does the above program print? code format="code" int x = 99; int y = 10;

y = x++ ;

System.out.println("x: " + x + " y: " + y );

code

a. x : 100 y : 99 b. x: 99 y : 90 c. x: 100 y: 91 d. x: 101 y: 99

__**Answers**__ 1. a. 2. b. 3. d. 4. a. 5. d. 6. c. 7. a.