Operators

Operators are symbols used to represent computations like addition and multiplication. Most operators in Java do what you expect them to do because they are common mathematical symbols. For example, the operator
for addition is +. Subtraction is -, multiplication is *, and division is /.

1+1       hour-1       hour*60 + minute       minute/60

Expressions can contain both variable names and numbers. Variables are replaced with their values before the computation is performed.

Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, this 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);


generates this output:

  Number of minutes since midnight: 719
  Fraction of the hour that has passed: 0

The first line is expected, but the second line is odd. The value of minute is 59, and 59 divided by 60 is 0.98333, not 0. The problem is that Java is performing integer division.

When both operands are integers (operands are the things operators operate on), the result is also an integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close.

An alternative 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: 98

Again the result is rounded down, but at least now the answer is approximately correct. To get a more accurate answer, we can use a deferent type of variable, called floating-point, that can store fractional values.

 

Operators for Strings
In general you cannot perform mathematical operations on Strings, even if the strings look like numbers. The following are illegal (if we know that bob has type String)

bob - 1       "Hello"/123         bob * "Hello"

By the way, can you tell by looking at those expressions whether bob is an integer or a string? Nope. The only way to tell the type of a variable is to look at the place where it is declared.

Interestingly, the + operator does work with Strings, but it might not do what you expect. For Strings, the + operator represents concatenation, which means joining up the two operands by linking them end-to-end.

So "Hello, " + "world." yields the string "Hello, world." and bob +"ism" adds the suffix ism to the end of whatever bob is, which is handy for naming new forms of bigotry.