Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Assignment Operators
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
An assignment operator functions to change the value that is stored inside a variable. In order for the operator to change a value, the variable must be declared beforehand. Also remember that we can declare a variable and assign it a value at the same time. Look at the code below for an example of the three assignment operators we will discuss: '=', "+=", and "-=".
AssignmentStatementExample.java
package exlcode;
public class AssignmentStatementExample {
public static int exampleVariableOne = 10;
public static int exampleVariableTwo = 50;
public static void main(String[] args) {
exampleVariableOne = exampleVariableOne + exampleVariableTwo;
exampleVariableTwo += 5;
exampleVariableTwo -= 2;
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
Something to keep in mind when assigning values is that the calculation on the right side of the equal sign is completed before assigning the variable on the left with its new value. As we see in the code above, exampleVariableOne and exampleVariableTwo are added before being assigned to the new value of variable exampleVariableOne. This makes the new value for exampleVariableOne 60.
The "+=" and the "-=" functions add or subtract integers together before assigning them to the variable. Therefore, exampleVariableTwo += 5; is actually the same as the statement exampleVariableTwo = exampleVariableTwo + 5;. exampleVariableTwo increases by a value of 3 as a result of the program because it adds 5 and subtracts 2 before printing.
Keep in mind that it is possible to also use "*=", "/=", or "%=" if you are comfortable with using these "shortcut" operators.