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 SubtractionThe standard C incremetor function ++, or -- for decrementing a variable still holds in Java. For example:
int val = 1;
val = val + 1; // val is now 2Further, 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 DivisionTo multiply a variable by a numerical value, we use the * operator, like this:
val = val * 10; // Multiply val by 10We can also multiply a variable by a number like this:
val *= 10; // Same as val = val * 10Multiplying one variable by another is also simple:
var = var * par;ORvar *= 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:
val = val / par; // Same as val = val / parORval /= par; // Same as val = val / parNext: Making code more readable >>
More Java Articles
More By Chris Noack