Skip to main content
Lesson 3 - Data Types in Java
Lesson MenuPreviousNext
  
Assignment Statements and Math Operators page 8 of 11

  1. An assignment statement has the following basic syntax:

    variable = expression;
    1. The expression can be a literal constant value such as 2, 12.25, 't'.
    2. The expression can also be a numeric expression involving operands (values) and operators.
    3. The = operator returns the value of the expression. This means that the statement
      a = 5;

      assigns 5 to the variable and returns the value 5. This allows for chaining of assignment operators.

      a = b = 5;

      The assignment operator (=) is right-associative. This means that the above statement is really solved in this order:

      a = (b = 5);  // solved from right to left.

      Since (b = 5) returns the integer 5, the value 5 is also assigned to variable a.

  2. Java provides 5 math operators as listed below:

    +Addition, as well as unary +
    -Subtraction, as well as unary -
    *Multiplication
    /Real and integer division
    %Modulus, remainder of integer or floating point division

  3. The numerical result and data type of the answer depends on the type of operands used in a problem.

  4. For all the operators, if both operands are integers, the result is an integer. Examples:

         2 + 3 = 5  (integer)    9 - 3 = 6  (integer)
         4 * 8 = 32 (integer)    11/2 = 5  (integer)
  5. If either of the operands is a float type, the result is a float type. Examples:

    2 + 3.000 = 5.000  (float)
    25 / 6.75 = 3.7037 (float)
    11.0 / 2.0 = 5.5 (float)
    1. When an integer and a float value are used in a binary math expression, the integer is promoted to a float value, and then the math is executed.
    2. In the example 2 + 3.000 = 5.000, the integer value 2 is promoted to a float (2.000) and then added to the 3.000.

  6. The modulus operator (%) returns the remainder of dividing the first operand by the second. For example:

    10 % 3 = 1    2 % 4 = 2    16 % 2 = 0    27.475 % 7.22 = 5.815
  7. Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator. A unary operator works with only one value. Applying the negation operator to an integer returns an integer, while applying it to a float returns a float value. For example:

    -(67) = -67      -(-2.345) = 2.345
  8. To obtain the fractional answer to a question like 11/2 = 5.5, a type conversion must be applied to one of the operands.

    (double)11/2results in 5.5
    11.000/2then we do division
    5.5

    The type conversion operators are unary operators with the following syntax:

    (type) operand
  9. There is more to cover regarding operators in Java. Topics such as math precedence and assignment operators will be covered in a later lesson.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.