In this, part two of this ten part series on Java, Chris looks at the Java language syntax, variable declerations, truth conditions, loops and more. He finishes by wrapping everything up into a simple Java function.
Java Part 2: Syntax - Decleration and assignment (Page 2 of 8 )
Java variables are declared in exactly the same way as in both C and C++. Let's declare a variable of type int and then set it to a value:
int val;
val = 1;
This decleration could be shorted to just one line of code, like this:
int val = 1;
Addition and Subtraction
The standard C incremetor function ++, or -- for decrementing a variable still holds in Java. For example:
int val = 1;
val = val + 1; // val is now 2
Further, we can simplify the second line even more:
val++;
This works the same for decrementing. These two operators for incrementing and decrementing are known as unary operators because they only require one argument.
Multiplication and Division
To multiply a variable by a numerical value, we use the * operator, like this:
val = val * 10; // Multiply val by 10
We can also multiply a variable by a number like this:
val *= 10; // Same as val = val * 10
Multiplying one variable by another is also simple:
var = var * par;
OR
var *= par;
Division follows exactly the same principles as addition, subtraction and multiply:
val = val / 50;
OR
val /= 50;
Also, dividing one value by another is easily accomplished: