Difference between revisions of "Increment and Decrement Operators"

From CompSciWiki
Jump to: navigation, search
(Change the codeblock tag to outputblock in Review Output)
 
(35 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[Java Fundamentals]]|Introduction=Increment and decrement are arithmetic operators which quickly add or subtract one from a variable. These operators work on basic data types such as int and long. These operators can appear as an expression by themselves or as part of a complex expression. Increment and decrement can be used to add or subtract one from a variable.|Overview=This section will teach you about the increment and decrement operators, how to use them, the distinction between pre/post-increment and pre/post-decrement, and about special cases to watch out for.}}
+
{{Template:1010Topic
 +
|Chapter_TOC=[[Java Fundamentals]]
 +
|Previous=[[Logical Operators]]
 +
|Next=[[Strings]]
 +
|Body=
 +
 
 +
==Introduction==
 +
 
 +
This section outlines alternative syntax for increasing or decreasing the value of a variable. These methods help by allowing code to be written quicker and can even increase legibility. The increment and decrement operators increase or decrease a variable by 1. The combined assignment operator can be used for values other than 1.
 +
 
 +
See page 179 in the Gaddis text: http://tinyurl.com/gaddis179
 +
 
  
 
== The Increment and Decrement Operators ==
 
== The Increment and Decrement Operators ==
  
The increment and decrement operators increase or decrease the value of a variable by 1. The increment operator is <code>++</code> and decrement is <code>--</code>. These operators can be used on int, long, float and double data types. They are primarily used on integer value variables such as int and long. Increasing or decreasing the value of a variable can be done by using the increment or decrement operators.
+
Then increment operator increases the value of a variable by 1 (equivalent to x = x+1). The decrement operator decreases the value of an operator by 1 (equivalent to x = x-1). The increment operator is <code>++</code> and decrement is <code>--</code>. These operators can be used on int, long, float, and double data types. They are primarily used on integers such as int and long.  
 +
 
  
 
== Usage ==
 
== Usage ==
  
There are two ways to use these operators. We can use these operators on their own along with a variable, or as part of a larger expression. Using them as part of a larger expression may be difficult depending on the complexity of the expression. As useful as these operators are, we should always keep in mind that code readability is important.  Care should be taken when using these operators in complex expressions. We look at the two ways of using increment and decrement below.
+
The below code shows how these shorthand operators work.  
 +
{{CodeBlock
 +
|Code=
 +
  x = 1;
 +
  x++; //is a shorter way of writing x = x + 1
 +
  x--; //is a shorter way of writing x = x - 1
 +
  //note: at this point the value of x is 1.  
 +
}}
  
=== Basic Expression ===
+
These shorthand notations do not change any logic in your programming but they do reduce the number of keystrokes. This shorthand notation is especially useful when using loops with counters.
  
We can use these operators by placing them before or after the variable. If the operator is placed before a variable, it is known as preincrement or predecrement. Pre - increment/decrement means the variable is increased or decreased before we use it for anything else. If the operator is placed after a variable, it is known as postincrement or postdecrement. Post - increment/decrement means the variable is used by the expression and then modified after.
 
  
The following code snippet demonstrates the difference between these four operators:
+
REVIEW! What will the following code output?
 +
{{CodeBlock
 +
|Code=
 +
  int marbles= 2;
 +
  System.out.println("You have " + marbles + " marbles.");
 +
  marbles ++;
 +
  System.out.println("Now you have " + marbles + " marbles.");
 +
  marbles --;
 +
  marbles --;
 +
  marbles --;
 +
  System.out.println("Now you have " + marbles + " marbles.");
 +
  marbles --;
 +
  System.out.println("Now you have " + marbles + " marbles.");
 +
}}
  
<pre>
+
REVIEW OUTPUT
  int number = 5;
+
{{OutputBlock
 +
|Code=
 +
You have 2 marbles.
 +
Now you have 3 marbles.
 +
Now you have 0 marbles.
 +
Now you have -1 marbles.
 +
}}
  
  ++number; // preincrement, the variable 'number' would be 6 as a result
+
NOTE: The expression <code>marbles++</code> is pronounced "marbles plus plus" and <code>marbles--</code> is pronounced "marbles minus minus". Does it make sense to you that the programming language C++ ("C Plus Plus") is based on the programming language C?
  number++; // postincrement, the variable 'number' would be 7 as a result
+
  --number; // predecrement, number = 6
+
  number--; // postdecrement, number = 5
+
</pre>
+
  
When an expression is only the increment or decrement operator, there is no difference between post and pre. The results are the same. You can change ++number with number++ and still get the same results.
 
  
These increment and decrement expressions are really shorthand for:
+
== Combined Assignment Operators ==
  
<pre>
+
If you want to use a shortcut for increasing a variable by a value other than 1, you can use a combined assignment operator. For example <code>x = x + y</code> can also be written as <code>x += y</code> or <code>a = a + 2</code> can be written as <code>a += 2</code>. The below table shows you common combined assignment operators.
  number = number + 1; // longer way of writing number++ or ++number
+
  number = number - 1; // longer way of writing number-- or --number
+
</pre>
+
  
Note that the regular [[Your_First_Java_Program#Rules_for_Evaluating_Expressions|rules for arithmetic]] in Java apply here. Be careful not to unintentionally increment or decrement beyond the range a variable can hold. Strange things can happen when this occurs.
+
<table border=1>
 +
<tr>
 +
<td>Operator
 +
<td>Meaning
 +
</tr>
 +
<tr>
 +
<td>x += y
 +
<td>x = x + y
 +
<tr>
 +
<td>x -= y
 +
<td>x = x - y
 +
<tr>
 +
<td>x *= y
 +
<td>x = x * y
 +
<tr>
 +
<td>x /= y
 +
<td>x = x / y
 +
<tr>
 +
<td>x %= y
 +
<td>x = x % y
 +
</tr>
 +
</table>
  
=== Within a Complex Expression ===
 
  
These increment and decrement operators can occur as part of a larger expression as well. Some might write the operator as part of a complex expression to avoid writing the increment or decrement on its own line. In this case, the meaning of the expression may change depending on whether the operator is placed before or after the variable name. It may be easy to add these operators to some complex expressions. Other complex expressions may be a nightmare and should generally be avoided. Again, when using these operators in complex expressions, readability is very important.
+
==Postfix and Prefix Modes==
 +
The operators <code>++</code> and <code>--</code> update the variable at different times depending on whether they are placed before or after the variable. If the operator is placed before a variable, it is known as preincrement or predecrement. Preincrement/predecrement means the variable is increased or decreased before we use it for anything else. If the operator is placed after a variable, it is known as postincrement or postdecrement. Postincrement/postdecrement means the variable is used by the expression and then modified after.
 +
 
 +
In simple expressions it doesn't make a difference if whether you use postfix or prefix mode. In more complex expressions however, the placement of the operator changes the result of the expression. The following code snippet demonstrates the difference between these four operators:
 +
 
 +
{{CodeBlock
 +
|Code=
 +
  int number = 5;
 +
  int y;
  
When a preincrement is done, the variable is changed '''before''' it is used in the expression. Oppositely, when a postincrement is done the variable is changed '''after''' the expression is evaluated.
+
  //the next four simple expressions show how the placement of the operators sometimes works the same way
 +
  ++number; // preincrement, the variable 'number' stores the value 6
 +
  number++; // postincrement, the variable 'number' now stores the value 7
 +
  --number; // predecrement, the variable 'number' stores the value 6
 +
  number--; // postdecrement, the variable 'number' stores the value 5
  
The following example illustrates the difference between pre- and post- increment.
+
  //now, watch how the value of y changes depending on the placement of the operators
 +
  y = number++;  //the value of y is equal to the value in x BEFORE the increment takes place. So y = 5 and number = 6;
 +
  y = ++number;  //this time the value of number is increased before the value is assigned to y. So y = 7 and number = 7.
  
<pre>
 
  int number = 3;
 
  int value = (++number) * 2; // number is increased to 4 and then multiplied by 2
 
  // value = 8, number = 4
 
  
  int number = 3;
+
}}
  int value = (number++) * 2; // number is multiplied by 2 and then number is increased to 4
+
  //value = 6, number = 4 
+
</pre>
+
  
As you can see, whether or not the modified value of ''number'' is used as part of the expression in which it occurs depends on which side of the variable the <code>++</code>, and likewise <code>--</code>, occur.
 
  
== Precautions ==
+
Be careful not to unintentionally increment or decrement beyond the range a variable can hold. Strange things can happen when this occurs.
  
Note that some expressions have unclear meaning, such as <code>number = number++</code> or <code>number = ++number</code>. Does the variable ''number'' receive its incremented value, or is number incremented after the assignment has taken place? It is best to avoid assignment to a variable when that variable is incremented or decremented as part of the assignment's expression.
 
  
 
== Summary ==
 
== Summary ==
  
The increment and decrement operators are used to add or subtract one from a variable. These operators can be used on the basic data types of int, long, float, and double. The operators can be used as part of a complex expression or as a simple expression. The most common use for the increment operator is as a counter. The increment and decrement operators easily add or subtract one to a variable.
+
This section shows ways to speed up your typing by using less characters. You can always write expressions the long way, but you may prefer to use increment, decrement or combined assignment operators to save key strokes. You also need to know these shorthand strategies so you can read and understand expressions in programs that you read.
  
 +
The increment and decrement operators are used to add or subtract one from a variable. The operators can be used as part of a complex expression or as a simple expression. The most common use for the increment operator is as a counter, such as in a loop.
  
== Full Program of Examples ==
 
  
<PRE>
+
==Review==
class Increment_Decrement_Example
+
1. What will be printed by the following code?
{
+
{{CodeBlock
 +
|Code=
 +
  int x=2;
 +
  int y;
 +
  x++; 
 +
  System.out.print(x);
 +
  x+=2;
 +
  System.out.print(x);
 +
  y=x++;
 +
  System.out.print(y);
 +
  System.out.print(x);
 +
}}
  
    public static void main(String args[])
 
    {
 
        System.out.println("Starting Increment_Decrement_Example...");
 
       
 
        int a, b, c, d, e, f;
 
        int iResult1, iResult2, iResult3;
 
        int iCount;
 
  
        /*** Section 1
+
2. Note the code below puts the expressions x++ and x+=2 in the println statement. Does output change?
        *
+
{{CodeBlock
        *  A standard use for the increment operator is a counter.
+
|Code=
        * These are generally found in loops and other control structures.
+
  int x=2;
        *
+
  int y;  
        ***/
+
  System.out.print(x++);
       
+
  System.out.print(x+=2);
        System.out.println("\nSection 1:");
+
  y=x++;
       
+
  System.out.print(y);
        iCount = 0;
+
  System.out.print(x);
       
+
}}
        for(int i=0; i<10; i++) // This 'for loop' uses the increment operator
+
        { // You can change the i++ to ++i with no problems
+
       
+
            if(0 == i%2) // We are looking for even numbers and counting them.
+
            {
+
                ++iCount; // this saves having to write 'iCount = iCount + 1;'
+
            }
+
        }
+
       
+
        System.out.println(" There are " + iCount  + " even numbers from 0 to 9.");
+
       
+
       
+
       
+
        /*** Section 2
+
        *
+
        *  Increment and decrement can be used as part of an expression.
+
        * Generally it is a good idea to only use them in simple expressions.
+
        * The more complex the expression, the more difficult it is to predict
+
        * the results.
+
        *
+
        ***/
+
       
+
        System.out.println("\nSection 2:");
+
       
+
        a = 5;
+
        b = 6;
+
        c = 7;
+
       
+
        iResult1 = a + (b++);
+
        iResult2 = (++a) + c;
+
        iResult3 = a + b - (c--);
+
       
+
        System.out.println(" a = " + a + ", b = " + b + ", c = " + c);
+
        System.out.println(" iResult1 = " + iResult1 + ", iResult2 = " +
+
                        iResult2 + ", iResult3 = " + iResult3);
+
       
+
       
+
       
+
        /*** Section 3
+
        *
+
        *  Remember that readability is important to a program. You can create
+
        * quite a mess of code if you are not careful using the increment and
+
        * decrement operators.
+
        *
+
        * Lets add some more variables with a,b and c.
+
        *
+
        ***/
+
       
+
        System.out.println("\nSection 3:");
+
       
+
        a = 1;
+
        b = 2;
+
        c = 3;
+
        d = 4;
+
        e = 5;
+
        f = 6;
+
       
+
        // This expression works, but is it difficult to read?
+
        iResult1 = a++ + ++b - --c + d-- + ++e + --f;
+
       
+
        // What do you think the result is?
+
        System.out.println(" iResult1 = a++ + ++b - --c + d-- + ++e + --f;");
+
        System.out.println(" iResult1 = " + iResult1);
+
       
+
       
+
       
+
        /*** Section 4
+
        *
+
        *  If you are going to use these operators in a complex expression
+
        * you also need to be careful between post and pre.
+
        *
+
        * Take care when you are using these operators and you will rarely have
+
        * problems.
+
        *
+
        ***/
+
+
        System.out.println("\nSection 4:");
+
       
+
        a = 1;
+
        b = 2;
+
        c = 3;
+
       
+
        iResult1 = a++ + c * --b / b--; // This line works?
+
       
+
        // Comment out the line above and uncomment the one below. Then recompile
+
        // and rerun the program. are the results the same?
+
       
+
//        iResult1 = a++ + c * b-- / --b; // Does this expression work?
+
  
        System.out.println(" iResult1 = " + iResult1 + "\n");
 
    }
 
}
 
  
</PRE>
+
ANSWERS: 1) 3556 2) Yes, the value of x is printed first (as 2) then increased to 3. But the combined operator expression x+=2 does not change the output when placed in the print statement.
 +
}}

