The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Variables and Types Operators | ||
Search the VIAS Library | Index | ||
Operators
Operators are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in Java do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is +. The following are all legal Java expressions whose meaning is more or less obvious: 1+1 hour-1 hour*60 + minute minute/60Expressions can contain both variable names and numbers. In each case the name of the variable is replaced with its value before the computation is performed. Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, the following program: int hour, minute;hour = 11; minute = 59; System.out.print ("Number of minutes since midnight: "); System.out.println (hour*60 + minute); System.out.print ("Fraction of the hour that has passed: "); System.out.println (minute/60); would generate the following output: Number of minutes since midnight: 719Fraction of the hour that has passed: 0 The first line is what we expected, but the second line is odd. The value of the variable minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Java is performing integer division. When both of the operands are integers (operands are the things operators operate on), the result must also be an integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close. A possible alternative in this case is to calculate a percentage rather than a fraction: System.out.print ("Percentage of the hour that has passed: ");System.out.println (minute*100/60); The result is: Percentage of the hour that has passed: 98Again the result is rounded down, but at least now the answer is approximately correct. In order to get an even more accurate answer, we could use a different type of variable, called floating-point, that is capable of storing fractional values. We'll get to that in the next chapter.
|
||
Home Variables and Types Operators |