Compound Assignment Operators
look at storing items in variables with assignment statemt.
also look at compound assignment operators (+=, -= etc) to modify values stored in variables in one step
+= adds value to existing variable value
x += 7 is equivalent to x = x + 7; x -= 5 is equivalent to x = x - 5;
same for all compound assignment operators.
public class CompoundDemo {
public static void main(String[] args) {
int x = 6;
x += 7; // 6 + 7 = 13
x -= 3; // 13 - 3 = 10
System.out.println(x);
x *= 10; // 10 * 10
x /= 5; // 100 / 5 = 20
System.out.println(x);
x %= 3; // remainder of 100/3 = 2
System.out.println(x);
}
}
CompoundDemo.main(null);
// NOTE: going through these compound assignments with comments is called tracing,
// when we do what the compiler does, and go through the code step by step. Should be
//done on the AP test to avoid human error.
10
20
2
increment and decrement operator
IMPORTANT: THE USE OF INCREMENT AND DECREMENT OPERATORS IN THE PREFIX FORM (++X) AND INSIDE OTHER EXPRESSIONS (ARR[X++]) IS OUTSIDE THE SCOPE OF THE COURSE AND THE AP EXAM
public class incdecDemo {
public static void main(String[] args) {
int x = 1;
int y = 1;
x++; // x = x + 1, x = 2;
y--; // y = y - 1, y = 1 - 1 = 1;
System.out.println(x);
System.out.println(y);
}
}
incdecDemo.main(null);
// NOTE: going through these compound assignments in order is important to
// ensure you get the correct output at the end
2
0
learn how to describe code
the following code segment has comments that describe the line of code the comment is on. Look at how the code is described.
public class behaviorDemo {
public static void main(String[] args) {
int x = 20; // define an int variable x and set its initial value to 23
x *= 2; // take the current value of x, multiply it by 2, assign the result back to x
x %= 10; // take the current value of x, find x modulus 10 (remainder x divided by 10),
//assign result back to x
System.out.println(x); // display the current value of x
}
}
behaviorDemoDemo.main(null);
// DESCRIBE EACH LINE OF CODE
int x = 5;
x++;
x /= 2;
System.out.println(x);
what you must know
compound operators perform an operation on a variable and assign the result to the variable
ex: x /= 25; would take x and divide it by 25, then assign the result to x.
if x = 100, then the result of x/= 25; would be 4.
increment and decrement operators take x and either increment it or decrement it by 1, then assign the value to x.
x++; would take x and add 1 to it, then assign the value to x.
x–; takes x and subtracts 1 from x, then assigns the value to x.