Latest revision as of 15:23, 8 December 2011

COMP 1010 Home > Java Fundamentals


Introduction

This section outlines alternative syntax for increasing or decreasing the value of a variable. These methods help by allowing code to be written quicker and can even increase legibility. The increment and decrement operators increase or decrease a variable by 1. The combined assignment operator can be used for values other than 1.

See page 179 in the Gaddis text: http://tinyurl.com/gaddis179


The Increment and Decrement Operators

Then increment operator increases the value of a variable by 1 (equivalent to x = x+1). The decrement operator decreases the value of an operator by 1 (equivalent to x = x-1). The increment operator is ++ and decrement is --. These operators can be used on int, long, float, and double data types. They are primarily used on integers such as int and long.


Usage

The below code shows how these shorthand operators work.

 x = 1;
  x++; //is a shorter way of writing x = x + 1
  x--; //is a shorter way of writing x = x - 1
  //note: at this point the value of x is 1. 

These shorthand notations do not change any logic in your programming but they do reduce the number of keystrokes. This shorthand notation is especially useful when using loops with counters.


REVIEW! What will the following code output?

 int marbles= 2;
  System.out.println("You have " + marbles + " marbles.");
  marbles ++;
  System.out.println("Now you have " + marbles + " marbles.");
  marbles --;
  marbles --;
  marbles --;
  System.out.println("Now you have " + marbles + " marbles.");
  marbles --;
  System.out.println("Now you have " + marbles + " marbles."); 

