- Forward


Updating
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • We need keep track of something that is changing
    • We want to refer to thing that is changing using one name
  • Examples:
    • Age changes over time
    • Temperature changes over time
    • Position changes over space
Review
Back SMYC Forward
  • The Pre/Post Increment/Decrement Operators:
    • ++
    • --
  • A Limitation:
    • They only change the variable by 1
Thinking About the Problem
Back SMYC Forward
  • The Assignment Operator:
    • Takes the result of evaluating the expression on its right and puts it in the memory location identified by the variable on its left
  • Some Examples:
    • javaexamples/programmingpatterns/Updating.java (Fragment: additionage)
       
Thinking About the Problem (cont.)
Back SMYC Forward
  • An Observation:
    • These three assignment statements are particularly easy to understand because the expression on the right side of the assignment operator does not involve the variable on the left side
  • A Different Situation:
    • javaexamples/programmingpatterns/Updating.java (Fragment: update1)
       
Thinking About the Problem (cont.)
Back SMYC Forward
  • To the Non-Programmer:
    • This statement looks like a mistake
  • To the Programmer:
    • Nothing about the syntax of assignment statements prevents this
The Pattern
Back SMYC Forward
  • The Idea:
    • Use the same variable on the left and right sides of the assignment operator in order to change its value
  • An Abstract Version:
    • value = value operator adjustment
  • Why It Works:
    • The assignment operator has the lowest precedence so it is executed last
    • The assignment operator places the value on the right side into the variable on the left side
A Gradebook Example
Back SMYC Forward
javaexamples/programmingpatterns/Updating.java (Fragment: grade)
 
A Retail Sales Example
Back SMYC Forward
javaexamples/programmingpatterns/Updating.java (Fragment: sales)
 

Tracing the Execution

Updating
A Banking Example
Back SMYC Forward
javaexamples/programmingpatterns/Updating.java (Fragment: banking)
 
Compound Assignment Operators
Back SMYC Forward
  • The Operators:
    • +=
    • *=
    • -=
    • /=
    • %=
  • Examples:
    • age += 1; price /= 2.0; grade -= penalty;
A Warning
Back SMYC Forward
  • A Question:
    • Will the statements i =+ 1; and j =- 1; compile?
  • The Answer:
    • Yes because they are the assignment operator followed by a unary positive/negative operator (but they are not compound assignment operators)
    • Expand
There's Always More to Learn
Back -