Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a variable has changed?

Tags:

java

I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:

int x = 1;
int initialx = x;

...//code that may or may not change the value of x

if (x!=initialx){
    doOneTimeTaskIfVariableHasChanged();
    initialx = x; //reset initialx for future change tests
}  

Is there a better/simpler way of doing this?

like image 321
Amplify91 Avatar asked Mar 23 '11 06:03

Amplify91


People also ask

How do you know if a variable has changed on Roblox?

There are multiple ways to do it. Use a Value Instance and use the Changed or PropertyChanged event to do it. Use the __newindex metamethod in a metatable to do it.

When a variable is changed what happens to the value?

When you reassign a variable to another value, it simply changes the reference to that new value and becomes bound to it.

Can a variable have its value changed?

A variable is a data item whose value can change during the program's execution.

Can variables change over time?

It is called a variable because the value may vary between data units in a population, and may change in value over time.


2 Answers

Example:

create a variable with the same name with a number.

int var1;
int var2;

if(var1 != var2)
{
//do the code here

var2 = var1;
}

hope this help.

like image 130
Santiago Perez Avatar answered Sep 24 '22 03:09

Santiago Perez


Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:

public class X
{
    private int x = 1;

    //some other code here

    public void setX(int proposedValueForX)
    {
       if(proposedValueForX != x)
       {
           doOneTimeTaskIfVariableHasChanged();
           x = proposedValueForX;
       }
    }
}
like image 42
james_bond Avatar answered Sep 23 '22 03:09

james_bond