CIS 160 Operators and operator precedence

Objectives

  • Use operators
  • Explain operator precedence
  • Demonstrate how a value can be cast to another data type

Operators and operator precedence

Examples

  • int a = 5 + 7; // addition, 12 is stored in a
  • double b = 3 - 5 * 3; // subtraction and multiplication, -12 is stored in b
  • double c = a / b; // division, -1 is stored in c
  • double b = (3 - 5) * 3; // subtraction and multiplication, -6 is stored in b
  • double c = a / b; // division, -2 is stored in c

More common operators

  • ++ is the increment operator. If x contains the value 5, then x++ increments x to 6
  • ++ can be used before or after the variable. The position causes slightly different behavior in expressions - so don't use it with other operators.
  • -- is the decrement operator. If x contains the value 5, then x-- decrements x to 4
  • -- can be used before or after the variable. The position causes slightly different behavior in expressions - so don't use it with other operators.
  • x += y is equivalent to: x = x + y
  • x -= y is equivalent to: x = x - y
  • x *= y is equivalent to: x = x * y
  • x /= y is equivalent to: x = x / y
  • There are many other operators. We will cover some additional operators as we need them.

Type casting

  • Place a data type name in parentheses in front of a value or variable (called typecasting) to temporarily make it the data type of the cast.
  • 5 / 2 is integer division and produces an integer result of 2 (NOT 2.5)
  • (float)5 / 2 is floating-point division and leaves an answer of 2.5
  • 5/(float) 2 is floating-point division and leaves an answer of 2.5
  • (double)5 / 2 is floating-point division and leaves an answer of 2.5
  • 5/(double) 2 is floating-point division and leaves an answer of 2.5
  • If a number contains a decimal point, Java assumes it is a "double" (double precision floating point)
  • 5.0 / 2 is floating-point division and leaves an answer of 2.5
  • 5 / 2.0 is floating-point division and leaves an answer of 2.5
  • An "f" trailing a number tells Java the number is a float (single precision floating point)).
  • 5f / 2 is floating-point division and leaves an answer of 2.5
  • 5 / 2f is floating-point division and leaves an answer of 2.5

External resource