Thank you for visiting Blazing Games

Mathematics and the Order of Operations

Java uses a Algebra like method of manipulating numbers. How variables are assigned numbers is not exactly valid algebraically, as equals has very strict meaning in algebra. Some languages, such as pascal, avoid this confusion by using something other than an equals sign to indicate assignment. To assign a value to a variable in java you simply use an equals sign. for example

The above would put the value 21 into the variable number and the words "Hello world!" into s. It is possible to save a couple of lines by having the variable declaration and the assignment all on the same line as in

Doing mathematical operations to variables is also possible. for instance, to add the value of two variables you can simply do something like the following:

Java follows algebraic order of operations when performing arithmetic. This means that 1 + 2 * 3 would result in 7 not 9! This is because multiplications are calculated first, unless parentheses are used.

Sometimes you will want to use a variable of one type with a variable of a different type. This is possible, but requires something known as casting. What casting does is it tells the compiler to convert a variable into a different type of variable before using that variable. Casting can only be done with similar variables. For instance, math variables can be cast into other math types. I will cover class instance casting in a different chapter.

Casting mathematical variables only needs to be done in cases where information can be lost or if you are going from a whole number (integer, for instance) to a real number (such as a double). Casting is done by putting the type of variable you want to cast to in brackets in front of the variable to be cast. for example:

Previous Chapter 3 Contents Page 9 of 10 Book Contents Next

About - Privacy Policy - Contact - Links - FAQ
Copyright © 2005-2006 Blazing Games Inc. All Rights Reserved