Both of these examples rely on the assignment operator (=), which takes a value on the right and stores it (assigns it) to a variable on the left. The addition and subtraction operators (+ and -) carry out simple addition and subtraction, much like a calculator.
The first line of code results in a value of 1999 being stored in curYear. The second line then effectively performs the computation 2000 - 1999, which results in a value of 1 being stored in tilY2K.
Most of these operators are probably very familiar to you already. Addition, subtraction, multiplication,
and division are used in everyday calculations. It is worth noting at this point that while they operate in the way you understand and expect, the answer is not always exactly what you are looking for. In other cases, the way data is stored as binary numbers cannot accurately represent non-whole numbers. For this reason, operations on floating point numbers often result in a number that is very close to what you expect,
but with several digits after the decimal point. This is simply due to the fact that these decimals are approximations. For example, if you multiply 1.3 times 0.01, the answer would be 0.013.
However, when you ask Java to calculate
1.3f*0.01f
, the result is 0.12999999. Of course, this rounds to the 0.013 you are expecting, so the operation is the same. Sometimes the problem is not with rounding, but due to the data type being used. To illustrate this, imagine you have two integers, 5 and 2. If you add them together, you expect 7 (and this is what Java will return as well). However, if you divide 5 by 2, you already know the answer is 2.5. However, Java is using integers, so the result of integer operations must be an integer. Therefore, Java evaluates 5/2 = 2. The remainder is not included in the result.
This is where the modulo operator comes in. It will calculate the remainder in division.
So, while 5/2 = 2 (and the remainder of 1 was ignored), 5%2 = 1 (here is that remainder of 1). Between the two operators, you have the complete solution. It is interesting to note that the modulo operator is often used to check whether a number is even or odd. For an even number, %2 will result in 0, whereas for an odd number, %2 will result in 1.