I confirmed my initial thoughts that in Java a variable can only be changed if specifically told to change:
public class VariableChangeTest {
public VariableChangeTest() {
}
public static void main(String[] args) {
int first = 1;
int second = 2;
int third = first + second;
System.out.println("first = " + first); /* first = 1 */
System.out.println("second = " + second); /* second = 2 */
System.out.println("third = " + third); /* third = 3 */
second += first;
System.out.println("********************");
System.out.println("first = " + first); /* first = 1 */
System.out.println("second = " + second); /* second = 3 */
System.out.println("third = " + third); /* third = 4 */
first += third;
System.out.println("********************");
System.out.println("first = " + first); /* first = 5 */
System.out.println("second = " + second); /* second = 3 */
System.out.println("third = " + third); /* third = 8 */
}
}
In this example, the comments reflect I want to happens, not what actually happens. What actually happens is that third
always stays at what first + second
originally was, that is, 3. What I want is to be able to assign a variable to the current value of one or more other variables, so that it updates if one of its right-hand assignment values changes. Is this possible in Java?