Program Logic

Unit 2 Index

Assignment Operator

The Assignment Operator

The assignment operator is the equals sign ( = ). You assign a value to a variable. Hopefully you remember this example from a previous chapter:

“After declaration, you can assign the value of one variable to be the value of another variable. Study the below code. Notice we declare and initialize count and maxCount. Then we set count equal to maxCount, which means we assign the value of maxCount to count. Therefore, after the line of code count = maxCount; executes, the value of count become the same as the value of maxCount. In our example that is 99.”

int count = 0;
int maxCount = 99;
		
count = maxCount;

Order Matters!

Let's take a deeper dive into the above example. First, ORDER MATTERS! It is very important to declare and initialize your variables prior to using them. If you do not, you will get a Cannot find symbol error. It is also very important to have the variable that is accepting the value on the left of the assignment operator. If you do not, you will get an Unexpected type error.

On left side of the equals sign you need a variable or a named constant. On the right you need a literal value or a variable that contains a value.

thisVariableWillAcceptTheValue = thisVariableWillGiveTheValue;

Remember to end your assignment statement with a semicolon.

Compatible Data Types

Please note, the variable on the left and the value/variable on the right MUST be of compatible data types. If not, you will get an Incompatible types error. If you try to assign a double into an int variable, you may get an error message about a possible lossy conversion. BUT you will not get this error if you assign an int into a double variable. Be careful and know your data types!

Error! myStringVariable = myIntVariable;

Error! myIntVariable = myDoubleVariable;

No error myDoubleVariable = myIntVariable;

Understanding Error Messages

Do not be embarrassed when you get errors; everyone gets them. Understanding your errors goes a long way to increasing your knowledge. It is best not to attempt to fix your code until you understand why it is broken. Below are two resources that list common errors in Java.

My suggestion is that you visit these sites and learn more about the error messages talked about on this page. With more programming experience the potential for errors is greater. However, anytime you encounter an error, please re-visit these sites (or others) to determine the root cause of the error.

What's next?

The next chapter in this unit is: Errors, Testing, and Debugging.