Arithmetic evaluation in Java

Modulo

The modulo operator works as follows:

(a / b) * b + (a % b) = a where a / b is the integer division (with rest).

So -11 % 4 is equal to -3 and not 1.

In general, if the a is negative, the result is negative.

Associativity

+, *, /, % are left-associative, meaning that X op Y op Z = (X op Y) op Z.

= for example is right-associative. That is also why a = b = c = 5 means all are equal to 5.

Operator precedence

*, /, % binden stärker als +, -.

Unary operators (-) bind stronger than binary ones.

== and other comparison operators have higher precedence than the boolean comparison operators like &&.

Implicit ()

First operators with higher precedence are bound, ex: 2 * x + 3 = (2 * x) + 3.

Then if two operators have the same precedence, then associativity is relevant:

  • x - 7 + y (x - 7) + y because of same precedence and left-associative
  • x = y = 0 x = (y = 0) because of same precedence and right-associative

Typecasting

(type) expression is the cast-operator, which is unary (highest precedence) and right-associative.

It’s also higher-precedence than all other arithmetic operators.

Casting from lower-precision types (int long, int double) is always implicit. Down-casting into less bits has to be explicit.

The only special case is long double, which is implicit, even though we may incur precision-loss.

Errors

n % 0 and n / 0 both throw the divide by zero error.

Types

Keep in mind the explicit casts will be a compile error if the cast is not specified.

Doing + with a string will cast any primitive type to a string representation.

Scanner

The Scanner sc = new Scanner(System.in) (you can also use file handles as inputs, using new File("file.txt")) allows for the methods:

  1. nextInt() to consume the next int from the input.
  2. nextDouble()
  3. next() reads a one-word string (delimited by spaces and newlines)
  4. nextLine() reads in the entire next line

Randoms

Use Random rand = new Random() to generate random numbers.

  1. nextInt() returns the next random integer (range over int.MIN_VALUE to MAX_VALUE)
  2. nextInt(n) random integer in the range [0, n).
  3. nextDouble() random real number in the range `[0.0, 1.0)