More Assignment Operators

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page
int x = 99;
int y = 10;
y = --x ;
System.out.println("x: " + x + "  y: " + y );

Answer:

x: 98 y: 98

More Assignment Operators

The operators +, -, *, /, (and others) can be can be used with = to make combined operators. For example, the following adds 5 to sum:

sum += 5;        // add 5 to sum
This statement has the same effect as:
sum = sum + 5;   // add 5 to sum

Here is a list of some combined operators. These operators work in three steps. First, the complete expression on the right of the = is evaluated. Second, the operation that is combined with the = is performed. Finally the result is assigned to the variable.

Operator Operation Example Effect
=assignment sum = 5;sum = 5;
+=addition with assignment sum += 5;sum = sum + 5;
-=subtraction with assignment sum -= 5;sum = sum - 5;
*=multiplication with assignment sum *= 5;sum = sum * 5;
/=division with assignment sum /= 5;sum = sum/5;

 

QUESTION 9:

Here is a program fragment:

double w = 12.5 ;
double x =  3.0;

w *= x - 1 ;
x -= 1 + 1;

System.out.println( " w is " + w + " x is " + x );

What does this program fragment write out?