Java programs consist of many statements:
Now, we examine assignment statements.
Java programs abstract the concept of memory addresses with variables. A variable reserves a segment of memory for a given type of data.
We'll use three types, corresponding to the ones we saw earlier.
char character int integer double floating-point number
Before using variables, we must first declare them to reserve memory and to assign type.
int variable_name0;
The int gives the type of variable. variable_name0 is the name of the variable (consisting of letters, digits, and underscores, but beginning with a letter). The semicolon ends the statement.
Other examples:
char character; int k; double root_n;
To give a value to a variable, we use an assignment statement.
k = 2;
Here k is the variable to be changed. The value to give it is 2. And we see yet another statement-terminating semicolon.
The right-hand side can be any expression. Some expressions:
4 9 + k 30 / 4 12 - 3 * 4 k 3 * k 30.0 / 4 (12 - 3) * 4 -k 6 - 9 20 % 4
So we can also write:
k = 9 * k * k + 6;
We reserve long blocks of memory with arrays. To declare an array of 30 characters, we write
char[] arr = new char[30];Here the type of array element (char) occurs twice. We have named the array array, and the number appearing in brackets (30) is the array length.
We use an index in brackets to specify array elements in assignments.
arr[0] = 'S'; arr[k / 2] = '0';
Note: Arrays are indexed from 0. So arr[30] doesn't exist.
Arrays of arrays, too, are OK, as are arrays of arrays of arrays (and deeper). An array of arrays is a two-dimensional array.
double[][] m = new double[4][5];
Access is as before.
m[k - 39][4] = k / 3 / 2; m[0][0] = m[3][4] / k;