Thursday 21 July 2011

Java: Variables (Assignment)

Changing the value of a variable, or giving it it's initial value, is known as assignment. Assigning a variable that already has a value overwrites its current value. Doing this changes the value contained by the variable, not the variable itself.

Further, you must declare variables as some type before trying to assign them to let the computer know how to read it. Some simple types are:


int
double
String
char
boolean


int being integer, double (sometimes referred to as floating point numbers) being decimal point numbers, String being a collection of characters, words or otherwise ("program", "asjdfbsf", "23"), char being single characters ('g', 'l') and boolean being a simple True/False value.


int x; //This declares a variable, named "x" to be an integer.
x = 1; //This assigns the value 1 to x.
x = 2; //Without changing the name of the variable x, this is changing its contained value to 2
x= "nope" //This just can't happen. x has already been declared as an integer, and here, we try to assign a string to it. We would need a new variable to do this.

Assignment can happen with expressions (on the right hand side of the equation only, since the left is reserved for the one variable being assigned a value), such as:

x = y*2 + z;

...which itself can use other, already assigned variables. Most of the operators remain the same as they do in regular arithmetic,+, -, /, *, but when we get to it later, we'll see some differences in other functions. However, a useful function not worth putting off is the ability to have a line of code such as:

x = x + 1;

Which adds 1 to the current value of x. (So if x was 3, after the above line, its new value would be 4).


That's all, folks!

No comments:

Post a Comment