REVIEW OUTPUT

 You have 2 marbles.
 Now you have 3 marbles.
 Now you have 0 marbles.
 Now you have -1 marbles. 

NOTE: The expression marbles++ is pronounced "marbles plus plus" and marbles-- is pronounced "marbles minus minus". Does it make sense to you that the programming language C++ ("C Plus Plus") is based on the programming language C?


Combined Assignment Operators

If you want to use a shortcut for increasing a variable by a value other than 1, you can use a combined assignment operator. For example x = x + y can also be written as x += y or a = a + 2 can be written as a += 2. The below table shows you common combined assignment operators.

Operator Meaning
x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
x %= y x = x % y


Postfix and Prefix Modes

The operators ++ and -- update the variable at different times depending on whether they are placed before or after the variable. If the operator is placed before a variable, it is known as preincrement or predecrement. Preincrement/predecrement means the variable is increased or decreased before we use it for anything else. If the operator is placed after a variable, it is known as postincrement or postdecrement. Postincrement/postdecrement means the variable is used by the expression and then modified after.

In simple expressions it doesn't make a difference if whether you use postfix or prefix mode. In more complex expressions however, the placement of the operator changes the result of the expression. The following code snippet demonstrates the difference between these four operators:

 int number = 5;
  int y; 

  //the next four simple expressions show how the placement of the operators sometimes works the same way
  ++number; // preincrement, the variable 'number' stores the value 6
  number++; // postincrement, the variable 'number' now stores the value 7
  --number; // predecrement, the variable 'number' stores the value 6
  number--; // postdecrement, the variable 'number' stores the value 5

  //now, watch how the value of y changes depending on the placement of the operators
  y = number++;  //the value of y is equal to the value in x BEFORE the increment takes place. So y = 5 and number = 6;
  y = ++number;  //this time the value of number is increased before the value is assigned to y. So y = 7 and number = 7. 


Be careful not to unintentionally increment or decrement beyond the range a variable can hold. Strange things can happen when this occurs.


Summary

This section shows ways to speed up your typing by using less characters. You can always write expressions the long way, but you may prefer to use increment, decrement or combined assignment operators to save key strokes. You also need to know these shorthand strategies so you can read and understand expressions in programs that you read.

The increment and decrement operators are used to add or subtract one from a variable. The operators can be used as part of a complex expression or as a simple expression. The most common use for the increment operator is as a counter, such as in a loop.


Review

1. What will be printed by the following code?

 int x=2;
   int y;
   x++;   
   System.out.print(x);
   x+=2;
   System.out.print(x);
   y=x++;
   System.out.print(y);
   System.out.print(x); 


2. Note the code below puts the expressions x++ and x+=2 in the println statement. Does output change?

 int x=2;
   int y;   
   System.out.print(x++);
   System.out.print(x+=2);
   y=x++;
   System.out.print(y);
   System.out.print(x); 


ANSWERS: 1) 3556 2) Yes, the value of x is printed first (as 2) then increased to 3. But the combined operator expression x+=2 does not change the output when placed in the print statement.

Previous Page: Logical Operators Next Page: Strings